Sunday, August 18, 2013

avoiding collisions with pathfinding

We split bot navigation into two layers - pathfinding is run for each bot independently, which yields a path (which will persist for a long time), and we hand off that path to a more reactive system (eg. a steering system that uses velocity obstacles or something) which is responsible for dealing with surprises like other bots getting in the way. Even thought steering works well at preventing collisions between bots, it has to use the path it's given, and it can't avoid chokepoints that force it through other bots - paths that end up slowing everyone down and making them look dumb. 

Here's an example in my toy pathfinder: white squares are traversable, dark grey are blocked, and the colored plus signs are the paths of 4 different bots (they're taking paths that heavily overlap each other). All the paths go through the chokepoint in the middle. The purple bot could have easily avoided the traffic jam by going south a bit, but instead he's taking a (slower!) path that forces him to deal with everyone else.


If we increase the path cost of chokepoints by predicting heavily contested positions, A* will route us around those traffic jams. It's easy to predict where other bots will be - just look at their paths. To keep things fast, you can implement this with a per-position count of the number of paths that use each position (treated like a refcount) - that way, the cost of finding a path is independent of the number of other paths.

Here's my toy implementation: although the naive shortest path for all 4 bots would go through the same chokepoint, the bots now take paths that avoid each other. (their 'avoidance radius' falls off at 3 squares, so they're giving each other a wide berth). If the cost were higher, they'd worker harder to avoid each other - but some path intersection is unavoidable here.


This sort of system could be an improvement for style reasons, too - imagine a swat team spreading out to clear an apartment - although maybe they're ultimately going to the same place, you want them to explore as much as they can (kind of like a cheapo version of influence maps).

One complication is that paths become order dependent. The first bot to path in an area ignores everyone else, the second bot only ignores the first, etc. Finding truly 'correct' paths in this case would need to be done simultaneously for everyone (but I don't see how that would even work! Any ideas?).

A less tricky implementation would be to only approximately track positions - by keeping a per-area refcount (if your game spaces are hierarchically partitioned), or only attaching the cost to doorways, or only tracking bend points on the path rather than every position, etc.

A more tricky version would be time-indexed - meaning you care about the specific *time* that each bot will arrive in each position. This makes things more correct - a bot would be happy walking in single-file behind other bots. However, time-indexing has a few caveats:

  • makes the bookkeeping more complicated, and makes the runtime slower (slightly)
  • requires your pathfinding system to accurately predict the movement speed of a bot
I tried to implement time-indexing, but it introduced weird kinks in returned paths, where paths will intentionally waste time (running in a useless circle) to avoid a collision in the future (which makes sense in terms of pathfinding, but looks like a bug). I tried to fix this by adding a low-cost 'wait in place' action that bots can do (in addition to moving in their 8 directions), but that ended up being a giant can of worms - because it means A* needs to re-visit positions that are already in the closed set with a lower cost.


Maybe a simpler alternative to time-indexing would be to tag each position with a velocity - that way you'd get more cooperative groups without all the complexity of real time-indexing. Ie. you're saying "you can use this door without trouble if you're going north".

Here's a paper that does something kind of similar that got me thinking about all this: I think their videos show really impressive group dynamics, and I think a big part of what makes it look good is the planned-local-avoidance thing (more than the footstep planning animation synthesis, although that's pretty cool too!).

Sunday, April 7, 2013

exploring more dimensions with A*

When you're running A*, you're searching over the edges and vertices of a graph, where the graph's vertices represent some kind of state, and the edges between vertices are the state changes. In pathfinding, the states are positions, and edges are the smallest movements you can do to get between neighboring positions, like "move +X", or "move +Z".
State = {x, z}
State Transitions = { +x, -x, +z, -z }


You end up with a resulting path like this: Grey tiles are blocked, white are unblocked, and red shows the resulting path found by a pretty vanilla A*, going from upper right to lower left.
Blue shows the nodes we visited during the search.


This can be kind of crappy for games where you want to model more complex mechanics of motion: characters in games can't really just "move +Z". For an example, imagine a car - they can take several seconds to accelerate up to full speed, or to make a 90 degree turn. If we build a shortest-length path for the car to follow, he'll have to drive really slowly to make all the tiny fiddly sharp turns (or in the worst case, be completely unable to make them at all). This might be the shortest distance, but it's not the shortest duration path. And even in games with just human characters (which I work on), you can sometimes spot guys running at full speed trying to follow a shortest-distance path, which makes them look robotic. It can also cause bugs if we try to satisfy physical constraints about limited acceleration or turn speeds, and the path violates those contraints (eg. making 90 degree turns around corners).

If we can more accurately model the state space, we'll get a more accurate shortest-duration path:
State = { x,  z, vel_x, vel_z }
State Transitions = { +vel_x, -vel_x, +vel_z, -vel_z }  
// the driver only controls acceleration, not position
Then if we also have an appropriate interface for A* to know about this more complex state (so get_neighbors(state) needs to return the result of acceleration in each direction, and heuristic_cost(state) takes velocity and acceleration into account to derive a minimum arrival time), we get something like this instead:


For this image, our dude can move at a top speed of 10 tiles/sec, but can only accelerate at 1 tile/sec^2 (which is a roughly car-ish ratio of top speed to acceleration).
What's cool about this is:
- it's indeed a shorter-duration path even though it's longer
- the driver avoids navigating around all the little obstacles
- you can see the faster path "swings wide" around that corner to be able to go faster
- you can see the explored region (in blue) finds the few quick paths through the obstacles

Neat! It makes me want to make an all-terrain driving obstacle course game. I think to be really accurate, you'd want to feed something close to the game's real rules/simulation into A* - so that it could explore the accurate consequences of its choices. In that case, the inputs for a car would probably be something like:
State Transitions = { rotate steering left, rotate steering right, more gas, less gas (or brake) }
(or whatever the inputs to a car are for your AIs).

The big downside, of course, is the cost of computing this stuff, since we're exploring in more dimensions. For the blue region shown on the map, in the worst case there can be up to 200 "visited" nodes overlapped on each tile position (because of how I quantized my velocity - I don't know how you'd do this with a more analog velocity space). Practically it wouldn't be so bad, but in my test code, paths were about 20x more expensive to find - and certain clever optimizations to A* (like jump point search) don't work anymore.

My pipedream, though is to write a bot for "quake done quick" that has the player's inputs as the state space:
State Transitions = { w, a, s, d, jump, aim delta, fire, switch weapons }
But that sounds impossibly slow, right? If that bot could discover rocket jumping, I'd be ecstatic.

Saturday, July 28, 2012

Spelunky

Spelunky is difficult, but not in the style of technical platformers (VVVVVV or N+ or whatever). It’s difficult in the same way roguelikes are – lots of things will kill you, so you have to be attentive, and learn how the game mechanics can combine in unexpected ways. The levels are procedural, so there are no hand-crafted puzzles to solve. I feel like my deaths are always my fault, which is good in a game with permadeath and a life expectancy of a few minutes.

I can only play for about an hour at a time, though – even though I’m still enjoying playing, I can’t stay focused and cautious for that long :( 

Get it at http://spelunkyworld.com/

Sunday, August 14, 2011

graph optimization

Is there a well-known method to simplify a nav graph? From what I've seen most people have a nav mesh (made of triangles), not a graph (made of edges). But assume you have a graph - is there a well-known method to remove the edges that wouldn't significantly shorten the paths found on the graph? I wonder if this is a well-known problem (I don't know what to search for on google - "graph simplification" turns up a bunch of weird topology papers).

I wrote up a little solution for it that I think works pretty well. Here's my sweet-ass visualization: http://i.imgur.com/XMOaM.png
It's a graph made of random edges in 3d. Black lines were rejected from the original graph, white lines were kept in the simplified graph.

The method is to keep candidate edges from the original graph only when they're shorter than some fraction of the shortest existing path between those vertices. Like building a minimum spanning tree, visit the candidates in length order.

The tricky part is you need to know those shortest path lengths (for all pairs of verts in the graph as they're added). To do that, you can propagate shortest-path updates each time you add an edge (a newly shortened path AB adds new potential shortened paths from A to each of B's neighbors and from B to each of A's neighbors too).

All paths in the shrunk graph are guaranteed to be within an arbitrary threshold of optimal. (if the threshold is small, you get a minimum spanning tree, which is neat!). In the picture, it's a <2x optimal path length guarantee.

Performance is weird, something like O(#verts * #edges)? The shortest-path-update ordering (stack vs. queue for the to-visit list) has a huge impact on performance and I'm not really sure why :o It handles graphs up to about 500-1000 edges instantly, but barfs on bigger inputs. The aspect that could be improved is the shortest path propogation - depending on the edge add order, a lot of the path shrinking is wasted effort.

I think a further improvement would be start with the minimum spanning tree (which is decently fast), compute the all-pairs shortest paths, then start adding the remaining candidate edges. This skips the majority of the shortest-path updating, since the graph is mostly connected.

Let me know if you want me to post the code somewhere, it's pretty simple.

Wednesday, June 1, 2011

spacechem!

Spacechem is my game of the year so far (either that or terraria!): Introductory video.

It’s in the weird little genre of engineering games, where you design a machine that performs some task, like “fantastic contraption”, “the incredible machine”, or “armadillo run”. They’re never really that popular, but they’re like catnip to me - puzzle games where you invent a solution instead of discovering it.

Here's an interview with the developer that I really liked.

Although it’s called spacechem, it’s only fictionally about chemistry (you’re physically manipulating atoms to perform chemical reactions... in space!). It’s really a programming game – you design a machine on a 2D grid of component machine parts, and the parts have different interaction rules. It’s kind of like visual scripting, kind of like designing a circuit. You watch the machine run, then tweak your design until your machine can perform some task.

The game does a great job of building up complexity gradually – at the beginning of the game you’re given simple components and tasks, and by the end of the game you’re doing things that would have been completely impossible for you in the beginning. It’s the good kind of mind-bending – you feel yourself getting better at the game, and you see your designs getting more efficient and elegant.

The game has a demo if it seems like your kind of thing!

Friday, December 17, 2010

Tiny multiplayer RTS

I made a tiny multiplayer RTS for XNA. You don't get direct control over your units, you only get an abstract kind of strategic choice - a balance between higher-level strategies. In a real RTS, being able to micro your units is critical, but so is knowing the higher-level strategies, and this is a toy model of those higher level strategies. In almost every RTS (with the exception of myth?), you have to maintain a constant balance between defending, attacking, and expanding - and there's an RPS relationship between them. (Turtle beats rush, rush beats expand, expand beats turtle). In this tiny RTS, instead of having direct control over your units, all you get is control over that production balance (choosing to produce more offense, defense, or econ units), and choosing how to time attacks.

Here's a screenshot of some of my attackers (the swords) on their way from my base (upper left) to the enemy base (lower right).


Design: I like the RPS relationship between the three strategies, and how your opponent's strategy is hidden from you - you have to scout out the enemy, since there's a fog of war.

I like the exponential economic growth, I think that nicely captures the quick economic ramp-up you find in RTSs. It doesn't plateau as naturally as in real RTSs, where your growth is quickly limited by various bottlenecks (like having a cap on simultaneous peon units extracting resources, or tying economic growth to expanding over the whole map).

I don't like how scouting is "free" - normally in RTSs you're sacrificing the units to do scouting. I also don't like how geography doesn't really matter - you can't position your attackers and defenders in a way that protects your base, or fighting over one resource instead of another. In an earlier version of the game, I made it so that the attackers couldn't kill econ units until all the attackers and defenders were dead, but that ended up being pretty broken.

Technical details: It's using GFWL for the matchmaking - although I hate it as a gamer, it's is super easy to code with it and XNA. However, unless you're a registered Indie/Community/AppHub developer, you're limited to playing LAN games, which is sucky. I made the game automatically host if no games are available, and automatically connect to any games that are waiting for players - so run a copy of the game on two machines on a LAN and you're set to have the most fun possible! You *may* have to create a new "offline" GFWL profile to make it not search for games on the internet :(

It's a clickonce installer, which is pretty slick (although the installer UI can be a little janky, it's cool that it automatically installs and updates itself with barely any work on my part). The source is available on the codeplex project page, but it's nothing special.

As for networking, it's a lockstep/deterministic simulation that sends user input over the network before it's used in the simulation (in the style of starcraft), so it's really low bandwidth, at the cost of a fixed 250ms latency on your input. It's been forever since I've done any networking code, and I'm glad this was relatively straightforward (with a couple desyncing bugs).

I stole the barycentric-allocation-triangle idea from simant :)

Sunday, October 24, 2010

how to make bechamel sauce the first time

* melt butter in saucepan
* begin panicking
* with one hand on the tippy saucepan and the other hand whisking, use another hand to add flour, milk, bay leaves, allspice, salt and pepper, and another hand to adjust the heat to keep it between getting too hot and drying out, and getting too cold and coagulating
* be suprised it's not a lumpy burned mess, optionally stop panicking
* put on moussaka