# yapf_costrail.hpp

Go to the documentation of this file.

    00001 /* $Id: yapf_costrail.hpp 19927 2010-06-04 21:10:18Z 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  YAPF_COSTRAIL_HPP
    00013 #define  YAPF_COSTRAIL_HPP
    00014
    00015 #include "../../pbs.h"
    00016
    00017 template <class Types>
    00018 class CYapfCostRailT
    00019   : public CYapfCostBase
    00020   , public CostRailSettings
    00021 {
    00022 public:
    00023   typedef typename Types::Tpf Tpf;
    00024   typedef typename Types::TrackFollower TrackFollower;
    00025   typedef typename Types::NodeList::Titem Node;
    00026   typedef typename Node::Key Key;
    00027   typedef typename Node::CachedData CachedData;
    00028
    00029 protected:
    00030
    00031   /* Structure used inside PfCalcCost() to keep basic tile information. */
    00032   struct TILE {
    00033     TileIndex   tile;
    00034     Trackdir    td;
    00035     TileType    tile_type;
    00036     RailType    rail_type;
    00037
    00038     TILE()
    00039     {
    00040       tile = INVALID_TILE;
    00041       td = INVALID_TRACKDIR;
    00042       tile_type = MP_VOID;
    00043       rail_type = INVALID_RAILTYPE;
    00044     }
    00045
    00046     TILE(TileIndex tile, Trackdir td)
    00047     {
    00048       this->tile = tile;
    00049       this->td = td;
    00050       this->tile_type = GetTileType(tile);
    00051       this->rail_type = GetTileRailType(tile);
    00052     }
    00053
    00054     TILE(const TILE &src)
    00055     {
    00056       tile = src.tile;
    00057       td = src.td;
    00058       tile_type = src.tile_type;
    00059       rail_type = src.rail_type;
    00060     }
    00061   };
    00062
    00063 protected:
    00068   int           m_max_cost;
    00069   CBlobT<int>   m_sig_look_ahead_costs;
    00070   bool          m_disable_cache;
    00071
    00072 public:
    00073   bool          m_stopped_on_first_two_way_signal;
    00074 protected:
    00075
    00076   static const int s_max_segment_cost = 10000;
    00077
    00078   CYapfCostRailT()
    00079     : m_max_cost(0)
    00080     , m_disable_cache(false)
    00081     , m_stopped_on_first_two_way_signal(false)
    00082   {
    00083     /* pre-compute look-ahead penalties into array */
    00084     int p0 = Yapf().PfGetSettings().rail_look_ahead_signal_p0;
    00085     int p1 = Yapf().PfGetSettings().rail_look_ahead_signal_p1;
    00086     int p2 = Yapf().PfGetSettings().rail_look_ahead_signal_p2;
    00087     int *pen = m_sig_look_ahead_costs.GrowSizeNC(Yapf().PfGetSettings().rail_look_ahead_max_signals);
    00088     for (uint i = 0; i < Yapf().PfGetSettings().rail_look_ahead_max_signals; i++) {
    00089       pen[i] = p0 + i * (p1 + i * p2);
    00090     }
    00091   }
    00092
    00094   Tpf& Yapf()
    00095   {
    00096     return *static_cast<Tpf*>(this);
    00097   }
    00098
    00099 public:
    00100   FORCEINLINE int SlopeCost(TileIndex tile, Trackdir td)
    00101   {
    00102     CPerfStart perf_cost(Yapf().m_perf_slope_cost);
    00103     if (!stSlopeCost(tile, td)) return 0;
    00104     return Yapf().PfGetSettings().rail_slope_penalty;
    00105   }
    00106
    00107   FORCEINLINE int CurveCost(Trackdir td1, Trackdir td2)
    00108   {
    00109     assert(IsValidTrackdir(td1));
    00110     assert(IsValidTrackdir(td2));
    00111     int cost = 0;
    00112     if (TrackFollower::Allow90degTurns()
    00113         && ((TrackdirToTrackdirBits(td2) & (TrackdirBits)TrackdirCrossesTrackdirs(td1)) != 0)) {
    00114       /* 90-deg curve penalty */
    00115       cost += Yapf().PfGetSettings().rail_curve90_penalty;
    00116     } else if (td2 != NextTrackdir(td1)) {
    00117       /* 45-deg curve penalty */
    00118       cost += Yapf().PfGetSettings().rail_curve45_penalty;
    00119     }
    00120     return cost;
    00121   }
    00122
    00123   FORCEINLINE int SwitchCost(TileIndex tile1, TileIndex tile2, DiagDirection exitdir)
    00124   {
    00125     if (IsPlainRailTile(tile1) && IsPlainRailTile(tile2)) {
    00126       bool t1 = KillFirstBit(GetTrackBits(tile1) & DiagdirReachesTracks(ReverseDiagDir(exitdir))) != TRACK_BIT_NONE;
    00127       bool t2 = KillFirstBit(GetTrackBits(tile2) & DiagdirReachesTracks(exitdir)) != TRACK_BIT_NONE;
    00128       if (t1 && t2) return Yapf().PfGetSettings().rail_doubleslip_penalty;
    00129     }
    00130     return 0;
    00131   }
    00132
    00134   FORCEINLINE int OneTileCost(TileIndex& tile, Trackdir trackdir)
    00135   {
    00136     int cost = 0;
    00137     /* set base cost */
    00138     if (IsDiagonalTrackdir(trackdir)) {
    00139       cost += YAPF_TILE_LENGTH;
    00140       switch (GetTileType(tile)) {
    00141         case MP_ROAD:
    00142           /* Increase the cost for level crossings */
    00143           if (IsLevelCrossing(tile)) {
    00144             cost += Yapf().PfGetSettings().rail_crossing_penalty;
    00145           }
    00146           break;
    00147
    00148         default:
    00149           break;
    00150       }
    00151     } else {
    00152       /* non-diagonal trackdir */
    00153       cost = YAPF_TILE_CORNER_LENGTH;
    00154     }
    00155     return cost;
    00156   }
    00157
    00159   FORCEINLINE bool IsAnyStationTileReserved(TileIndex tile, Trackdir trackdir, int skipped)
    00160   {
    00161     TileIndexDiff diff = TileOffsByDiagDir(TrackdirToExitdir(ReverseTrackdir(trackdir)));
    00162     for (; skipped >= 0; skipped--, tile += diff) {
    00163       if (HasStationReservation(tile)) return true;
    00164     }
    00165     return false;
    00166   }
    00167
    00169   FORCEINLINE int ReservationCost(Node& n, TileIndex tile, Trackdir trackdir, int skipped)
    00170   {
    00171     if (n.m_num_signals_passed >= m_sig_look_ahead_costs.Size() / 2) return 0;
    00172     if (!IsPbsSignal(n.m_last_signal_type)) return 0;
    00173
    00174     if (IsRailStationTile(tile) && IsAnyStationTileReserved(tile, trackdir, skipped)) {
    00175       return Yapf().PfGetSettings().rail_pbs_station_penalty * (skipped + 1);
    00176     } else if (TrackOverlapsTracks(GetReservedTrackbits(tile), TrackdirToTrack(trackdir))) {
    00177       int cost = Yapf().PfGetSettings().rail_pbs_cross_penalty;
    00178       if (!IsDiagonalTrackdir(trackdir)) cost = (cost * YAPF_TILE_CORNER_LENGTH) / YAPF_TILE_LENGTH;
    00179       return cost * (skipped + 1);
    00180     }
    00181     return 0;
    00182   }
    00183
    00184   int SignalCost(Node& n, TileIndex tile, Trackdir trackdir)
    00185   {
    00186     int cost = 0;
    00187     /* if there is one-way signal in the opposite direction, then it is not our way */
    00188     CPerfStart perf_cost(Yapf().m_perf_other_cost);
    00189     if (IsTileType(tile, MP_RAILWAY)) {
    00190       bool has_signal_against = HasSignalOnTrackdir(tile, ReverseTrackdir(trackdir));
    00191       bool has_signal_along = HasSignalOnTrackdir(tile, trackdir);
    00192       if (has_signal_against && !has_signal_along && IsOnewaySignal(tile, TrackdirToTrack(trackdir))) {
    00193         /* one-way signal in opposite direction */
    00194         n.m_segment->m_end_segment_reason |= ESRB_DEAD_END;
    00195       } else {
    00196         if (has_signal_along) {
    00197           SignalState sig_state = GetSignalStateByTrackdir(tile, trackdir);
    00198           SignalType sig_type = GetSignalType(tile, TrackdirToTrack(trackdir));
    00199
    00200           n.m_last_signal_type = sig_type;
    00201
    00202           /* cache the look-ahead polynomial constant only if we didn't pass more signals than the look-ahead limit is */
    00203           int look_ahead_cost = (n.m_num_signals_passed < m_sig_look_ahead_costs.Size()) ? m_sig_look_ahead_costs.Data()[n.m_num_signals_passed] : 0;
    00204           if (sig_state != SIGNAL_STATE_RED) {
    00205             /* green signal */
    00206             n.flags_u.flags_s.m_last_signal_was_red = false;
    00207             /* negative look-ahead red-signal penalties would cause problems later, so use them as positive penalties for green signal */
    00208             if (look_ahead_cost < 0) {
    00209               /* add its negation to the cost */
    00210               cost -= look_ahead_cost;
    00211             }
    00212           } else {
    00213             /* we have a red signal in our direction
    00214              * was it first signal which is two-way? */
    00215             if (!IsPbsSignal(sig_type) && Yapf().TreatFirstRedTwoWaySignalAsEOL() && n.flags_u.flags_s.m_choice_seen && has_signal_against && n.m_num_signals_passed == 0) {
    00216               /* yes, the first signal is two-way red signal => DEAD END */
    00217               n.m_segment->m_end_segment_reason |= ESRB_DEAD_END;
    00218               Yapf().m_stopped_on_first_two_way_signal = true;
    00219               return -1;
    00220             }
    00221             n.m_last_red_signal_type = sig_type;
    00222             n.flags_u.flags_s.m_last_signal_was_red = true;
    00223
    00224             /* look-ahead signal penalty */
    00225             if (!IsPbsSignal(sig_type) && look_ahead_cost > 0) {
    00226               /* add the look ahead penalty only if it is positive */
    00227               cost += look_ahead_cost;
    00228             }
    00229
    00230             /* special signal penalties */
    00231             if (n.m_num_signals_passed == 0) {
    00232               switch (sig_type) {
    00233                 case SIGTYPE_COMBO:
    00234                 case SIGTYPE_EXIT:   cost += Yapf().PfGetSettings().rail_firstred_exit_penalty; break; // first signal is red pre-signal-exit
    00235                 case SIGTYPE_NORMAL:
    00236                 case SIGTYPE_ENTRY:  cost += Yapf().PfGetSettings().rail_firstred_penalty; break;
    00237                 default: break;
    00238               }
    00239             }
    00240           }
    00241
    00242           n.m_num_signals_passed++;
    00243           n.m_segment->m_last_signal_tile = tile;
    00244           n.m_segment->m_last_signal_td = trackdir;
    00245         }
    00246
    00247         if (has_signal_against && IsPbsSignal(GetSignalType(tile, TrackdirToTrack(trackdir)))) {
    00248           cost += n.m_num_signals_passed < Yapf().PfGetSettings().rail_look_ahead_max_signals ? Yapf().PfGetSettings().rail_pbs_signal_back_penalty : 0;
    00249         }
    00250       }
    00251     }
    00252     return cost;
    00253   }
    00254
    00255   FORCEINLINE int PlatformLengthPenalty(int platform_length)
    00256   {
    00257     int cost = 0;
    00258     const Train *v = Yapf().GetVehicle();
    00259     assert(v != NULL);
    00260     assert(v->type == VEH_TRAIN);
    00261     assert(v->tcache.cached_total_length != 0);
    00262     int missing_platform_length = (v->tcache.cached_total_length + TILE_SIZE - 1) / TILE_SIZE - platform_length;
    00263     if (missing_platform_length < 0) {
    00264       /* apply penalty for longer platform than needed */
    00265       cost += Yapf().PfGetSettings().rail_longer_platform_penalty + Yapf().PfGetSettings().rail_longer_platform_per_tile_penalty * -missing_platform_length;
    00266     } else if (missing_platform_length > 0) {
    00267       /* apply penalty for shorter platform than needed */
    00268       cost += Yapf().PfGetSettings().rail_shorter_platform_penalty + Yapf().PfGetSettings().rail_shorter_platform_per_tile_penalty * missing_platform_length;
    00269     }
    00270     return cost;
    00271   }
    00272
    00273 public:
    00274   FORCEINLINE void SetMaxCost(int max_cost)
    00275   {
    00276     m_max_cost = max_cost;
    00277   }
    00278
    00282   FORCEINLINE bool PfCalcCost(Node &n, const TrackFollower *tf)
    00283   {
    00284     assert(!n.flags_u.flags_s.m_targed_seen);
    00285     assert(tf->m_new_tile == n.m_key.m_tile);
    00286     assert((TrackdirToTrackdirBits(n.m_key.m_td) & tf->m_new_td_bits) != TRACKDIR_BIT_NONE);
    00287
    00288     CPerfStart perf_cost(Yapf().m_perf_cost);
    00289
    00290     /* Does the node have some parent node? */
    00291     bool has_parent = (n.m_parent != NULL);
    00292
    00293     /* Do we already have a cached segment? */
    00294     CachedData &segment = *n.m_segment;
    00295     bool is_cached_segment = (segment.m_cost >= 0);
    00296
    00297     int parent_cost = has_parent ? n.m_parent->m_cost : 0;
    00298
    00299     /* Each node cost contains 2 or 3 main components:
    00300      *  1. Transition cost - cost of the move from previous node (tile):
    00301      *    - curve cost (or zero for straight move)
    00302      *  2. Tile cost:
    00303      *    - base tile cost
    00304      *      - YAPF_TILE_LENGTH for diagonal tiles
    00305      *      - YAPF_TILE_CORNER_LENGTH for non-diagonal tiles
    00306      *    - tile penalties
    00307      *      - tile slope penalty (upward slopes)
    00308      *      - red signal penalty
    00309      *      - level crossing penalty
    00310      *      - speed-limit penalty (bridges)
    00311      *      - station platform penalty
    00312      *      - penalty for reversing in the depot
    00313      *      - etc.
    00314      *  3. Extra cost (applies to the last node only)
    00315      *    - last red signal penalty
    00316      *    - penalty for too long or too short platform on the destination station
    00317      */
    00318     int transition_cost = 0;
    00319     int extra_cost = 0;
    00320
    00321     /* Segment: one or more tiles connected by contiguous tracks of the same type.
    00322      * Each segment cost includes 'Tile cost' for all its tiles (including the first
    00323      * and last), and the 'Transition cost' between its tiles. The first transition
    00324      * cost of segment entry (move from the 'parent' node) is not included!
    00325      */
    00326     int segment_entry_cost = 0;
    00327     int segment_cost = 0;
    00328
    00329     const Train *v = Yapf().GetVehicle();
    00330
    00331     /* start at n.m_key.m_tile / n.m_key.m_td and walk to the end of segment */
    00332     TILE cur(n.m_key.m_tile, n.m_key.m_td);
    00333
    00334     /* the previous tile will be needed for transition cost calculations */
    00335     TILE prev = !has_parent ? TILE() : TILE(n.m_parent->GetLastTile(), n.m_parent->GetLastTrackdir());
    00336
    00337     EndSegmentReasonBits end_segment_reason = ESRB_NONE;
    00338
    00339     TrackFollower tf_local(v, Yapf().GetCompatibleRailTypes(), &Yapf().m_perf_ts_cost);
    00340
    00341     if (!has_parent) {
    00342       /* We will jump to the middle of the cost calculator assuming that segment cache is not used. */
    00343       assert(!is_cached_segment);
    00344       /* Skip the first transition cost calculation. */
    00345       goto no_entry_cost;
    00346     }
    00347
    00348     for (;;) {
    00349       /* Transition cost (cost of the move from previous tile) */
    00350       transition_cost = Yapf().CurveCost(prev.td, cur.td);
    00351       transition_cost += Yapf().SwitchCost(prev.tile, cur.tile, TrackdirToExitdir(prev.td));
    00352
    00353       /* First transition cost counts against segment entry cost, other transitions
    00354        * inside segment will come to segment cost (and will be cached) */
    00355       if (segment_cost == 0) {
    00356         /* We just entered the loop. First transition cost goes to segment entry cost)*/
    00357         segment_entry_cost = transition_cost;
    00358         transition_cost = 0;
    00359
    00360         /* It is the right time now to look if we can reuse the cached segment cost. */
    00361         if (is_cached_segment) {
    00362           /* Yes, we already know the segment cost. */
    00363           segment_cost = segment.m_cost;
    00364           /* We know also the reason why the segment ends. */
    00365           end_segment_reason = segment.m_end_segment_reason;
    00366           /* We will need also some information about the last signal (if it was red). */
    00367           if (segment.m_last_signal_tile != INVALID_TILE) {
    00368             assert(HasSignalOnTrackdir(segment.m_last_signal_tile, segment.m_last_signal_td));
    00369             SignalState sig_state = GetSignalStateByTrackdir(segment.m_last_signal_tile, segment.m_last_signal_td);
    00370             bool is_red = (sig_state == SIGNAL_STATE_RED);
    00371             n.flags_u.flags_s.m_last_signal_was_red = is_red;
    00372             if (is_red) {
    00373               n.m_last_red_signal_type = GetSignalType(segment.m_last_signal_tile, TrackdirToTrack(segment.m_last_signal_td));
    00374             }
    00375           }
    00376           /* No further calculation needed. */
    00377           cur = TILE(n.GetLastTile(), n.GetLastTrackdir());
    00378           break;
    00379         }
    00380       } else {
    00381         /* Other than first transition cost count as the regular segment cost. */
    00382         segment_cost += transition_cost;
    00383       }
    00384
    00385 no_entry_cost: // jump here at the beginning if the node has no parent (it is the first node)
    00386
    00387       /* All other tile costs will be calculated here. */
    00388       segment_cost += Yapf().OneTileCost(cur.tile, cur.td);
    00389
    00390       /* If we skipped some tunnel/bridge/station tiles, add their base cost */
    00391       segment_cost += YAPF_TILE_LENGTH * tf->m_tiles_skipped;
    00392
    00393       /* Slope cost. */
    00394       segment_cost += Yapf().SlopeCost(cur.tile, cur.td);
    00395
    00396       /* Signal cost (routine can modify segment data). */
    00397       segment_cost += Yapf().SignalCost(n, cur.tile, cur.td);
    00398
    00399       /* Reserved tiles. */
    00400       segment_cost += Yapf().ReservationCost(n, cur.tile, cur.td, tf->m_tiles_skipped);
    00401
    00402       end_segment_reason = segment.m_end_segment_reason;
    00403
    00404       /* Tests for 'potential target' reasons to close the segment. */
    00405       if (cur.tile == prev.tile) {
    00406         /* Penalty for reversing in a depot. */
    00407         assert(IsRailDepot(cur.tile));
    00408         segment_cost += Yapf().PfGetSettings().rail_depot_reverse_penalty;
    00409         /* We will end in this pass (depot is possible target) */
    00410         end_segment_reason |= ESRB_DEPOT;
    00411
    00412       } else if (cur.tile_type == MP_STATION && IsRailWaypoint(cur.tile)) {
    00413         if (v->current_order.IsType(OT_GOTO_WAYPOINT) &&
    00414             GetStationIndex(cur.tile) == v->current_order.GetDestination() &&
    00415             !Waypoint::Get(v->current_order.GetDestination())->IsSingleTile()) {
    00416           /* This waypoint is our destination; maybe this isn't an unreserved
    00417            * one, so check that and if so see that as the last signal being
    00418            * red. This way waypoints near stations should work better. */
    00419           CFollowTrackRail ft(v);
    00420           TileIndex t = cur.tile;
    00421           Trackdir td = cur.td;
    00422           while (ft.Follow(t, td)) {
    00423             assert(t != ft.m_new_tile);
    00424             t = ft.m_new_tile;
    00425             if (KillFirstBit(ft.m_new_td_bits) != TRACKDIR_BIT_NONE) {
    00426               /* We encountered a junction; it's going to be too complex to
    00427                * handle this perfectly, so just bail out. There is no simple
    00428                * free path, so try the other possibilities. */
    00429               td = INVALID_TRACKDIR;
    00430               break;
    00431             }
    00432             td = RemoveFirstTrackdir(&ft.m_new_td_bits);
    00433             /* If this is a safe waiting position we're done searching for it */
    00434             if (IsSafeWaitingPosition(v, t, td, true, _settings_game.pf.forbid_90_deg)) break;
    00435           }
    00436           if (td == INVALID_TRACKDIR ||
    00437               !IsSafeWaitingPosition(v, t, td, true, _settings_game.pf.forbid_90_deg) ||
    00438               !IsWaitingPositionFree(v, t, td, _settings_game.pf.forbid_90_deg)) {
    00439             extra_cost += Yapf().PfGetSettings().rail_lastred_exit_penalty;
    00440           }
    00441         }
    00442         /* Waypoint is also a good reason to finish. */
    00443         end_segment_reason |= ESRB_WAYPOINT;
    00444
    00445       } else if (tf->m_is_station) {
    00446         /* Station penalties. */
    00447         uint platform_length = tf->m_tiles_skipped + 1;
    00448         /* We don't know yet if the station is our target or not. Act like
    00449          * if it is pass-through station (not our destination). */
    00450         segment_cost += Yapf().PfGetSettings().rail_station_penalty * platform_length;
    00451         /* We will end in this pass (station is possible target) */
    00452         end_segment_reason |= ESRB_STATION;
    00453
    00454       } else if (TrackFollower::DoTrackMasking() && cur.tile_type == MP_RAILWAY) {
    00455         /* Searching for a safe tile? */
    00456         if (HasSignalOnTrackdir(cur.tile, cur.td) && !IsPbsSignal(GetSignalType(cur.tile, TrackdirToTrack(cur.td)))) {
    00457           end_segment_reason |= ESRB_SAFE_TILE;
    00458         }
    00459       }
    00460
    00461       /* Apply min/max speed penalties only when inside the look-ahead radius. Otherwise
    00462        * it would cause desync in MP. */
    00463       if (n.m_num_signals_passed < m_sig_look_ahead_costs.Size())
    00464       {
    00465         int min_speed = 0;
    00466         int max_speed = tf->GetSpeedLimit(&min_speed);
    00467         if (max_speed < v->max_speed) {
    00468           extra_cost += YAPF_TILE_LENGTH * (v->max_speed - max_speed) * (4 + tf->m_tiles_skipped) / v->max_speed;
    00469         }
    00470         if (min_speed > v->max_speed) {
    00471           extra_cost += YAPF_TILE_LENGTH * (min_speed - v->max_speed);
    00472         }
    00473       }
    00474
    00475       /* Finish if we already exceeded the maximum path cost (i.e. when
    00476        * searching for the nearest depot). */
    00477       if (m_max_cost > 0 && (parent_cost + segment_entry_cost + segment_cost) > m_max_cost) {
    00478         end_segment_reason |= ESRB_PATH_TOO_LONG;
    00479       }
    00480
    00481       /* Move to the next tile/trackdir. */
    00482       tf = &tf_local;
    00483       tf_local.Init(v, Yapf().GetCompatibleRailTypes(), &Yapf().m_perf_ts_cost);
    00484
    00485       if (!tf_local.Follow(cur.tile, cur.td)) {
    00486         assert(tf_local.m_err != TrackFollower::EC_NONE);
    00487         /* Can't move to the next tile (EOL?). */
    00488         if (tf_local.m_err == TrackFollower::EC_RAIL_TYPE) {
    00489           end_segment_reason |= ESRB_RAIL_TYPE;
    00490         } else {
    00491           end_segment_reason |= ESRB_DEAD_END;
    00492         }
    00493
    00494         if (TrackFollower::DoTrackMasking() && !HasOnewaySignalBlockingTrackdir(cur.tile, cur.td)) {
    00495           end_segment_reason |= ESRB_SAFE_TILE;
    00496         }
    00497         break;
    00498       }
    00499
    00500       /* Check if the next tile is not a choice. */
    00501       if (KillFirstBit(tf_local.m_new_td_bits) != TRACKDIR_BIT_NONE) {
    00502         /* More than one segment will follow. Close this one. */
    00503         end_segment_reason |= ESRB_CHOICE_FOLLOWS;
    00504         break;
    00505       }
    00506
    00507       /* Gather the next tile/trackdir/tile_type/rail_type. */
    00508       TILE next(tf_local.m_new_tile, (Trackdir)FindFirstBit2x64(tf_local.m_new_td_bits));
    00509
    00510       if (TrackFollower::DoTrackMasking() && IsTileType(next.tile, MP_RAILWAY)) {
    00511         if ((HasSignalOnTrackdir(next.tile, next.td) && IsPbsSignal(GetSignalType(next.tile, TrackdirToTrack(next.td)))) ||
    00512             (HasSignalOnTrackdir(next.tile, ReverseTrackdir(next.td)) && GetSignalType(next.tile, TrackdirToTrack(next.td)) == SIGTYPE_PBS_ONEWAY)) {
    00513           /* Possible safe tile. */
    00514           end_segment_reason |= ESRB_SAFE_TILE;
    00515         }
    00516       }
    00517
    00518       /* Check the next tile for the rail type. */
    00519       if (next.rail_type != cur.rail_type) {
    00520         /* Segment must consist from the same rail_type tiles. */
    00521         end_segment_reason |= ESRB_RAIL_TYPE;
    00522         break;
    00523       }
    00524
    00525       /* Avoid infinite looping. */
    00526       if (next.tile == n.m_key.m_tile && next.td == n.m_key.m_td) {
    00527         end_segment_reason |= ESRB_INFINITE_LOOP;
    00528         break;
    00529       }
    00530
    00531       if (segment_cost > s_max_segment_cost) {
    00532         /* Potentially in the infinite loop (or only very long segment?). We should
    00533          * not force it to finish prematurely unless we are on a regular tile. */
    00534         if (IsTileType(tf->m_new_tile, MP_RAILWAY)) {
    00535           end_segment_reason |= ESRB_SEGMENT_TOO_LONG;
    00536           break;
    00537         }
    00538       }
    00539
    00540       /* Any other reason bit set? */
    00541       if (end_segment_reason != ESRB_NONE) {
    00542         break;
    00543       }
    00544
    00545       /* For the next loop set new prev and cur tile info. */
    00546       prev = cur;
    00547       cur = next;
    00548
    00549     } // for (;;)
    00550
    00551     bool target_seen = false;
    00552     if ((end_segment_reason & ESRB_POSSIBLE_TARGET) != ESRB_NONE) {
    00553       /* Depot, station or waypoint. */
    00554       if (Yapf().PfDetectDestination(cur.tile, cur.td)) {
    00555         /* Destination found. */
    00556         target_seen = true;
    00557       }
    00558     }
    00559
    00560     /* Update the segment if needed. */
    00561     if (!is_cached_segment) {
    00562       /* Write back the segment information so it can be reused the next time. */
    00563       segment.m_cost = segment_cost;
    00564       segment.m_end_segment_reason = end_segment_reason & ESRB_CACHED_MASK;
    00565       /* Save end of segment back to the node. */
    00566       n.SetLastTileTrackdir(cur.tile, cur.td);
    00567     }
    00568
    00569     /* Do we have an excuse why not to continue pathfinding in this direction? */
    00570     if (!target_seen && (end_segment_reason & ESRB_ABORT_PF_MASK) != ESRB_NONE) {
    00571       /* Reason to not continue. Stop this PF branch. */
    00572       return false;
    00573     }
    00574
    00575     /* Special costs for the case we have reached our target. */
    00576     if (target_seen) {
    00577       n.flags_u.flags_s.m_targed_seen = true;
    00578       /* Last-red and last-red-exit penalties. */
    00579       if (n.flags_u.flags_s.m_last_signal_was_red) {
    00580         if (n.m_last_red_signal_type == SIGTYPE_EXIT) {
    00581           /* last signal was red pre-signal-exit */
    00582           extra_cost += Yapf().PfGetSettings().rail_lastred_exit_penalty;
    00583         } else {
    00584           /* last signal was red, but not exit */
    00585           extra_cost += Yapf().PfGetSettings().rail_lastred_penalty;
    00586         }
    00587       }
    00588
    00589       /* Station platform-length penalty. */
    00590       if ((end_segment_reason & ESRB_STATION) != ESRB_NONE) {
    00591         const BaseStation *st = BaseStation::GetByTile(n.GetLastTile());
    00592         assert(st != NULL);
    00593         uint platform_length = st->GetPlatformLength(n.GetLastTile(), ReverseDiagDir(TrackdirToExitdir(n.GetLastTrackdir())));
    00594         /* Reduce the extra cost caused by passing-station penalty (each station receives it in the segment cost). */
    00595         extra_cost -= Yapf().PfGetSettings().rail_station_penalty * platform_length;
    00596         /* Add penalty for the inappropriate platform length. */
    00597         extra_cost += PlatformLengthPenalty(platform_length);
    00598       }
    00599     }
    00600
    00601     /* total node cost */
    00602     n.m_cost = parent_cost + segment_entry_cost + segment_cost + extra_cost;
    00603
    00604     return true;
    00605   }
    00606
    00607   FORCEINLINE bool CanUseGlobalCache(Node& n) const
    00608   {
    00609     return !m_disable_cache
    00610       && (n.m_parent != NULL)
    00611       && (n.m_parent->m_num_signals_passed >= m_sig_look_ahead_costs.Size());
    00612   }
    00613
    00614   FORCEINLINE void ConnectNodeToCachedData(Node& n, CachedData& ci)
    00615   {
    00616     n.m_segment = &ci;
    00617     if (n.m_segment->m_cost < 0) {
    00618       n.m_segment->m_last_tile = n.m_key.m_tile;
    00619       n.m_segment->m_last_td = n.m_key.m_td;
    00620     }
    00621   }
    00622
    00623   void DisableCache(bool disable)
    00624   {
    00625     m_disable_cache = disable;
    00626   }
    00627 };
    00628
    00629 #endif /* YAPF_COSTRAIL_HPP */