Representing MultiSpatialMap as a MapView

Hello! So I'm writing this unity wrapper for GoRogue. u/Chris3606, thanks for the minimal build, it works great so far.

The map I'm using right now to store GameObjects is a MultiSpatialMap. I'd like to implement pathfinding, but in order to do so I need to access a MapView, but I'm not sure what the right way is to access a MapView from my MultiSpatialMap. Is there a way to do that?

Posted Mar 27, 2019, 10:32 PM UTC

218
Chris3606GoRogue•

There isn't a built-in class to do this exactly, for a couple reasons - mostly because, IMapView is designed to expose a "view" of the map, which is typically not exactly the map itself. For example, the IMapView<bool> that pathing takes represents the map as boolean values telling whether any given location is passable or not for the sake of pathing -- it doesn't particularly matter to the pathfinding algorithm if that data comes from a spatial map, Unity ray-casting, or something else, as long as you implement a map view that tells it how to get the information it needs.

GoRogue does provide a number of implementations of IMapView to help you out though, that typically make implementation easy. How exactly to implement it, however, will depend on a few specifics of what you're storing. The game objects you are storing in the spatial map -- does the term "game object" refer to the GameObject class from GoRogue, or some other custom class? If it's a GoRogue GameObject, then each GameObject has an IsWalkable flag that says whether or not it is a collidable object. In this case, you might consider using a GoRogue.GameFramework.Map in place of your MultiSpatialMap, as it implements the map view (and AStar based on that IsWalkable flag) for you.

If you want to keep the spatial map, provided it's a spatial map of GoRogue GameObject instances, you would probably want to create a map view that returns false for a location if any GameObject at that location has its IsWalkable set to false, and true otherwise. GoRogue provides the LambdaMapView class (which implements IMapView) that can make this fairly easy -- you can just create a function to check the spatial map at that position, and pass that function to a LambdaMapView:

bool IsPositionWalkable(Coord position)
{
    foreach (var item in mySpatialMap.GetItems(position))
        if (!item.IsWalkable) return false;

    return true;
}

// When you want to create the map view and pathfinder
var mapView = new LambdaMapView<bool>(myMapsWidth, myMapsHeight, IsPositionWalkable);
var astarPather = new AStar(mapView, Distance.CHEBYSHEV);

There are some shorter ways to define that function via System.Linq, and/or by passing a lambda function to LambdaMapView if you're familiar with those, but the principle would be the same.

If the objects in your MultiSpatialMap aren't GoRogue GameObjects, that's absolutely doable too -- I just don't know exactly what the contents of the IsPositionWalkable function would be -- it would depend on how you determine whether a position is considered passable or not based on those game objects :D

Hope that helps -- if not or if you end up with more questions, I'll be around :D

2
roundedgeOP•

Hey thanks for your quick response. I really appreciate your help with this.

So I'm wondering about the map width and height parameters. I'm trying to decide what the appropriate values to pass for myMapsWidth and myMapsHeight, from the perspective of the intended design of mapview. For a multi spatial map there are no bounds on the positions of the objects (besides the size of an int), and they can also in principle be negative coordinates. So the map itself has no width and height, and it is not clear to me what specifying a width and height corresponds to with respect to the multi spatial map. Will it only consider coordinates from x=[0, width] and y=[0, height]? Is there a way to center this rect so that it includes negative coordinates? I am also uncertain about if the map width and map height need to represent the full extent of the map, or can correspond to some subset of the map, for instance as a way of bounding how far afield the pathfinder searches. It seems like this would be the intended functionality of the viewport, but I am uncertain how to take a viewport of the multi spatial map.

My current strategy is something like the following:

//get lower left occupied coord of mySpatialMap
//get upper right occupied coord of mySpatialMap

Rectangle extent = new Rectangle(lowerLeft, upperRight);

bool IsPositionWalkable(Coord position)
{
    Coord offset = extent.position
    foreach (var item in mySpatialMap.GetItems(position + offset))
        if (!item.IsWalkable) return false;

    return true;
}

// When you want to create the map view and pathfinder
var mapView = new LambdaMapView<bool>(extent.width, extent.height, IsPositionWalkable);
var astarPather = new AStar(mapView, Distance.CHEBYSHEV);

Now we have something like a viewport for the spatial map. However it feels to me that you've put so much nice work into the polymorphism of your code that I shouldn't be reinventing functionality in this way. Do you have any thoughts? It seems to me that the natural thing to do is to have a constructor for the viewport that takes the spatial map as input. Or else a new class which extends from viewport and does this. Maybe I will write something like that.

One thing that might be useful is if the spatialmap stored the lower left and upper right occupied coordinates, and dynamically updated that information when modified, since then they wouldn't need to be searched for. Better yet, if the spatial map stored a rectangle.
I hope you don't mind my interrogations, I am mostly just trying to document my confusions and thoughts, since I imagine it could be useful for your development process.

​

1
Chris3606GoRogue•

No problem, I'm glad I'm able to help :D

I think some of the confusion on this is due to some differences in the way GoRogue uses the term "position", vs Unity. GoRogue, for the most part, "thinks" in grid squares when it talks about maps -- eg, thinks in terms of map "tiles". Coord and some other data structures don't restrict themselves to only this definition -- Coord itself can represent any integral position, whether that be pixel coordinates, grid coordinates, or otherwise. Similarly, although spatial maps make more sense conceptually when you think of them as representing items and associating those items with their map-grid coordinates, they don't enforce some of the invariants you might expect there -- they do allow negative coordinates, for instance. This is largely because spatial maps are really just data structures that happen to be useful for representing elements of maps. There's a lot of ways to do that, though -- you could have one spatial map that represents the entire map like you currently have, certainly. -- Or, you might decide for a particular use case to break it down into chunks, with one multi spatial map per chunk (in which case the coordinates in the spatial map might be chunk-relative, not map-relative), or you might in some cases not use spatial maps at all -- it depends on the specific situation of what you're implementing and the tools you have available. In short, spatial maps are at their core data structures (that can be useful for maps), not an abstraction of the map itself, so it doesn't enforce the same invariants about what "position" means, like map view does.

Generally, though, when a GoRogue algorithm wants to interact with a map (eg, a map view), it considers that map as having grid coordinates that are in range ([0, width], [0, height]), as you noted in your post, and this is indeed the subset of coordinates that must be represented by a map view. The reasoning behind this generally relates to the idea that, when you consider a map outside of any specific graphics/pre-built game engine, this definition of position (eg. defining it by grid squares) is the only one that makes sense in all environments. For instance, consider three game/graphics engines -- MonoGame, Unity, and BearLib terminal emulator. MonoGame works in pixel coordinates -- so you have to perform the (mapPosition.X * textureWidth) + (mapPosition.Y + textureHeight) type math for most of what you do in a grid-like game. BearLib, on the other hand, is a terminal emulator, so it thinks of positions as character locations on the screen, so effectively what already amounts to map grid positions. Unity is somewhere in between because it generally thinks of positions as scene coordinates -- if you define the pixels per unit on your textures in the correct manner, one map grid square might equate to one scene distance unit. If you import the textures differently, it might not and might require similar translation math to the MonoGame example. Also, unlike the first two, unity's scene coordinates can go negative. Since these definitions vary widely, and I wanted GoRogue to be able to support all of them, GoRogue simply "thinks" about maps in terms of map grid squares from 0 to end of map dimension, and leaves it to the user to do translation between whatever graphics library/game you are using it with as necessary.

In summary yes, IMapView supports only coordinates in range ([0, width], [0, height]), so you'll need to perform some translation if you choose to allow negative scene coordinates and/or negative coordinates in your spatial map. The differentiation between spatial map and map view (data structure vs. map abstraction) is why I don't define a direct translation between the two (a constructor like you had mentioned) -- if I define it so it makes sense for one of the potential use cases I mentioned, then it doesn't make sense for some of the other toolset use cases mentioned.

As for how to define the translation in your case, the method you have could potentially work -- I myself typically took the easy way out when I dealt with Unity, and made sure the map started at scene coordinates (0, 0) and set the pixels per unit such that one scene unit = one grid unit, so no translation was necessary. Another solution would have been to deal with the positions relative to a parent object that could be positioned freely in the scene, so the relative positions similarly align with the grid. Yet another option is to have both the spatial map and the map view deal in grid coordinates, and perform the offset translation as items are added/moved around.

The bounds-tracking idea for spatial maps is an interesting concept -- however, it may have some run-time implications, as when an item on the edge of the map is moved or removed, it becomes somewhat challenging to efficiently find the new bound on that side of the map (you potentially have to search all objects in the spatial map, in the worst case). GoRogue typically assumes maps are static-sized (meaning, the size might be determined by dynamically but isn't modified after its determined), as this is nearly necessary for traditional RL map generation and some other concepts. That doesn't mean all the algorithms require it, but just that generally that was the use case in mind. That much said, spatial maps to do provide ItemAdded and ItemRemoved events, so it wouldn't be too hard to create a bolt-on component that tracks that bounds data based on those events -- and that could potentially be added to GoRogue.

As for your question about viewports -- this is definitely something that GoRogue implements for you, via its map view system. If you define a map view that does represent the whole map based on your spatial map, you can then define a GoRogue.MapViews.Viewport as you suspected, based on that map view. It does what the name implies -- takes an existing map view, and represents a subset of that map view, as a map view. Something like:

// When you want to create the map view and pathfinder
var fullMap = new LambdaMapView<bool>(extent.width, extent.height, IsPositionWalkable);
// Viewport represents coordinates (0, 0) through (79, 79) of the fullMap map view
var mapView = new Viewport<bool>(fullMap, new Rectangle(0, 0, 80, 80); 
var astarPather = new AStar(mapView, Distance.CHEBYSHEV);
// later on, you can move the mapView view area around wherever you need to.

The above implementation does have a downside -- the coordinates you pass to ShortestPath need to then be relative to the mapView, not fullMap. This wouldn't be the case with something like goal maps where you don't provide coordinates to it in that way, and if you needed to do this with A*, you should be able create a wrapper function that calls an Viewport function to do the coordinate translation. There might be some room in GoRogue for making this slightly more direct, though -- I'll create an issue for it I have created an issue for it on the GitHub repo and can experiment at some point, and feel free to add any input to that issue you want to.

Truthfully though, this isn't something I could see you needing to do for performance reasons with A* -- A* is generally so fast even on a big map (500x500 grid squares or more) that it's not necessary. It might still have its uses from a mechanical standpoint, though, and absolutely has some great uses when paired with goal maps or even FOV when you have a bunch of objects all calculating their own FOVs.

I don't mind the input at all -- its definately useful all around. And if you disagree with the design behind something (whether it's something I mentioned or otherwise), feel free to bring it up, by all means -- discussions about it are how the library gets better :D. I hope this answers your current question -- either way, you know where to find me :D

2
roundedgeOP•

Thanks for your help. I've got a bit of a pathfinding demo working in unity now. Here's the project in case you're interested https://www.dropbox.com/s/er5tpx1n6wr7nx5/GoRogueUnityDemo.unitypackage?dl=0 I'm still new to exporting unity packages, so let me know if it doesn't work.

I ended up writing a MultiSpatialMapView class which stores a rectangle as the view, and has some helper functions to convert from the spatial map coordinates to the view coordinates.

​

One thing that struck me is the following. As you explained, A* is in the coordinates of the Mapview, not the underlying SpatialMap data structure. So when A* returned a path, it was in those coordinates. I wanted to shift those coordinates, to put it back in the coordinates of the underlying data structure, but I could not manipulate the path in this way, nor could I construct my own path, with offset coordinates. So I ended up writing a wrapper class called OffsetPath, which just stores and offset and adds it on the fly. This seems like something that could come up often, given your comments about Viewports. I wonder if it would be useful to include an offset parameter in the A* shortest path routine, or else a built in way to add an offset to a Path object.

Playing with the pathfinding, its much faster than my original code :D, although it's not clear to me exactly why. I'm starting to suspect it was because I had originally used a bad hash function for my dicitonary data structure. Two thing's I've noticed. The first is that when the pathfinding target is inaccessible, the pathfinding routine struggles. This is not surprising, but I've been trying to think about the right way to address it. The second is that when the target is far away, the pathfinding also struggles, this is also not surprising, but this happens even when there's a clear line of sight. I remembered reading something about this, where if you add a tiebreaking clause in the pathfinder it can dramatically improve the performance, and dug up this comment on the rot.js project: https://github.com/ondras/rot.js/pull/91

One last thing. Is there a performance reason you use a boolean map for pathfinding instead of a float map? With a float map one could have paths which are passable but undesirable.Is it straightforward to make these minimal builds for unity myself? I wouldn't mind trying some modifications to the source and adding them to my build.

(I should add that right now the pathfinders are pathfinding every update, which is obviously a bad idea. But for the purposes of testing its a good way to see the performance.)

1
Chris3606GoRogue•

Hm. I'm curious as to why pathfinding is struggling at all -- how big are your maps, and how many paths are you calculating, if you don't mind me asking? In my performance tests, I'm able to crank out multiple paths completely across a 500x500 open map without falling below a time that would break 60FPS. That much said, it is slower than I remember it being (just ran those tests), so I will check to see if something got broken somewhere along the line.

​

An offset to path may be included in the eventual solution to the viewport problem I put in the github issue I linked in my last post -- it could definitely be useful, I agree :D.

​

If the target is inaccessible, it will indeed struggle, only because to verify that there is no path, it basically has to hit a wall in every direction (which means it practically becomes Dijkstra's algorithm on an open map in the worst case). Particularly on a map that is mostly open until very close to the target, this is expected and unfortunately unpreventable if the target location is truly inaccessible.

​

Regarding the tie-breaking aspect, unless either I broke something in a GoRogue update, or some assumptions I made about the priority queue implementation it uses are no longer valid (which I will be checking), GoRogue already implements this. In the AStar source file, the neighbor function it uses returns the directions in order of the one that leads most directly to the end path first. Like I said, I'll be double checking to make sure some assumptions have not broken down, as this would absolutely cause slower behavior. You might try having AStar calculate its path using Distance.EUCLIDEAN instead, which may illustrate if the tie-breaking has broken down.

​

The reason for the boolean map is indeed performance related. GoRogue implements the common use of weights (euclidean distance) via the distance calculation you pass it, however there are absolutely other uses for weights. I didn't want to implement them in the existing AStar algorithm because it does have a significant impact on performance (floating point operations are significantly more expensive than boolean checks, and are not as cache-friendly), however I have planned to implement a version of AStar that supports these weights.

​

The minimal builds are unfortunately not as easy as they should be currently. The only thing not in the minimal build that is in the regular release is some implicit conversions/interoperability operators for MonoGame primitives that correspond to some GoRogue types (Coord and Point, etc). When GoRogue is deployed via nuget, it is done in such a way that these operators do not create a required dependency on monogame, however when the DLL is manually added to a Unity project, the compiler isn't apparently smart enough to resolve these properly. Thus, the minimal builds are exactly GoRogue with all the MonoGame interoperability operators commented out (which you currently have to do by hand). I will be automating this in the somewhat near future, though, as knowing this now I intend to release these builds with every GoRogue release, so it will after I'm done be as simple as changing a preprocessor flag in the csproj.

​

Regarding the performance difference between your AStar and GoRogues -- my best guess, to be honest, is the priority queue implementation GoRogue uses, which is very highly optimized -- using a efficient heap-based priority queue implementation can make a huge difference in the algorithm in general :D

​

EDIT:

Another possibility might be the source of the data -- I don't know how you were storing items on the map prior to MultiSpatialMap, but spatial maps are designed to be significantly more efficient than implementations like a simple list of items, for operations like getting items at the location (which is something that AStar does frequently). That much said, MultiSpatialMap may also be part of the problem if your pathing is significantly slower than it should be based on the benchmarks I listed -- if you're using a spatial map to store terrain (wall, floor, etc -- stuff where each location has exactly one piece of terrain), you may get some speed improvements by pulling those specific objects out into an ArrayMap or a 2d array, and using the spatial map for the others. Spatial maps excel at instances where the items are sparse -- eg, when there are fewer items than there are map squares. While asymptotically, spatial map performs the same way as a 2D array in cases where the map is dense, in practice the constants are higher, and thus spatial map will be slower at getting the item at a location than an ArrayMap or 2D array is when there are items at every location.

​

Regarding how to handle the pathing slowness in practice -- you definitely won't need to path in the Update loop, so depending on what level of performance you mean by "struggling", it may not be a practical issue. In all honesty, particularly when you are pathing across a huge map, you might not even want to path every turn, instead just calculate a path then follow that path without calculating a new one for several turns, or some such. This may alleviate some of the stress you will find on a larger map.

1
Chris3606GoRogue•

After a quick look, I am seeing some evidence that the tiebreaking in GoRogue's AStar may not be correct,at least as of 2.1.0. It may not be today, but I'll investigate this further, and post if I come up with anything that affects performance. Thanks!

1
Chris3606GoRogue•

Update on this u/roundedge. I have found some potential ways to speed up the AStar implementation in GoRogue -- some of the assumptions it currently makes are the best in asymptotic worst-case, however the worst case seems to rarely occur in practice, and thus some alternatives can yield speed increases.

​

First, I'm looking into replacing the current priority queue implementation with a very simple sorted-linked-list implementation, and pairing many of the current elements of internal astar nodes out into their own arrays. While this can produce asymptotically worse results, as heap is asymptotically the correct implementation to use for generic AStar, it appears that the increase in cache locality as well as the fact that the worst case for sorted-linked-list operations occurs infrequently compared to the worst case for heap operations, yields a measurable performance increase -- particularly so for chebyshev distance. There is an implementation of AStar here that uses a similar implementation (and in fact my new implementation is based/taken from theirs in places), and it seems to have a measurable impact in many cases, and has yet to produce slower results in my testing.

​

Another item that is evident in the above implementation is the need for GoRogue's AStar to allow customized heurisitics. The current implementation of AStar in GoRogue uses a heuristic to estimate remaining distance to the endpoint corresponding to the actual distance type being used -- if Manhattan, 4-way distance is being used as the movement scheme, then Manhattan distance from a node to the endpoint is used as the heuristic. Similarly, if Chebyshev distance/8-way movement is used as the movement scheme, chebyshev distance is used as the heuristic. As you noted via your post on ties and tiebreaking, this can produce cases where significant numbers of equivalently long paths to the goal causes more nodes to be evaluated than needed. There are, as your post again pointed out, methods of tiebreaking that are designed to reduce the number of equivalent nodes, and gorogue implements one that also functions as path smoothing -- however, many of the ones that make significant dents in performance for certain cases have some quirky results in other cases, etc. So, an alternative (and one that can yield even greater performance increases than tiebreaking), is to use an over-estimating heuristic that results in less ties. In short, if you use Manhattan distance as the heuristic for Chebyshev/8-way movement schemes, the manhattan distance (estimated distance) between a node and the end point might actually turn up greater than the actual minimum distance (because ManhattanDistance(x, y) >= ChebyshevDistance(x, y). In terms of AStar, this somewhat breaks the "admissibility" of the heuristic, in that when you use a heuristic that can over-estimate, the algorithm is no longer guaranteed to produce a shortest path. The implementation I linked above does this, and claims that it always produces lowest cost paths, however some reading here, as well as some testing where I can get that algorithm to return paths longer than a shortest path, indicates that this is a mistake (I'm actually planning on filing a bug report on that algorithm's github page). At any rate, despite the paths not being guaranteed to be the shortest, they are quite close to shortest paths (no more than 5% longer than the actual shortest paths in the cases i've tested, and often-times less than that or even the shortest path itself). More importantly, using a heuristic like this significantly decreases the run-time -- the algorithm performs about 4x faster than gorogue's current implementation when using this heuristic. As such, it seems critical that GoRogue's implementation be modified to support custom heuristics (and the new one I'm working on does, and nets that 4x speed increase when calculating 100 paths on a 500x500 map).

​

Finally, modifications to gorogue's algorithm resulting from the one I linked led to a very easy way to include the weights feature you were discussing with virtually no performance loss. That is also in the new implementation.

The new implementation should not break existing code if everything happens the way I expect. It will probably look something like, modify the AStar class to use the new implementation, and accept optionally custom heuristics and custom weights. Then create a new GoRogue class FastAStar, which is marked as being significantly faster at the cost of not being guaranteed to produce perfectly lowest cost paths, which will just use AStar with manhattan distance as the custom heuristic.

​

Thanks for the feedback!

2
roundedgeOP•

Wow great to hear!

One thing I'm seeing is that in fact most of my performance hit is coming from calling the Astar constructor. I call the constructor every time before I run the shortest path routine. This is because if the agent or target moves, then I need to create a new mapview of my base data structure, and thus a new Astar representation of that mapview, since not only might its width and height have changed, but also where the view is centered might have changed. I suppose in the case where you have a fixed size map you wouldn't do this, but for a very large sparse map, which is what I wish to use, I do need to do this to some extent. There are some ways around this, like only reconstructing Astar when the target or agent have changed position significantly from the last time, but I'm curious to explore why the constructor is so expensive. What I see is that when I call the constructor I populate an array with an AStarNode for every site. For a 500x500 map this is 250000 constructor calls, which seems needlessly expensive, since I don't expect to visit every site. For unity I think this is creating a lot of garbage as well, although I'm still sussing it out. Even if I were not to reconstruct my AStar object, I see a similarly sized while loop in the ShortestPath routine, although I haven't tested this yet. Can I ask, how is it that visiting every site on the map every time you instantiate an AStar object, or call ShortestPath, not significantly impact the performance for you?

I want to see if I can write an alternative which doesn't have to do this. But I'm wondering if there are particular design decisions you've made which motivate this choice?

​

1
Chris3606GoRogue•

Long story short, this won't be a problem in the new implementation (that should be done inside of a week, earliest tonight), as its a positive side-effect of the new implementation, but right now reallocating an AStar instance every time you create a path is not desireable at all.

​

First, I don't think there's a while loop in ShortestPath that typically ever visits all nodes. There is a foreach loop: foreach (var node in nodes) that resets the node values to their beginning values, however it is surprisingly cheap -- I'd played around with removing it in some controlled cases where that's possible, and it didn't affect much performance-wise, I assume due to cache locality of the entries being modified, and the fact that it neither performs any calculations nor allocates any new memory (thus while it obviously costs time it's simply not the bottleneck). Certainly, that foreach loop is nearly guaranteed to be cheaper than reallocating the array of nodes (the only alternative to resetting them when that array exists), as allocation of reference types in managed languages like C# is generally ridiculously expensive compared to nearly any other operation. Why the node array exists at all, though, is a good question -- reasons detailed below, but again in the new AStar implementation (that I've almost completed now, really just testing and bugfixes) it won't be necessary. If you're referring to the while loop: while (openNodes.Count != 0), this could only ever visit all walkable nodes, as only walkable nodes are added to openNodes, and even then would only do that under the worst of circumstances where a path to the target is difficult to find (eg, very much not a straight line). The loop aborts early via a return statement in nearly every case that is practically encountered. The loop is required to be set up in a way that has the potential to iterate over all walkable nodes, to ensure that it finds the shortest path in all cases -- remember astar in the worst case (which is where the accuracy of the heuristic fails miserably) is equivalent in time complexity to dijkstra -- it just pretty much never actually does so :D

​

As for why the offending array of AStarNode instances exists -- the short of it is because it's more or less requried by the current priority queue implementation that the algorithm is using. In order to have reasonable performance for the Contains/UpdatePriority function calls, it is necessary to be able to retrieve the node representing an arbitrary location in constant time. Thus the code stores them in an array indexed by position. It would be possible to only actually allocate the nodes that are needed (leave the rest as null), but this is only really a small optimization for most cases because the foreach loop in the ShortestPath function to reset things would still be requried and would simply iterate over a bunch of null values. There are some more complex workarounds to mitigate, but there's not much need anymore as the better workaround of no longer requiring the array of nodes in the new implementation is already in the works :D. The assumption was generally that the constructor penalty isn't a huge deal because AStar (in its current form) isn't really designed to be reallocated like this.

​

Which does lead me to a question -- it won't be particularly relevant with GoRogue's new AStar implementation granted, but why do you allocate a new map view every time something moves? I understand that the centered point or width/height can have changed, but map view implementations are not restricted to having static values at locations, nor static width/height values, and astar, even as is, is currently designed to account for map views that change values/change sizes. I can't look at the unity package code right now, unfortunately, but I would assume that if your implementation is as you described here, it would be something like:

class MultiSpatialMapView : IMapView<bool>
{
    private MultiSpatialMap<Thingy> _spatialMap;

    // This can simply be modified as things move, or via events as below
    public Rectangle MapBounds;

    public int Width => MapBounds.Width;
    public int Height => MapBounds.Height;
    public bool this[Coord pos] => /* Offset math to check spatial map and return bool */
    /* other indexers here */

    public MultiSpatialMapView(MultiSpatialMap<Thingy> spatialMap)
    {
        _spatialMap = spatialMap;
        /* Go through existing spatial map entities, track MapBounds appropriately */
        
        // Don't know how you're tracking moves/new entities, but assuming events:
        spatialMap.ItemAdded += onAdded;
        spatialmap.ItemRemoved += onRemoved;
        spatialMap.Moved += onMoved;
    }

    private void onAdded(object s, ItemEventArgs<Thingy> e)
    { /* If e.Position is outside MapBounds, update MapBounds */ }
    private void onRemoved(object s, ItemEventArgs<Thingy> e)
    { /* if e.Position was on map edge, find new map edge and update MapBounds*/ }
    private void onMoved(object s, ItemMovedEventArgs<Thingy> e)
    { /* if old e.OldPosition/e.NewPosition changed bounds, update MapBounds*/ }
}

If that's the case, where the map view effectively just "changes" when things move around, you don't need to reallocate it, and thus it shouldn't require you to create a new AStar instance when something moves -- and in fact AStar implements the optimization you talked about in this case, where it only reallocates the node array if the width/height have actually changed.

1
roundedgeOP•

Hey, you're absolutely right, there's no need to reinitialize, I've made that change. You're also right that it wasn't a while loop, I should have been more clear. What I meant was the for loop which creates new nodes when the width and height change.

I noticed that even when I don't reinitialize every time I still get a big performance hit when I move the target around and it is far away from the pathfinder. This is because I'm changing the width and height of the map view, and it is allocating nodes in the for loop. Suppose the target teleports from 200 squares away to 400 squares away. Then in that frame the algorithm must allocate something on the order of 400^2-200^2 new nodes. I wanted to see if I could avoid this problem, so I modified your pathfinding algorithm so that one doesn't need to store all of the nodes, only the open ones. I basically used a hashset called closed, which stores the hash of every coordinate which has been closed, instead of having the closed flag be a property of a node. Then I made the nodes iequatable, and made two nodes equal if they have the same coordinate. Then I removed the array of nodes, and instead generated new nodes on the fly when I need them. Most of the rest of the logic stays the same. When I test this in my unity build, it is significantly more performant. Maybe this is what you are also working on changing? Anyways, I've pasted the code for the alternative pathfinder is here:

https://pastebin.com/6WnLT8vu

in case it is useful

Also, I should say I am still experimenting with this, so there may be bugs. I also may still be missing something crucial regarding the reasons for the node array.

1
Chris3606GoRogue•

Looking at your code, I think some of the changes have merit, at least for when you're dealing with dynamic sized maps. One minor thing that does jump out at me -- you shouldn't need to do closed.Add(current.GetHashCode());, as HashSet will do the hashing for you (and is actually hashing the hash code you give it internally right now -- rather, you can do closed.Add(current) and it will call GetHashCode for you.

​

As I'd stated previously, the reasons for the node array are partly because of the implementation of priority that the currently AStar implementation uses (which I am no longer using, thus giving me some more freedom to avoid some of the corner cases that really hurt performance on larger maps). Also keep in mind the algorithm will perform differently on a open map vs. a closed one.

​

As for using a closed HashSet, I'd experimented with this in the past. The reason the original implementation didn't do it, is because the overhead of the hashing that HashSet has to do for adds and contains actually significantly hurts performance on certain cases in _static_ maps, where the resize overhead doesn't occur in the first place. That much said, this was in part due to the number of allocations of Coord it required. I haven't touched the AStar in GoRogue really since 1.x, and pre-GoRogue 2.0, Coord was a pre-allocated reference type instead of a value type, so I've realized some of the issues are holdovers from when the overhead of operations was a little different. These reasons have changed to some extent due to GoRogue updates and the change in priority queue, however, so I'll likely revisit it, at the least in my dynamic-map-size version of AStar (see below). In either case, I'll take the code you have, and stack it up against my new AStar implementation, and see how it goes.

​

Between our conversations and the experimentation I've done, I think a lot of this results from the fact that what is an "optimization" differs drastically between when you assume the map is resizing frequently, and when you do not. What helps performance in one case may actually hurt performance in the other, and vice versa. For this reason, in GoRogue's new A* is split into two base classes -- AStar, which is generally good when the map isn't resizing frequently, and AStarDynamic, which is designed to be better when the map is resizing frequently. This has allowed me to consider these cases separately, and thus implement some of those optimizations that can hurt the other case without worry.

​

That much said, to be honest, while it's not always possible, it seems that, if you want the best performance, it's better to declare a static map view size, even if that's just a maximum map size that is huge, or or a an UnboundedViewport of the area around an entity that returns false for everything that's outside current edges (eg, where the view size is static even if the map is "changing"). Comparing the two implementations I have right now, I can get AStarDynamic to perform better than AStar (the static-map-size version) when the map size is changing frequently. However, I really can't get AStarDynamic to have the same performance in the dynamic case that AStar does in the static size case. The static (or infrequently changing) case optimizations, when they apply, just seem to go farther. Thought I'd mention this in case it's helpful for your case :D

​

As for what I've changed thus far, a lot :D The priority queue implementation I am now using is different, which changes not only performance directly but some of the optimizations I can implement effectively as well. As I stated above, I've split the implementations into a version that assumes the size changes relatively infrequently, and one that assumes the size changes relatively frequently, and provided slightly different implementations for each. This combined with the priority queue change opens up some doors to revisit old optimizations I'd tried like the HashSet -- though, right now in the dynamic-map-size version, I've eliminated the closed set entirely. Depending on your implementation, the closed set isn't required, as it is really just an excuse for early loop termination on visiting neighbors. The overhead of maintaining it at all (even if that maintenance is just hashSet.Clear()) seemed greater than keeping it around at all, particularly since on a closed node, the loop will terminate anyway as soon as the old/new cost comparison is done. The new a-star I've got also supports not only weights but also custom heuristics, allowing things like the manhattan distance trick I outlined previously, which is really a huge performance saver (albeit at the cost of (possibly) a very slight increase in path length).

​

So, really all I've got remaining is to revisit a few potential optimizations, and see if I can increase performance further, and then I should be able to release it. Unfortunately, I was rebuilding my computer this weekend, which has eaten most of my dev time, and as such I'm a little behind where I want to be on this.

​

I'll let you know what I come up wth! I'd also be very interested if you happened to test the new algorithm once it's released and see how it works for you :D

1
Chris3606GoRogue•

Digging in, a few bugs on that pastebin implementation, in case it's helpful for you (don't know how similar this is to what you're actually using -- some of these may well apply to your actual implementation): currently, I'm getting an index out of bounds exception when I run it over the course of 100 paths -- this seems to be due to the fact that the queue is having more than maxSize nodes added to it. This probably won't show up on an open map, however when shortest paths start to become indirect it shows up, I think for the following reason:

​

The way the priority queue implementation (link here) performs Contains, is it checks an internal value that is set to the specific instance of the queue that is holding it when a node is added. Thus, if Contains() is called on a separate instance than the one that was added to the queue originally (even if that node is by equality equivalent), Contains() will always return false since that specific instance was never added to the queue. Thus, when new nodes that represent already enqueued nodes are created (which on a winding path, they will be), the AStar's openNodes.Contains() returns false when it should return true, and a new node is added that represents the same value, rather than an existing node being updated via UpdatePriority. This causes more than max nodes to potentially be added to a queue depending on the map conditions, which will cause an exception to be thrown. This is the limitation of the priority queue implementation that forced me to use the array in the first place :D.

​

Also, using GetHashCode directly like you are in the closed set, I believe, is actually going to break things in certain cases. Hash codes are not guaranteed to be unique (as they are not meant to be), and I believe the same applies to your GetHashCode algorithm for nodes (although the collision rate is relatively low) -- hash set (and anything else like Dictionary that depend on hashing) use the equality comparison on the objects they hold to determine if two things that have the same hash code are actually equal, to account for this. Since you're adding the hash code itself, though, I believe anything that has the same hash code will be viewed as the same object to (closed.Contains()), which would be incorrect and could cause early termination on the neighbor loop when it should not do so.

​

Please feel free to let me know if I've misinterpreted any of this horribly :D

1
Chris3606GoRogue•

Update on this. I've finally got a new implementation and deals with the allocation issues better, I believe. It's measurably faster than GoRogue's old implementation on bigger maps, and if you choose to use the manhattan heuristic trick (which will be implemented as the FastAStar class), the benefit is significantly greater than that. It also performs better in the cases that I've been able to come up with on dynamically resizing maps, though performance is still not exactly where I'd like to be on that (granted it's much better). I'll be releasing this as 2.2.0, and once I do, if you happen to be able to give it a test, it'd be an awesome bonus :D

​

I also tried subbing some arrays for HashSet and Dictionary, however in many cases this caused worse performance simply because the array access is soo much faster than hash set access, and the accesses occur many times in the algorithm, so the additional access time overwhelms the allocations saved.

I'm going to continue to play around and see where I can get, but since what I have is almost universally a very, very significant improvement over the current algorithm, I want to get it released so it can get tested by users (since it checks out as far as I've been able to test it). Hope it proves helpful!

1
roundedgeOP•

That's awesome! I'll be sure to try it out if you'd be willing to make another simple build for unity for me.

I'm currently playing around with trying to write a mapview which tracks the connectivity of regions, so that I can pre-check connectivity before attempting pathfinding. But I don't really have a lot of time these days.

1
roundedgeOP•

So I ended up getting that connectivity tracking working faster than I thought. At least it works in principle. What I'm particularly proud of is that it tracks connectivity of regions on an infinite map, like the MultiSpatialMap, so instead of flood filling the whole map, it has to be a bit more delicate. Here's some footage of it in action:

https://gfycat.com/SnappySleepyArmednylonshrimp

https://gfycat.com/ObedientThoughtfulBobwhite

It still needs some work, but I'm pretty pleased my algorithm worked out. :D

1
Chris3606GoRogue•

Sweet, I'll take a look! Hit a few delays on the AStar release, mostly due to lack of dev time to get it ported into gorogue code officially and released, but as soon as I do I'll create a build for it. I actually create those minimal builds now with every release, posted on the GitHub releases page. Also, I've added build configurations for Debug Minimal Dependencies and Release Minimal Dependencies, so if you ever need to compile GoRogue yourself you can easily do so :D

1
Chris3606GoRogue•

Finally -- these AStar changes are pushed and released as part of GoRogue 2.2.0. As per the standard for this and future 2.x release, a minimal dependencies build is provided on the [releases page](https://github.com/Chris3606/GoRogue/releases), should you wish to try it out.

​

Although this version, and even moreso the new FastAStar class also provided with that build, should be significantly faster in your case and in general, there may be some more I can do for optimizing a version specifically for dynamic map-size cases. It's on my to-do list down the road, but I'm not expecting to get to it super soon as my dev-time has become extremely limited over the last couple weeks, and will likely continue that way for a few more weeks.

1
roundedgeOP•

Hey I just wanted to say that I've included the new build into my demo scenes and so far the pathfinding is very performant! So thanks for the update! :) I'm going to keep working on making a nice little unity demo game.

1