OpenTTD Source  20241124-master-g9399a92a4f
yapf_base.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_BASE_HPP
11 #define YAPF_BASE_HPP
12 
13 #include "../../debug.h"
14 #include "../../settings_type.h"
15 #include "../../misc/dbg_helpers.h"
16 #include "yapf_type.hpp"
17 
48 template <class Types>
49 class CYapfBaseT {
50 public:
51  typedef typename Types::Tpf Tpf;
52  typedef typename Types::TrackFollower TrackFollower;
53  typedef typename Types::NodeList NodeList;
54  typedef typename Types::VehicleType VehicleType;
55  typedef typename NodeList::Item Node;
56  typedef typename Node::Key Key;
57 
59 
60 protected:
61  Node *best_dest_node = nullptr;
65  const VehicleType *vehicle = nullptr;
66 
67  int stats_cost_calcs = 0;
68  int stats_cache_hits = 0;
69 
70 public:
71  int num_steps = 0;
72 
73 public:
76 
79 
80 protected:
82  inline Tpf &Yapf()
83  {
84  return *static_cast<Tpf *>(this);
85  }
86 
87 public:
89  inline const YAPFSettings &PfGetSettings() const
90  {
91  return *this->settings;
92  }
93 
103  inline bool FindPath(const VehicleType *v)
104  {
105  this->vehicle = v;
106 
107  Yapf().PfSetStartupNodes();
108 
109  for (;;) {
110  this->num_steps++;
111  Node *best_open_node = this->nodes.GetBestOpenNode();
112  if (best_open_node == nullptr) break;
113 
114  if (Yapf().PfDetectDestination(*best_open_node)) {
115  this->best_dest_node = best_open_node;
116  break;
117  }
118 
119  Yapf().PfFollowNode(*best_open_node);
120  if (this->max_search_nodes != 0 && this->nodes.ClosedCount() >= this->max_search_nodes) break;
121 
122  this->nodes.PopOpenNode(best_open_node->GetKey());
123  this->nodes.InsertClosedNode(*best_open_node);
124  }
125 
126  const bool destination_found = (this->best_dest_node != nullptr);
127 
128  if (_debug_yapf_level >= 3) {
129  const UnitID veh_idx = (this->vehicle != nullptr) ? this->vehicle->unitnumber : 0;
130  const char ttc = Yapf().TransportTypeChar();
131  const float cache_hit_ratio = (this->stats_cache_hits == 0) ? 0.0f : ((float)this->stats_cache_hits / (float)(this->stats_cache_hits + this->stats_cost_calcs) * 100.0f);
132  const int cost = destination_found ? this->best_dest_node->cost : -1;
133  const int dist = destination_found ? this->best_dest_node->estimate - this->best_dest_node->cost : -1;
134 
135  Debug(yapf, 3, "[YAPF{}]{}{:4d} - {} rounds - {} open - {} closed - CHR {:4.1f}% - C {} D {}",
136  ttc, destination_found ? '-' : '!', veh_idx, this->num_steps, this->nodes.OpenCount(), this->nodes.ClosedCount(), cache_hit_ratio, cost, dist
137  );
138  }
139 
140  return destination_found;
141  }
142 
147  inline Node *GetBestNode()
148  {
149  return (this->best_dest_node != nullptr) ? this->best_dest_node : this->best_intermediate_node;
150  }
151 
156  inline Node &CreateNewNode()
157  {
158  Node &node = this->nodes.CreateNewNode();
159  return node;
160  }
161 
163  inline void AddStartupNode(Node &n)
164  {
165  Yapf().PfNodeCacheFetch(n);
166  /* insert the new node only if it is not there */
167  if (this->nodes.FindOpenNode(n.key) == nullptr) {
168  this->nodes.InsertOpenNode(n);
169  } else {
170  /* if we are here, it means that node is already there - how it is possible?
171  * probably the train is in the position that both its ends point to the same tile/exit-dir
172  * very unlikely, but it happened */
173  }
174  }
175 
177  inline void AddMultipleNodes(Node *parent, const TrackFollower &tf)
178  {
179  bool is_choice = (KillFirstBit(tf.new_td_bits) != TRACKDIR_BIT_NONE);
180  for (TrackdirBits rtds = tf.new_td_bits; rtds != TRACKDIR_BIT_NONE; rtds = KillFirstBit(rtds)) {
181  Trackdir td = (Trackdir)FindFirstBit(rtds);
182  Node &n = Yapf().CreateNewNode();
183  n.Set(parent, tf.new_tile, td, is_choice);
184  Yapf().AddNewNode(n, tf);
185  }
186  }
187 
197  {
198  bool intermediate_on_branch = false;
199  while (n != nullptr && (n->segment->end_segment_reason & ESRB_CHOICE_FOLLOWS) == 0) {
200  if (n == Yapf().best_intermediate_node) intermediate_on_branch = true;
201  n = n->parent;
202  }
203  if (intermediate_on_branch) Yapf().best_intermediate_node = n;
204  }
205 
210  void AddNewNode(Node &n, const TrackFollower &tf)
211  {
212  /* evaluate the node */
213  bool cached = Yapf().PfNodeCacheFetch(n);
214  if (!cached) {
215  this->stats_cost_calcs++;
216  } else {
217  this->stats_cache_hits++;
218  }
219 
220  bool valid = Yapf().PfCalcCost(n, &tf);
221 
222  if (valid) valid = Yapf().PfCalcEstimate(n);
223 
224  /* have the cost or estimate callbacks marked this node as invalid? */
225  if (!valid) return;
226 
227  /* The new node can be set as the best intermediate node only once we're
228  * certain it will be finalized by being inserted into the open list. */
229  bool set_intermediate = this->max_search_nodes > 0 && (this->best_intermediate_node == nullptr || (this->best_intermediate_node->GetCostEstimate() - this->best_intermediate_node->GetCost()) > (n.GetCostEstimate() - n.GetCost()));
230 
231  /* check new node against open list */
232  Node *open_node = this->nodes.FindOpenNode(n.GetKey());
233  if (open_node != nullptr) {
234  /* another node exists with the same key in the open list
235  * is it better than new one? */
236  if (n.GetCostEstimate() < open_node->GetCostEstimate()) {
237  /* update the old node by value from new one */
238  this->nodes.PopOpenNode(n.GetKey());
239  *open_node = n;
240  /* add the updated old node back to open list */
241  this->nodes.InsertOpenNode(*open_node);
242  if (set_intermediate) this->best_intermediate_node = open_node;
243  }
244  return;
245  }
246 
247  /* check new node against closed list */
248  Node *closed_node = this->nodes.FindClosedNode(n.GetKey());
249  if (closed_node != nullptr) {
250  /* another node exists with the same key in the closed list
251  * is it better than new one? */
252  int node_est = n.GetCostEstimate();
253  int closed_est = closed_node->GetCostEstimate();
254  if (node_est < closed_est) {
255  /* If this assert occurs, you have probably problem in
256  * your Tderived::PfCalcCost() or Tderived::PfCalcEstimate().
257  * The problem could be:
258  * - PfCalcEstimate() gives too large numbers
259  * - PfCalcCost() gives too small numbers
260  * - You have used negative cost penalty in some cases (cost bonus) */
261  NOT_REACHED();
262  }
263  return;
264  }
265  /* the new node is really new
266  * add it to the open list */
267  this->nodes.InsertOpenNode(n);
268  if (set_intermediate) this->best_intermediate_node = &n;
269  }
270 
271  const VehicleType * GetVehicle() const
272  {
273  return this->vehicle;
274  }
275 
276  void DumpBase(DumpTarget &dmp) const
277  {
278  dmp.WriteStructT("nodes", &this->nodes);
279  dmp.WriteValue("num_steps", this->num_steps);
280  }
281 };
282 
283 #endif /* YAPF_BASE_HPP */
constexpr uint8_t FindFirstBit(T x)
Search the first set bit in a value.
constexpr T KillFirstBit(T value)
Clear the first bit in an integer.
CYapfBaseT - A-star type path finder base class.
Definition: yapf_base.hpp:49
int num_steps
this is there for debugging purposes (hope it doesn't hurt)
Definition: yapf_base.hpp:71
void PruneIntermediateNodeBranch(Node *n)
In some cases an intermediate node branch should be pruned.
Definition: yapf_base.hpp:196
Node::Key Key
key to hash tables
Definition: yapf_base.hpp:56
CYapfBaseT()
default constructor
Definition: yapf_base.hpp:75
Node * GetBestNode()
If path was found return the best node that has reached the destination.
Definition: yapf_base.hpp:147
void AddNewNode(Node &n, const TrackFollower &tf)
AddNewNode() - called by Tderived::PfFollowNode() for each child node.
Definition: yapf_base.hpp:210
const VehicleType * vehicle
vehicle that we are trying to drive
Definition: yapf_base.hpp:65
Node & CreateNewNode()
Calls NodeList::CreateNewNode() - allocates new node that can be filled and used as argument for AddS...
Definition: yapf_base.hpp:156
const YAPFSettings & PfGetSettings() const
return current settings (can be custom - company based - but later)
Definition: yapf_base.hpp:89
Node * best_intermediate_node
here should be node closest to the destination if path not found
Definition: yapf_base.hpp:62
Tpf & Yapf()
to access inherited path finder
Definition: yapf_base.hpp:82
const YAPFSettings * settings
current settings (_settings_game.yapf)
Definition: yapf_base.hpp:63
int stats_cache_hits
stats - how many node's costs were reused from cache
Definition: yapf_base.hpp:68
void AddMultipleNodes(Node *parent, const TrackFollower &tf)
add multiple nodes - direct children of the given node
Definition: yapf_base.hpp:177
int stats_cost_calcs
stats - how many node's costs were calculated
Definition: yapf_base.hpp:67
int max_search_nodes
maximum number of nodes we are allowed to visit before we give up
Definition: yapf_base.hpp:64
~CYapfBaseT()
default destructor
Definition: yapf_base.hpp:78
bool FindPath(const VehicleType *v)
Main pathfinder routine:
Definition: yapf_base.hpp:103
NodeList nodes
node list multi-container
Definition: yapf_base.hpp:58
Types::Tpf Tpf
the pathfinder class (derived from THIS class)
Definition: yapf_base.hpp:51
Types::VehicleType VehicleType
the type of vehicle
Definition: yapf_base.hpp:54
void AddStartupNode(Node &n)
Add new node (created by CreateNewNode and filled with data) into open list.
Definition: yapf_base.hpp:163
Node * best_dest_node
pointer to the destination node found at last round
Definition: yapf_base.hpp:61
NodeList::Item Node
this will be our node type
Definition: yapf_base.hpp:55
Types::NodeList NodeList
our node list
Definition: yapf_base.hpp:53
Hash table based node list multi-container class.
Definition: nodelist.hpp:21
void InsertClosedNode(Titem &item)
close node
Definition: nodelist.hpp:122
Titem * FindClosedNode(const Key &key)
return the closed node specified by a key or nullptr if not found
Definition: nodelist.hpp:129
Titem * FindOpenNode(const Key &key)
return the open node specified by a key or nullptr if not found
Definition: nodelist.hpp:107
Titem & CreateNewNode()
allocate new data item from items
Definition: nodelist.hpp:59
void InsertOpenNode(Titem &item)
insert given item as open node (into m_open and m_open_queue)
Definition: nodelist.hpp:76
int OpenCount()
return number of open nodes
Definition: nodelist.hpp:41
int ClosedCount()
return number of closed nodes
Definition: nodelist.hpp:47
Titem * GetBestOpenNode()
return the best open node
Definition: nodelist.hpp:87
Titem & PopOpenNode(const Key &key)
remove and return the open node specified by a key
Definition: nodelist.hpp:113
#define Debug(category, level, format_string,...)
Ouptut a line of debugging information.
Definition: debug.h:37
uint8_t valid
Bits indicating what variable is valid (for each bit, 0 is invalid, 1 is valid).
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:57
Class that represents the dump-into-string target.
Definition: dbg_helpers.h:95
void WriteValue(const std::string &name, int value)
Write 'name = value' with indent and new-line.
void WriteStructT(const std::string &name, const S *s)
Dump nested object (or only its name if this instance is already known).
Definition: dbg_helpers.h:147
Settings related to the yet another pathfinder.
Trackdir
Enumeration for tracks and directions.
Definition: track_type.h:67
TrackdirBits
Allow incrementing of Trackdir variables.
Definition: track_type.h:98
@ TRACKDIR_BIT_NONE
No track build.
Definition: track_type.h:99
uint16_t UnitID
Type for the company global vehicle unit number.
VehicleType
Available vehicle types.
Definition: vehicle_type.h:21
Types used by YAPF.