r/roguelikedev • u/Kyzrati Cogmind | mastodon.gamedev.place/@Kyzrati • Nov 13 '15
FAQ Friday #25: Pathfinding
In FAQ Friday we ask a question (or set of related questions) of all the roguelike devs here and discuss the responses! This will give new devs insight into the many aspects of roguelike development, and experienced devs can share details and field questions about their methods, technical achievements, design philosophy, etc.
THIS WEEK: Pathfinding
We've already somewhat covered this topic with our AI FAQ, as pathfinding and AI are often intertwined, but we're revisiting it in more detail by request, and also because there really is a lot of depth to explore in this area. For this week rather than come up with a two-word title that would unnecessarily narrow down our topic, I decided it was best to simply call it "Pathfinding" to keep the discussion as broad and inclusive as it can be.
There are quite a number of unique but relevant angles to approach pathfinding in roguelikes. We can look at the basic technical requirements behind implementing various types of pathfinding (there are lots of them out there), common problems and possible solutions, unique applications for pathfinding in AI and even game mechanics themselves, etc.
With the latter category, for example, Brogue's much discussed Dijkstra maps have a wide array of applications, and are derived from from pathfinding techniques which affect mob movement. Those uses are essentially types of "influence maps," a very useful concept from RTS development.
What types of pathfinding techniques do you use? How do you use them? What kinds of problems have you encountered or solved via pathfinding? (Nothing is too simple!) Specific examples?
Keep in mind that "pathfinding" is used here in the most general sense--not simply about moving a creature from point A to B, but may include other interesting applications in any other part of the game, either currently in use or planned for the future.
(Also, please add screenshots/diagrams where possible!)
For those of you in search of background/learning material, Amit Patel's site is an excellent resource for understanding pathfinding. Heaps of explanations and informative diagrams, along with fancy interactive web demos :D
For readers new to this bi-weekly event (or roguelike development in general), check out the previous FAQ Fridays:
- #1: Languages and Libraries
- #2: Development Tools
- #3: The Game Loop
- #4: World Architecture
- #5: Data Management
- #6: Content Creation and Balance
- #7: Loot
- #8: Core Mechanic
- #9: Debugging
- #10: Project Management
- #11: Random Number Generation
- #12: Field of Vision
- #13: Geometry
- #14: Inspiration
- #15: AI
- #16: UI Design
- #17: UI Implementation
- #18: Input Handling
- #19: Permadeath
- #20: Saving
- #21: Morgue Files
- #22: Map Generation
- #23: Map Design
- #24: World Structure
PM me to suggest topics you'd like covered in FAQ Friday. Of course, you are always free to ask whatever questions you like whenever by posting them on /r/roguelikedev, but concentrating topical discussion in one place on a predictable date is a nice format! (Plus it can be a useful resource for others searching the sub.)
8
u/Kyzrati Cogmind | mastodon.gamedev.place/@Kyzrati Nov 13 '15
Occasionally I wonder if I should put some time into applying optimized A* variants like the newer JPS, but the efficiency of most optimizations can't be taken advantage of without static maps, and I don't believe I'll ever make a game that doesn't have very destructible maps. As such, I need the most versatile pathfinding solution possible, preferably one that can also be applied to virtually any game I'd make. So over a decade ago I started with good old A*, and that same implementation has been at the core of my pathfinding library used for every game I've made over the past 10 years (since before my personal Age of Roguelikes). It uses Manhattan distance to the goal as the heuristic, and search data is sorted in a binary heap.
I've never had to tweak the core of the library much, but its features have been expanded significantly over the years to satisfy new use cases. It supports standard cardinal and 8-direction movement, as well as arbitrary teleportation between any points defined by the game world as having a valid connection. Most importantly, it makes use of the most powerful component of a versatile pathfinding solution: Callbacks!
To me the most useful pathfinding class is one that is completely segregated from the game logic, dealing in nothing but analysis of point connections and the costs to travel between them, enabling a single class to be applied across a huge range of situations. Callbacks are the key to this capability.
When instructed to calculate a path this ultimate pathfinder ("Cartographer") doesn't ask for much, only the starting point and goal, who or what is doing the moving, a callback that defines the search behavior, and a place to store the result.
All of this is generic info. (For those versed in the language, notice the void* pointer and know that the callback type is an abstract class.) The game can create different callbacks that define different search behaviors, and provide the desired callback when asking for a path to a particular goal. Each type of callback can calculate movement costs differently depending on who is moving and what they're moving through/past, or even prevent some movers from going through certain areas at all (locked doors to which they have no key? rooms that are off-limits for other reasons?).
Using callbacks does slow down the whole pathfinding process compared to having a more hard-coded solution, but it significantly speeds up development and allows for much greater versatility in paths, so it's worth the sacrifice.
In Cogmind specifically, I use A* pathfinding to:
With Cogmind I finally formalized my Dijkstra implementation as part of the pathfinding library, too--before that I was coding makeshift Dijkstra-style searches every time I needed one, which eventually got annoying. Dijkstra is essentially the same thing as A* without heuristics, but combined with callbacks this same "pathfinding" method can be used to achieve all sorts of effects, even applying values throughout an area.
Common uses of Dijkstra in Cogmind:
Optimization
Pathfinding is easily the single most CPU intensive process in Cogmind (and many other games). Right now 47% of the CPU cycles are spent calculating paths!
Don't get too hung up on the specific number--it can vary by a good bit depending the circumstances of the testing, but in any case it's a lot! So if things ever start getting sluggish, the first candidate for optimization is naturally pathfinding :). I've done this several times throughout pre-alpha (and once during alpha, I believe).
That said, having been refined for years the pathfinding method doesn't have much room to improve in terms of performance, at least not while keeping the same level of functionality and flexibility. There comes a point where you can't really make the pathfinding routine itself faster, and instead need to think of other tricks to increase efficiency. Pathfinding code is also quite complex compared to the alternative: Just don't do as much pathfinding! Always try to reuse old/precalculated paths where possible, reduce the frequency of recalculations by being a little more lenient with the circumstances under which detours are required, etc.
Another optimization I added is completely outside the pathfinder itself: Before even using A*, the game will check whether there is an open direct Bresenham line to the target, and use that as the path if possible. These lines are very quick to calculate, and have the added advantage of following more realistic paths to nearby targets. (I could move this feature inside the pathfinder, but it's a more recent optimization so it doesn't yet get promoted to full library status =p)
The player's own pathfinding uses an even more advanced version of this, attempting to constantly update a currently-followed A* path by checking for a direct Bresenham line between the current position and last visible point on that path. If a more direct route is found, the path is updated in real time. This is way too time-consuming a process to apply to all entities so it's only used for the player, but it makes for really nice paths :D
6
u/aaron_ds Robinson Nov 13 '15
Robinson uses bog standard A* pathfinding for npcs. The library I use is a forked version of clj-tiny-astar and the code is so short that I'll just link to it here. Clojure has pretty lax rules for naming so the function is literally nammed a*.
The a* function, in addition to taking a start and end position, also takes a distance function and a blocking predicate so the library doesn't assume manhattan distance or euclidean distance, it's up to the user to specify what they want. The predicate function is called with (x, y) values and returns true if the tile @ (x, y) blocks movement. It's that simple. It returns a list of (x, y)s from the start to end positions if a path exists.
Since a* isn't exactly fast for large maps I use a lot of tricks to try and do as few a* calculations as possible. It helps that most animals are rather dumb in real life so I can play the simulationist card and get away with quite a lot. For one, npcs have to be within a certain range to try to find a path to the player. Outside of this range, npcs move randomly.
Furthermore, the a* search area is bounded, so that even though there might be a meandering path from the npc to the player, if it exceeds the bounded area it's invisible to the a* algorithm. In practice, this means this once you're out of sight of an npc, you're probably pretty safe.
I've also left myself the ability to evaluate pathfinding in parallel and then execute the steps in serial starting from the npcs closest to the player and moving outward. It turns out there are some worst-case scenarios, but they tend not to occur due to the npcs marching toward the player in almost all cases.
It's not really all that impressive, but it works and I'm happy with it. :)
5
u/Aukustus The Temple of Torment & Realms of the Lost Nov 13 '15
The Temple of Torment
I use the stock libtcod A* for every AI, and also for the mouse movement for the player. I like the A* because it looks more realistic than Dijkstra.
The pathfinding is calculated from the start every turn wholly, I believe this might be very expensive for the CPU, but there was an issue with monsters not being able to take into account other monsters, they tried to use the same paths in small corridors so I had to calculate it from the beginning every turn for every monster by making other monsters look like wall in the pathfinding calculation so they can easily the alternative paths if other monsters are in the way.
Before updating into the A* I used a custom pathfinding made by myself that was essentially a long series of if-clauses. It actually did work and monsters were able to navigate in small situations, for example in a room with 4 other monsters. There was an issue with longer routes though.
This might tie into the FOV somewhat, but the path used for the monsters is calculated from the thought that the monsters do know the dungeon thoroughly so they use routes that players have not explored. They can ambush the player from behind if they take alternative routes. Friendly AI pathfinding is calculated from the player's FOV and what the player has explored. Allies won't take alternative routes even though if they exist, because player hasn't seen them.
5
u/thebracket Nov 13 '15
The timing on this one couldn't be better, since that's the next item on my to-do list (once the flu lets me think straight!). Black Future already has some path-finding, and is about to gain a whole lot more:
void line_func ( int x1, int y1, const int x2, const int y2, std::function<void ( int,int ) > func );. Combined with an angle sweep, that's how I do field-of-view.5
u/ais523 NetHack, NetHack 4 Nov 14 '15 edited Nov 14 '15
Sorry for not responding earlier; I was ill. Hopefully even a late reply can shed some light on some of the earlier pathfinding algorithms in Roguelikes (NetHack's, and the variants that copied from them).
The first, perhaps surprising, thing to note is that monsters in NetHack 3.4.3 have no pathfinding code of their own. When a monster in 3.4.3 wants to pathfind, it has two options. If it's aiming for the player, and the player has been through that area recently, it follows the path the player took (or attempts to; the code is very buggy, and likely produces the wrong answer more than half the time). Otherwise, it considers the 8 squares around it, and picks whichever pathable one is closest to the player. This also seems to work on perfect knowledge of the player's actual location, and happens even when the player is well out of LOS. If you use a potion of monster detection to observe hostile monsters moving around at the other end of the map, you'll notice that it's a very artificial and implausible sort of movement. The lack of monster pathfinding is also the main reason why pets keep getting separated from the player (people have commented on how much better pets follow in NetHack 4).
For player travel, the game uses an algorithm that's basically equivalent to Dijkstra's algorithm. The game has two working arrays. First it stores all the squares that can be reached in one step in one of the arrays; then the squares that can be reached in two steps in the other array; then all the squares that can be reached in three steps in the first array; and so on. (This way, it has the previous distance's information available when it calculates the next distance.) Incidentally, NetHack 4 uses a cut-down version of this algorithm for monster pathing (and paths monsters who are unaware of the player's location to random squares, changing when they reach their destination or get stuck, which looks a lot more realistic than aiming for the player.)
I notice other devs talking about performance issues with travel. Travel is one of only three points in NetHack 4's code that have ever needed performance optimization to save CPU cycles due to the code running too slowly (the other two were quadratic algorithms in the save restoring code). However, it was easily fixed with a bit of loop-invariant code motion (anything that was previously being calculated every step of the travel algorithm, but that comes to the same value each time, is simply calculated once at the start of the loop instead).
Although simple, there are actually at least two bugs in the travel algorithm, both of which took years to pin down. (/u/wheals, you say that DCSS has stolen NetHack's travel algorithm? It might be worth checking to see if they're still there; unlikely after all the work DCSS has done, but you never know.)
The first was that travel can sometimes get into a loop (sometimes ending only when the player fainted from hunger). This had been observed in the wild on a couple of times, but nobody knew what was causing it. Eventually tungtn figured it out, and left the following, very clear, explanation along with the fix:
In other words, NetHack attempts to travel as near as possible to a square if there's no known route to it, but whether it knows a route to the square or not depends on where the player is on the map, so you can get a situation where the routes from any particular squares aren't consistent with each other. NetHack doesn't remember its planned route from one turn to the next, so that happens.
The other bug, I discovered by accident when working on AceHack. You know how I said that the game stores reachability after one action, two actions, three actions, and so on? Well, the game does this with a list of squares that are reached in the given time, and some squares (e.g. closed doors and boulders) are counted as three actions rather than one. If a square is on the first or second of its three actions, then it gets added back at the same square, rather than looking at the adjacent directions. Unfortunately, this is accidentally done inside the loop that checks adjacent directions, so the square gets added back at the same place eight times, rather than once. As a result, by the third of the actions (when the game checks adjacent squares), the square has been added sixty-four times. Now, the game expects duplicates when looking at adjacent squares, so this duplication only lasts for one action. However, if you get enough closed doors or boulders equidistant from the origin of pathing, then the 64 duplications of each of those are enough to overflow the array. (In AceHack, the bug is much easier to reproduce, because lava works the same way there. The simplest, and only known, reproduction in 3.4.3 involves finding a very open level and filling it pretty much entirely full with boulders.)
As mentioned above, NetHack 4 differs from NetHack 3.4.3 in that monsters can pathfind. Another difference is the implementation of autoexplore; this basically works by adapting the travel location "guessing" algorithm to find an unexplored square, rather than a square near the (nonexistent) travel target.
In other roguelike pathfinding-related news, I have a much more efficient roguelike pathfinding algorithm lying around somewhere, which I created for TAEB, and which I'm quite proud of (it doesn't have anything to do with NetHack, other than that TAEB is a roguelike AI that plays NetHack). The basic idea is to find chokepoints or near-chokepoints on the map, then run pathing between only those points, and more localized pathing on the area around them when required. This means that it's possible to have an optimized structure that quickly answers many pathfinding questions on one map, but that when the map changes or you learn more about it (as often happens in roguelikes), you only have to redo a small proportion of your pathing structures, rather than the whole thing. There isn't much documented about it yet, and the original hosting of the code has long since vanished from the Internet, but it seems like someone mirrored it here. Unfortunately it's pretty tightly intertwined with the rest of the logic. Perhaps some day I'll rip it out into a stand-alone module. (And/or write a paper about it; I'm quite fond of the algorithm, although I haven't checked the literature yet to see if anything else like it has been tried.)
4
u/wheals DCSS Nov 13 '15 edited Nov 14 '15
Unsurprisingly, Crawl has code duplication here: the code for player travel pathfinding (re-used for flood fills and autoexplore) is totally separate from that for monster pathfinding (re-used for placing monsters near a location). This happens a lot when you have a big, old codebase. Admittedly, neither of these predate Stone Soup, being used for features that didn't exist before.
Travel was in fact the feature that started Stone Soup: the fork began when greensnark ported the travel code from NetHack to Crawl 4.0b26. He tweaked it a little to produce autoexplore, and eventually more minor and not-so-minor patches started getting glommed on to form "the travel patch," which eventually turned into the fork. You can check out his blog post on the thing for the full story.
Here's the big comment for player travel (but a NetHack dev could probably explain it better :P):
Monster pathfinding is pretty interesting as well. Originally, monsters just walked directly towards their target. If they hit an obstacle, they tried either adjacent direction; if that failed, they just stood there. That's still around, but a pathfinding phase was added before. The monster creates a path to get to its ultimate target, then the path gets split up into waypoints, which sequentially become its next immediate target, whereupon it uses the old code. Comment dump:
Two cool things I thought were worth mentioning:
It is an exceedingly good idea, given crawl's unique line of sight properties.(but that comment was written many, many revisions of the LOS code back).There are a lot of... complications I don't understand whatsoever (and I don't plan on putting in the time to do so). In general I think the monster AI code is some of the crappiest we have, full of incomprehensible special cases, incorrect algorithms, people grafting code onto places that don't make sense, and checks referring to behaviours that were removed many versions ago. If you don't believe me, I found not one, but two bugs just glancing around the code for writing this up. (And also two @crawlcode entries.)
4
u/chiguireitor dev: Ganymede Gate Nov 14 '15
For Ganymede Gate i was trying to use some kind of bounded Djikstra map, but it seems kinda intensive because the map must be recalculated each time an AI or player moves.
From that i have found out i would rather use A*.
However, for the squad tactics i'm implementing a different metric for curved paths. This will allow to divide squads into different groups that won't go directly to the player but instead circle them and try to attack from behind, trying to stay outside the fov of the player and using the squad's intelligence regarding the player position.
Still needed to implement: cover detection (for dividing squads into hallways and ambush the player), scouting and formations.
4
u/Shlkt Nov 16 '15
I've been very pleased with the results of incorporating pathfinding into various aspects dungeon generation; first with Cryptband and then with Malastro.
There's definitely a price to pay in terms of performance, but level generation only happens every once in a while and IMO an interesting looking level is well worth another second of generation time.
5
u/ArmouredCommander ArmCom Nov 13 '15
Armoured Commander uses A* pathfinding for the campaign day map. It's not used that often, but it does have an important job to do. First, because some map nodes are inaccessible by the player, it tests every newly generated map to ensure there's a path from the start to the exit node. It also does this check in case the exit node needs to be moved.
Pathfinding is also used for laying out roads on the map. For this, a custom weighting value is assigned to each map node type, so roads will tend to go around forests, and through villages, for example.
I wrote my implementation of A* in python from scratch, and it really helped me understand how it works!
5
u/gamepopper Gemstone Keeper Nov 13 '15 edited Nov 13 '15
Gemstone Keeper uses A* Pathfinding, using a C++ class I wrote to work specifically for tilemaps produced in my level generator, so it can work as either one complete tilemap (where # are considered non-walkable tiles) or as a series of rooms in a tree structure.
A* Path Testing
More A* Path Testing
The way I use it at the moment varies from enemy type, depending on how I want them to behave. For example, the rats follow the generated path towards a random point by changing the velocity, so it appears to move quick and erratic. Bats follow paths towards the player by changing the acceleration, so it appears to fly around and occasionally miss the player. In both cases I do allow a margin of error between points so that it will try to reach the end of a path in most cases.
I also try to reduce the amount of path finding calculations by only recalculating when the player has moved towards a new grid space, so if the player moves 32 pixels either horizontally or vertically, the path is recalculated for each enemy that uses it to follow the player.
4
u/Slogo Spellgeon, Pieux, B-Line Nov 13 '15 edited Nov 13 '15
For Fearless Fencer I'm using Brogue's system, but I have also left the door open to work in some improvements. If at some point I need new features or functionality becomes a problem I will go back to the system and do more work.
I gain a lot by using Brogue's system because I'm not using a bump to attack system and the NPCS do a lot of managing their range from the player. It's really handy that it's pretty easy for them to evaluate the path distance to the player from not only their current location, but all their possible adjacent tiles. This will become more significant as NPCs become even smarter and start trying to avoid the player's sword. I can simply generate a range limited map centered around the player's sword (with consideration for the player tile itself so the opposite of the player from the sword is an attractive place to be) that will help enemies use the player's weapon in their navigation.
My map algorithm generates maps out of room and edges connecting those rooms and ends up with a resulting graph of the map. It's pretty easy to use a hierarchical approach here which can save a lot of time. What I'll end up doing is calculate paths based on room to room navigation while simultaneously caching djisktra maps for room to edge navigation. It's memory inefficient, but memory is in large abundance for a game of my complexity.
It would be a less attractive option if I had destructible terrain, but not one that's impossible. The cost of recomputing the maps when the terrain is changed would be notable, but probably not that bad (currently every time the player moves the whole map is updated with a new map and that performs reasonably).
The trickier problem to solve with a hierarchy approach would be supporting terrain that's not navigable by all creatures. Especially if you had something like a room that was divided in half by water and creatures that can't swim. But we'll cross that (lack of a) bridge when we get there.
1
u/Valmond Nov 27 '15
I'm using a pathfinder that has virtually no cpu cost, I know I'm late to the party but if people are interested I'll write something. It works really well too and works in big / unknown maps too. Sorry for short post, am on mobile Valmond @ Mindoki Games
3
u/DarrenGrey @ Nov 14 '15
I tried figuring out A* or Djikstra when making Toby the Trapper and it just wasn't sinking in, so I did a smell map instead and that was way easier. Just do a floodfill from player position with incrementing (or decrementing) values marked on the map squares. Do this every turn, either rewriting every value or making the existing values decay before adding new positional values. Have NPCs look at the nearby values when deciding how to move - simply make a list of nearby values and choose the highest if trying to move closer.
For Toby this worked great because setting a slow decay on the smell value meant that enemies would congregate towards areas you had spent some time in, not just exactly where you were. For the luring into traps gameplay this added some fun nuance.
Since using the T-Engine I started using the built-in path-finding algorithms, which I presume are Djikstra or similar. However when it came to making FireTail I got sick of this and put in the smell map again. The previous system didn't give me enough control for interesting AI decisions, or at least made them harder to programme. A smell map with simple numbers from the player is far more intuitive to code AI routines around - you know exactly what sort of numbers will happen and how they interact with terrain.
In FireTail enemies have limits on how they behave based on how smell-close they are from you (ie how many steps away - not simple Cartesian distance). If too far away they just move randomly, with some enemies having a higher limit for this than others. Some enemies will flee if they end up within a certain distance, some will have powers they can only use at certain ranges. Different terrain can block or reduce smell values, making enemies unwilling or unlikely to traverse them, with a bit of variation between enemy types on this. The player going invisible essentially reduces their smell value to a much smaller amount.
The big limiting factor to smell maps is that it's all very player-centric. You can't have a monster chasing another monster without involving a lot more smell maps. This means little scope for enemy infighting, use of allies, and a number of other interactions. However I personally like designing games with the focus on the player experience and with every value in the game being centred on how things affect the player, so for me this is perfectly fine. It's also so very easy to implement and so intuitive to work with. For any starting designer who struggles with the more complex path-finding algorithms I highly recommended trying out the cheap and easy smell map!