10#include "../../stdafx.h"
17#include "../../viewport_func.h"
18#include "../../newgrf_station.h"
20#include "../../safeguards.h"
22template <
typename Tpf>
void DumpState(Tpf &pf1, Tpf &pf2)
29 assert(f1.has_value());
30 assert(f2.has_value());
31 fwrite(dmp1.
m_out.data(), 1, dmp1.
m_out.size(), *f1);
32 fwrite(dmp2.
m_out.data(), 1, dmp2.
m_out.size(), *f2);
39 typedef typename Types::Tpf
Tpf;
40 typedef typename Types::TrackFollower TrackFollower;
41 typedef typename Types::NodeList::Item
Node;
47 return *
static_cast<Tpf *
>(
this);
63 this->res_dest_tile = tile;
64 this->res_dest_td = td;
97 this->res_fail_tile = tile;
98 this->res_fail_td = td;
103 this->res_fail_tile = tile;
104 this->res_fail_td = td;
110 this->signals_set_to_red.emplace_back(tile, rev_td);
122 return tile != this->res_dest_tile || td != this->
res_dest_td;
135 }
else if (tile != this->res_fail_tile || td != this->res_fail_td) {
138 return (tile != this->res_dest_tile || td != this->res_dest_td) && (tile != this->res_fail_tile || td != this->
res_fail_td);
145 this->res_dest_node = node;
146 this->res_dest_tile = tile;
147 this->res_dest_td = td;
153 assert(node->parent !=
nullptr);
156 if (node->parent->num_signals_passed >= 2)
return;
159 this->res_dest_node = node;
167 this->origin_tile = origin;
169 if (target !=
nullptr) {
172 target->
okay =
false;
178 this->signals_set_to_red.clear();
179 for (
Node *node = this->res_dest_node; node->parent !=
nullptr; node = node->parent) {
187 this->res_fail_tile = fail_node == node ? stop_tile :
INVALID_TILE;
189 }
while (fail_node != node && (fail_node = fail_node->parent) !=
nullptr);
200 if (target !=
nullptr) target->
okay =
true;
202 if (
Yapf().CanUseGlobalCache(*this->res_dest_node)) {
210template <
class Types>
214 typedef typename Types::Tpf
Tpf;
215 typedef typename Types::TrackFollower TrackFollower;
216 typedef typename Types::NodeList::Item
Node;
217 typedef typename Node::Key
Key;
223 return *
static_cast<Tpf *
>(
this);
234 TrackFollower F(
Yapf().GetVehicle());
235 if (F.Follow(old_node.GetLastTile(), old_node.GetLastTrackdir())) {
236 Yapf().AddMultipleNodes(&old_node, F);
258 if (max_penalty != 0) pf1.DisableCache(
true);
259 FindDepotData result1 = pf1.FindNearestDepotTwoWay(v, t1, td1, t2, td2, max_penalty, reverse_penalty);
261 if (_debug_desync_level >= 2) {
263 pf2.DisableCache(
true);
264 FindDepotData result2 = pf2.FindNearestDepotTwoWay(v, t1, td1, t2, td2, max_penalty, reverse_penalty);
266 Debug(desync, 2,
"warning: FindNearestDepotTwoWay cache mismatch: {} vs {}",
279 Yapf().SetOrigin(t1, td1, t2, td2, reverse_penalty);
280 Yapf().SetTreatFirstRedTwoWaySignalAsEOL(
true);
281 Yapf().SetDestination(v);
282 Yapf().SetMaxCost(max_penalty);
292 while (node->parent !=
nullptr) {
298 return FindDepotData(n->GetLastTile(), n->cost, node->cost != 0);
302template <
class Types>
306 typedef typename Types::Tpf
Tpf;
307 typedef typename Types::TrackFollower TrackFollower;
308 typedef typename Types::NodeList::Item
Node;
309 typedef typename Node::Key
Key;
315 return *
static_cast<Tpf *
>(
this);
326 TrackFollower F(
Yapf().GetVehicle(),
Yapf().GetCompatibleRailTypes());
327 if (F.Follow(old_node.GetLastTile(), old_node.GetLastTrackdir()) && F.MaskReservedTracks()) {
328 Yapf().AddMultipleNodes(&old_node, F);
343 if (_debug_desync_level < 2) {
344 result1 = pf1.FindNearestSafeTile(v, t1, td, override_railtype,
false);
346 bool result2 = pf1.FindNearestSafeTile(v, t1, td, override_railtype,
true);
348 pf2.DisableCache(
true);
349 result1 = pf2.FindNearestSafeTile(v, t1, td, override_railtype,
false);
350 if (result1 != result2) {
351 Debug(desync, 2,
"warning: FindSafeTile cache mismatch: {} vs {}", result2 ?
"T" :
"F", result1 ?
"T" :
"F");
359 bool FindNearestSafeTile(
const Train *v,
TileIndex t1,
Trackdir td,
bool override_railtype,
bool dont_reserve)
362 Yapf().SetOrigin(t1, td);
363 Yapf().SetTreatFirstRedTwoWaySignalAsEOL(
false);
364 Yapf().SetDestination(v, override_railtype);
366 if (!
Yapf().FindPath(v))
return false;
373 Node *prev =
nullptr;
374 while (node->parent !=
nullptr) {
381 return dont_reserve || this->
TryReservePath(
nullptr, node->GetLastTile());
385template <
class Types>
389 typedef typename Types::Tpf
Tpf;
390 typedef typename Types::TrackFollower TrackFollower;
391 typedef typename Types::NodeList::Item
Node;
392 typedef typename Node::Key
Key;
398 return *
static_cast<Tpf *
>(
this);
409 TrackFollower F(
Yapf().GetVehicle());
410 if (F.Follow(old_node.GetLastTile(), old_node.GetLastTrackdir())) {
411 Yapf().AddMultipleNodes(&old_node, F);
427 if (_debug_desync_level < 2) {
428 result1 = pf1.ChooseRailTrack(v, tile, enterdir, tracks, path_found, reserve_track, target, dest);
430 result1 = pf1.ChooseRailTrack(v, tile, enterdir, tracks, path_found,
false,
nullptr,
nullptr);
432 pf2.DisableCache(
true);
433 Trackdir result2 = pf2.ChooseRailTrack(v, tile, enterdir, tracks, path_found, reserve_track, target, dest);
434 if (result1 != result2) {
435 Debug(desync, 2,
"warning: ChooseRailTrack cache mismatch: {} vs {}", result1, result2);
451 Yapf().SetTreatFirstRedTwoWaySignalAsEOL(
true);
452 Yapf().SetDestination(v);
455 path_found =
Yapf().FindPath(v);
460 if (node !=
nullptr) {
466 Node *prev =
nullptr;
467 while (node->parent !=
nullptr) {
479 Node &best_next_node = *prev;
480 next_trackdir = best_next_node.GetTrackdir();
482 if (reserve_track && path_found) {
483 if (dest !=
nullptr) *dest =
Yapf().GetBestNode()->GetLastTile();
489 path_found |=
Yapf().stopped_on_first_two_way_signal;
490 return next_trackdir;
496 bool result1 = pf1.CheckReverseTrain(v, t1, td1, t2, td2, reverse_penalty);
498 if (_debug_desync_level >= 2) {
500 pf2.DisableCache(
true);
501 bool result2 = pf2.CheckReverseTrain(v, t1, td1, t2, td2, reverse_penalty);
502 if (result1 != result2) {
503 Debug(desync, 2,
"warning: CheckReverseTrain cache mismatch: {} vs {}", result1 ?
"T" :
"F", result2 ?
"T" :
"F");
515 Yapf().SetOrigin(t1, td1, t2, td2, reverse_penalty);
516 Yapf().SetTreatFirstRedTwoWaySignalAsEOL(
false);
517 Yapf().SetDestination(v);
520 if (!
Yapf().FindPath(v))
return false;
525 while (node->parent !=
nullptr) {
530 bool reversed = (node->cost != 0);
535template <
class Tpf_,
class Ttrack_follower,
class Tnode_list,
template <
class Types>
class TdestinationT,
template <
class Types>
class TfollowT>
541 typedef Ttrack_follower TrackFollower;
545 typedef TfollowT<Types> PfFollow;
547 typedef TdestinationT<Types> PfDestination;
552struct CYapfRail1 :
CYapfT<CYapfRail_TypesT<CYapfRail1 , CFollowTrackRail , CRailNodeListTrackDir, CYapfDestinationTileOrStationRailT, CYapfFollowRailT> > {};
553struct CYapfRail2 :
CYapfT<CYapfRail_TypesT<CYapfRail2 , CFollowTrackRailNo90, CRailNodeListTrackDir, CYapfDestinationTileOrStationRailT, CYapfFollowRailT> > {};
555struct CYapfAnyDepotRail1 :
CYapfT<CYapfRail_TypesT<CYapfAnyDepotRail1, CFollowTrackRail , CRailNodeListTrackDir, CYapfDestinationAnyDepotRailT , CYapfFollowAnyDepotRailT> > {};
556struct CYapfAnyDepotRail2 :
CYapfT<CYapfRail_TypesT<CYapfAnyDepotRail2, CFollowTrackRailNo90, CRailNodeListTrackDir, CYapfDestinationAnyDepotRailT , CYapfFollowAnyDepotRailT> > {};
558struct CYapfAnySafeTileRail1 :
CYapfT<CYapfRail_TypesT<CYapfAnySafeTileRail1, CFollowTrackFreeRail , CRailNodeListTrackDir, CYapfDestinationAnySafeTileRailT , CYapfFollowAnySafeTileRailT> > {};
559struct CYapfAnySafeTileRail2 :
CYapfT<CYapfRail_TypesT<CYapfAnySafeTileRail2, CFollowTrackFreeRailNo90, CRailNodeListTrackDir, CYapfDestinationAnySafeTileRailT , CYapfFollowAnySafeTileRailT> > {};
565 ? CYapfRail2::stChooseRailTrack(v, tile, enterdir, tracks, path_found, reserve_track, target, dest)
566 : CYapfRail1::stChooseRailTrack(v, tile, enterdir, tracks, path_found, reserve_track, target, dest);
583 int reverse_penalty = 0;
615 if (reverse_penalty == 0) reverse_penalty = 1;
618 ? CYapfRail2::stCheckReverseTrain(v, tile, td, tile_rev, td_rev, reverse_penalty)
619 : CYapfRail1::stCheckReverseTrain(v, tile, td, tile_rev, td_rev, reverse_penalty);
640 ? CYapfAnySafeTileRail2::stFindNearestSafeTile(v, tile, td, override_railtype)
641 : CYapfAnySafeTileRail1::stFindNearestSafeTile(v, tile, td, override_railtype);
649 CSegmentCostCacheBase::NotifyTrackLayoutChange(tile, track);
CYapfBaseT - A-star type path finder base class.
Types::Tpf Tpf
the pathfinder class (derived from THIS class)
Tpf & Yapf()
to access inherited path finder
void PfFollowNode(Node &old_node)
Called by YAPF to move from the given node to the next tile.
char TransportTypeChar() const
return debug report character to identify the transportation type
Types::NodeList::Item Node
this will be our node type
Node::Key Key
key to hash tables
char TransportTypeChar() const
Return debug report character to identify the transportation type.
Node::Key Key
key to hash tables
Types::Tpf Tpf
the pathfinder class (derived from THIS class)
void PfFollowNode(Node &old_node)
Called by YAPF to move from the given node to the next tile.
Types::NodeList::Item Node
this will be our node type
Tpf & Yapf()
to access inherited path finder
Node::Key Key
key to hash tables
Tpf & Yapf()
to access inherited path finder
char TransportTypeChar() const
return debug report character to identify the transportation type
Types::Tpf Tpf
the pathfinder class (derived from THIS class)
Types::NodeList::Item Node
this will be our node type
void PfFollowNode(Node &old_node)
Called by YAPF to move from the given node to the next tile.
YAPF origin provider base class - used when there are two tile/trackdir origins.
void SetReservationTarget(Node *node, TileIndex tile, Trackdir td)
Set the target to where the reservation should be extended.
Types::NodeList::Item Node
this will be our node type
TileIndex res_fail_tile
The tile where the reservation failed.
bool UnreserveSingleTrack(TileIndex tile, Trackdir td)
Unreserve a single track/platform.
bool ReserveRailStationPlatform(TileIndex &tile, DiagDirection dir)
Reserve a railway platform.
bool ReserveSingleTrack(TileIndex tile, Trackdir td)
Try to reserve a single track/platform.
std::vector< std::pair< TileIndex, Trackdir > > signals_set_to_red
List of signals turned red during a path reservation.
Trackdir res_fail_td
The trackdir where the reservation failed.
Node * res_dest_node
The reservation target node.
TileIndex origin_tile
Tile our reservation will originate from.
TileIndex res_dest_tile
The reservation target tile.
bool TryReservePath(PBSTileInfo *target, TileIndex origin)
Try to reserve the path till the reservation target.
Tpf & Yapf()
to access inherited pathfinder
void FindSafePositionOnNode(Node *node)
Check the node for a possible reservation target.
Trackdir res_dest_td
The reservation target trackdir.
Types::Tpf Tpf
the pathfinder class (derived from THIS class)
CYapfSegmentCostCacheGlobalT - the yapf cost cache provider that adds the segment cost caching functi...
YAPF template that uses Ttypes template argument to determine all YAPF components (base classes) from...
static std::optional< FileHandle > Open(const std::string &filename, std::string_view mode)
Open an RAII file handle if possible.
Hash table based node list multi-container class.
#define Debug(category, level, format_string,...)
Output a line of debugging information.
DiagDirection
Enumeration for diagonal directions.
void MarkTileDirtyByTile(TileIndex tile, int bridge_level_offset, int tile_height_override)
Mark a tile given by its index dirty for repaint.
uint DistanceManhattan(TileIndex t0, TileIndex t1)
Gets the Manhattan distance between the two given tiles.
constexpr TileIndex TileAdd(TileIndex tile, TileIndexDiff offset)
Adds a given offset to a tile.
TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
Convert a DiagDirection to a TileIndexDiff.
static debug_inline TileIndex TileVirtXY(uint x, uint y)
Get a tile from the virtual XY-coordinate.
int32_t TileIndexDiff
An offset value between two tiles.
void TriggerStationRandomisation(BaseStation *st, TileIndex trigger_tile, StationRandomTrigger trigger, CargoType cargo_type)
Trigger station randomisation.
static const int YAPF_INFINITE_PENALTY
This penalty is the equivalent of "infinite", which means that paths that get this penalty will be ch...
static const int YAPF_TILE_LENGTH
Length (penalty) of one tile with YAPF.
PBSTileInfo FollowTrainReservation(const Train *v, Vehicle **train_on_res)
Follow a train reservation to the last tile.
bool TryReserveRailTrack(TileIndex tile, Track t, bool trigger_stations)
Try to reserve a specific track on a tile.
bool IsWaitingPositionFree(const Train *v, TileIndex tile, Trackdir trackdir, bool forbid_90deg)
Check if a safe position is free.
void UnreserveRailTrack(TileIndex tile, Track t)
Lift the reservation of a specific track on a tile.
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.
void SetSignalStateByTrackdir(Tile tile, Trackdir trackdir, SignalState state)
Sets the state of the signal along the given trackdir.
bool HasPbsSignalOnTrackdir(Tile tile, Trackdir td)
Is a pbs signal present along the trackdir?
SignalState GetSignalStateByTrackdir(Tile tile, Trackdir trackdir)
Gets the state of the signal along the given trackdir.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
@ SIGNAL_STATE_RED
The signal is red.
@ SIGNAL_STATE_GREEN
The signal is green.
bool IsRailWaypointTile(Tile t)
Is this tile a station tile and a rail waypoint?
bool IsCompatibleTrainStationTile(Tile test_tile, Tile station_tile)
Check if a tile is a valid continuation to a railstation tile.
bool IsRailStationTile(Tile t)
Is this tile a station tile and a rail station?
void SetRailStationReservation(Tile t, bool b)
Set the reservation state of the rail station.
bool HasStationReservation(Tile t)
Get the reservation state of the rail station.
@ PathReservation
Trigger platform when train reserves path.
@ PathReservation
Trigger platform when train reserves path.
static BaseStation * GetByTile(TileIndex tile)
Get the base station belonging to a specific tile.
static int s_rail_change_counter
if any track changes, this counter is incremented - that will invalidate segment cost cache
Class that represents the dump-into-string target.
std::string m_out
the output string
Helper container to find a depot.
bool reverse
True if reversing is necessary for the train to get to this depot.
TileIndex tile
The tile of the depot.
PathfinderSettings pf
settings for all pathfinders
This struct contains information about the end of a reserved path.
Trackdir trackdir
The reserved trackdir on the tile.
TileIndex tile
Tile the path ends, INVALID_TILE if no valid path was found.
bool okay
True if tile is a safe waiting position, false otherwise.
bool forbid_90_deg
forbid trains to make 90 deg turns
T * Last()
Get the last vehicle in the chain.
'Train' is either a loco or a wagon.
Trackdir GetVehicleTrackdir() const override
Get the tracks of the train vehicle.
int32_t y_pos
y coordinate.
int32_t x_pos
x coordinate.
TileIndex tile
Current tile index.
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
Track TrackdirToTrack(Trackdir trackdir)
Returns the Track that a given Trackdir represents.
Trackdir ReverseTrackdir(Trackdir trackdir)
Maps a trackdir to the reverse trackdir.
Track FindFirstTrack(TrackBits tracks)
Returns first Track from TrackBits or INVALID_TRACK.
DiagDirection TrackdirToExitdir(Trackdir trackdir)
Maps a trackdir to the (4-way) direction the tile is exited when following that trackdir.
TrackBits
Allow incrementing of Track variables.
@ TRACK_BIT_WORMHOLE
Bitflag for a wormhole (used for tunnels)
Trackdir
Enumeration for tracks and directions.
@ INVALID_TRACKDIR
Flag for an invalid trackdir.
Track
These are used to specify a single track.
@ INVALID_TRACK
Flag for an invalid track.
DiagDirection GetTunnelBridgeDirection(Tile t)
Get the direction pointing to the other end.
TileIndex GetOtherTunnelBridgeEnd(Tile t)
Determines type of the wormhole and returns its other end.
Base includes/functions for YAPF.
Entry point for OpenTTD to YAPF's cache.
Cost determination for rails.
Determining the destination for rail vehicles.
Node tailored for rail pathfinding.
void YapfNotifyTrackLayoutChange(TileIndex tile, Track track)
Use this function to notify YAPF that track layout (or signal configuration) has change.
bool YapfTrainFindNearestSafeTile(const Train *v, TileIndex tile, Trackdir td, bool override_railtype)
Try to extend the reserved path of a train to the nearest safe tile using YAPF.
Track YapfTrainChooseTrack(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool reserve_track, PBSTileInfo *target, TileIndex *dest)
Finds the best path for given train using YAPF.
FindDepotData YapfTrainFindNearestDepot(const Train *v, int max_penalty)
Used when user sends train to the nearest depot or if train needs servicing using YAPF.
bool YapfTrainCheckReverse(const Train *v)
Returns true if it is better to reverse the train before leaving station using YAPF.