Polygon Raycast

Hi everyone,

I decided not to post this in the big thread about jbox2d because I figured that thread was more about the official development of the library.

Anyway, I wrote a little code to raycast on PolygonShape objects which you can see in action here:
EDIT: Press '0' (thats zero) to toggle debug rendering
http://blissfulthinking.nl/gamezero

If you are interrested I could post the code here.
Sure, it'll help other developers do ray casting as well.
Ok here goes. People using it will need to modify how they access their shapes. I call upon a LinkedList of Wall objects. These are basicly my custom userdata objects tied to the world bodies. Anyway, get some Shape objects in there.

There are three methods:
isVisible, the fastest, to know if two points are visible from one another.
getIntersections, slower, but returns all intersections between two points
getClosestIntersection, slowest but returns the closest intersetion

I think getClosestIntersection could be made faster by comparing the distance to the Shape with the closest intersection found before checking the vertices.

It can now also be seen to work in the normal version, toggle it on and off with '0'
http://blissfulthinking.nl/gamezero

Sorry for verbatim lines of code but I didn't feel like splitting it further.

Code:
/**
    * Can tell you whether two points are visible from one another
    * @param point1
    * @param point2
    * @return TRUE if the points are visible from one another , FALSE if there is a wall blocking the view
    */
   public final boolean isVisible(Vec2 point1, Vec2 point2) {
      //Get a iterator for the Walls
      ListIterator<Wall> wallsI = walls.listIterator();
      
      //Run through the list of Walls
      while(wallsI.hasNext()) {
   
         //Load a Wall
         Wall w = wallsI.next();
         
         //WALLS ARE ALWAYS POLYGON SHAPES OR THIS EXPLODES!
         
         //Get its Shape
         PolygonShape s = (PolygonShape) w.getBody().getShapeList();
         
         //Load the number of lines in this Shape
         int linesCount = s.getVertexCount();
         //Load the vertices of this Shape
         Vec2[] vertices = s.getVertices();
         
         //This iterator represents the end point of a segment
         int ii = 1;
         //For the number of lines in the Shape
         for(int i=0;i<linesCount;i++) {
            //Call Java2D intersect method which tells us IF there is an intersection between the given lines
            if(Line2D.linesIntersect(
                  //Supply the beginning and end point of the provided segment
                  point1.x,point1.y,
                  point2.x,point2.y,
                  //The start-vertex of the Shape's segment
                  vertices[i].x,vertices[i].y,
                  //The end-vertex of the Shape's segment
                  vertices[ii].x,vertices[ii].y)) {
               
               //If there is a intersection the view is blocked
               return false;
            }
            
            //Increment Shape's segment end-vertex
            ii++;
            //If it is greater than the array's length, we take the first vertex at index zero
            if(ii == linesCount) {
               ii=0;
            }
         }   
      }
      
      //The method has not returned so the two points can see each other
      return true;
   }
   
   /**
    * Can tell you all intersections between two provided points
    * @param point1
    * @param point2
    * @return An ArrayList<Vec2> containing all the intersections found
    */
   public final ArrayList<Vec2> getIntersections(Vec2 point1, Vec2 point2) {
      //Make an array to store results
      ArrayList<Vec2> intersections = new ArrayList<Vec2>();
      
      //Get a iterator for the Walls
      ListIterator<Wall> wallsI = walls.listIterator();
      
      //Declare variable to store the Shape's number of segments
      int linesCount;
      //Declare variable to store the Shape's number of segments
      Vec2[] vertices;
      
      //Run through the list of Walls
      while(wallsI.hasNext()) {
         
         //Load a Wall
         Wall w = wallsI.next();
         
         //WALLS ARE ALWAYS POLYGON SHAPES OR THIS EXPLODES!
         
         //Get the shape
         PolygonShape s = (PolygonShape) w.getBody().getShapeList();
         
         //Load the number of lines in this Shape
         linesCount = s.getVertexCount();   
         //Load the vertices of this Shape
         vertices = s.getVertices();
         
         //This iterator represents the end point of a segment
         int ii = 1;
         //For the number of lines in the Shape
         for(int i=0;i<linesCount;i++) {
            //Call Java2D intersect method which tells us IF there is an intersection between the given lines
            if(Line2D.linesIntersect(
                  //Supply the beginning and end point of the provided segment
                  point1.x,point1.y,
                  point2.x,point2.y,
                  
                  //The start-vertex of the Shape's segment
                  vertices[i].x,vertices[i].y,
                  //The end-vertex of the Shape's segment
                  vertices[ii].x,vertices[ii].y)) {
               
               //Declare variables to store the slope of both segments
               float slope1;
               float slope2;
               
               //We need to know the horizontal difference to prevent divide by zero
               float xSlope1 = (point2.x - point1.x);
               float xSlope2 = (vertices[ii].x - vertices[i].x);
               
               //We check if it is not zero
               if(xSlope1 == 0) {
                  //We will use the static horizontal position
                  slope1 = point1.x;
               }
               //Else we calculate it
               else {
                  slope1 = ((point2.y - point1.y) / (point2.x - point1.x));
               }
               //Same for the other segment
               if(xSlope2 == 0) {
                  slope2 = vertices[i].x;
               }
               else {
                  slope2 = ((vertices[ii].y - vertices[i].y) / (vertices[ii].x - vertices[i].x));
               }
               
               //Calculate the vertical interception-point
               float intercept1 = point1.y - (slope1 * point1.x);
               float intercept2 = vertices[i].y - (slope2 * vertices[i].x);
               
               //Calculate the intersection
               Vec2 intersection = new Vec2(0.0f,0.0f);
               intersection.x = ( (intercept2 - intercept1) / (slope1 - slope2) );
               intersection.y = (slope1 * intersection.x) + intercept1;

               //Add this intersection to the result-set
               intersections.add(intersection);
               
               //Calling worldToScreen from a DebugDraw type class
               Vec2 screenPos = Main.getMain().getRenderer().worldToScreen(intersection);
               Main.getMain().stroke(0.0f,0.0f,255.0f);
               Main.getMain().rect(screenPos.x-5,screenPos.y-5,10,10);
            }
            
            //Increment Shape's segment end-vertex
            ii++;
            //If it is greater than the array's length, we take the first vertex at index zero
            if(ii == linesCount) {
               ii=0;
            }
         }
         
      }
      
      //Return the set of results, with or without intersections
      return intersections;
   }
   
   /**
    * Find the intersection closest to a given point
    * @param point1
    * @param point2
    * @param proximityTarget
    * @return A Vec2 object containing the intersection found closest to the provided position or NULL if no intersestions were found
    */
   public final Vec2 getClosestIntersect(Vec2 point1, Vec2 point2, Vec2 proximityTarget) {
      //Get a iterator for the Walls
      ListIterator<Wall> wallsI = walls.listIterator();
   
      //Variable that stores the distance to the closest intersection found
      float closestProximity = Float.MAX_VALUE;
      //Variable containing the position of the closest intersection found
      Vec2 closestIntersection = null;
      
      //Declare variable to store the Shape's number of segments
      int linesCount;
      //Declare variable to store the Shape's number of segments
      Vec2[] vertices;
      
      //Run through the list of Walls
      while(wallsI.hasNext()) {
         //Load a Wall
         Wall w = wallsI.next();
         
         //WALLS ARE ALWAYS POLYGON SHAPES OR THIS EXPLODES!
         
         //Get the shape
         PolygonShape s = (PolygonShape) w.getBody().getShapeList();
         
         //Load the number of lines in this Shape
         linesCount = s.getVertexCount();   
         //Load the vertices of this Shape
         vertices = s.getVertices();
            
         //This iterator represents the end point of a segment
         int ii = 1;
         //For the number of lines in the Shape
         for(int i=0;i<linesCount;i++) {
            //Call Java2D intersect method which tells us IF there is an intersection between the given lines
            if(Line2D.linesIntersect(
                  //Supply the beginning and end point of the provided segment
                  point1.x,point1.y,
                  point2.x,point2.y,
                  
                  //The start-vertex of the Shape's segment
                  vertices[i].x,vertices[i].y,
                  //The end-vertex of the Shape's segment
                  vertices[ii].x,vertices[ii].y)) {
               
               //Declare variables to store the slope of both segments
               float slope1;
               float slope2;
               
               //We need to know the horizontal difference to prevent divide by zero
               float xSlope1 = (point2.x - point1.x);
               float xSlope2 = (vertices[ii].x - vertices[i].x);
               
               //We check if it is not zero
               if(xSlope1 == 0) {
                  //We will use the static horizontal position
                  slope1 = point1.x;
               }
               //Else we calculate it
               else {
                  slope1 = ((point2.y - point1.y) / (point2.x - point1.x));
               }
               //Same for the other segment
               if(xSlope2 == 0) {
                  slope2 = vertices[i].x;
               }
               else {
                  slope2 = ((vertices[ii].y - vertices[i].y) / (vertices[ii].x - vertices[i].x));
               }
               
               //Calculate the vertical interception-point
               float intercept1 = point1.y - (slope1 * point1.x);
               float intercept2 = vertices[i].y - (slope2 * vertices[i].x);
               
               //Calculate the intersection
               Vec2 intersection = new Vec2(0.0f,0.0f);
               intersection.x = ( (intercept2 - intercept1) / (slope1 - slope2) );
               intersection.y = (slope1 * intersection.x) + intercept1;

               //Calculate the distance to this intersection
               float proximity = CalculationTool.getDistance(intersection, proximityTarget);
               //If it is closer than the closest yet found
               if(proximity < closestProximity) {
                  //Update these variables
                  closestProximity = proximity;
                  closestIntersection = intersection;
               }
            }
            
            //Increment Shape's segment end-vertex
            ii++;
            //If it is greater than the array's length, we take the first vertex at index zero
            if(ii == linesCount) {
               ii=0;
            }
         }
         
      }
      
      if(closestIntersection != null) {
         Vec2 screenPos = Main.getMain().getRenderer().worldToScreen(closestIntersection);
         Main.getMain().stroke(0.0f,255.0f,0.0f);
         Main.getMain().rect(screenPos.x-5,screenPos.y-5,10,10);
      }
      
      //Return the closest intersection found or NULL if there were no intersections
      return closestIntersection;
   }
I like these, very nice work, and easily understandable. In case you didn't know, jbox2d does have some raycasting support (testSegment() methods), but it isn't as integrated as box2d yet (we're updating it in the next version). But it's more low level.
Would it be faster to do a overlap check of the Shape's upper and lower bounds and the line's upper and lower bounds first. before checking the vertices?
Right, the demo now makes good use of the isVisible() method.

What you can see:
Little blue squares which are Waypoints, they are added to my level in Inkscape as just unconnected dots. When the world is loaded it will do a visibility check from each Waypoint to all other Waypoints. Each Waypoint stores all other Waypoints it can see. The links between them are drawn yellowish.

When you fly around you can see a green line snapping to your player and your mouse position. There is a simple method at work called getClosestWaypoint(Vec2) which return the closest, visisble Waypoint to a position.

Right, now for the magic, you can press '9' and the program will try to make a path which, when found, will be shown with red squares and lines. This is done by calling the method getShortestRoute(Vec2 from, Vec2 to).

This method return a Route object or NULL if no Route can be made. If the two requested points are visible from each other a "empty" Route is returned containing only the provided positions. Else a Route also hold an array with the Waypoints that are between those points.

It takes the neighbours of the Waypoint closest to your starting position and sorts them with respect to their distance to the waypoint closest to the target position. It then recursively runs this same principle over these Waypoints.

There is more to it and I will post it soon once I clean up the code.

EDIT: I hope you can find quircks in it because you know how unpredictable these things can be, the idea is it to be fast but... it might give some strange suggestion one in a while.
It all looks fantastic. Are your waypoints automatically generated?
Waypoints are put there by hand. You can see it in this file:
http://blissfulthinking.nl/levelzero.svg (EDIT: try "save as")
Look for a layer called "Waypoints", it contains rectangular shapes which are parsed into Waypoint object which end up in a ArrayList in my custom World class.

This is the Waypoint class:
Code:
import java.util.ArrayList;

import nl.blissfulthinking.java.gamezero.Main;

import org.jbox2d.common.Vec2;

/**
* Waypoints have a world position and have references to all Waypoints visible from their position.
* @author Michiel
*
*/
public class Waypoint {
   
   /**
    * The Waypoint's (static) world position
    */
   public final Vec2 position;
   
   /**
    * The Waypoint's neighbours, i.e. the Waypoints visible from its location
    */
   private final ArrayList<Waypoint> neighbours = new ArrayList<Waypoint>();
   
   /**
    * Constructor, makes a new Waypoint object
    * @param position The world position of this Waypoint
    */
   public Waypoint(Vec2 position) {
      this.position = position;
   }

   /**
    * Debug rendering of this Waypoint. It displays the Waypoint and draws a line to all its neighbours.
    */
   public void render() {
      //Draw a rectangle around the Waypoint
      Vec2 screenPos = Main.getMain().getRenderer().worldToScreen(position);
      Main.getMain().stroke(0.0f,144.0f,144.0f);
      Main.getMain().fill(0);
      Main.getMain().rect(screenPos.x-5,screenPos.y-5,10,10);
      
      //Draws lines to all neighbouring Waypoints
      Main.getMain().stroke(200.0f,200.0f,0.0f);
      Vec2 neighbourPos = new Vec2(0.0f,0.0f);
      for(Waypoint w : neighbours) {
         neighbourPos = Main.getMain().getRenderer().worldToScreen(w.position);
         Main.getMain().line(screenPos.x, screenPos.y, neighbourPos.x, neighbourPos.y);
      }
   }
   
   /**
    * Adds a Waypoint to this Waypoint's list of neighbours.
    * @param waypoint The Waypoint you want added.
    */
   public void addNeighbour(Waypoint waypoint) {
      if(!neighbours.contains(waypoint)) {
         neighbours.add(waypoint);
      }
   }
   
   /**
    * Return an ArrayList containing all the neighbouring Waypoints of this Waypoint.
    * @return neighbours ArrayList<Waypoint> containing all the neighbouring Waypoints.
    */
   public ArrayList<Waypoint> getNeighbours() {
      return neighbours;
   }

}


Righty, when I finilize the World before playing I link them up with this method:
Code:
   /**
    * Initializes all static waypoints in this world. SHOULD ONLY BE CALLED ONCE!
    */
   public void initWaypoints() {
      for(Waypoint w0 : waypoints) {
         for(Waypoint w1 : waypoints) {
            if(w0.equals(w1)) {
               //System.out.println("this is the same waypoint, continueing");
               continue;
            }
            if(isVisible(w0.position,w1.position)) {
               //System.out.println("making neighbour");
               w0.addNeighbour(w1);
            }
         }
      }
      
      //Remove Waypoints without neighbours
      ArrayList<Waypoint> emptyWaypoints = new ArrayList<Waypoint>();
      for(Waypoint w : waypoints) {
         if(w.getNeighbours().size() == 0) {
            System.out.println("There is a useless Waypoint at :"+w.position);
            emptyWaypoints.add(w);
         }
      }
      waypoints.removeAll(emptyWaypoints);
   }


Ok they are linked up now and empty Waypoints didn't make it into the list.

Now from inside the game we can try to get a Route from point A to point B. This is the Route class, it will become more clear once you see the methods that use it:
Code:
import java.util.ArrayList;

import org.jbox2d.common.Vec2;

import nl.blissfulthinking.java.gamezero.Main;
import nl.blissfulthinking.java.gamezero.tools.CalculationTool;

/**
* Holds route information.
* @author Michiel
*
*/
public class Route {

   /**
    * The Waypoints that make up this Route
    */
   private ArrayList<Waypoint> waypoints = null;

   /**
    * The starting position of this Route
    */
   public Vec2 startPos = new Vec2(0.0f,0.0f);
   
   /**
    * The target position of this Route
    */
   public Vec2 targetPos = new Vec2(0.0f,0.0f);
   
   /**
    * The length of this Route
    */
   public float length = 0.0f;
   
   /**
    * Add a Waypoint to this Route. Also updates the length of this Route if successful.
    * @param waypoint
    * @return TRUE if the Waypoint was added, FALSE if it could not be added because the Waypoint was already part of this Route.
    */
   public boolean addWaypoint(Waypoint waypoint) {
      if(!waypoints.contains(waypoint)) {
         float length = CalculationTool.getDistance(waypoints.get(waypoints.size()-1).position,waypoint.position);
         this.length += length;
         waypoints.add(waypoint);
         return true;
      }
      else {
         return false;
      }
   }
   
   /**
    * Create a new Route object with only its starting and target position set.
    * @param startPos
    * @param targetPos
    */
   public Route(Vec2 startPos, Vec2 targetPos) {
      this.startPos = startPos;
      this.targetPos = targetPos;
   }
   
   /**
    * Tries to nibble off some Waypoints by checking if the second and second last Waypoint are visible,
    * from respectively the starting and target position.
    */
   public void prune() {
      if(waypoints != null) {   
         if(waypoints.size() > 1) {
            if(Level.getWorld().isVisible(startPos, waypoints.get(1).position)) {
               System.out.println("pruned off the first node");
               waypoints.remove(0);
            }
            if(waypoints.size() > 1) {   
               if(Level.getWorld().isVisible(targetPos, waypoints.get(waypoints.size()-2).position)) {
                  System.out.println("pruned off the last node");
                  waypoints.remove(waypoints.size()-1);
               }
            }
         }   
      }
   }

   /**
    * Clone constructor
    * @param r
    */
   @SuppressWarnings("unchecked")
   public Route(Route r) {
      //Copy values from the provided Route
      waypoints = (ArrayList<Waypoint>) r.getWaypoints().clone();
      length = r.length;
      this.startPos.x = r.startPos.x;
      this.startPos.y = r.startPos.y;
      this.targetPos.x = r.targetPos.x;
      this.targetPos.y = r.targetPos.y;
   }
   
   /**
    * Create a new Route with at least one Waypoint, more can (and should) be added afterwards with addWaypoint()
    * @param w The Waypoint you want the Route to start with
    * @param startPos The starting position of this Route
    * @param targetPos The target position of this Route
    */
   public Route(Waypoint w, Vec2 startPos, Vec2 targetPos) {
      waypoints = new ArrayList<Waypoint>();
      waypoints.add(w);
      this.startPos = startPos;
      this.targetPos = targetPos;
   }
   
   /**
    * Returns the ArrayList<Waypoint> containing all Waypoints belonging to this Route
    * @return ArrayList<Waypoint> if this Route has Waypoints or NULL if it does not hve any.
    */
   public ArrayList<Waypoint> getWaypoints() {
      return waypoints;
   }
   
   /**
    * Debug rendering of Route information
    */
   public void render() {
      //If the Route has Waypoints attached
      if(waypoints != null) {
         Vec2 screenPos;
         Vec2 neighbourPos;
         
         for(int i=0;i<waypoints.size();i++) {
            screenPos = Main.getMain().getRenderer().worldToScreen(waypoints.get(i).position);
            Main.getMain().stroke(255.0f,0.0f,0.0f);
            Main.getMain().rect(screenPos.x-5,screenPos.y-5,10,10);
            
            if(i<waypoints.size()-1) {
               Main.getMain().stroke(255.0f,0.0f,255.0f);
               neighbourPos = waypoints.get(i+1).position;
            
               neighbourPos = Main.getMain().getRenderer().worldToScreen(neighbourPos);
               Main.getMain().line(screenPos.x, screenPos.y, neighbourPos.x, neighbourPos.y);
            }
         }
         
         screenPos = Main.getMain().getRenderer().worldToScreen(startPos);
         Main.getMain().stroke(255.0f,0.0f,0.0f);
         Main.getMain().rect(screenPos.x-5,screenPos.y-5,10,10);
         
         Main.getMain().stroke(255.0f,0.0f,255.0f);
         neighbourPos = waypoints.get(0).position;
         neighbourPos = Main.getMain().getRenderer().worldToScreen(neighbourPos);
         Main.getMain().line(screenPos.x, screenPos.y, neighbourPos.x, neighbourPos.y);
         
         screenPos = Main.getMain().getRenderer().worldToScreen(targetPos);
         Main.getMain().stroke(255.0f,0.0f,0.0f);
         Main.getMain().rect(screenPos.x-5,screenPos.y-5,10,10);
         
         Main.getMain().stroke(255.0f,0.0f,255.0f);
         neighbourPos = waypoints.get(waypoints.size()-1).position;
         neighbourPos = Main.getMain().getRenderer().worldToScreen(neighbourPos);
         Main.getMain().line(screenPos.x, screenPos.y, neighbourPos.x, neighbourPos.y);   
      }
      //If there are no Waypoints in this route
      else {
         Vec2 startPosScreen = Main.getMain().getRenderer().worldToScreen(startPos);
         Vec2 targetPosScreen =  Main.getMain().getRenderer().worldToScreen(targetPos);

         Main.getMain().stroke(255.0f,0.0f,0.0f);
         Main.getMain().rect(startPosScreen.x-5,startPosScreen.y-5,10,10);
         Main.getMain().rect(targetPosScreen.x-5,targetPosScreen.y-5,10,10);
         
         Main.getMain().stroke(255.0f,0.0f,255.0f);
         Main.getMain().line(startPosScreen.x, startPosScreen.y, targetPosScreen.x, targetPosScreen.y);
      }
   }
   
}


Now, to put it all together one can call the getFastestRoute(Vec2,Vec2) method from the World class:
important: The World class has a field "float shortestRouteLength" which is not visible down here.

The storedRoute thing is something I use to render the last Route created, you can remove that.


Code:
/**
    * This method will try to provide you with a Route object containing a path from the provided starting position to the provided target position.
    * @param startPos
    * @param targetPos
    * @return    A Route object containing Waypoints between the provided positions,
    *          or a Route object with no Waypoints when the provided positions are visible from each other,
    *          or NULL if no Route can be made.
    */
   public final Route getFastestRoute(Vec2 startPos, Vec2 targetPos) {
      //If the positions are visible from each other
      if(isVisible(startPos, targetPos)) {
         System.out.println("CustomWorld.getFastestRoute() > TARGETS ARE VISIBLE !!!");
         //We make an "empty" Route with only the start and target position
         Route route = new Route(startPos,targetPos);
         //I render the last Route that has been made, thats why this is here
         storedRoute =  route;
         //Return result
         return route;
      }
      
      //Since start and target are not visible we need starting and target Waypoints
      Waypoint startWaypoint = getClosestWaypoint(startPos);
      Waypoint targetWaypoint = getClosestWaypoint(targetPos);
   
      //If either of them returns as NULL it means we can't make a route
      if(startWaypoint == null || targetWaypoint == null) {
         return null;
      }
      
      //If they return the same Waypoint, we can make a Route out of it and return that.
      if(startWaypoint.equals(targetWaypoint)) {
         Route route = new Route(startWaypoint,startPos,targetPos);
         storedRoute = route;
         return route;
      }
      
      //Make a new Route object with the starting Waypoint and the provided positions
      Route route = new Route(startWaypoint,startPos,targetPos);
      
      //Set the length of the shortest Route found to a maximum value
      shortestRouteLength = Float.MAX_VALUE;

      //Declare a array which can hold all valid Routes found and fill it with the result of the recursive method getRoutes()
      ArrayList<Route> routes = getRoutes(route, targetWaypoint);
      
      //If no routes were returned
      if(routes.size() < 1) {
         System.out.println("CustomWorld.getFastestRoute() > NO VALID ROUTE FOUND !!!");
         //Return null
         return null;
      }
      //If one or more Routes returned
      else {
         System.out.println("CustomWorld.getFastestRoute() > ROUTE FOUND !!!");
         //Get the last Route in the array, which is the shortest Route
         route = routes.get(routes.size()-1);
         //Try to prune it
         route.prune();
         
         storedRoute = route;
         
         return route;
      }   
   }
   
   public final ArrayList<Route> getRoutes(Route route, Waypoint target) {
      //Make a new array to store found routes
      ArrayList<Route> routes = new ArrayList<Route>();
      
      //Get the neighbours of the last Waypoint in the route
      ArrayList<Waypoint> neighbours = route.getWaypoints().get(route.getWaypoints().size()-1).getNeighbours();
      
      //If the target is one of its neighbours
      if(neighbours.contains(target)) {
         System.out.println("Found target in waypoint's neighbours");
         
         //Add the target to the route
         route.addWaypoint(target);
         System.out.println("Found a valid route over : " + route.getWaypoints().size() + " waypoints and a length of : " + route.length);
         
         //If the route's length is now the shortestRouteLength
         if(route.length < shortestRouteLength) {
            
            //Update the shortestRouteLength length
            shortestRouteLength = route.length;
            System.out.println("It is the new shortestRouteLength path!");
            
            //Add this route to the results
            routes.add(route);
            
            //Fastest route has been found from this Waypoint so we return it
            return routes;
         }
      }
      
      //Retrieve a sorted version
      ArrayList<Waypoint> sortedNeighbours = getSortedNeighbours(neighbours,target);
      
      //Declare a new Route object
      Route r;
      
      //Target was not amongst its neighbours so we search from there
      for(Waypoint w : sortedNeighbours) {
         
         //Make a new Route object
         r = new Route(route);
         
         //If the neighbour can be added it means it is at least valid, up to here
         if(r.addWaypoint(w)) {
            
            //This route is doomed because a faster route has been determined
            if(r.length > shortestRouteLength) {
               continue;
            }
            //Try to find more Routes from here
            else {
               routes.addAll(getRoutes(r,target));
            }
         }
      }
      
      //Return the possible results
      return routes;
   }
   
   /**
    * Sorts and returns a sorted version of the provided ArrayList<Waypoint> on the basis of their distance to the target Waypoint
    * @param neighbours
    * @param target
    * @return
    */
   @SuppressWarnings("unchecked")
   private ArrayList<Waypoint> getSortedNeighbours(ArrayList<Waypoint> neighbours, Waypoint target) {
      //Make a shallow copy
      ArrayList<Waypoint> copy = (ArrayList<Waypoint>)neighbours.clone();
      ArrayList<Waypoint> sorted = new ArrayList<Waypoint>();
      
      float nearest = Float.MAX_VALUE;
      int nearestIndex = 0;
      int allWaypoints = copy.size();
      float distance;
      while(sorted.size() < allWaypoints) {
         nearest = Float.MAX_VALUE;
         nearestIndex = 0;
         
         for(int i=0;i<copy.size();i++) {
            distance = CalculationTool.getDistance(copy.get(i).position,target.position);
            if(distance < nearest) {
               nearest = distance;
               nearestIndex = i;
            }
         }
         
         sorted.add(copy.get(nearestIndex));
         copy.remove(nearestIndex);
      }
      return sorted;
   }


I will post some code showing how an enemy uses a Route shortly.

This method does not return the theoretical shortest path. I could make it that way but it would mean I would have to start searching from EVERY Waypoint visible from the starting position and start looking for EVERY Waypoint visible from the target location...

Any questions, suggestions, please post them. If I have left something out (could happen) please tell me.
New in the series "one-hundred-and-one things to do with polygon raycating during your summer break": breakable geometry 🙂

http://blissfulthinking.nl/gamezero now has geometry in place that breaks randomly when shot.

It has quircks right now; very small pieces are created and the algorithms are a total mess/resource hog. But I will post it here once it has been cleaned up a bit.

I promised to show how enemies follow a route so here it is, in its messy form.
Code:
package nl.blissfulthinking.java.gamezero.world.objects.behaviors;

import nl.blissfulthinking.java.gamezero.player.Player;
import nl.blissfulthinking.java.gamezero.tools.CalculationTool;
import nl.blissfulthinking.java.gamezero.world.Level;
import nl.blissfulthinking.java.gamezero.world.Route;
import nl.blissfulthinking.java.gamezero.world.objects.NPC;

import org.jbox2d.common.Vec2;

public class KamikazeBehavior extends Behavior {

   private int counter = 1 * CalculationTool.getTargetFps();
   
   protected Route route = null;
   protected int at = 0;
   
   public KamikazeBehavior(NPC npc) {
      super(npc);
   }
   
   @Override
   public void behave() {
      if(counter < 0) {
         approachPlayer();
         
      }
      else {
         counter--;
      }
   }
   
   protected final void approachPlayer() {
      //When there is no more route and the distance has become very large
      if(route == null && getDistanceFromPlayer() > 100.0f ) {
         //We stop the behaviour
         stopBehavior();
      }
      //We want to move towards the player, directly or via a route
      else {
         //When the player is not visible
         if(!Level.getWorld().isVisible(Player.get().getBody().getPosition(), npc.getBody().getPosition())) {
            
            //If there is no route set we try and get one
            if(route == null) {
               //Easier when standing still
               npc.getBody().setLinearVelocity(new Vec2(0.0f,0.0f));
               route = Level.getWorld().getFastestRoute(npc.getBody().getPosition(),Player.get().getBody().getPosition());
               if(route != null) {
                  at = 0;
                  System.out.println("Enemy has a route now!");
               }
            }
            //Follow the route
            else {
               if(at == route.getWaypoints().size()-1) {
                  if(Level.getWorld().isVisible(route.targetPos,npc.getBody().getPosition())) {
                     System.out.println("******ROUTE FINISHED");
                     route = null;
                     return;
                  }
               }
               //If the next waypoint is visible
               else {
                  if(Level.getWorld().isVisible(npc.getBody().getPosition(),route.getWaypoints().get(at+1).position)) {
                     at++;
                  }
               }
               
               npc.getBody().setLinearVelocity(new Vec2(npc.getBody().getLinearVelocity().x/4f,npc.getBody().getLinearVelocity().y/4f));
               
               
               //Simple Kamikaze behaviour
               float angleRelative = (float) Math.atan2(route.getWaypoints().get(at).position.y - npc.getBody().getPosition().y, route.getWaypoints().get(at).position.x - npc.getBody().getPosition().x);
               
               float power = (float) (4);
               
               Vec2 impulse = new Vec2(0.0f,0.0f);
               impulse.x = (float) (power * Math.cos(angleRelative));
               impulse.y = (float) (power * Math.sin(angleRelative));
               
               npc.getBody().applyImpulse(impulse,npc.getBody().getPosition());

               counter = (int)(1.0f) * CalculationTool.getTargetFps();
            }
            
         }
         //When the player IS visible
         else {
            //Simple Kamikaze behaviour
            float angleRelative = (float) Math.atan2(Player.get().getBody().getPosition().y - npc.getBody().getPosition().y, Player.get().getBody().getPosition().x - npc.getBody().getPosition().x);
            
            //npc.getBody().setLinearVelocity(new Vec2(npc.getBody().getLinearVelocity().x/4.0f,npc.getBody().getLinearVelocity().y/4.0f));
            
            float power = (float) (5*Math.random()+0.5);
            
            Vec2 impulse = new Vec2(0.0f,0.0f);
            impulse.x = (float) (power * Math.cos(angleRelative));
            impulse.y = (float) (power * Math.sin(angleRelative));
            
            npc.getBody().applyImpulse(impulse,npc.getBody().getPosition());
            
            counter = (int) ((1.5*Math.random())+0.3) * CalculationTool.getTargetFps();
//            if(power > ???) {
//               SoundTool.kamikaze_move.trigger();
//            }
         }      
      }            
   }
}
This might give you smoother steering behavior (this is my static steer class, take what you want from it). Based off of OpenSteer (C++ ai steering test engine). This is possibly the longest forum page I've ever seen.

Code:
public class Steer {
   
   /**
    * Uses the supplied wander variable to generate a wander lateral force.
    * This changes the first element in the argWanderVar.
    * @param argObject
    * @param argWanderVar must be a float array with a defined element at 0
    * @param dt
    * @return
    */
   public static Vec2 steerForWander(final IPhysicsObject argObject, float[] argWanderVar, float dt){
      // TODO: better way of doing this
      final float speed = 12*dt;
      argWanderVar[0] = MathHelper.scalarRandomWalk(argWanderVar[0], speed, -1, 1);
      
      return argObject.getSide().mul(argWanderVar[0]);
   }

   public static Vec2 steerForSeek(final IPhysicsObject argObject, final Vec2 argTarget) {
      final Vec2 desiredVel = argTarget.sub(argObject.getXForm().position);
      
      MathHelper.truncateLength(desiredVel, argObject.getMaxSpeed());
      return desiredVel.sub(argObject.getVelocity());
   }
   
   public static Vec2 steerForSeek( final Vec2 argPosition, final Vec2 argVelocity,
                                       final Vec2 argTarget, final float maxSpeed){
      final Vec2 desiredVel = argTarget.sub(argPosition);
      
      MathHelper.truncateLength(desiredVel, maxSpeed);
      return desiredVel.sub(argVelocity);
   }

   public static Vec2 steerForFlee(final IPhysicsObject argObject, final Vec2 argTarget) {
      final Vec2 desiredVel = argObject.getXForm().position.sub(argTarget);
      
      MathHelper.truncateLength(desiredVel, argObject.getMaxSpeed());
      return desiredVel.sub(argObject.getVelocity());
   }

   // djm pooling,
   private static final Vec2 futurePosition = new Vec2();
   /**
    * tries to keep the object on the path
    *
    * @param argObject
    * @param argPredictionTime
    * @param argPathway
    * @return
    */
   public static Vec2 steerToStayOnPath(final IPhysicsObject argObject,
                                 final float argPredictionTime,
                                 final AbstractPathway argPathway) {
      argObject.predictFuturePosition(argPredictionTime, futurePosition);

      final Vec2 tangent = new Vec2();
      final float[] outside = new float[1];
      final Vec2 onPath = argPathway.mapPointToPath(futurePosition, tangent, outside);

      if (outside[0] < 0) {
         return new Vec2();
      }
      else {
         return Steer.steerForSeek(argObject, onPath);
      }
   }

   // djm pooling, from above
   /**
    * Directed path following
    *
    * @param argObject
    * @param argDirection
    *            -1 or +1
    * @param argPredictionTime
    * @param argPath
    * @return
    */
   public static Vec2 steerToFollowPath(final IPhysicsObject argObject, final int argDirection,
                                 final float argPredictionTime,
                                 final AbstractPathway argPath) {
      // our goal will be offset from our path distance by this amount
      final float pathDistanceOffset = argDirection * argPredictionTime * argObject.getSpeed();

      // predict our future getPosition
      argObject.predictFuturePosition(argPredictionTime, futurePosition);

      // measure distance along path of our current and predicted getPositions
      final float nowPathDistance = argPath.mapPointToPathDistance(argObject.getXForm().position);
      final float futurePathDistance = argPath.mapPointToPathDistance(futurePosition);

      // are we facing in the correction direction?
      final boolean rightway = ((pathDistanceOffset > 0)   ? (nowPathDistance < futurePathDistance)
                                             : (nowPathDistance > futurePathDistance));

      // find the point on the path nearest the predicted future getPosition
      // XXX need to improve calling sequence, maybe change to return a
      // XXX special path-defined object which includes two Vec2s and a
      // XXX boolean (onPath,tangent (ignored), withinPath)
      final Vec2 tangent = new Vec2();
      final float[] outside = new float[1];
      argPath.mapPointToPath(futurePosition,
      // output arguments:
                           tangent, outside);

      // no steering is required if (a) our future getPosition is inside
      // the path tube and (b) we are facing in the correct direction
      if ((outside[0] < 0) && rightway) {
         // all is well, return zero steering
         return new Vec2();
      }
      else {
         // otherwise we need to steer towards a target point obtained
         // by adding pathDistanceOffset to our current path getPosition

         final float targetPathDistance = nowPathDistance + pathDistanceOffset;
         final Vec2 target = argPath.mapPathDistanceToPoint(targetPathDistance);

         // return steering to seek target on path
         return Steer.steerForSeek(argObject, target);
      }
   }

   /**
    * Given two vehicles, based on their current positions and velocities,
    * determine the time until nearest approach
    *
    * XXX should this return zero if they are already in contact?
    * @param argMe
    * @param argOther
    * @return
    */
   public static float predictNearestApproachTime(final IPhysicsObject argMe,
                                       final IPhysicsObject argOther) {
      // imagine we are at the origin with no velocity,
      // compute the relative velocity of the other vehicle
      final Vec2 myVelocity = argMe.getVelocity();
      final Vec2 otherVelocity = argOther.getVelocity();
      final Vec2 relVelocity = otherVelocity.sub(myVelocity);
      final float relSpeed = relVelocity.length();

      // for parallel paths, the vehicles will always be at the same distance,
      // so return 0 (aka "now") since "there is no time like the present"
      if (relSpeed == 0) {
         return 0;
      }

      // Now consider the path of the other vehicle in this relative
      // space, a line defined by the relative getPosition and velocity.
      // The distance from the origin (our vehicle) to that line is
      // the nearest approach.

      // Take the unit tangent along the other vehicle's path
      final Vec2 relTangent = relVelocity.mul(1 / relSpeed);

      // find distance from its path to origin (compute offset from
      // other to us, find length of projection onto path)
      final Vec2 relPosition = argMe.getXForm().position.sub(argOther.getXForm().position);
      final float projection = Vec2.dot(relTangent, relPosition);

      return projection / relSpeed;
   }
   
   /**
    * Given the time until nearest approach (predictNearestApproachTime)
    * determine position of each vehicle at that time
    *
    * @param argMe
    * @param argOther
    * @param argMeFinal returning position
    * @param argOtherFinal returning position
    * @param time
    */
   public static void computeNearestApproachPositions (IPhysicsObject argMe,
                                                        IPhysicsObject argOther,
                                                        Vec2 argMeFinal,
                                                        Vec2 argOtherFinal,
                                                        float time){
       final XForm melocal = argMe.getXForm();
       final XForm themlocal = argOther.getXForm();
      
      final Vec2    myTravel = argMe.getForward().mul(argMe.getSpeed() * time);
       final Vec2 otherTravel = argOther.getForward().mul(argOther.getSpeed () * time);

       myTravel.add(melocal.position);
       otherTravel.add(themlocal.position);
      
       argMeFinal.set(myTravel);
       argOtherFinal.set(otherTravel);
   }
   

   /**
    * Obstacle Avoidance behavior
    *
    * Returns a steering force to avoid a given obstacle.  The purely lateral
    * steering force will turn our vehicle towards a silhouette edge of the
    * obstacle.  Avoidance is required when (1) the obstacle intersects the
    * vehicle's current path, (2) it is in front of the vehicle, and (3) is
    * within minTimeToCollision seconds of travel at the vehicle's current
    * velocity.  Returns a zero vector value (Vec3::zero) when no avoidance is
    * required.
    *
    * XXX The current (4-23-03) scheme is to dump all the work on the various
    * XXX Obstacle classes, making them provide a "steer vehicle to avoid me"
    * XXX method.  This may well change.
    * @param argMe
    * @param minTimeToCollision
    * @param argObstacle
    * @return
    */
   public static Vec2 steerToAvoidObstacle(final IPhysicsObject argMe,
                                              final float minTimeToCollision,
                                              final IObstacle argObstacle){
      // TODO should this be different?
      final Vec2 avoidance = argObstacle.steerToAvoid(argMe, minTimeToCollision);
      return avoidance;
   }
   
   /**
    * this version avoids all of the obstacles in an ObstacleGroup
    *
    * XXX 9-12-03: note this does NOT use the Obstacle::steerToAvoid protocol
    * XXX like the older steerToAvoidObstacle does/did.  It needs to be fixed
    * @param argMe
    * @param minTimeToCollision
    * @param argObstacle
    * @return
    */
   public static Vec2 steerToAvoidObstacles(final IPhysicsObject argMe,
                                               final float minTimeToCollision,
                                               final LinkedList<IObstacle> argObstacles){
      Vec2 avoidance = new Vec2();
      PathIntersection nearest, next;
      next = new PathIntersection();
      nearest = new PathIntersection();
      next.intersect = false;
      nearest.intersect = false;
      
      
      final float minDistanceToCollision = minTimeToCollision * argMe.getSpeed();
      
      Iterator<IObstacle> it = argObstacles.iterator();
      
      while(it.hasNext()){
         it.next().findIntersection(argMe, next);
         
         if(nearest.intersect == false ||
               (next.intersect != false && next.distance < nearest.distance)){
            nearest.cloneFrom(next);
         }
      }
      
      if( nearest.intersect != false && nearest.distance < minDistanceToCollision){
         // compute avoidance steering force: take offset from obstacle to me,
           // take the component of that which is lateral (perpendicular to my
           // forward direction), set length to maxForce
         
         final Vec2 offset = argMe.getXForm().position.sub(nearest.obstacle.getCenter());
         avoidance.set(MathHelper.parallelComponent(offset,argMe.getForward()));
         avoidance.normalize();
         avoidance.mulLocal(argMe.getMaxForce());
      }
      return avoidance;
   }
   

   public static Vec2 steerToAvoidCloseNeighbors(final IPhysicsObject argMe,
                                          final float minSeparationDist,
                                          final LinkedList<IPhysicsObject> argOthers) {
      final Iterator<IPhysicsObject> it = argOthers.iterator();
      while (it.hasNext()) {
         final IPhysicsObject object = it.next();
         if (object != argMe) {
            final float sumOfRadii = argMe.getRadius() + object.getRadius();
            final float minCenterToCenter = minSeparationDist + sumOfRadii;
            final Vec2 offset = object.getXForm().position.sub(argMe.getXForm().position);
            final float currentDistance = offset.length();

            if (currentDistance < minCenterToCenter) {
               return MathHelper.perpendicularComponent((offset.mul(-1)), argMe.getForward());
            }
         }
      }
      return new Vec2();
   }

   public static boolean inBoidNeighborhood(final IPhysicsObject argMe,
                                    final IPhysicsObject argOther,
                                    final float minDistance, final float maxDistance,
                                    final float cosMaxAngle) {
      if (argOther == argMe) {
         return false;
      }
      else {
         final Vec2 offset = argOther.getXForm().position.sub(argMe.getXForm().position);
         final float distanceSquared = offset.lengthSquared();

         // definitely in neighborhood if inside minDistance sphere
         if (distanceSquared < (minDistance * minDistance)) {
            return true;
         }
         else {
            // definitely not in neighborhood if outside maxDistance sphere
            if (distanceSquared > (maxDistance * maxDistance)) {
               return false;
            }
            else {
               // otherwise, test angular offset from forward axis
               final Vec2 unitOffset = offset.mul(1 / MathHelper.sqrt(distanceSquared));
               final float forwardness = Vec2.dot(argMe.getForward(), unitOffset);
               return forwardness > cosMaxAngle;
            }
         }
      }
   }

   /**
    * normalized direction
    *
    * @param argMe
    * @param maxDistance
    * @param cosMaxAngle
    * @param argFlock
    * @return
    */
   public static Vec2 steerForSeparation(final IPhysicsObject argMe, final float maxDistance,
                                    final float cosMaxAngle,
                                    final LinkedList<IPhysicsObject> argFlock) {
      // steering accumulator and count of neighbors, both initially zero
      Vec2 steering = new Vec2();
      int neighbors = 0;
      final Iterator<IPhysicsObject> it = argFlock.iterator();
      while (it.hasNext()) {
         final IPhysicsObject other = it.next();
         if (Steer.inBoidNeighborhood(argMe, other, argMe.getRadius() * 3, maxDistance,
                                 cosMaxAngle)) {
            // add in steering contribution
            // (opposite of the offset direction, divided once by distance
            // to normalize, divided another time to get 1/d falloff)
            final Vec2 offset = other.getXForm().position.sub(argMe.getXForm().position);
            final float distanceSquared = Vec2.dot(offset, offset);
            steering.addLocal(offset.mul(1 / -distanceSquared));

            // count neighbors
            neighbors++;
         }
      }

      // divide by neighbors, then normalize to pure direction
      if (neighbors > 0) {
         (steering.mulLocal(1f / neighbors)).normalize();
      }

      return steering;
   }

   /**
    *
    * @param argMe
    * @param maxDistance
    * @param cosMaxAngle
    * @param argFlock
    * @return normalized direction
    */
   public static Vec2 steerForCohesion(final IPhysicsObject argMe, final float maxDistance,
                                 final float cosMaxAngle,
                                 final LinkedList<IPhysicsObject> argFlock) {
      // steering accumulator and count of neighbors, both initially zero
      final Vec2 steering = new Vec2();
      int neighbors = 0;
      final Iterator<IPhysicsObject> it = argFlock.iterator();
      while (it.hasNext()) {
         final IPhysicsObject object = it.next();

         if (Steer.inBoidNeighborhood(argMe, object, argMe.getRadius() * 3, maxDistance,
                                 cosMaxAngle)) {
            // accumulate sum of neighbor's getPositions
            steering.add(object.getXForm().position);

            // count neighbors
            neighbors++;
         }
      }

      // divide by neighbors, subtract off current getPosition to get error-
      // correcting direction, then normalize to pure direction
      if (neighbors > 0) {
         steering.mul(1f / neighbors).subLocal(argMe.getXForm().position).normalize();
      }

      return steering;
   }

   // pooling
   private static final Vec2 target = new Vec2();
   
   public static Vec2 steerForPursuit(final IPhysicsObject argMe,
                                 final IPhysicsObject argQuery,
                                 final float maxPredictionTime) {
      final XForm melocal = argMe.getXForm();
      final XForm themlocal = argQuery.getXForm();
      // offset from this to quarry, that distance, unit vector toward quarry
      final Vec2 offset = themlocal.position.sub(melocal.position);
      final float distance = offset.length();
      final Vec2 unitOffset = offset.mul(1 / distance);

      // how parallel are the paths of "this" and the quarry
      // (1 means parallel, 0 is pependicular, -1 is anti-parallel)
      final float parallelness = Vec2.dot(argMe.getForward(), argQuery.getForward());

      // how "forward" is the direction to the quarry
      // (1 means dead ahead, 0 is directly to the side, -1 is straight back)
      final float forwardness = Vec2.dot(argMe.getForward(), unitOffset);

      final float directTravelTime = distance / argMe.getSpeed();
      final int f = MathHelper.intervalComparison(forwardness, -0.707f, 0.707f);
      final int p = MathHelper.intervalComparison(parallelness, -0.707f, 0.707f);

      float timeFactor = 0; // to be filled in below
      // Vec2 color; // to be filled in below (xxx just for debugging)

      // Break the pursuit into nine cases, the cross product of the
      // quarry being [ahead, aside, or behind] us and heading
      // [parallel, perpendicular, or anti-parallel] to us.
      switch (f) {
         case +1:
            switch (p) {
               case +1: // ahead, parallel
                  timeFactor = 4;
                  break;
               case 0: // ahead, perpendicular
                  timeFactor = 1.8f;
                  break;
               case -1: // ahead, anti-parallel
                  timeFactor = 0.85f;
                  break;
            }
            break;
         case 0:
            switch (p) {
               case +1: // aside, parallel
                  timeFactor = 1;
                  break;
               case 0: // aside, perpendicular
                  timeFactor = 0.8f;
                  break;
               case -1: // aside, anti-parallel
                  timeFactor = 4;
                  break;
            }
            break;
         case -1:
            switch (p) {
               case +1: // behind, parallel
                  timeFactor = 0.5f;
                  break;
               case 0: // behind, perpendicular
                  timeFactor = 2;
                  break;
               case -1: // behind, anti-parallel
                  timeFactor = 2;
                  break;
            }
            break;
      }

      // estimated time until intercept of quarry
      final float et = directTravelTime * timeFactor;

      // XXX experiment, if kept, this limit should be an argument
      final float etl = (et > maxPredictionTime) ? maxPredictionTime : et;

      // estimated position of quarry at intercept
      argQuery.predictFuturePosition(etl, target);

      return Steer.steerForSeek(argMe, target);
   }

   /**
    * returns a force that's constrained to the object's max force to reach the target speed
    * @param argMe
    * @param targetSpeed
    * @return
    */
   public static Vec2 steerForTargetSpeed(final IPhysicsObject argMe, final float targetSpeed){
      final float mf = argMe.getMaxForce();
      final float speedError = targetSpeed - argMe.getSpeed();
      return argMe.getForward().mul( MathHelper.constrain(speedError, -mf, mf));
   }
}


I can give you the pathway and obstacle classes if you want.

Original thread: https://box2d.org/forum/viewtopic.php?t=3411