A* with manhattan distance or euclidean distance for maze solving? - path-finding

I have obtained all the possible paths of maze through image processing. Now, I want to use A* algorithm in order to find shortest path of maze. However, I am confused as to whether euclidean distance will be a better heuristic or manhattan distance. Does it depend upon maze type or is the choice of heuristic independent of maze type? Which distance (manhattan or euclidean) will be a good choice for the following possible paths and why? Please suggest.
PS. (Please add your reference too, if your have any. It will be helpful)

The objective of a Heuristic is to provide contextual information to the pathfinder. The more accurate this information is, the more efficient the pathfinder can be.
You have two contradicting requirements to get a good heuristic, which is good because it means there is a sweet spot. Here they are:
An Heuristic must be admissible, which means it shall never overestimate the distance. Otherwise, the algorithm will be broken and may return paths that are not even optimal.
An heuristic must return the largest distance possible. An heuristic that underestimates the remaining path from a cell, will favour that cell when another might have been better.
Of course the optimal Heuristic would return the exact, correct length (which generally is not achievable or defeats the purpose) because it cannot return a longer path without ceasing to be admissible.
In your case, it looks like you're dealing with 4-connected grids. In that case the manhattan distance will be a better metric than euclidian distance, because the Euclidian will under-estimate the cost of all displacements compared to Manhattan (due to the Pythagorean Theorem).
Whithout any further knowledge than 'the graph is a 4-connected Grid', there is no better metric than Manhattan. If however you manage to obtain more data (obstacle density, 'highways', etc.) then you might be able to devise a better heuristic - though keeping it admissible would be a very hard problem in itself.
EDIT Having a closer look, it looks like you have angled vertices in the bottom left. If that is so, you're not in a 4-connected graph, then you MUST use Euclidian distance, because Manhattan would not be admissible.

Its not clear what moves are available to your hero. Does you graph make up a rectangular grid like chess board and can you go diagonally in one step like king in chess? If yes then Chebyshev distance is the best https://en.wikipedia.org/wiki/Chebyshev_distance.
Otherwise use Euclidian distance.
You cant use Manhattan here if you want an optimal path because Manhattan heuristic is not admissible on diagonal routes (it overestimates them) so it can lead to suboptimal pathes

Related

Minimum length of lines needed

Suppose we have a set of N points on the cartesian plane (x_i and y_i). Suppose we connect those points with lines.
Is there any way like using a graph and something like a shortest path algorithm or minimum spanning tree so that we can reach any point starting from any point but minimizing the total length of the lines??
I though that maybe I could set the cost of the edges with the distance of a graph and use a shortest path algorithm but I'm not sure if this is possible.
Any ideas ?
I'm not 100% sure what you want, so I go for two algorithms.
First: you just want a robust algorithm, use dijkstras algorithm. The only challange left is to define the edge cost. Which would be 1 for neighboring nodes, I assume.
Second: you want to use heuristics to estimate the next best node and optimize time consumption. Use A*, but you need to write a heuristic which under estimates the distance. You could use the euclidean distance to do so. The edge problematic stays the same.

Path finding for games

What are some path finding algorithms used in games of all types? (Of all types where characters move, anyway) Is Dijkstra's ever used? I'm not really looking to code anything; just doing some research, though if you paste pseudocode or something, that would be fine (I can understand Java and C++).
I know A* is like THE algorithm to use in 2D games. That's great and all, but what about 2D games that are not grid-based? Things like Age of Empires, or Link's Awakening. There aren't distinct square spaces to navigate to, so what do they do?
What do 3D games do? I've read this thingy http://www.ai-blog.net/archives/000152.html, which I hear is a great authority on the subject, but it doesn't really explain HOW, once the meshes are set, the path finding is done. IF A* is what they use, then how is something like that done in a 3D environment? And how exactly do the splines work for rounding corners?
Dijkstra's algorithm calculates the shortest path to all nodes in a graph that are reachable from the starting position. For your average modern game, that would be both unnecessary and incredibly expensive.
You make a distinction between 2D and 3D, but it's worth noting that for any graph-based algorithm, the number of dimensions of your search space doesn't make a difference. The web page you linked to discusses waypoint graphs and navigation meshes; both are graph-based and could in principle work in any number of dimensions. Although there are no "distinct square spaces to move to", there are discrete "slots" in the space that the AI can move to and which have been carefully layed out by the game designers.
Concluding, A* is actually THE algorithm to use in 3D games just as much as in 2D games. Let's see how A* works:
At the start, you know the coordinates of your current position and
your target position. You make an optimistic estimate of the
distance to your destination, for example the length of the straight
line between the start position and the target.
Consider the adjacent nodes in the graph. If one of them is your
target (or contains it, in case of a navigation mesh), you're done.
For each adjacent node (in the case of a navigation mesh, this could
be the geometric center of the polygon or some other kind of
midpoint), estimate the associated cost of traveling along there as the
sum of two measures: the length of the path you'd have traveled so
far, and another optimistic estimate of the distance that would still
have to be covered.
Sort your options from the previous step by their estimated cost
together with all options that you've considered before, and pick
the option with the lowest estimated cost. Repeat from step 2.
There are some details I haven't discussed here, but this should be enough to see how A* is basically independent of the number of dimensions of your space. You should also be able to see why this works for continous spaces.
There are some closely related algorithms that deal with certain problems in the standard A* search. For example recursive best-first search (RBFS) and simplified memory-bounded A* (SMA*) require less memory, while learning real-time A* (LRTA*) allows the agent to move before a full path has been computed. I don't know whether these algorithms are actually used in current games.
As for the rounding of corners, this can be done either with distance lines (where corners are replaced by circular arcs), or with any kind of spline function for full-path smoothing.
In addition, algorithms are possible that rely on a gradient over the search space (where each point in space is associated with a value), rather than a graph. These are probably not applied in most games because they take more time and memory, but might be interesting to know about anyway. Examples include various hill-climbing algorithms (which are real-time by default) and potential field methods.
Methods to procedurally obtain a graph from a continuous space exist as well, for example cell decomposition, Voronoi skeletonization and probabilistic roadmap skeletonization. The former would produce something compatible with a navigation mesh (though it might be hard to make it equally efficient as a hand-crafted navigation mesh) while the latter two produce results that will be more like waypoint graphs. All of these, as well as potential field methods and A* search, are relevant to robotics.
Sources:
Artificial Intelligence: A Modern Approach, 2nd edition
Introduction to The Design and Analysis of Algorithms, 2nd edition

AABB vs Circle - Vise versa using separate axis theorem

Am following this tutorial for my 2d game collision handling , this tutorial explains about the collision used in one of my favorite game "N". How they used separate axis theorem more efficiently for collision between AABB vs AABB and AABB vs Circle. http://www.metanetsoftware.com/technique/tutorialA.html. I understand the implementation of AABB vs AABB collision handling but I couldn't understand AABB vs Circle collision detection especially voronoi regions.Totally confused how/where to start.
AABB vs AABB collision detection
Find the axis along all the edge by finding the normal of each edge.
Projection all the vertices to the
resultant Axis , final result should
be a scalar value.
The resultant scalar value in turn
is used to find whether collision is
present or not.
Can someone please explain how to handle collision AABB vc Circle - vise versa?
Since collisions with a circle always come down to a comparison against the radius (in your case, via projection), having the closest line segment (edge of the polygon) and the normal vector are the only building blocks you need. The normal vector is easily computed from the points of the line segment (something like unit(y2-y1, x1-x2) ... the negative reciprocal of the slope). Figuring out which edge is closest is the building block that remains. Voronoi regions give us the last building block.
You understand collisions between axis-aligned bounding boxes. I assume you also understand collisions between two circles. I'm assuming you don't understand voronoi regions. So, where to start? Voronoi diagrams. I highly suggest that you find a diagrammed explanation. This link is quite good. However, depending on how lost you are, perhaps a little additional background (seriously, though, no explanation can beat the visual):
A voronoi diagram is one of the ubiquitous data structures of computational geometry. Any computational geometry book will discuss the Voronoi diagram. It answers a simple question: where is the closest post office? Given a set of points in a plane (post offices), a voronoi diagram separates the plane into different regions, each containing one of the points. If you are in a particular region, you know which point (post office) is closest to you. If you were a circle, this would be nice for collision detection for a simple reason: the closest point is the most important one to test for collisions.
Note that if you want to mathematically derive a voronoi diagram, you simply consider all point pairs and calculate all bisecting lines. Then you intersect all of the bisecting lines and throw away the segments that are unimportant because some other point is closer to the point of interest (which happens at every intersection). This leads to a terribly inefficient algorithm, though. The efficient implementation involves another ubiquitous thing in computational geometry: the line-sweep algorithm. Its details can be found elsewhere; the important bit is that it provides a method of considering only the important points at any stage of the algorithm.
The voronoi regions in your tutorial are a little more complex. Instead of just points, we have line segments. Fortunately, the line-sweep algorithm handles this nicely. You mostly have to worry about the start or end of the line segments. Conceptually, not much changes once you have the basic algorithm down. Again, this is exceptionally helpful for collision detection with a circle: given the voronoi region, you know which line segment to test collisions against.
Does that even help? Feedback appreciated. I'll be happy to clarify anything. Explaining voronoi diagrams without visuals is probably a bad idea.

Optimal rotation of 3D model for 2D projection

I'm looking for a way to determine the optimal X/Y/Z rotation of a set of vertices for rendering (using the X/Y coordinates, ignoring Z) on a 2D canvas.
I've had a couple of ideas, one being pure brute-force involving performing a 3-dimensional loop ranging from 0..359 (either in steps of 1 or more, depending on results/speed requirements) on the set of vertices, measuring the difference between the min/max on both X/Y axis, storing the highest results/rotation pairs and using the most effective pair.
The second idea would be to determine the two points with the greatest distance between them in Euclidean distance, calculate the angle required to rotate the 'path' between these two points to lay along the X axis (again, we're ignoring the Z axis, so the depth within the result would not matter) and then repeating several times. The problem I can see with this is first by repeating it we may be overriding our previous rotation with a new rotation, and that the original/subsequent rotation may not neccesarily result in the greatest 2D area used. The second issue being if we use a single iteration, then the same problem occurs - the two points furthest apart may not have other poitns aligned along the same 'path', and as such we will probably not get an optimal rotation for a 2D project.
Using the second idea, perhaps using the first say 3 iterations, storing the required rotation angle, and averaging across the 3 would return a more accurate result, as it is taking into account not just a single rotation but the top 3 'pairs'.
Please, rip these ideas apart, give insight of your own. I'm intreaged to see what solutions you all may have, or algorithms unknown to me you may quote.
I would compute the principal axes of inertia, and take the axis vector v with highest corresponding moment. I would then rotate the vertices to align v with the z-axis. Let me know if you want more details about how to go about this.
Intuitively, this finds the axis about which it's hardest to rotate the points, ie, around which the vertices are the most "spread out".
Without a concrete definition of what you consider optimal, it's impossible to say how well this method performs. However, it has a few desirable properties:
If the vertices are coplanar, this method is optimal in that it will always align that plane with the x-y plane.
If the vertices are arranged into a rectangular box, the box's shortest dimension gets aligned to the z-axis.
EDIT: Here's more detailed information about how to implement this approach.
First, assign a mass to each vertex. I'll discuss options for how to do this below.
Next, compute the center of mass of your set of vertices. Then translate all of your vertices by -1 times the center of mass, so that the new center of mass is now (0,0,0).
Compute the moment of inertia tensor. This is a 3x3 matrix whose entries are given by formulas you can find on Wikipedia. The formulas depend only on the vertex positions and the masses you assigned them.
Now you need to diagonalize the inertia tensor. Since it is symmetric positive-definite, it is possible to do this by finding its eigenvectors and eigenvalues. Unfortunately, numerical algorithms for finding these tend to be complicated; the most direct approach requires finding the roots of a cubic polynomial. However finding the eigenvalues and eigenvectors of a matrix is an extremely common problem and any linear algebra package worth its salt will come with code that can do this for you (for example, the open-source linear algebra package Eigen has SelfAdjointEigenSolver.) You might also be able to find lighter-weight code specialized to the 3x3 case on the Internet.
You now have three eigenvectors and their corresponding eigenvalues. These eigenvalues will be positive. Take the eigenvector corresponding to the largest eigenvalue; this vector points in the direction of your new z-axis.
Now, about the choice of mass. The simplest thing to do is to give all vertices a mass of 1. If all you have is a cloud of points, this is probably a good solution.
You could also set each star's mass to be its real-world mass, if you have access to that data. If you do this, the z-axis you compute will also be the axis about which the star system is (most likely) rotating.
This answer is intended to be valid only for convex polyhedra.
In http://203.208.166.84/masudhasan/cgta_silhouette.pdf you can find
"In this paper, we study how to select view points of convex polyhedra such that the silhouette satisfies certain properties. Specifically, we give algorithms to find all projections of a convex polyhedron such that a given set of edges, faces and/or vertices appear on the silhouette."
The paper is an in-depth analysis of the properties and algorithms of polyhedra projections. But it is not easy to follow, I should admit.
With that algorithm at hand, your problem is combinatorics: select all sets of possible vertexes, check whether or not exist a projection for each set, and if it does exists, calculate the area of the convex hull of the silhouette.
You did not provide the approx number of vertex. But as always, a combinatorial solution is not recommended for unbounded (aka big) quantities.

How can I compute the mass and moment of inertia of a polyhedron?

For use in a rigid body simulation, I want to compute the mass and inertia tensor (moment of inertia), given a triangle mesh representing the boundary of the (not necessarily convex) object, and assuming constant density in the interior.
Assuming your trimesh is closed (whether convex or not) there is a way!
As dmckee points out, the general approach is building tetrahedrons from each surface triangle, then applying the obvious math to total up the mass and moment contributions from each tet. The trick comes in when the surface of the body has concavities that make internal pockets when viewed from whatever your reference point is.
So, to get started, pick some reference point (the origin in model coordinates will work fine), it doesn't even need to be inside of the body. For every triangle, connect the three points of that triangle to the reference point to form a tetrahedron. Here's the trick: use the triangle's surface normal to figure out if the triangle is facing towards or away from the reference point (which you can find by looking at the sign of the dot product of the normal and a vector pointing at the centroid of the triangle). If the triangle is facing away from the reference point, treat its mass and moment normally, but if it is facing towards the reference point (suggesting that there is open space between the reference point and the solid body), negate your results for that tet.
Effectively what this does is over-count chunks of volume and then correct once those areas are shown to be not part of the solid body. If a body has lots of blubbery flanges and grotesque folds (got that image?), a particular piece of volume may be over-counted by a hefty factor, but it will be subtracted off just enough times to cancel it out if your mesh is closed. Working this way you can even handle internal bubbles of space in your objects (assuming the normals are set correctly). On top of that, each triangle can be handled independently so you can parallelize at will. Enjoy!
Afterthought: You might wonder what happens when that dot product gives you a value at or near zero. This only happens when the triangle face is parallel (its normal is perpendicular) do the direction to the reference point -- which only happens for degenerate tets with small or zero area anyway. That is to say, the decision to add or subtract a tet's contribution is only questionable when the tet wasn't going to contribute anything anyway.
Decompose your object into a set of tetrahedrons around the selected interior point. (That is solids using each triangular face element and the chosen center.)
You should be able to look up the volume of each element. The moment of inertia should also be available.
It gets to be rather more trouble if the surface is non-convex.
I seem to have miss-remembered by nomenclature and skew is not the adjective I wanted. I mean non-regular.
This is covered in the book "Game Physics, Second Edition" by D. Eberly. The chapter 2.5.5 and sample code is available online. (Just found it, haven't tried it out yet.)
Also note that the polyhedron doesn't have to be convex for the formulas to work, it just has to be simple.
I'd take a look at vtkMassProperties. This is a fairly robust algorithm for computing this, given a surface enclosing a volume.
If your polydedron is complicated, consider using Monte Carlo integration, which is often used for multidimensional integrals. You will need an enclosing hypercube, and you will need to be able to test whether a given point is inside or outside the polyhedron. And you will need to be patient, as Monte Carlo integration is slow.
Start as usual at Wikipedia, and then follow the external links pages for further reading.
(For those unfamiliar with Monte Carlo integration, here's how to compute a mass. Pick a point in the containing hypercube. Add to the point_total counter. Is it in the polyhedron? If yes, add to the point_internal counter. Do this lots (see the convergence and error bound estimates.) Then
mass_polyhedron/mass_hypercube \approx points_internal/points_total.
For a moment of inertia, you weight each count by the square of the distance of the point to the reference axis.
The tricky part is testing whether a point is inside or outside your polyhedron. I'm sure that there are computational geometry algorithms for that.

Resources