OpenTTD Source  12.0-beta2
yapf_costrail.hpp
Go to the documentation of this file.
1 /*
2  * This file is part of OpenTTD.
3  * 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.
4  * 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.
5  * 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/>.
6  */
7 
10 #ifndef YAPF_COSTRAIL_HPP
11 #define YAPF_COSTRAIL_HPP
12 
13 #include <vector>
14 
15 #include "../../pbs.h"
16 
17 template <class Types>
18 class CYapfCostRailT : public CYapfCostBase {
19 public:
20  typedef typename Types::Tpf Tpf;
21  typedef typename Types::TrackFollower TrackFollower;
22  typedef typename Types::NodeList::Titem Node;
23  typedef typename Node::Key Key;
24  typedef typename Node::CachedData CachedData;
25 
26 protected:
27 
28  /* Structure used inside PfCalcCost() to keep basic tile information. */
29  struct TILE {
30  TileIndex tile;
31  Trackdir td;
32  TileType tile_type;
33  RailType rail_type;
34 
35  TILE()
36  {
37  tile = INVALID_TILE;
38  td = INVALID_TRACKDIR;
39  tile_type = MP_VOID;
40  rail_type = INVALID_RAILTYPE;
41  }
42 
43  TILE(TileIndex tile, Trackdir td)
44  {
45  this->tile = tile;
46  this->td = td;
47  this->tile_type = GetTileType(tile);
48  this->rail_type = GetTileRailType(tile);
49  }
50  };
51 
52 protected:
58  bool m_disable_cache;
59  std::vector<int> m_sig_look_ahead_costs;
60 
61 public:
62  bool m_stopped_on_first_two_way_signal;
63 protected:
64 
65  static const int s_max_segment_cost = 10000;
66 
67  CYapfCostRailT() : m_max_cost(0), m_disable_cache(false), m_stopped_on_first_two_way_signal(false)
68  {
69  /* pre-compute look-ahead penalties into array */
70  int p0 = Yapf().PfGetSettings().rail_look_ahead_signal_p0;
71  int p1 = Yapf().PfGetSettings().rail_look_ahead_signal_p1;
72  int p2 = Yapf().PfGetSettings().rail_look_ahead_signal_p2;
73  m_sig_look_ahead_costs.clear();
74  m_sig_look_ahead_costs.reserve(Yapf().PfGetSettings().rail_look_ahead_max_signals);
75  for (uint i = 0; i < Yapf().PfGetSettings().rail_look_ahead_max_signals; i++) {
76  m_sig_look_ahead_costs.push_back(p0 + i * (p1 + i * p2));
77  }
78  }
79 
81  Tpf& Yapf()
82  {
83  return *static_cast<Tpf *>(this);
84  }
85 
86 public:
87  inline int SlopeCost(TileIndex tile, Trackdir td)
88  {
89  if (!stSlopeCost(tile, td)) return 0;
90  return Yapf().PfGetSettings().rail_slope_penalty;
91  }
92 
93  inline int CurveCost(Trackdir td1, Trackdir td2)
94  {
95  assert(IsValidTrackdir(td1));
96  assert(IsValidTrackdir(td2));
97  int cost = 0;
98  if (TrackFollower::Allow90degTurns()
99  && HasTrackdir(TrackdirCrossesTrackdirs(td1), td2)) {
100  /* 90-deg curve penalty */
101  cost += Yapf().PfGetSettings().rail_curve90_penalty;
102  } else if (td2 != NextTrackdir(td1)) {
103  /* 45-deg curve penalty */
104  cost += Yapf().PfGetSettings().rail_curve45_penalty;
105  }
106  return cost;
107  }
108 
109  inline int SwitchCost(TileIndex tile1, TileIndex tile2, DiagDirection exitdir)
110  {
111  if (IsPlainRailTile(tile1) && IsPlainRailTile(tile2)) {
113  bool t2 = KillFirstBit(GetTrackBits(tile2) & DiagdirReachesTracks(exitdir)) != TRACK_BIT_NONE;
114  if (t1 && t2) return Yapf().PfGetSettings().rail_doubleslip_penalty;
115  }
116  return 0;
117  }
118 
120  inline int OneTileCost(TileIndex &tile, Trackdir trackdir)
121  {
122  int cost = 0;
123  /* set base cost */
124  if (IsDiagonalTrackdir(trackdir)) {
125  cost += YAPF_TILE_LENGTH;
126  switch (GetTileType(tile)) {
127  case MP_ROAD:
128  /* Increase the cost for level crossings */
129  if (IsLevelCrossing(tile)) {
130  cost += Yapf().PfGetSettings().rail_crossing_penalty;
131  }
132  break;
133 
134  default:
135  break;
136  }
137  } else {
138  /* non-diagonal trackdir */
140  }
141  return cost;
142  }
143 
145  inline bool IsAnyStationTileReserved(TileIndex tile, Trackdir trackdir, int skipped)
146  {
148  for (; skipped >= 0; skipped--, tile += diff) {
149  if (HasStationReservation(tile)) return true;
150  }
151  return false;
152  }
153 
155  inline int ReservationCost(Node &n, TileIndex tile, Trackdir trackdir, int skipped)
156  {
157  if (n.m_num_signals_passed >= m_sig_look_ahead_costs.size() / 2) return 0;
158  if (!IsPbsSignal(n.m_last_signal_type)) return 0;
159 
160  if (IsRailStationTile(tile) && IsAnyStationTileReserved(tile, trackdir, skipped)) {
161  return Yapf().PfGetSettings().rail_pbs_station_penalty * (skipped + 1);
162  } else if (TrackOverlapsTracks(GetReservedTrackbits(tile), TrackdirToTrack(trackdir))) {
163  int cost = Yapf().PfGetSettings().rail_pbs_cross_penalty;
164  if (!IsDiagonalTrackdir(trackdir)) cost = (cost * YAPF_TILE_CORNER_LENGTH) / YAPF_TILE_LENGTH;
165  return cost * (skipped + 1);
166  }
167  return 0;
168  }
169 
170  int SignalCost(Node &n, TileIndex tile, Trackdir trackdir)
171  {
172  int cost = 0;
173  /* if there is one-way signal in the opposite direction, then it is not our way */
174  if (IsTileType(tile, MP_RAILWAY)) {
175  bool has_signal_against = HasSignalOnTrackdir(tile, ReverseTrackdir(trackdir));
176  bool has_signal_along = HasSignalOnTrackdir(tile, trackdir);
177  if (has_signal_against && !has_signal_along && IsOnewaySignal(tile, TrackdirToTrack(trackdir))) {
178  /* one-way signal in opposite direction */
179  n.m_segment->m_end_segment_reason |= ESRB_DEAD_END;
180  } else {
181  if (has_signal_along) {
182  SignalState sig_state = GetSignalStateByTrackdir(tile, trackdir);
183  SignalType sig_type = GetSignalType(tile, TrackdirToTrack(trackdir));
184 
185  n.m_last_signal_type = sig_type;
186 
187  /* cache the look-ahead polynomial constant only if we didn't pass more signals than the look-ahead limit is */
188  int look_ahead_cost = (n.m_num_signals_passed < m_sig_look_ahead_costs.size()) ? m_sig_look_ahead_costs[n.m_num_signals_passed] : 0;
189  if (sig_state != SIGNAL_STATE_RED) {
190  /* green signal */
191  n.flags_u.flags_s.m_last_signal_was_red = false;
192  /* negative look-ahead red-signal penalties would cause problems later, so use them as positive penalties for green signal */
193  if (look_ahead_cost < 0) {
194  /* add its negation to the cost */
195  cost -= look_ahead_cost;
196  }
197  } else {
198  /* we have a red signal in our direction
199  * was it first signal which is two-way? */
200  if (!IsPbsSignal(sig_type) && Yapf().TreatFirstRedTwoWaySignalAsEOL() && n.flags_u.flags_s.m_choice_seen && has_signal_against && n.m_num_signals_passed == 0) {
201  /* yes, the first signal is two-way red signal => DEAD END. Prune this branch... */
202  Yapf().PruneIntermediateNodeBranch(&n);
203  n.m_segment->m_end_segment_reason |= ESRB_DEAD_END;
204  Yapf().m_stopped_on_first_two_way_signal = true;
205  return -1;
206  }
207  n.m_last_red_signal_type = sig_type;
208  n.flags_u.flags_s.m_last_signal_was_red = true;
209 
210  /* look-ahead signal penalty */
211  if (!IsPbsSignal(sig_type) && look_ahead_cost > 0) {
212  /* add the look ahead penalty only if it is positive */
213  cost += look_ahead_cost;
214  }
215 
216  /* special signal penalties */
217  if (n.m_num_signals_passed == 0) {
218  switch (sig_type) {
219  case SIGTYPE_COMBO:
220  case SIGTYPE_EXIT: cost += Yapf().PfGetSettings().rail_firstred_exit_penalty; break; // first signal is red pre-signal-exit
221  case SIGTYPE_NORMAL:
222  case SIGTYPE_ENTRY: cost += Yapf().PfGetSettings().rail_firstred_penalty; break;
223  default: break;
224  }
225  }
226  }
227 
228  n.m_num_signals_passed++;
229  n.m_segment->m_last_signal_tile = tile;
230  n.m_segment->m_last_signal_td = trackdir;
231  }
232 
233  if (has_signal_against && IsPbsSignal(GetSignalType(tile, TrackdirToTrack(trackdir)))) {
234  cost += n.m_num_signals_passed < Yapf().PfGetSettings().rail_look_ahead_max_signals ? Yapf().PfGetSettings().rail_pbs_signal_back_penalty : 0;
235  }
236  }
237  }
238  return cost;
239  }
240 
241  inline int PlatformLengthPenalty(int platform_length)
242  {
243  int cost = 0;
244  const Train *v = Yapf().GetVehicle();
245  assert(v != nullptr);
246  assert(v->type == VEH_TRAIN);
247  assert(v->gcache.cached_total_length != 0);
248  int missing_platform_length = CeilDiv(v->gcache.cached_total_length, TILE_SIZE) - platform_length;
249  if (missing_platform_length < 0) {
250  /* apply penalty for longer platform than needed */
251  cost += Yapf().PfGetSettings().rail_longer_platform_penalty + Yapf().PfGetSettings().rail_longer_platform_per_tile_penalty * -missing_platform_length;
252  } else if (missing_platform_length > 0) {
253  /* apply penalty for shorter platform than needed */
254  cost += Yapf().PfGetSettings().rail_shorter_platform_penalty + Yapf().PfGetSettings().rail_shorter_platform_per_tile_penalty * missing_platform_length;
255  }
256  return cost;
257  }
258 
259 public:
260  inline void SetMaxCost(int max_cost)
261  {
262  m_max_cost = max_cost;
263  }
264 
270  inline bool PfCalcCost(Node &n, const TrackFollower *tf)
271  {
272  assert(!n.flags_u.flags_s.m_targed_seen);
273  assert(tf->m_new_tile == n.m_key.m_tile);
274  assert((HasTrackdir(tf->m_new_td_bits, n.m_key.m_td)));
275 
276  /* Does the node have some parent node? */
277  bool has_parent = (n.m_parent != nullptr);
278 
279  /* Do we already have a cached segment? */
280  CachedData &segment = *n.m_segment;
281  bool is_cached_segment = (segment.m_cost >= 0);
282 
283  int parent_cost = has_parent ? n.m_parent->m_cost : 0;
284 
285  /* Each node cost contains 2 or 3 main components:
286  * 1. Transition cost - cost of the move from previous node (tile):
287  * - curve cost (or zero for straight move)
288  * 2. Tile cost:
289  * - base tile cost
290  * - YAPF_TILE_LENGTH for diagonal tiles
291  * - YAPF_TILE_CORNER_LENGTH for non-diagonal tiles
292  * - tile penalties
293  * - tile slope penalty (upward slopes)
294  * - red signal penalty
295  * - level crossing penalty
296  * - speed-limit penalty (bridges)
297  * - station platform penalty
298  * - penalty for reversing in the depot
299  * - etc.
300  * 3. Extra cost (applies to the last node only)
301  * - last red signal penalty
302  * - penalty for too long or too short platform on the destination station
303  */
304  int transition_cost = 0;
305  int extra_cost = 0;
306 
307  /* Segment: one or more tiles connected by contiguous tracks of the same type.
308  * Each segment cost includes 'Tile cost' for all its tiles (including the first
309  * and last), and the 'Transition cost' between its tiles. The first transition
310  * cost of segment entry (move from the 'parent' node) is not included!
311  */
312  int segment_entry_cost = 0;
313  int segment_cost = 0;
314 
315  const Train *v = Yapf().GetVehicle();
316 
317  /* start at n.m_key.m_tile / n.m_key.m_td and walk to the end of segment */
318  TILE cur(n.m_key.m_tile, n.m_key.m_td);
319 
320  /* the previous tile will be needed for transition cost calculations */
321  TILE prev = !has_parent ? TILE() : TILE(n.m_parent->GetLastTile(), n.m_parent->GetLastTrackdir());
322 
323  EndSegmentReasonBits end_segment_reason = ESRB_NONE;
324 
325  TrackFollower tf_local(v, Yapf().GetCompatibleRailTypes());
326 
327  if (!has_parent) {
328  /* We will jump to the middle of the cost calculator assuming that segment cache is not used. */
329  assert(!is_cached_segment);
330  /* Skip the first transition cost calculation. */
331  goto no_entry_cost;
332  }
333 
334  for (;;) {
335  /* Transition cost (cost of the move from previous tile) */
336  transition_cost = Yapf().CurveCost(prev.td, cur.td);
337  transition_cost += Yapf().SwitchCost(prev.tile, cur.tile, TrackdirToExitdir(prev.td));
338 
339  /* First transition cost counts against segment entry cost, other transitions
340  * inside segment will come to segment cost (and will be cached) */
341  if (segment_cost == 0) {
342  /* We just entered the loop. First transition cost goes to segment entry cost)*/
343  segment_entry_cost = transition_cost;
344  transition_cost = 0;
345 
346  /* It is the right time now to look if we can reuse the cached segment cost. */
347  if (is_cached_segment) {
348  /* Yes, we already know the segment cost. */
349  segment_cost = segment.m_cost;
350  /* We know also the reason why the segment ends. */
351  end_segment_reason = segment.m_end_segment_reason;
352  /* We will need also some information about the last signal (if it was red). */
353  if (segment.m_last_signal_tile != INVALID_TILE) {
354  assert(HasSignalOnTrackdir(segment.m_last_signal_tile, segment.m_last_signal_td));
355  SignalState sig_state = GetSignalStateByTrackdir(segment.m_last_signal_tile, segment.m_last_signal_td);
356  bool is_red = (sig_state == SIGNAL_STATE_RED);
357  n.flags_u.flags_s.m_last_signal_was_red = is_red;
358  if (is_red) {
359  n.m_last_red_signal_type = GetSignalType(segment.m_last_signal_tile, TrackdirToTrack(segment.m_last_signal_td));
360  }
361  }
362  /* No further calculation needed. */
363  cur = TILE(n.GetLastTile(), n.GetLastTrackdir());
364  break;
365  }
366  } else {
367  /* Other than first transition cost count as the regular segment cost. */
368  segment_cost += transition_cost;
369  }
370 
371 no_entry_cost: // jump here at the beginning if the node has no parent (it is the first node)
372 
373  /* All other tile costs will be calculated here. */
374  segment_cost += Yapf().OneTileCost(cur.tile, cur.td);
375 
376  /* If we skipped some tunnel/bridge/station tiles, add their base cost */
377  segment_cost += YAPF_TILE_LENGTH * tf->m_tiles_skipped;
378 
379  /* Slope cost. */
380  segment_cost += Yapf().SlopeCost(cur.tile, cur.td);
381 
382  /* Signal cost (routine can modify segment data). */
383  segment_cost += Yapf().SignalCost(n, cur.tile, cur.td);
384 
385  /* Reserved tiles. */
386  segment_cost += Yapf().ReservationCost(n, cur.tile, cur.td, tf->m_tiles_skipped);
387 
388  end_segment_reason = segment.m_end_segment_reason;
389 
390  /* Tests for 'potential target' reasons to close the segment. */
391  if (cur.tile == prev.tile) {
392  /* Penalty for reversing in a depot. */
393  assert(IsRailDepot(cur.tile));
394  segment_cost += Yapf().PfGetSettings().rail_depot_reverse_penalty;
395 
396  } else if (IsRailDepotTile(cur.tile)) {
397  /* We will end in this pass (depot is possible target) */
398  end_segment_reason |= ESRB_DEPOT;
399 
400  } else if (cur.tile_type == MP_STATION && IsRailWaypoint(cur.tile)) {
401  if (v->current_order.IsType(OT_GOTO_WAYPOINT) &&
402  GetStationIndex(cur.tile) == v->current_order.GetDestination() &&
404  /* This waypoint is our destination; maybe this isn't an unreserved
405  * one, so check that and if so see that as the last signal being
406  * red. This way waypoints near stations should work better. */
407  CFollowTrackRail ft(v);
408  TileIndex t = cur.tile;
409  Trackdir td = cur.td;
410  /* Arbitrary maximum tiles to follow to avoid infinite loops. */
411  uint max_tiles = 20;
412  while (ft.Follow(t, td)) {
413  assert(t != ft.m_new_tile);
414  t = ft.m_new_tile;
415  if (t == cur.tile || --max_tiles == 0) {
416  /* We looped back on ourself or found another loop, bail out. */
417  td = INVALID_TRACKDIR;
418  break;
419  }
421  /* We encountered a junction; it's going to be too complex to
422  * handle this perfectly, so just bail out. There is no simple
423  * free path, so try the other possibilities. */
424  td = INVALID_TRACKDIR;
425  break;
426  }
428  /* If this is a safe waiting position we're done searching for it */
429  if (IsSafeWaitingPosition(v, t, td, true, _settings_game.pf.forbid_90_deg)) break;
430  }
431 
432  /* In the case this platform is (possibly) occupied we add penalty so the
433  * other platforms of this waypoint are evaluated as well, i.e. we assume
434  * that there is a red signal in the waypoint when it's occupied. */
435  if (td == INVALID_TRACKDIR ||
438  extra_cost += Yapf().PfGetSettings().rail_lastred_penalty;
439  }
440  }
441  /* Waypoint is also a good reason to finish. */
442  end_segment_reason |= ESRB_WAYPOINT;
443 
444  } else if (tf->m_is_station) {
445  /* Station penalties. */
446  uint platform_length = tf->m_tiles_skipped + 1;
447  /* We don't know yet if the station is our target or not. Act like
448  * if it is pass-through station (not our destination). */
449  segment_cost += Yapf().PfGetSettings().rail_station_penalty * platform_length;
450  /* We will end in this pass (station is possible target) */
451  end_segment_reason |= ESRB_STATION;
452 
453  } else if (TrackFollower::DoTrackMasking() && cur.tile_type == MP_RAILWAY) {
454  /* Searching for a safe tile? */
455  if (HasSignalOnTrackdir(cur.tile, cur.td) && !IsPbsSignal(GetSignalType(cur.tile, TrackdirToTrack(cur.td)))) {
456  end_segment_reason |= ESRB_SAFE_TILE;
457  }
458  }
459 
460  /* Apply min/max speed penalties only when inside the look-ahead radius. Otherwise
461  * it would cause desync in MP. */
462  if (n.m_num_signals_passed < m_sig_look_ahead_costs.size())
463  {
464  int min_speed = 0;
465  int max_speed = tf->GetSpeedLimit(&min_speed);
466  int max_veh_speed = std::min<int>(v->GetDisplayMaxSpeed(), v->current_order.GetMaxSpeed());
467  if (max_speed < max_veh_speed) {
468  extra_cost += YAPF_TILE_LENGTH * (max_veh_speed - max_speed) * (4 + tf->m_tiles_skipped) / max_veh_speed;
469  }
470  if (min_speed > max_veh_speed) {
471  extra_cost += YAPF_TILE_LENGTH * (min_speed - max_veh_speed);
472  }
473  }
474 
475  /* Finish if we already exceeded the maximum path cost (i.e. when
476  * searching for the nearest depot). */
477  if (m_max_cost > 0 && (parent_cost + segment_entry_cost + segment_cost) > m_max_cost) {
478  end_segment_reason |= ESRB_PATH_TOO_LONG;
479  }
480 
481  /* Move to the next tile/trackdir. */
482  tf = &tf_local;
483  tf_local.Init(v, Yapf().GetCompatibleRailTypes());
484 
485  if (!tf_local.Follow(cur.tile, cur.td)) {
486  assert(tf_local.m_err != TrackFollower::EC_NONE);
487  /* Can't move to the next tile (EOL?). */
488  if (tf_local.m_err == TrackFollower::EC_RAIL_ROAD_TYPE) {
489  end_segment_reason |= ESRB_RAIL_TYPE;
490  } else {
491  end_segment_reason |= ESRB_DEAD_END;
492  }
493 
494  if (TrackFollower::DoTrackMasking() && !HasOnewaySignalBlockingTrackdir(cur.tile, cur.td)) {
495  end_segment_reason |= ESRB_SAFE_TILE;
496  }
497  break;
498  }
499 
500  /* Check if the next tile is not a choice. */
501  if (KillFirstBit(tf_local.m_new_td_bits) != TRACKDIR_BIT_NONE) {
502  /* More than one segment will follow. Close this one. */
503  end_segment_reason |= ESRB_CHOICE_FOLLOWS;
504  break;
505  }
506 
507  /* Gather the next tile/trackdir/tile_type/rail_type. */
508  TILE next(tf_local.m_new_tile, (Trackdir)FindFirstBit2x64(tf_local.m_new_td_bits));
509 
510  if (TrackFollower::DoTrackMasking() && IsTileType(next.tile, MP_RAILWAY)) {
511  if (HasSignalOnTrackdir(next.tile, next.td) && IsPbsSignal(GetSignalType(next.tile, TrackdirToTrack(next.td)))) {
512  /* Possible safe tile. */
513  end_segment_reason |= ESRB_SAFE_TILE;
514  } else if (HasSignalOnTrackdir(next.tile, ReverseTrackdir(next.td)) && GetSignalType(next.tile, TrackdirToTrack(next.td)) == SIGTYPE_PBS_ONEWAY) {
515  /* Possible safe tile, but not so good as it's the back of a signal... */
516  end_segment_reason |= ESRB_SAFE_TILE | ESRB_DEAD_END;
517  extra_cost += Yapf().PfGetSettings().rail_lastred_exit_penalty;
518  }
519  }
520 
521  /* Check the next tile for the rail type. */
522  if (next.rail_type != cur.rail_type) {
523  /* Segment must consist from the same rail_type tiles. */
524  end_segment_reason |= ESRB_RAIL_TYPE;
525  break;
526  }
527 
528  /* Avoid infinite looping. */
529  if (next.tile == n.m_key.m_tile && next.td == n.m_key.m_td) {
530  end_segment_reason |= ESRB_INFINITE_LOOP;
531  break;
532  }
533 
534  if (segment_cost > s_max_segment_cost) {
535  /* Potentially in the infinite loop (or only very long segment?). We should
536  * not force it to finish prematurely unless we are on a regular tile. */
537  if (IsTileType(tf->m_new_tile, MP_RAILWAY)) {
538  end_segment_reason |= ESRB_SEGMENT_TOO_LONG;
539  break;
540  }
541  }
542 
543  /* Any other reason bit set? */
544  if (end_segment_reason != ESRB_NONE) {
545  break;
546  }
547 
548  /* For the next loop set new prev and cur tile info. */
549  prev = cur;
550  cur = next;
551 
552  } // for (;;)
553 
554  /* Don't consider path any further it if exceeded max_cost. */
555  if (end_segment_reason & ESRB_PATH_TOO_LONG) return false;
556 
557  bool target_seen = false;
558  if ((end_segment_reason & ESRB_POSSIBLE_TARGET) != ESRB_NONE) {
559  /* Depot, station or waypoint. */
560  if (Yapf().PfDetectDestination(cur.tile, cur.td)) {
561  /* Destination found. */
562  target_seen = true;
563  }
564  }
565 
566  /* Update the segment if needed. */
567  if (!is_cached_segment) {
568  /* Write back the segment information so it can be reused the next time. */
569  segment.m_cost = segment_cost;
570  segment.m_end_segment_reason = end_segment_reason & ESRB_CACHED_MASK;
571  /* Save end of segment back to the node. */
572  n.SetLastTileTrackdir(cur.tile, cur.td);
573  }
574 
575  /* Do we have an excuse why not to continue pathfinding in this direction? */
576  if (!target_seen && (end_segment_reason & ESRB_ABORT_PF_MASK) != ESRB_NONE) {
577  /* Reason to not continue. Stop this PF branch. */
578  return false;
579  }
580 
581  /* Special costs for the case we have reached our target. */
582  if (target_seen) {
583  n.flags_u.flags_s.m_targed_seen = true;
584  /* Last-red and last-red-exit penalties. */
585  if (n.flags_u.flags_s.m_last_signal_was_red) {
586  if (n.m_last_red_signal_type == SIGTYPE_EXIT) {
587  /* last signal was red pre-signal-exit */
588  extra_cost += Yapf().PfGetSettings().rail_lastred_exit_penalty;
589  } else if (!IsPbsSignal(n.m_last_red_signal_type)) {
590  /* Last signal was red, but not exit or path signal. */
591  extra_cost += Yapf().PfGetSettings().rail_lastred_penalty;
592  }
593  }
594 
595  /* Station platform-length penalty. */
596  if ((end_segment_reason & ESRB_STATION) != ESRB_NONE) {
597  const BaseStation *st = BaseStation::GetByTile(n.GetLastTile());
598  assert(st != nullptr);
599  uint platform_length = st->GetPlatformLength(n.GetLastTile(), ReverseDiagDir(TrackdirToExitdir(n.GetLastTrackdir())));
600  /* Reduce the extra cost caused by passing-station penalty (each station receives it in the segment cost). */
601  extra_cost -= Yapf().PfGetSettings().rail_station_penalty * platform_length;
602  /* Add penalty for the inappropriate platform length. */
603  extra_cost += PlatformLengthPenalty(platform_length);
604  }
605  }
606 
607  /* total node cost */
608  n.m_cost = parent_cost + segment_entry_cost + segment_cost + extra_cost;
609 
610  return true;
611  }
612 
613  inline bool CanUseGlobalCache(Node &n) const
614  {
615  return !m_disable_cache
616  && (n.m_parent != nullptr)
617  && (n.m_parent->m_num_signals_passed >= m_sig_look_ahead_costs.size());
618  }
619 
620  inline void ConnectNodeToCachedData(Node &n, CachedData &ci)
621  {
622  n.m_segment = &ci;
623  if (n.m_segment->m_cost < 0) {
624  n.m_segment->m_last_tile = n.m_key.m_tile;
625  n.m_segment->m_last_td = n.m_key.m_td;
626  }
627  }
628 
629  void DisableCache(bool disable)
630  {
631  m_disable_cache = disable;
632  }
633 };
634 
635 #endif /* YAPF_COSTRAIL_HPP */
TileIndex
uint32 TileIndex
The index/ID of a Tile.
Definition: tile_type.h:83
TRACK_BIT_NONE
@ TRACK_BIT_NONE
No track.
Definition: track_type.h:39
CYapfCostRailT::IsAnyStationTileReserved
bool IsAnyStationTileReserved(TileIndex tile, Trackdir trackdir, int skipped)
Check for a reserved station platform.
Definition: yapf_costrail.hpp:145
Order::IsType
bool IsType(OrderType type) const
Check whether this order is of the given type.
Definition: order_base.h:64
TileOffsByDiagDir
static TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
Convert a DiagDirection to a TileIndexDiff.
Definition: map_func.h:341
RemoveFirstTrackdir
static Trackdir RemoveFirstTrackdir(TrackdirBits *trackdirs)
Removes first Trackdir from TrackdirBits and returns it.
Definition: track_func.h:155
LinkGraph::Node
Updatable node class.
Definition: linkgraph.h:380
PathfinderSettings::forbid_90_deg
bool forbid_90_deg
forbid trains to make 90 deg turns
Definition: settings_type.h:451
CYapfCostRailT::m_max_cost
int m_max_cost
Definition: yapf_costrail.hpp:57
GetReservedTrackbits
TrackBits GetReservedTrackbits(TileIndex t)
Get the reserved trackbits for any tile, regardless of type.
Definition: pbs.cpp:24
CYapfCostRailT::PfCalcCost
bool PfCalcCost(Node &n, const TrackFollower *tf)
Called by YAPF to calculate the cost from the origin to the given node.
Definition: yapf_costrail.hpp:270
BaseStation::GetByTile
static BaseStation * GetByTile(TileIndex tile)
Get the base station belonging to a specific tile.
Definition: base_station_base.h:155
Order::GetDestination
DestinationID GetDestination() const
Gets the destination of this order.
Definition: order_base.h:97
KillFirstBit
static T KillFirstBit(T value)
Clear the first bit in an integer.
Definition: bitmath_func.hpp:239
MP_RAILWAY
@ MP_RAILWAY
A railway.
Definition: tile_type.h:47
TILE_SIZE
static const uint TILE_SIZE
Tile size in world coordinates.
Definition: tile_type.h:13
SignalState
SignalState
These are states in which a signal can be.
Definition: signal_type.h:44
GetTrackBits
static TrackBits GetTrackBits(TileIndex tile)
Gets the track bits of the given tile.
Definition: rail_map.h:136
CYapfCostRailT
Definition: yapf_costrail.hpp:18
SpecializedStation< Waypoint, true >::Get
static Waypoint * Get(size_t index)
Gets station with given index.
Definition: base_station_base.h:219
CYapfCostRailT::ReservationCost
int ReservationCost(Node &n, TileIndex tile, Trackdir trackdir, int skipped)
The cost for reserved tiles, including skipped ones.
Definition: yapf_costrail.hpp:155
MP_ROAD
@ MP_ROAD
A tile with road (or tram tracks)
Definition: tile_type.h:48
IsRailDepot
static bool IsRailDepot(TileIndex t)
Is this rail tile a rail depot?
Definition: rail_map.h:95
IsLevelCrossing
static bool IsLevelCrossing(TileIndex t)
Return whether a tile is a level crossing.
Definition: road_map.h:84
SignalType
SignalType
Type of signal, i.e.
Definition: signal_type.h:23
Order::GetMaxSpeed
uint16 GetMaxSpeed() const
Get the maxmimum speed in km-ish/h a vehicle is allowed to reach on the way to the destination.
Definition: order_base.h:195
CYapfCostRailT::Key
Node::Key Key
key to hash tables
Definition: yapf_costrail.hpp:23
CYapfCostBase
Base implementation for cost accounting.
Definition: yapf_costbase.hpp:14
CYapfCostBase::stSlopeCost
static bool stSlopeCost(TileIndex tile, Trackdir td)
Does the given track direction on the given tile yield an uphill penalty?
Definition: yapf_costbase.hpp:21
GameSettings::pf
PathfinderSettings pf
settings for all pathfinders
Definition: settings_type.h:582
GroundVehicleCache::cached_total_length
uint16 cached_total_length
Length of the whole vehicle (valid only for the first engine).
Definition: ground_vehicle.hpp:42
IsWaitingPositionFree
bool IsWaitingPositionFree(const Train *v, TileIndex tile, Trackdir trackdir, bool forbid_90deg)
Check if a safe position is free.
Definition: pbs.cpp:427
RailType
RailType
Enumeration for all possible railtypes.
Definition: rail_type.h:27
Waypoint::IsSingleTile
bool IsSingleTile() const
Is this a single tile waypoint?
Definition: waypoint_base.h:53
SIGTYPE_NORMAL
@ SIGTYPE_NORMAL
normal signal
Definition: signal_type.h:24
TileIndexDiff
int32 TileIndexDiff
An offset value between to tiles.
Definition: map_func.h:154
YAPF_TILE_LENGTH
static const int YAPF_TILE_LENGTH
Length (penalty) of one tile with YAPF.
Definition: pathfinder_type.h:28
SIGNAL_STATE_RED
@ SIGNAL_STATE_RED
The signal is red.
Definition: signal_type.h:45
TrackdirToExitdir
static DiagDirection TrackdirToExitdir(Trackdir trackdir)
Maps a trackdir to the (4-way) direction the tile is exited when following that trackdir.
Definition: track_func.h:438
SIGTYPE_EXIT
@ SIGTYPE_EXIT
presignal block exit
Definition: signal_type.h:26
Vehicle::current_order
Order current_order
The current order (+ status, like: loading)
Definition: vehicle_base.h:329
FindFirstBit2x64
static uint8 FindFirstBit2x64(const int value)
Finds the position of the first non-zero bit in an integer.
Definition: bitmath_func.hpp:216
SIGTYPE_COMBO
@ SIGTYPE_COMBO
presignal inter-block
Definition: signal_type.h:27
HasSignalOnTrackdir
static bool HasSignalOnTrackdir(TileIndex tile, Trackdir trackdir)
Checks for the presence of signals along the given trackdir on the given rail tile.
Definition: rail_map.h:426
GroundVehicle::gcache
GroundVehicleCache gcache
Cache of often calculated values.
Definition: ground_vehicle.hpp:80
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:53
TrackdirCrossesTrackdirs
static TrackdirBits TrackdirCrossesTrackdirs(Trackdir trackdir)
Maps a trackdir to all trackdirs that make 90 deg turns with it.
Definition: track_func.h:605
DiagdirReachesTracks
static TrackBits DiagdirReachesTracks(DiagDirection diagdir)
Returns all tracks that can be reached when entering a tile from a given (diagonal) direction.
Definition: track_func.h:572
IsRailDepotTile
static bool IsRailDepotTile(TileIndex t)
Is this tile rail tile and a rail depot?
Definition: rail_map.h:105
CYapfCostRailT::Yapf
Tpf & Yapf()
to access inherited path finder
Definition: yapf_costrail.hpp:81
Train
'Train' is either a loco or a wagon.
Definition: train.h:86
ReverseDiagDir
static DiagDirection ReverseDiagDir(DiagDirection d)
Returns the reverse direction of the given DiagDirection.
Definition: direction_func.h:118
HasOnewaySignalBlockingTrackdir
static bool HasOnewaySignalBlockingTrackdir(TileIndex tile, Trackdir td)
Is a one-way signal blocking the trackdir? A one-way signal on the trackdir against will block,...
Definition: rail_map.h:475
HasStationReservation
static bool HasStationReservation(TileIndex t)
Get the reservation state of the rail station.
Definition: station_map.h:393
IsSafeWaitingPosition
bool IsSafeWaitingPosition(const Train *v, TileIndex tile, Trackdir trackdir, bool include_line_end, bool forbid_90deg)
Determine whether a certain track on a tile is a safe position to end a path.
Definition: pbs.cpp:381
INVALID_TRACKDIR
@ INVALID_TRACKDIR
Flag for an invalid trackdir.
Definition: track_type.h:89
DiagDirection
DiagDirection
Enumeration for diagonal directions.
Definition: direction_type.h:77
IsRailStationTile
static bool IsRailStationTile(TileIndex t)
Is this tile a station tile and a rail station?
Definition: station_map.h:102
IsOnewaySignal
static bool IsOnewaySignal(TileIndex t, Track track)
One-way signals can't be passed the 'wrong' way.
Definition: rail_map.h:319
CYapfCostRailT::Tpf
Types::Tpf Tpf
the pathfinder class (derived from THIS class)
Definition: yapf_costrail.hpp:20
CYapfCostRailT::Node
Types::NodeList::Titem Node
this will be our node type
Definition: yapf_costrail.hpp:22
IsTileType
static bool IsTileType(TileIndex tile, TileType type)
Checks if a tile is a given tiletype.
Definition: tile_map.h:150
TrackOverlapsTracks
static bool TrackOverlapsTracks(TrackBits tracks, Track track)
Check if a given track is contained within or overlaps some other tracks.
Definition: track_func.h:661
TRACKDIR_BIT_NONE
@ TRACKDIR_BIT_NONE
No track build.
Definition: track_type.h:102
SIGTYPE_PBS_ONEWAY
@ SIGTYPE_PBS_ONEWAY
no-entry signal
Definition: signal_type.h:29
SIGTYPE_ENTRY
@ SIGTYPE_ENTRY
presignal block entry
Definition: signal_type.h:25
IsRailWaypoint
static bool IsRailWaypoint(TileIndex t)
Is this station tile a rail waypoint?
Definition: station_map.h:113
MP_VOID
@ MP_VOID
Invisible tiles at the SW and SE border.
Definition: tile_type.h:53
TileType
TileType
The different types of tiles.
Definition: tile_type.h:45
GetSignalStateByTrackdir
static SignalState GetSignalStateByTrackdir(TileIndex tile, Trackdir trackdir)
Gets the state of the signal along the given trackdir.
Definition: rail_map.h:438
MP_STATION
@ MP_STATION
A tile of a station.
Definition: tile_type.h:51
GetStationIndex
static StationID GetStationIndex(TileIndex t)
Get StationID from a tile.
Definition: station_map.h:28
BaseStation
Base class for all station-ish types.
Definition: base_station_base.h:52
CFollowTrackT::m_new_tile
TileIndex m_new_tile
the new tile (the vehicle has entered)
Definition: follow_track.hpp:43
Train::GetDisplayMaxSpeed
int GetDisplayMaxSpeed() const
Gets the maximum speed in km-ish/h that can be sent into SetDParam for string processing.
Definition: train.h:117
CFollowTrackT::Follow
bool Follow(TileIndex old_tile, Trackdir old_td)
main follower routine.
Definition: follow_track.hpp:119
IsPlainRailTile
static bool IsPlainRailTile(TileIndex t)
Checks whether the tile is a rail tile or rail tile with signals.
Definition: rail_map.h:60
CFollowTrackT::m_new_td_bits
TrackdirBits m_new_td_bits
the new set of available trackdirs
Definition: follow_track.hpp:44
YAPF_TILE_CORNER_LENGTH
static const int YAPF_TILE_CORNER_LENGTH
Length (penalty) of a corner with YAPF.
Definition: pathfinder_type.h:31
INVALID_TILE
static const TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition: tile_type.h:88
GetTileRailType
RailType GetTileRailType(TileIndex tile)
Return the rail type of tile, or INVALID_RAILTYPE if this is no rail tile.
Definition: rail.cpp:155
ReverseTrackdir
static Trackdir ReverseTrackdir(Trackdir trackdir)
Maps a trackdir to the reverse trackdir.
Definition: track_func.h:246
CeilDiv
static uint CeilDiv(uint a, uint b)
Computes ceil(a / b) for non-negative a and b.
Definition: math_func.hpp:254
Trackdir
Trackdir
Enumeration for tracks and directions.
Definition: track_type.h:70
NextTrackdir
static Trackdir NextTrackdir(Trackdir trackdir)
Maps a trackdir to the trackdir that you will end up on if you go straight ahead.
Definition: track_func.h:402
GetTileType
static TileType GetTileType(TileIndex tile)
Get the tiletype of a given tile.
Definition: tile_map.h:96
VEH_TRAIN
@ VEH_TRAIN
Train vehicle type.
Definition: vehicle_type.h:24
BaseVehicle::type
VehicleType type
Type of vehicle.
Definition: vehicle_type.h:52
BaseStation::GetPlatformLength
virtual uint GetPlatformLength(TileIndex tile) const =0
Obtain the length of a platform.
CYapfCostRailT::TILE
Definition: yapf_costrail.hpp:29
HasTrackdir
static bool HasTrackdir(TrackdirBits trackdirs, Trackdir trackdir)
Checks whether a TrackdirBits has a given Trackdir.
Definition: track_func.h:339
IsValidTrackdir
static bool IsValidTrackdir(Trackdir trackdir)
Checks if a Trackdir is valid for non-road vehicles.
Definition: track_func.h:51
CYapfCostRailT::OneTileCost
int OneTileCost(TileIndex &tile, Trackdir trackdir)
Return one tile cost (base cost + level crossing penalty).
Definition: yapf_costrail.hpp:120
CFollowTrackT
Track follower helper template class (can serve pathfinders and vehicle controllers).
Definition: follow_track.hpp:28
TrackdirToTrack
static Track TrackdirToTrack(Trackdir trackdir)
Returns the Track that a given Trackdir represents.
Definition: track_func.h:261
IsDiagonalTrackdir
static bool IsDiagonalTrackdir(Trackdir trackdir)
Checks if a given Trackdir is diagonal.
Definition: track_func.h:630
INVALID_RAILTYPE
@ INVALID_RAILTYPE
Flag for invalid railtype.
Definition: rail_type.h:34