follow_track.hpp

Go to the documentation of this file.
00001 /* $Id: follow_track.hpp 26109 2013-11-25 14:34:09Z 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  FOLLOW_TRACK_HPP
00013 #define  FOLLOW_TRACK_HPP
00014 
00015 #include "../pbs.h"
00016 #include "../roadveh.h"
00017 #include "../station_base.h"
00018 #include "../train.h"
00019 #include "../tunnelbridge.h"
00020 #include "../tunnelbridge_map.h"
00021 #include "../depot_map.h"
00022 #include "pf_performance_timer.hpp"
00023 
00029 template <TransportType Ttr_type_, typename VehicleType, bool T90deg_turns_allowed_ = true, bool Tmask_reserved_tracks = false>
00030 struct CFollowTrackT
00031 {
00032   enum ErrorCode {
00033     EC_NONE,
00034     EC_OWNER,
00035     EC_RAIL_TYPE,
00036     EC_90DEG,
00037     EC_NO_WAY,
00038     EC_RESERVED,
00039   };
00040 
00041   const VehicleType  *m_veh;           
00042   Owner               m_veh_owner;     
00043   TileIndex           m_old_tile;      
00044   Trackdir            m_old_td;        
00045   TileIndex           m_new_tile;      
00046   TrackdirBits        m_new_td_bits;   
00047   DiagDirection       m_exitdir;       
00048   bool                m_is_tunnel;     
00049   bool                m_is_bridge;     
00050   bool                m_is_station;    
00051   int                 m_tiles_skipped; 
00052   ErrorCode           m_err;
00053   CPerformanceTimer  *m_pPerf;
00054   RailTypes           m_railtypes;
00055 
00056   inline CFollowTrackT(const VehicleType *v = NULL, RailTypes railtype_override = INVALID_RAILTYPES, CPerformanceTimer *pPerf = NULL)
00057   {
00058     Init(v, railtype_override, pPerf);
00059   }
00060 
00061   inline CFollowTrackT(Owner o, RailTypes railtype_override = INVALID_RAILTYPES, CPerformanceTimer *pPerf = NULL)
00062   {
00063     m_veh = NULL;
00064     Init(o, railtype_override, pPerf);
00065   }
00066 
00067   inline void Init(const VehicleType *v, RailTypes railtype_override, CPerformanceTimer *pPerf)
00068   {
00069     assert(!IsRailTT() || (v != NULL && v->type == VEH_TRAIN));
00070     m_veh = v;
00071     Init(v != NULL ? v->owner : INVALID_OWNER, IsRailTT() && railtype_override == INVALID_RAILTYPES ? Train::From(v)->compatible_railtypes : railtype_override, pPerf);
00072   }
00073 
00074   inline void Init(Owner o, RailTypes railtype_override, CPerformanceTimer *pPerf)
00075   {
00076     assert((!IsRoadTT() || m_veh != NULL) && (!IsRailTT() || railtype_override != INVALID_RAILTYPES));
00077     m_veh_owner = o;
00078     m_pPerf = pPerf;
00079     /* don't worry, all is inlined so compiler should remove unnecessary initializations */
00080     m_old_tile = INVALID_TILE;
00081     m_old_td = INVALID_TRACKDIR;
00082     m_new_tile = INVALID_TILE;
00083     m_new_td_bits = TRACKDIR_BIT_NONE;
00084     m_exitdir = INVALID_DIAGDIR;
00085     m_is_station = m_is_bridge = m_is_tunnel = false;
00086     m_tiles_skipped = 0;
00087     m_err = EC_NONE;
00088     m_railtypes = railtype_override;
00089   }
00090 
00091   inline static TransportType TT() { return Ttr_type_; }
00092   inline static bool IsWaterTT() { return TT() == TRANSPORT_WATER; }
00093   inline static bool IsRailTT() { return TT() == TRANSPORT_RAIL; }
00094   inline bool IsTram() { return IsRoadTT() && HasBit(RoadVehicle::From(m_veh)->compatible_roadtypes, ROADTYPE_TRAM); }
00095   inline static bool IsRoadTT() { return TT() == TRANSPORT_ROAD; }
00096   inline static bool Allow90degTurns() { return T90deg_turns_allowed_; }
00097   inline static bool DoTrackMasking() { return Tmask_reserved_tracks; }
00098 
00100   inline DiagDirection GetSingleTramBit(TileIndex tile)
00101   {
00102     assert(IsTram()); // this function shouldn't be called in other cases
00103 
00104     if (IsNormalRoadTile(tile)) {
00105       RoadBits rb = GetRoadBits(tile, ROADTYPE_TRAM);
00106       switch (rb) {
00107         case ROAD_NW: return DIAGDIR_NW;
00108         case ROAD_SW: return DIAGDIR_SW;
00109         case ROAD_SE: return DIAGDIR_SE;
00110         case ROAD_NE: return DIAGDIR_NE;
00111         default: break;
00112       }
00113     }
00114     return INVALID_DIAGDIR;
00115   }
00116 
00121   inline bool Follow(TileIndex old_tile, Trackdir old_td)
00122   {
00123     m_old_tile = old_tile;
00124     m_old_td = old_td;
00125     m_err = EC_NONE;
00126     assert(((TrackStatusToTrackdirBits(GetTileTrackStatus(m_old_tile, TT(), IsRoadTT() ? RoadVehicle::From(m_veh)->compatible_roadtypes : 0)) & TrackdirToTrackdirBits(m_old_td)) != 0) ||
00127            (IsTram() && GetSingleTramBit(m_old_tile) != INVALID_DIAGDIR)); // Disable the assertion for single tram bits
00128     m_exitdir = TrackdirToExitdir(m_old_td);
00129     if (ForcedReverse()) return true;
00130     if (!CanExitOldTile()) return false;
00131     FollowTileExit();
00132     if (!QueryNewTileTrackStatus()) return TryReverse();
00133     if (!CanEnterNewTile()) return false;
00134     m_new_td_bits &= DiagdirReachesTrackdirs(m_exitdir);
00135     if (m_new_td_bits == TRACKDIR_BIT_NONE) {
00136       /* In case we can't enter the next tile, but are
00137        * a normal road vehicle, then we can actually
00138        * try to reverse as this is the end of the road.
00139        * Trams can only turn on the appropriate bits in
00140        * which case reaching this would mean a dead end
00141        * near a building and in that case there would
00142        * a "false" QueryNewTileTrackStatus result and
00143        * as such reversing is already tried. The fact
00144        * that function failed can have to do with a
00145        * missing road bit, or inability to connect the
00146        * different bits due to slopes. */
00147       if (IsRoadTT() && !IsTram() && TryReverse()) return true;
00148       m_err = EC_NO_WAY;
00149       return false;
00150     }
00151     if (!Allow90degTurns()) {
00152       m_new_td_bits &= (TrackdirBits)~(int)TrackdirCrossesTrackdirs(m_old_td);
00153       if (m_new_td_bits == TRACKDIR_BIT_NONE) {
00154         m_err = EC_90DEG;
00155         return false;
00156       }
00157     }
00158     return true;
00159   }
00160 
00161   inline bool MaskReservedTracks()
00162   {
00163     if (!DoTrackMasking()) return true;
00164 
00165     if (m_is_station) {
00166       /* Check skipped station tiles as well. */
00167       TileIndexDiff diff = TileOffsByDiagDir(m_exitdir);
00168       for (TileIndex tile = m_new_tile - diff * m_tiles_skipped; tile != m_new_tile; tile += diff) {
00169         if (HasStationReservation(tile)) {
00170           m_new_td_bits = TRACKDIR_BIT_NONE;
00171           m_err = EC_RESERVED;
00172           return false;
00173         }
00174       }
00175     }
00176 
00177     TrackBits reserved = GetReservedTrackbits(m_new_tile);
00178     /* Mask already reserved trackdirs. */
00179     m_new_td_bits &= ~TrackBitsToTrackdirBits(reserved);
00180     /* Mask out all trackdirs that conflict with the reservation. */
00181     Track t;
00182     FOR_EACH_SET_TRACK(t, TrackdirBitsToTrackBits(m_new_td_bits)) {
00183       if (TracksOverlap(reserved | TrackToTrackBits(t))) m_new_td_bits &= ~TrackToTrackdirBits(t);
00184     }
00185     if (m_new_td_bits == TRACKDIR_BIT_NONE) {
00186       m_err = EC_RESERVED;
00187       return false;
00188     }
00189     return true;
00190   }
00191 
00192 protected:
00194   inline void FollowTileExit()
00195   {
00196     m_is_station = m_is_bridge = m_is_tunnel = false;
00197     m_tiles_skipped = 0;
00198 
00199     /* extra handling for tunnels and bridges in our direction */
00200     if (IsTileType(m_old_tile, MP_TUNNELBRIDGE)) {
00201       DiagDirection enterdir = GetTunnelBridgeDirection(m_old_tile);
00202       if (enterdir == m_exitdir) {
00203         /* we are entering the tunnel / bridge */
00204         if (IsTunnel(m_old_tile)) {
00205           m_is_tunnel = true;
00206           m_new_tile = GetOtherTunnelEnd(m_old_tile);
00207         } else { // IsBridge(m_old_tile)
00208           m_is_bridge = true;
00209           m_new_tile = GetOtherBridgeEnd(m_old_tile);
00210         }
00211         m_tiles_skipped = GetTunnelBridgeLength(m_new_tile, m_old_tile);
00212         return;
00213       }
00214       assert(ReverseDiagDir(enterdir) == m_exitdir);
00215     }
00216 
00217     /* normal or station tile, do one step */
00218     TileIndexDiff diff = TileOffsByDiagDir(m_exitdir);
00219     m_new_tile = TILE_ADD(m_old_tile, diff);
00220 
00221     /* special handling for stations */
00222     if (IsRailTT() && HasStationTileRail(m_new_tile)) {
00223       m_is_station = true;
00224     } else if (IsRoadTT() && IsRoadStopTile(m_new_tile)) {
00225       m_is_station = true;
00226     } else {
00227       m_is_station = false;
00228     }
00229   }
00230 
00232   inline bool QueryNewTileTrackStatus()
00233   {
00234     CPerfStart perf(*m_pPerf);
00235     if (IsRailTT() && IsPlainRailTile(m_new_tile)) {
00236       m_new_td_bits = (TrackdirBits)(GetTrackBits(m_new_tile) * 0x101);
00237     } else {
00238       m_new_td_bits = TrackStatusToTrackdirBits(GetTileTrackStatus(m_new_tile, TT(), IsRoadTT() ? RoadVehicle::From(m_veh)->compatible_roadtypes : 0));
00239 
00240       if (IsTram() && m_new_td_bits == 0) {
00241         /* GetTileTrackStatus() returns 0 for single tram bits.
00242          * As we cannot change it there (easily) without breaking something, change it here */
00243         switch (GetSingleTramBit(m_new_tile)) {
00244           case DIAGDIR_NE:
00245           case DIAGDIR_SW:
00246             m_new_td_bits = TRACKDIR_BIT_X_NE | TRACKDIR_BIT_X_SW;
00247             break;
00248 
00249           case DIAGDIR_NW:
00250           case DIAGDIR_SE:
00251             m_new_td_bits = TRACKDIR_BIT_Y_NW | TRACKDIR_BIT_Y_SE;
00252             break;
00253 
00254           default: break;
00255         }
00256       }
00257     }
00258     return (m_new_td_bits != TRACKDIR_BIT_NONE);
00259   }
00260 
00262   inline bool CanExitOldTile()
00263   {
00264     /* road stop can be left at one direction only unless it's a drive-through stop */
00265     if (IsRoadTT() && IsStandardRoadStopTile(m_old_tile)) {
00266       DiagDirection exitdir = GetRoadStopDir(m_old_tile);
00267       if (exitdir != m_exitdir) {
00268         m_err = EC_NO_WAY;
00269         return false;
00270       }
00271     }
00272 
00273     /* single tram bits can only be left in one direction */
00274     if (IsTram()) {
00275       DiagDirection single_tram = GetSingleTramBit(m_old_tile);
00276       if (single_tram != INVALID_DIAGDIR && single_tram != m_exitdir) {
00277         m_err = EC_NO_WAY;
00278         return false;
00279       }
00280     }
00281 
00282     /* road depots can be also left in one direction only */
00283     if (IsRoadTT() && IsDepotTypeTile(m_old_tile, TT())) {
00284       DiagDirection exitdir = GetRoadDepotDirection(m_old_tile);
00285       if (exitdir != m_exitdir) {
00286         m_err = EC_NO_WAY;
00287         return false;
00288       }
00289     }
00290     return true;
00291   }
00292 
00294   inline bool CanEnterNewTile()
00295   {
00296     if (IsRoadTT() && IsStandardRoadStopTile(m_new_tile)) {
00297       /* road stop can be entered from one direction only unless it's a drive-through stop */
00298       DiagDirection exitdir = GetRoadStopDir(m_new_tile);
00299       if (ReverseDiagDir(exitdir) != m_exitdir) {
00300         m_err = EC_NO_WAY;
00301         return false;
00302       }
00303     }
00304 
00305     /* single tram bits can only be entered from one direction */
00306     if (IsTram()) {
00307       DiagDirection single_tram = GetSingleTramBit(m_new_tile);
00308       if (single_tram != INVALID_DIAGDIR && single_tram != ReverseDiagDir(m_exitdir)) {
00309         m_err = EC_NO_WAY;
00310         return false;
00311       }
00312     }
00313 
00314     /* road and rail depots can also be entered from one direction only */
00315     if (IsRoadTT() && IsDepotTypeTile(m_new_tile, TT())) {
00316       DiagDirection exitdir = GetRoadDepotDirection(m_new_tile);
00317       if (ReverseDiagDir(exitdir) != m_exitdir) {
00318         m_err = EC_NO_WAY;
00319         return false;
00320       }
00321       /* don't try to enter other company's depots */
00322       if (GetTileOwner(m_new_tile) != m_veh_owner) {
00323         m_err = EC_OWNER;
00324         return false;
00325       }
00326     }
00327     if (IsRailTT() && IsDepotTypeTile(m_new_tile, TT())) {
00328       DiagDirection exitdir = GetRailDepotDirection(m_new_tile);
00329       if (ReverseDiagDir(exitdir) != m_exitdir) {
00330         m_err = EC_NO_WAY;
00331         return false;
00332       }
00333     }
00334 
00335     /* rail transport is possible only on tiles with the same owner as vehicle */
00336     if (IsRailTT() && GetTileOwner(m_new_tile) != m_veh_owner) {
00337       /* different owner */
00338       m_err = EC_NO_WAY;
00339       return false;
00340     }
00341 
00342     /* rail transport is possible only on compatible rail types */
00343     if (IsRailTT()) {
00344       RailType rail_type = GetTileRailType(m_new_tile);
00345       if (!HasBit(m_railtypes, rail_type)) {
00346         /* incompatible rail type */
00347         m_err = EC_RAIL_TYPE;
00348         return false;
00349       }
00350     }
00351 
00352     /* tunnel holes and bridge ramps can be entered only from proper direction */
00353     if (IsTileType(m_new_tile, MP_TUNNELBRIDGE)) {
00354       if (IsTunnel(m_new_tile)) {
00355         if (!m_is_tunnel) {
00356           DiagDirection tunnel_enterdir = GetTunnelBridgeDirection(m_new_tile);
00357           if (tunnel_enterdir != m_exitdir) {
00358             m_err = EC_NO_WAY;
00359             return false;
00360           }
00361         }
00362       } else { // IsBridge(m_new_tile)
00363         if (!m_is_bridge) {
00364           DiagDirection ramp_enderdir = GetTunnelBridgeDirection(m_new_tile);
00365           if (ramp_enderdir != m_exitdir) {
00366             m_err = EC_NO_WAY;
00367             return false;
00368           }
00369         }
00370       }
00371     }
00372 
00373     /* special handling for rail stations - get to the end of platform */
00374     if (IsRailTT() && m_is_station) {
00375       /* entered railway station
00376        * get platform length */
00377       uint length = BaseStation::GetByTile(m_new_tile)->GetPlatformLength(m_new_tile, TrackdirToExitdir(m_old_td));
00378       /* how big step we must do to get to the last platform tile; */
00379       m_tiles_skipped = length - 1;
00380       /* move to the platform end */
00381       TileIndexDiff diff = TileOffsByDiagDir(m_exitdir);
00382       diff *= m_tiles_skipped;
00383       m_new_tile = TILE_ADD(m_new_tile, diff);
00384       return true;
00385     }
00386 
00387     return true;
00388   }
00389 
00391   inline bool ForcedReverse()
00392   {
00393     /* rail and road depots cause reversing */
00394     if (!IsWaterTT() && IsDepotTypeTile(m_old_tile, TT())) {
00395       DiagDirection exitdir = IsRailTT() ? GetRailDepotDirection(m_old_tile) : GetRoadDepotDirection(m_old_tile);
00396       if (exitdir != m_exitdir) {
00397         /* reverse */
00398         m_new_tile = m_old_tile;
00399         m_new_td_bits = TrackdirToTrackdirBits(ReverseTrackdir(m_old_td));
00400         m_exitdir = exitdir;
00401         m_tiles_skipped = 0;
00402         m_is_tunnel = m_is_bridge = m_is_station = false;
00403         return true;
00404       }
00405     }
00406 
00407     /* single tram bits cause reversing */
00408     if (IsTram() && GetSingleTramBit(m_old_tile) == ReverseDiagDir(m_exitdir)) {
00409       /* reverse */
00410       m_new_tile = m_old_tile;
00411       m_new_td_bits = TrackdirToTrackdirBits(ReverseTrackdir(m_old_td));
00412       m_exitdir = ReverseDiagDir(m_exitdir);
00413       m_tiles_skipped = 0;
00414       m_is_tunnel = m_is_bridge = m_is_station = false;
00415       return true;
00416     }
00417 
00418     return false;
00419   }
00420 
00422   inline bool TryReverse()
00423   {
00424     if (IsRoadTT() && !IsTram()) {
00425       /* if we reached the end of road, we can reverse the RV and continue moving */
00426       m_exitdir = ReverseDiagDir(m_exitdir);
00427       /* new tile will be the same as old one */
00428       m_new_tile = m_old_tile;
00429       /* set new trackdir bits to all reachable trackdirs */
00430       QueryNewTileTrackStatus();
00431       m_new_td_bits &= DiagdirReachesTrackdirs(m_exitdir);
00432       if (m_new_td_bits != TRACKDIR_BIT_NONE) {
00433         /* we have some trackdirs reachable after reversal */
00434         return true;
00435       }
00436     }
00437     m_err = EC_NO_WAY;
00438     return false;
00439   }
00440 
00441 public:
00443   int GetSpeedLimit(int *pmin_speed = NULL) const
00444   {
00445     int min_speed = 0;
00446     int max_speed = INT_MAX; // no limit
00447 
00448     /* Check for on-bridge speed limit */
00449     if (!IsWaterTT() && IsBridgeTile(m_old_tile)) {
00450       int spd = GetBridgeSpec(GetBridgeType(m_old_tile))->speed;
00451       if (IsRoadTT()) spd *= 2;
00452       if (max_speed > spd) max_speed = spd;
00453     }
00454     /* Check for speed limit imposed by railtype */
00455     if (IsRailTT()) {
00456       uint16 rail_speed = GetRailTypeInfo(GetRailType(m_old_tile))->max_speed;
00457       if (rail_speed > 0) max_speed = min(max_speed, rail_speed);
00458     }
00459 
00460     /* if min speed was requested, return it */
00461     if (pmin_speed != NULL) *pmin_speed = min_speed;
00462     return max_speed;
00463   }
00464 };
00465 
00466 typedef CFollowTrackT<TRANSPORT_WATER, Ship,        true > CFollowTrackWater;
00467 typedef CFollowTrackT<TRANSPORT_ROAD,  RoadVehicle, true > CFollowTrackRoad;
00468 typedef CFollowTrackT<TRANSPORT_RAIL,  Train,       true > CFollowTrackRail;
00469 
00470 typedef CFollowTrackT<TRANSPORT_WATER, Ship,        false> CFollowTrackWaterNo90;
00471 typedef CFollowTrackT<TRANSPORT_ROAD,  RoadVehicle, false> CFollowTrackRoadNo90;
00472 typedef CFollowTrackT<TRANSPORT_RAIL,  Train,       false> CFollowTrackRailNo90;
00473 
00474 typedef CFollowTrackT<TRANSPORT_RAIL, Train, true,  true > CFollowTrackFreeRail;
00475 typedef CFollowTrackT<TRANSPORT_RAIL, Train, false, true > CFollowTrackFreeRailNo90;
00476 
00477 #endif /* FOLLOW_TRACK_HPP */