OpenTTD

- Main Page
- Related Pages
- Modules
- Namespaces
- Data Structures
- Files

- File List
- Globals

npf.cpp
Go to the documentation of this file.
1 /* $Id: npf.cpp 27912 2017-09-03 13:06:29Z michi_cc $ */
2
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
8 */
9
12 #include "../../stdafx.h"
13 #include "../../network/network.h"
14 #include "../../viewport_func.h"
15 #include "../../ship.h"
16 #include "../../roadstop_base.h"
17 #include "../pathfinder_func.h"
18 #include "../pathfinder_type.h"
19 #include "../follow_track.hpp"
20 #include "aystar.h"
21
22 #include "../../safeguards.h"
23
24 static const uint NPF_HASH_BITS = 12;
25 /* Do no change below values */
26 static const uint NPF_HASH_SIZE = 1 << NPF_HASH_BITS;
27 static const uint NPF_HASH_HALFBITS = NPF_HASH_BITS / 2;
28 static const uint NPF_HASH_HALFMASK = (1 << NPF_HASH_HALFBITS) - 1;
29
31 struct NPFFindStationOrTileData {
32 TileIndex dest_coords;
33 StationID station_index;
34 bool reserve_path;
35 StationType station_type;
36 bool not_articulated;
37 const Vehicle *v;
38 };
39
41 struct AyStarUserData {
42 Owner owner;
43 TransportType type;
44 RailTypes railtypes;
45 RoadTypes roadtypes;
46 };
47
49 enum AyStarNodeUserDataType {
50 NPF_TRACKDIR_CHOICE = 0,
51 NPF_NODE_FLAGS,
52 };
53
55 enum NPFNodeFlag {
56 NPF_FLAG_SEEN_SIGNAL,
57 NPF_FLAG_2ND_SIGNAL,
58 NPF_FLAG_3RD_SIGNAL,
59 NPF_FLAG_REVERSE,
60 NPF_FLAG_LAST_SIGNAL_RED,
61 NPF_FLAG_LAST_SIGNAL_BLOCK,
62 NPF_FLAG_IGNORE_START_TILE,
63 NPF_FLAG_TARGET_RESERVED,
64 NPF_FLAG_IGNORE_RESERVED,
65 };
66
68 struct NPFFoundTargetData {
69 uint best_bird_dist;
70 uint best_path_dist;
71 Trackdir best_trackdir;
72 AyStarNode node;
73 bool res_okay;
74 };
75
76 static AyStar _npf_aystar;
77
78 /* The cost of each trackdir. A diagonal piece is the full NPF_TILE_LENGTH,
79 * the shorter piece is sqrt(2)/2*NPF_TILE_LENGTH =~ 0.7071
80 */
81 #define NPF_STRAIGHT_LENGTH (uint)(NPF_TILE_LENGTH * STRAIGHT_TRACK_LENGTH)
82 static const uint _trackdir_length[TRACKDIR_END] = {
83 NPF_TILE_LENGTH, NPF_TILE_LENGTH, NPF_STRAIGHT_LENGTH, NPF_STRAIGHT_LENGTH, NPF_STRAIGHT_LENGTH, NPF_STRAIGHT_LENGTH,
84 0, 0,
85 NPF_TILE_LENGTH, NPF_TILE_LENGTH, NPF_STRAIGHT_LENGTH, NPF_STRAIGHT_LENGTH, NPF_STRAIGHT_LENGTH, NPF_STRAIGHT_LENGTH
86 };
87
91 static inline bool NPFGetFlag(const AyStarNode *node, NPFNodeFlag flag)
92 {
93 return HasBit(node->user_data[NPF_NODE_FLAGS], flag);
94 }
95
99 static inline void NPFSetFlag(AyStarNode *node, NPFNodeFlag flag, bool value)
100 {
101 SB(node->user_data[NPF_NODE_FLAGS], flag, 1, value);
102 }
103
110 static uint NPFDistanceTrack(TileIndex t0, TileIndex t1)
111 {
112 const uint dx = Delta(TileX(t0), TileX(t1));
113 const uint dy = Delta(TileY(t0), TileY(t1));
114
115 const uint straightTracks = 2 * min(dx, dy); // The number of straight (not full length) tracks
116 /* OPTIMISATION:
117 * Original: diagTracks = max(dx, dy) - min(dx,dy);
118 * Proof:
119 * (dx+dy) - straightTracks == (min + max) - straightTracks = min + max - 2 * min = max - min */
120 const uint diagTracks = dx + dy - straightTracks; // The number of diagonal (full tile length) tracks.
121
122 /* Don't factor out NPF_TILE_LENGTH below, this will round values and lose
123 * precision */
124 return diagTracks * NPF_TILE_LENGTH + straightTracks * NPF_TILE_LENGTH * STRAIGHT_TRACK_LENGTH;
125 }
126
134 static uint NPFHash(uint key1, uint key2)
135 {
136 /* TODO: think of a better hash? */
137 uint part1 = TileX(key1) & NPF_HASH_HALFMASK;
138 uint part2 = TileY(key1) & NPF_HASH_HALFMASK;
139
140 assert(IsValidTrackdir((Trackdir)key2));
141 assert(IsValidTile(key1));
142 return ((part1 << NPF_HASH_HALFBITS | part2) + (NPF_HASH_SIZE * key2 / TRACKDIR_END)) % NPF_HASH_SIZE;
143 }
144
145 static int32 NPFCalcZero(AyStar *as, AyStarNode *current, OpenListNode *parent)
146 {
147 return 0;
148 }
149
150 /* Calculates the heuristic to the target station or tile. For train stations, it
151 * takes into account the direction of approach.
152 */
153 static int32 NPFCalcStationOrTileHeuristic(AyStar *as, AyStarNode *current, OpenListNode *parent)
154 {
155 NPFFindStationOrTileData *fstd = (NPFFindStationOrTileData*)as->user_target;
156 NPFFoundTargetData *ftd = (NPFFoundTargetData*)as->user_path;
157 TileIndex from = current->tile;
158 TileIndex to = fstd->dest_coords;
159 uint dist;
160 AyStarUserData *user = (AyStarUserData *)as->user_data;
161
162 /* for train-stations, we are going to aim for the closest station tile */
163 if (user->type != TRANSPORT_WATER && fstd->station_index != INVALID_STATION) {
164 to = CalcClosestStationTile(fstd->station_index, from, fstd->station_type);
165 }
166
167 if (user->type == TRANSPORT_ROAD) {
168 /* Since roads only have diagonal pieces, we use manhattan distance here */
169 dist = DistanceManhattan(from, to) * NPF_TILE_LENGTH;
170 } else {
171 /* Ships and trains can also go diagonal, so the minimum distance is shorter */
172 dist = NPFDistanceTrack(from, to);
173 }
174
175 DEBUG(npf, 4, "Calculating H for: (%d, %d). Result: %d", TileX(current->tile), TileY(current->tile), dist);
176
177 if (dist < ftd->best_bird_dist) {
178 ftd->best_bird_dist = dist;
179 ftd->best_trackdir = (Trackdir)current->user_data[NPF_TRACKDIR_CHOICE];
180 }
181 return dist;
182 }
183
184
185 /* Fills AyStarNode.user_data[NPF_TRACKDIRCHOICE] with the chosen direction to
186 * get here, either getting it from the current choice or from the parent's
187 * choice */
188 static void NPFFillTrackdirChoice(AyStarNode *current, OpenListNode *parent)
189 {
190 if (parent->path.parent == NULL) {
191 Trackdir trackdir = current->direction;
192 /* This is a first order decision, so we'd better save the
193 * direction we chose */
194 current->user_data[NPF_TRACKDIR_CHOICE] = trackdir;
195 DEBUG(npf, 6, "Saving trackdir: 0x%X", trackdir);
196 } else {
197 /* We've already made the decision, so just save our parent's decision */
198 current->user_data[NPF_TRACKDIR_CHOICE] = parent->path.node.user_data[NPF_TRACKDIR_CHOICE];
199 }
200 }
201
202 /* Will return the cost of the tunnel. If it is an entry, it will return the
203 * cost of that tile. If the tile is an exit, it will return the tunnel length
204 * including the exit tile. Requires that this is a Tunnel tile */
205 static uint NPFTunnelCost(AyStarNode *current)
206 {
207 DiagDirection exitdir = TrackdirToExitdir(current->direction);
208 TileIndex tile = current->tile;
209 if (GetTunnelBridgeDirection(tile) == ReverseDiagDir(exitdir)) {
210 /* We just popped out if this tunnel, since were
211 * facing the tunnel exit */
212 return NPF_TILE_LENGTH * (GetTunnelBridgeLength(current->tile, GetOtherTunnelEnd(current->tile)) + 1);
213 /* @todo: Penalty for tunnels? */
214 } else {
215 /* We are entering the tunnel, the enter tile is just a
216 * straight track */
217 return NPF_TILE_LENGTH;
218 }
219 }
220
221 static inline uint NPFBridgeCost(AyStarNode *current)
222 {
223 return NPF_TILE_LENGTH * GetTunnelBridgeLength(current->tile, GetOtherBridgeEnd(current->tile));
224 }
225
226 static uint NPFSlopeCost(AyStarNode *current)
227 {
228 TileIndex next = current->tile + TileOffsByDiagDir(TrackdirToExitdir(current->direction));
229
230 /* Get center of tiles */
231 int x1 = TileX(current->tile) * TILE_SIZE + TILE_SIZE / 2;
232 int y1 = TileY(current->tile) * TILE_SIZE + TILE_SIZE / 2;
233 int x2 = TileX(next) * TILE_SIZE + TILE_SIZE / 2;
234 int y2 = TileY(next) * TILE_SIZE + TILE_SIZE / 2;
235
236 int dx4 = (x2 - x1) / 4;
237 int dy4 = (y2 - y1) / 4;
238
239 /* Get the height on both sides of the tile edge.
240 * Avoid testing the height on the tile-center. This will fail for halftile-foundations.
241 */
242 int z1 = GetSlopePixelZ(x1 + dx4, y1 + dy4);
243 int z2 = GetSlopePixelZ(x2 - dx4, y2 - dy4);
244
245 if (z2 - z1 > 1) {
246 /* Slope up */
247 return _settings_game.pf.npf.npf_rail_slope_penalty;
248 }
249 return 0;
250 /* Should we give a bonus for slope down? Probably not, we
251 * could just subtract that bonus from the penalty, because
252 * there is only one level of steepness... */
253 }
254
255 static uint NPFReservedTrackCost(AyStarNode *current)
256 {
257 TileIndex tile = current->tile;
258 TrackBits track = TrackToTrackBits(TrackdirToTrack(current->direction));
259 TrackBits res = GetReservedTrackbits(tile);
260
261 if (NPFGetFlag(current, NPF_FLAG_3RD_SIGNAL) || NPFGetFlag(current, NPF_FLAG_LAST_SIGNAL_BLOCK) || ((res & track) == TRACK_BIT_NONE && !TracksOverlap(res | track))) return 0;
262
263 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
264 DiagDirection exitdir = TrackdirToExitdir(current->direction);
265 if (GetTunnelBridgeDirection(tile) == ReverseDiagDir(exitdir)) {
266 return _settings_game.pf.npf.npf_rail_pbs_cross_penalty * (GetTunnelBridgeLength(tile, GetOtherTunnelBridgeEnd(tile)) + 1);
267 }
268 }
269 return _settings_game.pf.npf.npf_rail_pbs_cross_penalty;
270 }
271
276 static void NPFMarkTile(TileIndex tile)
277 {
278 #ifndef NO_DEBUG_MESSAGES
279 if (_debug_npf_level < 1 || _networking) return;
280 switch (GetTileType(tile)) {
281 case MP_RAILWAY:
282 /* DEBUG: mark visited tiles by mowing the grass under them ;-) */
283 if (!IsRailDepot(tile)) {
284 SetRailGroundType(tile, RAIL_GROUND_BARREN);
285 MarkTileDirtyByTile(tile);
286 }
287 break;
288
289 case MP_ROAD:
290 if (!IsRoadDepot(tile)) {
291 SetRoadside(tile, ROADSIDE_BARREN);
292 MarkTileDirtyByTile(tile);
293 }
294 break;
295
296 default:
297 break;
298 }
299 #endif
300 }
301
302 static int32 NPFWaterPathCost(AyStar *as, AyStarNode *current, OpenListNode *parent)
303 {
304 /* TileIndex tile = current->tile; */
305 int32 cost = 0;
306 Trackdir trackdir = current->direction;
307
308 cost = _trackdir_length[trackdir]; // Should be different for diagonal tracks
309
310 if (IsBuoyTile(current->tile) && IsDiagonalTrackdir(trackdir)) {
311 cost += _settings_game.pf.npf.npf_buoy_penalty; // A small penalty for going over buoys
312 }
313
314 if (current->direction != NextTrackdir((Trackdir)parent->path.node.direction)) {
315 cost += _settings_game.pf.npf.npf_water_curve_penalty;
316 }
317
318 /* @todo More penalties? */
319
320 return cost;
321 }
322
323 /* Determine the cost of this node, for road tracks */
324 static int32 NPFRoadPathCost(AyStar *as, AyStarNode *current, OpenListNode *parent)
325 {
326 TileIndex tile = current->tile;
327 int32 cost = 0;
328
329 /* Determine base length */
330 switch (GetTileType(tile)) {
331 case MP_TUNNELBRIDGE:
332 cost = IsTunnel(tile) ? NPFTunnelCost(current) : NPFBridgeCost(current);
333 break;
334
335 case MP_ROAD:
336 cost = NPF_TILE_LENGTH;
337 /* Increase the cost for level crossings */
338 if (IsLevelCrossing(tile)) cost += _settings_game.pf.npf.npf_crossing_penalty;
339 break;
340
341 case MP_STATION: {
342 cost = NPF_TILE_LENGTH;
343 const RoadStop *rs = RoadStop::GetByTile(tile, GetRoadStopType(tile));
344 if (IsDriveThroughStopTile(tile)) {
345 /* Increase the cost for drive-through road stops */
346 cost += _settings_game.pf.npf.npf_road_drive_through_penalty;
347 DiagDirection dir = TrackdirToExitdir(current->direction);
348 if (!RoadStop::IsDriveThroughRoadStopContinuation(tile, tile - TileOffsByDiagDir(dir))) {
349 /* When we're the first road stop in a 'queue' of them we increase
350 * cost based on the fill percentage of the whole queue. */
351 const RoadStop::Entry *entry = rs->GetEntry(dir);
352 cost += entry->GetOccupied() * _settings_game.pf.npf.npf_road_dt_occupied_penalty / entry->GetLength();
353 }
354 } else {
355 /* Increase cost for filled road stops */
356 cost += _settings_game.pf.npf.npf_road_bay_occupied_penalty * (!rs->IsFreeBay(0) + !rs->IsFreeBay(1)) / 2;
357 }
358 break;
359 }
360
361 default:
362 break;
363 }
364
365 /* Determine extra costs */
366
367 /* Check for slope */
368 cost += NPFSlopeCost(current);
369
370 /* Check for turns. Road vehicles only really drive diagonal, turns are
371 * represented by non-diagonal tracks */
372 if (!IsDiagonalTrackdir(current->direction)) {
373 cost += _settings_game.pf.npf.npf_road_curve_penalty;
374 }
375
376 NPFMarkTile(tile);
377 DEBUG(npf, 4, "Calculating G for: (%d, %d). Result: %d", TileX(current->tile), TileY(current->tile), cost);
378 return cost;
379 }
380
381
382 /* Determine the cost of this node, for railway tracks */
383 static int32 NPFRailPathCost(AyStar *as, AyStarNode *current, OpenListNode *parent)
384 {
385 TileIndex tile = current->tile;
386 Trackdir trackdir = current->direction;
387 int32 cost = 0;
388 /* HACK: We create a OpenListNode manually, so we can call EndNodeCheck */
389 OpenListNode new_node;
390
391 /* Determine base length */
392 switch (GetTileType(tile)) {
393 case MP_TUNNELBRIDGE:
394 cost = IsTunnel(tile) ? NPFTunnelCost(current) : NPFBridgeCost(current);
395 break;
396
397 case MP_RAILWAY:
398 cost = _trackdir_length[trackdir]; // Should be different for diagonal tracks
399 break;
400
401 case MP_ROAD: // Railway crossing
402 cost = NPF_TILE_LENGTH;
403 break;
404
405 case MP_STATION:
406 /* We give a station tile a penalty. Logically we would only want to give
407 * station tiles that are not our destination this penalty. This would
408 * discourage trains to drive through busy stations. But, we can just
409 * give any station tile a penalty, because every possible route will get
410 * this penalty exactly once, on its end tile (if it's a station) and it
411 * will therefore not make a difference. */
412 cost = NPF_TILE_LENGTH + _settings_game.pf.npf.npf_rail_station_penalty;
413
414 if (IsRailWaypoint(tile)) {
415 NPFFindStationOrTileData *fstd = (NPFFindStationOrTileData*)as->user_target;
416 if (fstd->v->current_order.IsType(OT_GOTO_WAYPOINT) && GetStationIndex(tile) == fstd->v->current_order.GetDestination()) {
417 /* This waypoint is our destination; maybe this isn't an unreserved
418 * one, so check that and if so see that as the last signal being
419 * red. This way waypoints near stations should work better. */
420 const Train *train = Train::From(fstd->v);
421 CFollowTrackRail ft(train);
422 TileIndex t = tile;
423 Trackdir td = trackdir;
424 while (ft.Follow(t, td)) {
425 assert(t != ft.m_new_tile);
426 t = ft.m_new_tile;
427 if (KillFirstBit(ft.m_new_td_bits) != TRACKDIR_BIT_NONE) {
428 /* We encountered a junction; it's going to be too complex to
429 * handle this perfectly, so just bail out. There is no simple
430 * free path, so try the other possibilities. */
431 td = INVALID_TRACKDIR;
432 break;
433 }
434 td = RemoveFirstTrackdir(&ft.m_new_td_bits);
435 /* If this is a safe waiting position we're done searching for it */
436 if (IsSafeWaitingPosition(train, t, td, true, _settings_game.pf.forbid_90_deg)) break;
437 }
438 if (td == INVALID_TRACKDIR ||
439 !IsSafeWaitingPosition(train, t, td, true, _settings_game.pf.forbid_90_deg) ||
440 !IsWaitingPositionFree(train, t, td, _settings_game.pf.forbid_90_deg)) {
441 cost += _settings_game.pf.npf.npf_rail_lastred_penalty;
442 }
443 }
444 }
445 break;
446
447 default:
448 break;
449 }
450
451 /* Determine extra costs */
452
453 /* Check for signals */
454 if (IsTileType(tile, MP_RAILWAY)) {
455 if (HasSignalOnTrackdir(tile, trackdir)) {
456 SignalType sigtype = GetSignalType(tile, TrackdirToTrack(trackdir));
457 /* Ordinary track with signals */
458 if (GetSignalStateByTrackdir(tile, trackdir) == SIGNAL_STATE_RED) {
459 /* Signal facing us is red */
460 if (!NPFGetFlag(current, NPF_FLAG_SEEN_SIGNAL)) {
461 /* Penalize the first signal we
462 * encounter, if it is red */
463
464 /* Is this a presignal exit or combo? */
465 if (!IsPbsSignal(sigtype)) {
466 if (sigtype == SIGTYPE_EXIT || sigtype == SIGTYPE_COMBO) {
467 /* Penalise exit and combo signals differently (heavier) */
468 cost += _settings_game.pf.npf.npf_rail_firstred_exit_penalty;
469 } else {
470 cost += _settings_game.pf.npf.npf_rail_firstred_penalty;
471 }
472 }
473 }
474 /* Record the state of this signal. Path signals are assumed to
475 * be green as the signal state of them has no meaning for this. */
476 NPFSetFlag(current, NPF_FLAG_LAST_SIGNAL_RED, !IsPbsSignal(sigtype));
477 } else {
478 /* Record the state of this signal */
479 NPFSetFlag(current, NPF_FLAG_LAST_SIGNAL_RED, false);
480 }
481 if (NPFGetFlag(current, NPF_FLAG_SEEN_SIGNAL)) {
482 if (NPFGetFlag(current, NPF_FLAG_2ND_SIGNAL)) {
483 NPFSetFlag(current, NPF_FLAG_3RD_SIGNAL, true);
484 } else {
485 NPFSetFlag(current, NPF_FLAG_2ND_SIGNAL, true);
486 }
487 } else {
488 NPFSetFlag(current, NPF_FLAG_SEEN_SIGNAL, true);
489 }
490 NPFSetFlag(current, NPF_FLAG_LAST_SIGNAL_BLOCK, !IsPbsSignal(sigtype));
491 }
492
493 if (HasPbsSignalOnTrackdir(tile, ReverseTrackdir(trackdir)) && !NPFGetFlag(current, NPF_FLAG_3RD_SIGNAL)) {
494 cost += _settings_game.pf.npf.npf_rail_pbs_signal_back_penalty;
495 }
496 }
497
498 /* Penalise the tile if it is a target tile and the last signal was
499 * red */
500 /* HACK: We create a new_node here so we can call EndNodeCheck. Ugly as hell
501 * of course... */
502 new_node.path.node = *current;
503 if (as->EndNodeCheck(as, &new_node) == AYSTAR_FOUND_END_NODE && NPFGetFlag(current, NPF_FLAG_LAST_SIGNAL_RED)) {
504 cost += _settings_game.pf.npf.npf_rail_lastred_penalty;
505 }
506
507 /* Check for slope */
508 cost += NPFSlopeCost(current);
509
510 /* Check for turns */
511 if (current->direction != NextTrackdir((Trackdir)parent->path.node.direction)) {
512 cost += _settings_game.pf.npf.npf_rail_curve_penalty;
513 }
514 /* TODO, with realistic acceleration, also the amount of straight track between
515 * curves should be taken into account, as this affects the speed limit. */
516
517 /* Check for reverse in depot */
518 if (IsRailDepotTile(tile) && as->EndNodeCheck(as, &new_node) != AYSTAR_FOUND_END_NODE) {
519 /* Penalise any depot tile that is not the last tile in the path. This
520 * _should_ penalise every occurrence of reversing in a depot (and only
521 * that) */
522 cost += _settings_game.pf.npf.npf_rail_depot_reverse_penalty;
523 }
524
525 /* Check for occupied track */
526 cost += NPFReservedTrackCost(current);
527
528 NPFMarkTile(tile);
529 DEBUG(npf, 4, "Calculating G for: (%d, %d). Result: %d", TileX(current->tile), TileY(current->tile), cost);
530 return cost;
531 }
532
533 /* Will find any depot */
534 static int32 NPFFindDepot(AyStar *as, OpenListNode *current)
535 {
536 AyStarUserData *user = (AyStarUserData *)as->user_data;
537 /* It's not worth caching the result with NPF_FLAG_IS_TARGET here as below,
538 * since checking the cache not that much faster than the actual check */
539 return IsDepotTypeTile(current->path.node.tile, user->type) ?
540 AYSTAR_FOUND_END_NODE : AYSTAR_DONE;
541 }
542
544 static int32 NPFFindSafeTile(AyStar *as, OpenListNode *current)
545 {
546 const Train *v = Train::From(((NPFFindStationOrTileData *)as->user_target)->v);
547
548 return (IsSafeWaitingPosition(v, current->path.node.tile, current->path.node.direction, true, _settings_game.pf.forbid_90_deg) &&
549 IsWaitingPositionFree(v, current->path.node.tile, current->path.node.direction, _settings_game.pf.forbid_90_deg)) ?
550 AYSTAR_FOUND_END_NODE : AYSTAR_DONE;
551 }
552
553 /* Will find a station identified using the NPFFindStationOrTileData */
554 static int32 NPFFindStationOrTile(AyStar *as, OpenListNode *current)
555 {
556 NPFFindStationOrTileData *fstd = (NPFFindStationOrTileData*)as->user_target;
557 AyStarNode *node = &current->path.node;
558 TileIndex tile = node->tile;
559
560 if (fstd->station_index == INVALID_STATION && tile == fstd->dest_coords) return AYSTAR_FOUND_END_NODE;
561
562 if (IsTileType(tile, MP_STATION) && GetStationIndex(tile) == fstd->station_index) {
563 if (fstd->v->type == VEH_TRAIN) return AYSTAR_FOUND_END_NODE;
564
565 assert(fstd->v->type == VEH_ROAD);
566 /* Only if it is a valid station *and* we can stop there */
567 if (GetStationType(tile) == fstd->station_type && (fstd->not_articulated || IsDriveThroughStopTile(tile))) return AYSTAR_FOUND_END_NODE;
568 }
569 return AYSTAR_DONE;
570 }
571
579 static const PathNode *FindSafePosition(PathNode *path, const Train *v)
580 {
581 /* If there is no signal, reserve the whole path. */
582 PathNode *sig = path;
583
584 for (; path->parent != NULL; path = path->parent) {
585 if (IsSafeWaitingPosition(v, path->node.tile, path->node.direction, true, _settings_game.pf.forbid_90_deg)) {
586 sig = path;
587 }
588 }
589
590 return sig;
591 }
592
596 static void ClearPathReservation(const PathNode *start, const PathNode *end)
597 {
598 bool first_run = true;
599 for (; start != end; start = start->parent) {
600 if (IsRailStationTile(start->node.tile) && first_run) {
601 SetRailStationPlatformReservation(start->node.tile, TrackdirToExitdir(start->node.direction), false);
602 } else {
603 UnreserveRailTrack(start->node.tile, TrackdirToTrack(start->node.direction));
604 }
605 first_run = false;
606 }
607 }
608
615 static void NPFSaveTargetData(AyStar *as, OpenListNode *current)
616 {
617 AyStarUserData *user = (AyStarUserData *)as->user_data;
618 NPFFoundTargetData *ftd = (NPFFoundTargetData*)as->user_path;
619 ftd->best_trackdir = (Trackdir)current->path.node.user_data[NPF_TRACKDIR_CHOICE];
620 ftd->best_path_dist = current->g;
621 ftd->best_bird_dist = 0;
622 ftd->node = current->path.node;
623 ftd->res_okay = false;
624
625 if (as->user_target != NULL && ((NPFFindStationOrTileData*)as->user_target)->reserve_path && user->type == TRANSPORT_RAIL) {
626 /* Path reservation is requested. */
627 const Train *v = Train::From(((NPFFindStationOrTileData *)as->user_target)->v);
628
629 const PathNode *target = FindSafePosition(&current->path, v);
630 ftd->node = target->node;
631
632 /* If the target is a station skip to platform end. */
633 if (IsRailStationTile(target->node.tile)) {
634 DiagDirection dir = TrackdirToExitdir(target->node.direction);
635 uint len = Station::GetByTile(target->node.tile)->GetPlatformLength(target->node.tile, dir);
636 TileIndex end_tile = TILE_ADD(target->node.tile, (len - 1) * TileOffsByDiagDir(dir));
637
638 /* Update only end tile, trackdir of a station stays the same. */
639 ftd->node.tile = end_tile;
640 if (!IsWaitingPositionFree(v, end_tile, target->node.direction, _settings_game.pf.forbid_90_deg)) return;
641 SetRailStationPlatformReservation(target->node.tile, dir, true);
642 SetRailStationReservation(target->node.tile, false);
643 } else {
644 if (!IsWaitingPositionFree(v, target->node.tile, target->node.direction, _settings_game.pf.forbid_90_deg)) return;
645 }
646
647 for (const PathNode *cur = target; cur->parent != NULL; cur = cur->parent) {
648 if (!TryReserveRailTrack(cur->node.tile, TrackdirToTrack(cur->node.direction))) {
649 /* Reservation failed, undo. */
650 ClearPathReservation(target, cur);
651 return;
652 }
653 }
654
655 ftd->res_okay = true;
656 }
657 }
658
668 static bool CanEnterTileOwnerCheck(Owner owner, TileIndex tile, DiagDirection enterdir)
669 {
670 if (IsTileType(tile, MP_RAILWAY) || // Rail tile (also rail depot)
671 HasStationTileRail(tile) || // Rail station tile/waypoint
672 IsRoadDepotTile(tile) || // Road depot tile
673 IsStandardRoadStopTile(tile)) { // Road station tile (but not drive-through stops)
674 return IsTileOwner(tile, owner); // You need to own these tiles entirely to use them
675 }
676
677 switch (GetTileType(tile)) {
678 case MP_ROAD:
679 /* rail-road crossing : are we looking at the railway part? */
680 if (IsLevelCrossing(tile) &&
681 DiagDirToAxis(enterdir) != GetCrossingRoadAxis(tile)) {
682 return IsTileOwner(tile, owner); // Railway needs owner check, while the street is public
683 }
684 break;
685
686 case MP_TUNNELBRIDGE:
687 if (GetTunnelBridgeTransportType(tile) == TRANSPORT_RAIL) {
688 return IsTileOwner(tile, owner);
689 }
690 break;
691
692 default:
693 break;
694 }
695
696 return true; // no need to check
697 }
698
699
703 static DiagDirection GetDepotDirection(TileIndex tile, TransportType type)
704 {
705 assert(IsDepotTypeTile(tile, type));
706
707 switch (type) {
708 case TRANSPORT_RAIL: return GetRailDepotDirection(tile);
709 case TRANSPORT_ROAD: return GetRoadDepotDirection(tile);
710 case TRANSPORT_WATER: return GetShipDepotDirection(tile);
711 default: return INVALID_DIAGDIR; // Not reached
712 }
713 }
714
716 static DiagDirection GetSingleTramBit(TileIndex tile)
717 {
718 if (IsNormalRoadTile(tile)) {
719 RoadBits rb = GetRoadBits(tile, ROADTYPE_TRAM);
720 switch (rb) {
721 case ROAD_NW: return DIAGDIR_NW;
722 case ROAD_SW: return DIAGDIR_SW;
723 case ROAD_SE: return DIAGDIR_SE;
724 case ROAD_NE: return DIAGDIR_NE;
725 default: break;
726 }
727 }
728 return INVALID_DIAGDIR;
729 }
730
741 static DiagDirection GetTileSingleEntry(TileIndex tile, TransportType type, uint subtype)
742 {
743 if (type != TRANSPORT_WATER && IsDepotTypeTile(tile, type)) return GetDepotDirection(tile, type);
744
745 if (type == TRANSPORT_ROAD) {
746 if (IsStandardRoadStopTile(tile)) return GetRoadStopDir(tile);
747 if (HasBit(subtype, ROADTYPE_TRAM)) return GetSingleTramBit(tile);
748 }
749
750 return INVALID_DIAGDIR;
751 }
752
762 static inline bool ForceReverse(TileIndex tile, DiagDirection dir, TransportType type, uint subtype)
763 {
764 DiagDirection single_entry = GetTileSingleEntry(tile, type, subtype);
765 return single_entry != INVALID_DIAGDIR && single_entry != dir;
766 }
767
776 static bool CanEnterTile(TileIndex tile, DiagDirection dir, AyStarUserData *user)
777 {
778 /* Check tunnel entries and bridge ramps */
779 if (IsTileType(tile, MP_TUNNELBRIDGE) && GetTunnelBridgeDirection(tile) != dir) return false;
780
781 /* Test ownership */
782 if (!CanEnterTileOwnerCheck(user->owner, tile, dir)) return false;
783
784 /* check correct rail type (mono, maglev, etc) */
785 if (user->type == TRANSPORT_RAIL) {
786 RailType rail_type = GetTileRailType(tile);
787 if (!HasBit(user->railtypes, rail_type)) return false;
788 }
789
790 /* Depots, standard roadstops and single tram bits can only be entered from one direction */
791 DiagDirection single_entry = GetTileSingleEntry(tile, user->type, user->roadtypes);
792 if (single_entry != INVALID_DIAGDIR && single_entry != ReverseDiagDir(dir)) return false;
793
794 return true;
795 }
796
808 static TrackdirBits GetDriveableTrackdirBits(TileIndex dst_tile, Trackdir src_trackdir, TransportType type, uint subtype)
809 {
810 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(GetTileTrackStatus(dst_tile, type, subtype));
811
812 if (trackdirbits == 0 && type == TRANSPORT_ROAD && HasBit(subtype, ROADTYPE_TRAM)) {
813 /* GetTileTrackStatus() returns 0 for single tram bits.
814 * As we cannot change it there (easily) without breaking something, change it here */
815 switch (GetSingleTramBit(dst_tile)) {
816 case DIAGDIR_NE:
817 case DIAGDIR_SW:
818 trackdirbits = TRACKDIR_BIT_X_NE | TRACKDIR_BIT_X_SW;
819 break;
820
821 case DIAGDIR_NW:
822 case DIAGDIR_SE:
823 trackdirbits = TRACKDIR_BIT_Y_NW | TRACKDIR_BIT_Y_SE;
824 break;
825
826 default: break;
827 }
828 }
829
830 DEBUG(npf, 4, "Next node: (%d, %d) [%d], possible trackdirs: 0x%X", TileX(dst_tile), TileY(dst_tile), dst_tile, trackdirbits);
831
832 /* Select only trackdirs we can reach from our current trackdir */
833 trackdirbits &= TrackdirReachesTrackdirs(src_trackdir);
834
835 /* Filter out trackdirs that would make 90 deg turns for trains */
836 if (_settings_game.pf.forbid_90_deg && (type == TRANSPORT_RAIL || type == TRANSPORT_WATER)) trackdirbits &= ~TrackdirCrossesTrackdirs(src_trackdir);
837
838 DEBUG(npf, 6, "After filtering: (%d, %d), possible trackdirs: 0x%X", TileX(dst_tile), TileY(dst_tile), trackdirbits);
839
840 return trackdirbits;
841 }
842
843
844 /* Will just follow the results of GetTileTrackStatus concerning where we can
845 * go and where not. Uses AyStar.user_data[NPF_TYPE] as the transport type and
846 * an argument to GetTileTrackStatus. Will skip tunnels, meaning that the
847 * entry and exit are neighbours. Will fill
848 * AyStarNode.user_data[NPF_TRACKDIR_CHOICE] with an appropriate value, and
849 * copy AyStarNode.user_data[NPF_NODE_FLAGS] from the parent */
850 static void NPFFollowTrack(AyStar *aystar, OpenListNode *current)
851 {
852 AyStarUserData *user = (AyStarUserData *)aystar->user_data;
853 /* We leave src_tile on track src_trackdir in direction src_exitdir */
854 Trackdir src_trackdir = current->path.node.direction;
855 TileIndex src_tile = current->path.node.tile;
856 DiagDirection src_exitdir = TrackdirToExitdir(src_trackdir);
857
858 /* Is src_tile valid, and can be used?
859 * When choosing track on a junction src_tile is the tile neighboured to the junction wrt. exitdir.
860 * But we must not check the validity of this move, as src_tile is totally unrelated to the move, if a roadvehicle reversed on a junction. */
861 bool ignore_src_tile = (current->path.parent == NULL && NPFGetFlag(&current->path.node, NPF_FLAG_IGNORE_START_TILE));
862
863 /* Information about the vehicle: TransportType (road/rail/water) and SubType (compatible rail/road types) */
864 TransportType type = user->type;
865 uint subtype = user->roadtypes;
866
867 /* Initialize to 0, so we can jump out (return) somewhere an have no neighbours */
868 aystar->num_neighbours = 0;
869 DEBUG(npf, 4, "Expanding: (%d, %d, %d) [%d]", TileX(src_tile), TileY(src_tile), src_trackdir, src_tile);
870
871 /* We want to determine the tile we arrive, and which choices we have there */
872 TileIndex dst_tile;
873 TrackdirBits trackdirbits;
874
875 /* Find dest tile */
876 if (ignore_src_tile) {
877 /* Do not perform any checks that involve src_tile */
878 dst_tile = src_tile + TileOffsByDiagDir(src_exitdir);
879 trackdirbits = GetDriveableTrackdirBits(dst_tile, src_trackdir, type, subtype);
880 } else if (IsTileType(src_tile, MP_TUNNELBRIDGE) && GetTunnelBridgeDirection(src_tile) == src_exitdir) {
881 /* We drive through the wormhole and arrive on the other side */
882 dst_tile = GetOtherTunnelBridgeEnd(src_tile);
883 trackdirbits = TrackdirToTrackdirBits(src_trackdir);
884 } else if (ForceReverse(src_tile, src_exitdir, type, subtype)) {
885 /* We can only reverse on this tile */
886 dst_tile = src_tile;
887 src_trackdir = ReverseTrackdir(src_trackdir);
888 trackdirbits = TrackdirToTrackdirBits(src_trackdir);
889 } else {
890 /* We leave src_tile in src_exitdir and reach dst_tile */
891 dst_tile = AddTileIndexDiffCWrap(src_tile, TileIndexDiffCByDiagDir(src_exitdir));
892
893 if (dst_tile != INVALID_TILE && !CanEnterTile(dst_tile, src_exitdir, user)) dst_tile = INVALID_TILE;
894
895 if (dst_tile == INVALID_TILE) {
896 /* We cannot enter the next tile. Road vehicles can reverse, others reach dead end */
897 if (type != TRANSPORT_ROAD || HasBit(subtype, ROADTYPE_TRAM)) return;
898
899 dst_tile = src_tile;
900 src_trackdir = ReverseTrackdir(src_trackdir);
901 }
902
903 trackdirbits = GetDriveableTrackdirBits(dst_tile, src_trackdir, type, subtype);
904
905 if (trackdirbits == 0) {
906 /* We cannot enter the next tile. Road vehicles can reverse, others reach dead end */
907 if (type != TRANSPORT_ROAD || HasBit(subtype, ROADTYPE_TRAM)) return;
908
909 dst_tile = src_tile;
910 src_trackdir = ReverseTrackdir(src_trackdir);
911
912 trackdirbits = GetDriveableTrackdirBits(dst_tile, src_trackdir, type, subtype);
913 }
914 }
915
916 if (NPFGetFlag(&current->path.node, NPF_FLAG_IGNORE_RESERVED)) {
917 /* Mask out any reserved tracks. */
918 TrackBits reserved = GetReservedTrackbits(dst_tile);
919 trackdirbits &= ~TrackBitsToTrackdirBits(reserved);
920
921 Track t;
922 FOR_EACH_SET_TRACK(t, TrackdirBitsToTrackBits(trackdirbits)) {
923 if (TracksOverlap(reserved | TrackToTrackBits(t))) trackdirbits &= ~TrackToTrackdirBits(t);
924 }
925 }
926
927 /* Enumerate possible track */
928 uint i = 0;
929 while (trackdirbits != 0) {
930 Trackdir dst_trackdir = RemoveFirstTrackdir(&trackdirbits);
931 DEBUG(npf, 5, "Expanded into trackdir: %d, remaining trackdirs: 0x%X", dst_trackdir, trackdirbits);
932
933 /* Tile with signals? */
934 if (IsTileType(dst_tile, MP_RAILWAY) && GetRailTileType(dst_tile) == RAIL_TILE_SIGNALS) {
935 if (HasSignalOnTrackdir(dst_tile, ReverseTrackdir(dst_trackdir)) && !HasSignalOnTrackdir(dst_tile, dst_trackdir) && IsOnewaySignal(dst_tile, TrackdirToTrack(dst_trackdir))) {
936 /* If there's a one-way signal not pointing towards us, stop going in this direction. */
937 break;
938 }
939 }
940 {
941 /* We've found ourselves a neighbour :-) */
942 AyStarNode *neighbour = &aystar->neighbours[i];
943 neighbour->tile = dst_tile;
944 neighbour->direction = dst_trackdir;
945 /* Save user data */
946 neighbour->user_data[NPF_NODE_FLAGS] = current->path.node.user_data[NPF_NODE_FLAGS];
947 NPFFillTrackdirChoice(neighbour, current);
948 }
949 i++;
950 }
951 aystar->num_neighbours = i;
952 }
953
954 /*
955 * Plan a route to the specified target (which is checked by target_proc),
956 * from start1 and if not NULL, from start2 as well. The type of transport we
957 * are checking is in type. reverse_penalty is applied to all routes that
958 * originate from the second start node.
959 * When we are looking for one specific target (optionally multiple tiles), we
960 * should use a good heuristic to perform aystar search. When we search for
961 * multiple targets that are spread around, we should perform a breadth first
962 * search by specifiying CalcZero as our heuristic.
963 */
964 static NPFFoundTargetData NPFRouteInternal(AyStarNode *start1, bool ignore_start_tile1, AyStarNode *start2, bool ignore_start_tile2, NPFFindStationOrTileData *target, AyStar_EndNodeCheck target_proc, AyStar_CalculateH heuristic_proc, AyStarUserData *user, uint reverse_penalty, bool ignore_reserved = false)
965 {
966 int r;
967 NPFFoundTargetData result;
968
969 /* Initialize procs */
970 _npf_aystar.CalculateH = heuristic_proc;
971 _npf_aystar.EndNodeCheck = target_proc;
972 _npf_aystar.FoundEndNode = NPFSaveTargetData;
973 _npf_aystar.GetNeighbours = NPFFollowTrack;
974 switch (user->type) {
975 default: NOT_REACHED();
976 case TRANSPORT_RAIL: _npf_aystar.CalculateG = NPFRailPathCost; break;
977 case TRANSPORT_ROAD: _npf_aystar.CalculateG = NPFRoadPathCost; break;
978 case TRANSPORT_WATER: _npf_aystar.CalculateG = NPFWaterPathCost; break;
979 }
980
981 /* Initialize Start Node(s) */
982 start1->user_data[NPF_TRACKDIR_CHOICE] = INVALID_TRACKDIR;
983 start1->user_data[NPF_NODE_FLAGS] = 0;
984 NPFSetFlag(start1, NPF_FLAG_IGNORE_START_TILE, ignore_start_tile1);
985 NPFSetFlag(start1, NPF_FLAG_IGNORE_RESERVED, ignore_reserved);
986 _npf_aystar.AddStartNode(start1, 0);
987 if (start2 != NULL) {
988 start2->user_data[NPF_TRACKDIR_CHOICE] = INVALID_TRACKDIR;
989 start2->user_data[NPF_NODE_FLAGS] = 0;
990 NPFSetFlag(start2, NPF_FLAG_IGNORE_START_TILE, ignore_start_tile2);
991 NPFSetFlag(start2, NPF_FLAG_REVERSE, true);
992 NPFSetFlag(start2, NPF_FLAG_IGNORE_RESERVED, ignore_reserved);
993 _npf_aystar.AddStartNode(start2, reverse_penalty);
994 }
995
996 /* Initialize result */
997 result.best_bird_dist = UINT_MAX;
998 result.best_path_dist = UINT_MAX;
999 result.best_trackdir = INVALID_TRACKDIR;
1000 result.node.tile = INVALID_TILE;
1001 result.res_okay = false;
1002 _npf_aystar.user_path = &result;
1003
1004 /* Initialize target */
1005 _npf_aystar.user_target = target;
1006
1007 /* Initialize user_data */
1008 _npf_aystar.user_data = user;
1009
1010 /* GO! */
1011 r = _npf_aystar.Main();
1012 assert(r != AYSTAR_STILL_BUSY);
1013
1014 if (result.best_bird_dist != 0) {
1015 if (target != NULL) {
1016 DEBUG(npf, 1, "Could not find route to tile 0x%X from 0x%X.", target->dest_coords, start1->tile);
1017 } else {
1018 /* Assumption: target == NULL, so we are looking for a depot */
1019 DEBUG(npf, 1, "Could not find route to a depot from tile 0x%X.", start1->tile);
1020 }
1021
1022 }
1023 return result;
1024 }
1025
1026 /* Will search as below, but with two start nodes, the second being the
1027 * reverse. Look at the NPF_FLAG_REVERSE flag in the result node to see which
1028 * direction was taken (NPFGetFlag(result.node, NPF_FLAG_REVERSE)) */
1029 static NPFFoundTargetData NPFRouteToStationOrTileTwoWay(TileIndex tile1, Trackdir trackdir1, bool ignore_start_tile1, TileIndex tile2, Trackdir trackdir2, bool ignore_start_tile2, NPFFindStationOrTileData *target, AyStarUserData *user)
1030 {
1031 AyStarNode start1;
1032 AyStarNode start2;
1033
1034 start1.tile = tile1;
1035 start2.tile = tile2;
1036 start1.direction = trackdir1;
1037 start2.direction = trackdir2;
1038
1039 return NPFRouteInternal(&start1, ignore_start_tile1, (IsValidTile(tile2) ? &start2 : NULL), ignore_start_tile2, target, NPFFindStationOrTile, NPFCalcStationOrTileHeuristic, user, 0);
1040 }
1041
1042 /* Will search from the given tile and direction, for a route to the given
1043 * station for the given transport type. See the declaration of
1044 * NPFFoundTargetData above for the meaning of the result. */
1045 static NPFFoundTargetData NPFRouteToStationOrTile(TileIndex tile, Trackdir trackdir, bool ignore_start_tile, NPFFindStationOrTileData *target, AyStarUserData *user)
1046 {
1047 return NPFRouteToStationOrTileTwoWay(tile, trackdir, ignore_start_tile, INVALID_TILE, INVALID_TRACKDIR, false, target, user);
1048 }
1049
1050 /* Search using breadth first. Good for little track choice and inaccurate
1051 * heuristic, such as railway/road with two start nodes, the second being the reverse. Call
1052 * NPFGetFlag(result.node, NPF_FLAG_REVERSE) to see from which node the path
1053 * originated. All paths from the second node will have the given
1054 * reverse_penalty applied (NPF_TILE_LENGTH is the equivalent of one full
1055 * tile).
1056 */
1057 static NPFFoundTargetData NPFRouteToDepotBreadthFirstTwoWay(TileIndex tile1, Trackdir trackdir1, bool ignore_start_tile1, TileIndex tile2, Trackdir trackdir2, bool ignore_start_tile2, NPFFindStationOrTileData *target, AyStarUserData *user, uint reverse_penalty)
1058 {
1059 AyStarNode start1;
1060 AyStarNode start2;
1061
1062 start1.tile = tile1;
1063 start2.tile = tile2;
1064 start1.direction = trackdir1;
1065 start2.direction = trackdir2;
1066
1067 /* perform a breadth first search. Target is NULL,
1068 * since we are just looking for any depot...*/
1069 return NPFRouteInternal(&start1, ignore_start_tile1, (IsValidTile(tile2) ? &start2 : NULL), ignore_start_tile2, target, NPFFindDepot, NPFCalcZero, user, reverse_penalty);
1070 }
1071
1072 void InitializeNPF()
1073 {
1074 static bool first_init = true;
1075 if (first_init) {
1076 first_init = false;
1077 _npf_aystar.Init(NPFHash, NPF_HASH_SIZE);
1078 } else {
1079 _npf_aystar.Clear();
1080 }
1081 _npf_aystar.loops_per_tick = 0;
1082 _npf_aystar.max_path_cost = 0;
1083 //_npf_aystar.max_search_nodes = 0;
1084 /* We will limit the number of nodes for now, until we have a better
1085 * solution to really fix performance */
1086 _npf_aystar.max_search_nodes = _settings_game.pf.npf.npf_max_search_nodes;
1087 }
1088
1089 static void NPFFillWithOrderData(NPFFindStationOrTileData *fstd, const Vehicle *v, bool reserve_path = false)
1090 {
1091 /* Ships don't really reach their stations, but the tile in front. So don't
1092 * save the station id for ships. For roadvehs we don't store it either,
1093 * because multistop depends on vehicles actually reaching the exact
1094 * dest_tile, not just any stop of that station.
1095 * So only for train orders to stations we fill fstd->station_index, for all
1096 * others only dest_coords */
1097 if (v->type != VEH_SHIP && (v->current_order.IsType(OT_GOTO_STATION) || v->current_order.IsType(OT_GOTO_WAYPOINT))) {
1098 assert(v->IsGroundVehicle());
1099 fstd->station_index = v->current_order.GetDestination();
1100 fstd->station_type = (v->type == VEH_TRAIN) ? (v->current_order.IsType(OT_GOTO_STATION) ? STATION_RAIL : STATION_WAYPOINT) : (RoadVehicle::From(v)->IsBus() ? STATION_BUS : STATION_TRUCK);
1101 fstd->not_articulated = v->type == VEH_ROAD && !RoadVehicle::From(v)->HasArticulatedPart();
1102 /* Let's take the closest tile of the station as our target for vehicles */
1103 fstd->dest_coords = CalcClosestStationTile(fstd->station_index, v->tile, fstd->station_type);
1104 } else {
1105 fstd->dest_coords = v->dest_tile;
1106 fstd->station_index = INVALID_STATION;
1107 }
1108 fstd->reserve_path = reserve_path;
1109 fstd->v = v;
1110 }
1111
1112 /*** Road vehicles ***/
1113
1114 FindDepotData NPFRoadVehicleFindNearestDepot(const RoadVehicle *v, int max_penalty)
1115 {
1116 Trackdir trackdir = v->GetVehicleTrackdir();
1117
1118 AyStarUserData user = { v->owner, TRANSPORT_ROAD, INVALID_RAILTYPES, v->compatible_roadtypes };
1119 NPFFoundTargetData ftd = NPFRouteToDepotBreadthFirstTwoWay(v->tile, trackdir, false, v->tile, ReverseTrackdir(trackdir), false, NULL, &user, 0);
1120
1121 if (ftd.best_bird_dist != 0) return FindDepotData();
1122
1123 /* Found target */
1124 /* Our caller expects a number of tiles, so we just approximate that
1125 * number by this. It might not be completely what we want, but it will
1126 * work for now :-) We can possibly change this when the old pathfinder
1127 * is removed. */
1128 return FindDepotData(ftd.node.tile, ftd.best_path_dist);
1129 }
1130
1131 Trackdir NPFRoadVehicleChooseTrack(const RoadVehicle *v, TileIndex tile, DiagDirection enterdir, TrackdirBits trackdirs, bool &path_found)
1132 {
1133 NPFFindStationOrTileData fstd;
1134
1135 NPFFillWithOrderData(&fstd, v);
1136 Trackdir trackdir = DiagDirToDiagTrackdir(enterdir);
1137
1138 AyStarUserData user = { v->owner, TRANSPORT_ROAD, INVALID_RAILTYPES, v->compatible_roadtypes };
1139 NPFFoundTargetData ftd = NPFRouteToStationOrTile(tile - TileOffsByDiagDir(enterdir), trackdir, true, &fstd, &user);
1140 if (ftd.best_trackdir == INVALID_TRACKDIR) {
1141 /* We are already at our target. Just do something
1142 * @todo: maybe display error?
1143 * @todo: go straight ahead if possible? */
1144 path_found = true;
1145 return (Trackdir)FindFirstBit2x64(trackdirs);
1146 }
1147
1148 /* If ftd.best_bird_dist is 0, we found our target and ftd.best_trackdir contains
1149 * the direction we need to take to get there, if ftd.best_bird_dist is not 0,
1150 * we did not find our target, but ftd.best_trackdir contains the direction leading
1151 * to the tile closest to our target. */
1152 path_found = (ftd.best_bird_dist == 0);
1153 return ftd.best_trackdir;
1154 }
1155
1156 /*** Ships ***/
1157
1158 Track NPFShipChooseTrack(const Ship *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found)
1159 {
1160 NPFFindStationOrTileData fstd;
1161 Trackdir trackdir = v->GetVehicleTrackdir();
1162 assert(trackdir != INVALID_TRACKDIR); // Check that we are not in a depot
1163
1164 NPFFillWithOrderData(&fstd, v);
1165
1166 AyStarUserData user = { v->owner, TRANSPORT_WATER, INVALID_RAILTYPES, ROADTYPES_NONE };
1167 NPFFoundTargetData ftd = NPFRouteToStationOrTile(tile - TileOffsByDiagDir(enterdir), trackdir, true, &fstd, &user);
1168
1169 /* If ftd.best_bird_dist is 0, we found our target and ftd.best_trackdir contains
1170 * the direction we need to take to get there, if ftd.best_bird_dist is not 0,
1171 * we did not find our target, but ftd.best_trackdir contains the direction leading
1172 * to the tile closest to our target. */
1173 path_found = (ftd.best_bird_dist == 0);
1174 if (ftd.best_trackdir == 0xff) return INVALID_TRACK;
1175 return TrackdirToTrack(ftd.best_trackdir);
1176 }
1177
1178 bool NPFShipCheckReverse(const Ship *v)
1179 {
1180 NPFFindStationOrTileData fstd;
1181 NPFFoundTargetData ftd;
1182
1183 NPFFillWithOrderData(&fstd, v);
1184
1185 Trackdir trackdir = v->GetVehicleTrackdir();
1186 Trackdir trackdir_rev = ReverseTrackdir(trackdir);
1187 assert(trackdir != INVALID_TRACKDIR);
1188 assert(trackdir_rev != INVALID_TRACKDIR);
1189
1190 AyStarUserData user = { v->owner, TRANSPORT_WATER, INVALID_RAILTYPES, ROADTYPES_NONE };
1191 ftd = NPFRouteToStationOrTileTwoWay(v->tile, trackdir, false, v->tile, trackdir_rev, false, &fstd, &user);
1192 /* If we didn't find anything, just keep on going straight ahead, otherwise take the reverse flag */
1193 return ftd.best_bird_dist == 0 && NPFGetFlag(&ftd.node, NPF_FLAG_REVERSE);
1194 }
1195
1196 /*** Trains ***/
1197
1198 FindDepotData NPFTrainFindNearestDepot(const Train *v, int max_penalty)
1199 {
1200 const Train *last = v->Last();
1201 Trackdir trackdir = v->GetVehicleTrackdir();
1202 Trackdir trackdir_rev = ReverseTrackdir(last->GetVehicleTrackdir());
1203 NPFFindStationOrTileData fstd;
1204 fstd.v = v;
1205 fstd.reserve_path = false;
1206
1207 assert(trackdir != INVALID_TRACKDIR);
1208 AyStarUserData user = { v->owner, TRANSPORT_RAIL, v->compatible_railtypes, ROADTYPES_NONE };
1209 NPFFoundTargetData ftd = NPFRouteToDepotBreadthFirstTwoWay(v->tile, trackdir, false, last->tile, trackdir_rev, false, &fstd, &user, NPF_INFINITE_PENALTY);
1210 if (ftd.best_bird_dist != 0) return FindDepotData();
1211
1212 /* Found target */
1213 /* Our caller expects a number of tiles, so we just approximate that
1214 * number by this. It might not be completely what we want, but it will
1215 * work for now :-) We can possibly change this when the old pathfinder
1216 * is removed. */
1217 return FindDepotData(ftd.node.tile, ftd.best_path_dist, NPFGetFlag(&ftd.node, NPF_FLAG_REVERSE));
1218 }
1219
1220 bool NPFTrainFindNearestSafeTile(const Train *v, TileIndex tile, Trackdir trackdir, bool override_railtype)
1221 {
1222 assert(v->type == VEH_TRAIN);
1223
1224 NPFFindStationOrTileData fstd;
1225 fstd.v = v;
1226 fstd.reserve_path = true;
1227
1228 AyStarNode start1;
1229 start1.tile = tile;
1230 start1.direction = trackdir;
1231
1232 RailTypes railtypes = v->compatible_railtypes;
1233 if (override_railtype) railtypes |= GetRailTypeInfo(v->railtype)->compatible_railtypes;
1234
1235 /* perform a breadth first search. Target is NULL,
1236 * since we are just looking for any safe tile...*/
1237 AyStarUserData user = { v->owner, TRANSPORT_RAIL, railtypes, ROADTYPES_NONE };
1238 return NPFRouteInternal(&start1, true, NULL, false, &fstd, NPFFindSafeTile, NPFCalcZero, &user, 0, true).res_okay;
1239 }
1240
1241 bool NPFTrainCheckReverse(const Train *v)
1242 {
1243 NPFFindStationOrTileData fstd;
1244 NPFFoundTargetData ftd;
1245 const Train *last = v->Last();
1246
1247 NPFFillWithOrderData(&fstd, v);
1248
1249 Trackdir trackdir = v->GetVehicleTrackdir();
1250 Trackdir trackdir_rev = ReverseTrackdir(last->GetVehicleTrackdir());
1251 assert(trackdir != INVALID_TRACKDIR);
1252 assert(trackdir_rev != INVALID_TRACKDIR);
1253
1254 AyStarUserData user = { v->owner, TRANSPORT_RAIL, v->compatible_railtypes, ROADTYPES_NONE };
1255 ftd = NPFRouteToStationOrTileTwoWay(v->tile, trackdir, false, last->tile, trackdir_rev, false, &fstd, &user);
1256 /* If we didn't find anything, just keep on going straight ahead, otherwise take the reverse flag */
1257 return ftd.best_bird_dist == 0 && NPFGetFlag(&ftd.node, NPF_FLAG_REVERSE);
1258 }
1259
1260 Track NPFTrainChooseTrack(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool reserve_track, struct PBSTileInfo *target)
1261 {
1262 NPFFindStationOrTileData fstd;
1263 NPFFillWithOrderData(&fstd, v, reserve_track);
1264
1265 PBSTileInfo origin = FollowTrainReservation(v);
1266 assert(IsValidTrackdir(origin.trackdir));
1267
1268 AyStarUserData user = { v->owner, TRANSPORT_RAIL, v->compatible_railtypes, ROADTYPES_NONE };
1269 NPFFoundTargetData ftd = NPFRouteToStationOrTile(origin.tile, origin.trackdir, true, &fstd, &user);
1270
1271 if (target != NULL) {
1272 target->tile = ftd.node.tile;
1273 target->trackdir = (Trackdir)ftd.node.direction;
1274 target->okay = ftd.res_okay;
1275 }
1276
1277 if (ftd.best_trackdir == INVALID_TRACKDIR) {
1278 /* We are already at our target. Just do something
1279 * @todo maybe display error?
1280 * @todo: go straight ahead if possible? */
1281 path_found = true;
1282 return FindFirstTrack(tracks);
1283 }
1284
1285 /* If ftd.best_bird_dist is 0, we found our target and ftd.best_trackdir contains
1286 * the direction we need to take to get there, if ftd.best_bird_dist is not 0,
1287 * we did not find our target, but ftd.best_trackdir contains the direction leading
1288 * to the tile closest to our target. */
1289 path_found = (ftd.best_bird_dist == 0);
1290 /* Discard enterdir information, making it a normal track */
1291 return TrackdirToTrack(ftd.best_trackdir);
1292 }