Java move in an angle between two GPS coordinates - java

I have a use case where I need to generate GPS coordinates to cover an specific area (marked by a list og GPS coordinates).
So I need to generate coordinates. I have the following functions tested and implemented:
//determines wether a Waypoint is inside the specified area
public boolean isInsideArea(Waypoint waypoint)
public double distanceInKmBetweenGPSCoordinates(Waypoint from, Waypoint to)
public double[] calculateCoordinatesAfterMove(Waypoint waypoint, double dx, double dy)
Here is my naive implementation of how to generate coordinates for a square (or approximately a square):
public static List<drone.Waypoint> addAutoGeneratedWaypoints(List<Waypoint> polygon_lat_long_pairs) {
List<Waypoint> waypoints = new ArrayList<>();
AreaTester tester = new GPSPolygonTester(polygon_lat_long_pairs);
GPSCoordinateCalculator coordinateCalculator = new GPSCoordinateCalculator();
CustomGPSMapper mapper = new CustomGPSMapper();
boolean finish = false;
String mode = "r";
Waypoint prev = polygon_lat_long_pairs.get(0);
int count = 0;
double distanceDown = mapper.distanceInKmBetweenGPSCoordinates(polygon_lat_long_pairs.get(2), polygon_lat_long_pairs.get(3));
double travelledDown = 0;
while (!finish) {
if (mode.equals("r")) {
double[] nextA = coordinateCalculator.calculateCoordinatesAfterMove(prev.getPosition().getLatitude(), prev.getPosition().getLongitude(), 5.0, 0.0);
Waypoint next = new DefaultWaypoint(nextA[0], nextA[1]);
if (tester.isInsideArea(next)) {
System.out.println("Waypoint was in area");
waypoints.add(next);
prev = next;
} else {
System.err.println("Left area, switching position");
mode = "l";
double[] nextB = coordinateCalculator.calculateCoordinatesAfterMove(prev.getPosition().getLatitude(), prev.getPosition().getLongitude(), 0.0, -3.0);
Waypoint next2 = new DefaultWaypoint(nextB[0], nextB[1]);
waypoints.add(next2);
travelledDown += mapper.distanceInKmBetweenGPSCoordinates(prev, next);
prev = next2;
}
count++;
} else {
double[] nextA = coordinateCalculator.calculateCoordinatesAfterMove(prev.getPosition().getLatitude(), prev.getPosition().getLongitude(), -5.0, 0.0);
Waypoint next = new DefaultWaypoint(nextA[0], nextA[1]);
if (tester.isInsideArea(next)) {
waypoints.add(next);
prev = next;
} else {
System.out.println("Left are, switching");
mode = "r";
double[] nextB = coordinateCalculator.calculateCoordinatesAfterMove(prev.getPosition().getLatitude(), prev.getPosition().getLongitude(), 0.0, -3.0);
Waypoint next2 = new DefaultWaypoint(nextB[0], nextB[1]);
waypoints.add(next2);
travelledDown += mapper.distanceInKmBetweenGPSCoordinates(prev, next);
prev = next2;
}
count++;
}
if (travelledDown >= distanceDown) {
finish = true;
}
}
List<de.dhbw.drone.waypoints.Waypoint> mapped = waypoints.stream().map(p -> new de.dhbw.drone.waypoints.Waypoint(p)).collect(Collectors.toList());
return mapped;
I stop the algorithm when it has travelled down the right/left side of the square.
However, I am struggeling if the shape of the marked area is no square and has sloped lines.
Therefore I would have to move with a bearing, like shown in this image:
When I could add this angle to my movement, I could use this algorithm for each shape of area, resulting in the following path:
Can someone help me how to move a distance in meters in this specific angle and how to calculate this angle between two GPS coordinates and how to calculate the angle after turning the side? (right to left instead of left to right and vice versa). Or could this be solved by calculating angle(point1, point2) and angle(point2, point1) ?

To calculate azimuth from one coordinate to another and point at given distancem you can use formulas from latlong page (bearing and destination point sections)
You can use the same approach as usually implemented in 2d polygon rasterization.
Horizontal picture lines are continous in memory, so filling horizontal lines is the most reliable way.
In your case you can use, for example, lines at constant latitude.
Sort vertices of your earth polygon by latitude and separate ranges between vertex latitude values, then fill resulting "trapezoids" with point sequences (plane example)
Sometimes (complex polygon etc) it would be simpler to use rejection method - generate grid points in escribed rectangle and ignore those outside of polygon.

Related

How should I be implementing a view clipping plane in a 3D Engine?

This project is written entirely from scratch in Java. I've just been bored ever since Covid started, so I wanted something that would take up my time, and teach me something cool. I've been stuck on this problem for about a week now though. When I try to use my near plane clipping method it skews the new vertices to the opposite side of the screen, but sometimes times it works just fine.
Failure Screenshot
Success Screenshot
So my thought is maybe that since it works sometimes, I'm just not doing the clipping at the correct time in the pipeline?
I start by face culling and lighting,
Then I apply a Camera View Transformation to the Vertices,
Then I clip on the near plane
Finally I apply the projection matrix and Clip any remaining off screen Triangles
Code:
This calculates the intersection points. Sorry if it's messy or to long I'm not very experienced in coding, my major is physics, not CS.
public Vertex vectorIntersectPlane(Vector3d planePos, Vector3d planeNorm, Vector3d lineStart, Vector3d lineEnd){
float planeDot = planeNorm.dotProduct(planePos);
float startDot = lineStart.dotProduct(planeNorm);
float endDot = lineEnd.dotProduct(planeNorm);
float midPoint = (planeDot - startDot) / (endDot - startDot);
Vector3d lineStartEnd = lineEnd.sub(lineStart);
Vector3d lineToIntersect = lineStartEnd.scale(midPoint);
return new Vertex(lineStart.add(lineToIntersect));
}
public float distanceFromPlane(Vector3d planePos, Vector3d planeNorm, Vector3d vert){
float x = planeNorm.getX() * vert.getX();
float y = planeNorm.getY() * vert.getY();
float z = planeNorm.getZ() * vert.getZ();
return (x + y + z - (planeNorm.dotProduct(planePos)));
}
//When a triangle gets clipped it has 4 possible outcomes
// 1 it doesn't actually need clipping and gets returned
// 2 it gets clipped into 1 new triangle, for testing these are red
// 3 it gets clipped into 2 new triangles, for testing 1 is green, and 1 is blue
// 4 it is outside the view planes and shouldn't be rendered
public void clipTriangles(){
Vector3d planePos = new Vector3d(0, 0, ProjectionMatrix.fNear, 1f);
Vector3d planeNorm = Z_AXIS.clone();
final int length = triangles.size();
for(int i = 0; i < length; i++) {
Triangle t = triangles.get(i);
if(!t.isDraw())
continue;
Vector3d[] insidePoint = new Vector3d[3];
int insidePointCount = 0;
Vector3d[] outsidePoint = new Vector3d[3];
int outsidePointCount = 0;
float d0 = distanceFromPlane(planePos, planeNorm, t.getVerticesVectors()[0]);
float d1 = distanceFromPlane(planePos, planeNorm, t.getVerticesVectors()[1]);
float d2 = distanceFromPlane(planePos, planeNorm, t.getVerticesVectors()[2]);
//Storing distances from plane and counting inside outside points
{
if (d0 >= 0){
insidePoint[insidePointCount] = t.getVerticesVectors()[0];
insidePointCount++;
}else{
outsidePoint[outsidePointCount] = t.getVerticesVectors()[0];
outsidePointCount++;
}
if (d1 >= 0){
insidePoint[insidePointCount] = t.getVerticesVectors()[1];
insidePointCount++;
}else{
outsidePoint[outsidePointCount] = t.getVerticesVectors()[1];
outsidePointCount++;
}
if (d2 >= 0){
insidePoint[insidePointCount] = t.getVerticesVectors()[2];
insidePointCount++;
}else{
outsidePoint[outsidePointCount] = t.getVerticesVectors()[2];
}
}
//Triangle has 1 point still inside view, remove original triangle add new clipped triangle
if (insidePointCount == 1) {
t.dontDraw();
Vertex newVert1 = vectorIntersectPlane(planePos, planeNorm, insidePoint[0], outsidePoint[0]);
Vertex newVert2 = vectorIntersectPlane(planePos, planeNorm, insidePoint[0], outsidePoint[1]);
vertices.add(newVert1);
vertices.add(newVert2);
//Triangles are stored with vertex references instead of the actual vertex object.
Triangle temp = new Triangle(t.getVertKeys()[0], vertices.size() - 2, vertices.size() - 1, vertices);
temp.setColor(1,0,0, t.getBrightness(), t.getAlpha());
triangles.add(temp);
continue;
}
//Triangle has two points inside remove original add two new clipped triangles
if (insidePointCount == 2) {
t.dontDraw();
Vertex newVert1 = vectorIntersectPlane(planePos, planeNorm, insidePoint[0], outsidePoint[0]);
Vertex newVert2 = vectorIntersectPlane(planePos, planeNorm, insidePoint[1], outsidePoint[0]);
vertices.add(newVert1);
vertices.add(newVert2);
Triangle temp = new Triangle(t.getVertKeys()[0], t.getVertKeys()[1], vertices.size() - 1, vertices);
temp.setColor(0, 1, 0, t.getBrightness(), t.getAlpha());
triangles.add(temp);
temp = new Triangle(t.getVertKeys()[0], t.getVertKeys()[1], vertices.size() - 2, vertices);
temp.setColor(0, 0, 1, t.getBrightness(), t.getAlpha());
triangles.add(temp);
continue;
}
}
}
I figured out the problem, The new clipped triangles were not being given the correct vertex references. they were just being given the first vertex of the triangle irregardless of if that was inside the view or not.

Java - How to check if a lat/lng coords are inside a polygon

I want to check if a given point on a map (with its latitude and longitude) is inside a certain polygon. I have the vertex coords (in lat/long) of the polygon.
I thought of creating a Polygon and check if point is inside, but it gives me that the point is always outside... Maybe the polygon does not work with georeferential coords?
Double[] xCoords = {40.842226, 40.829498, 40.833394, 40.84768, 40.858716}
Double[] yCoords = {14.211753, 14.229262, 14.26617, 14.278701, 14.27715}
Double[] myPoint = {40.86141, 14.279932};
Path2D myPolygon = new Path2D.Double();
myPolygon.moveTo(xCoords[0], yCoords[0]); //first point
for(int i = 1; i < xCoords.length; i ++) {
myPolygon.lineTo(xCoords[i], yCoords[i]); //draw lines
}
myPolygon.closePath(); //draw last line
if(myPolygon.contains(myPoint{0}, myPoint{1})) {
//it's inside;
}
This is how it looks like in google maps
It always return false... but the point it's inside the polygon...
That point can't possibly be contained in that polygon, no matter what shape the polygon has.
Your right-most coordinate is at 40.858716 while the point has an x value of 40.86141, this means that the point lies on the right of your polygon. Same for y, max y coordinate in the polygon is 14.278701 while the point is at 14.279932. This means that the point is outside.
Also, you're inverting the coordinates, the coordinates of our beloved city are 40.8518° N, 14.2681° E, this means that 40 is the y and 14 the x.
Path2D will do just fine. My observation just tells you that the point is not in the polygon but checking the extremes is not a general solution for verifying that a point is inside a polygon.
public class CoordinatesDTO {
private Long id;
private double latitude;
private double longnitude;
}
public static boolean isLocationInsideTheFencing(CoordinatesDTO location, List<CoordinatesDTO> fencingCoordinates) { //this is important method for Checking the point exist inside the fence or not.
boolean blnIsinside = false;
List<CoordinatesDTO> lstCoordinatesDTO = fencingCoordinates;
Path2D myPolygon = new Path2D.Double();
myPolygon.moveTo(lstCoordinatesDTO.get(0).getLatitude(), lstCoordinatesDTO.get(0).getLongnitude()); // first
// point
for (int i = 1; i < lstCoordinatesDTO.size(); i++) {
myPolygon.lineTo(lstCoordinatesDTO.get(i).getLatitude(), lstCoordinatesDTO.get(i).getLongnitude()); // draw
// lines
}
myPolygon.closePath(); // draw last line
// myPolygon.contains(p);
Point2D P2D2 = new Point2D.Double();
P2D2.setLocation(location.getLatitude(), location.getLongnitude());
if (myPolygon.contains(P2D2)) {
blnIsinside = true;
} else {
blnIsinside = false;
}
return blnIsinside;
}

Java PathIterator - How do I accurately calculate center of Shape object?

I am trying to use the PathIterator to calculate the center of any Shape object, so that curved paths can be accounted for, but upon finding the center of a standard 1x1 rectangle, my getCenter() method returns the point:
Point2D.Double[0.3333333333333333, 0.3333333333333333]
My getCenter() method:
shape = new Rectangle2D.Double(0, 0, 1, 1);
public Point2D.Double getCenter()
{
ArrayList<Point2D.Double> points = new ArrayList<Point2D.Double>();
double[] arr = new double[6];
for(PathIterator pi = shape.getPathIterator(null); !pi.isDone(); pi.next())
{
pi.currentSegment(arr);
points.add(new Point2D.Double(arr[0], arr[1]));
}
double cX = 0;
double cY = 0;
for(Point2D.Double p : points)
{
cX += p.x;
cY += p.y;
}
System.out.println(points.toString());
return new Point2D.Double(cX / points.size(), cY / points.size());
}
I have discovered that upon printing points.toString(), I get this in the Console:
[Point2D.Double[0.0, 0.0], Point2D.Double[1.0, 0.0], Point2D.Double[1.0, 1.0], Point2D.Double[0.0, 1.0], Point2D.Double[0.0, 0.0], Point2D.Double[0.0, 0.0]]
I noticed that there are six entries in the points array, as opposed to four which I was expecting, given that the input Shape object is Rectangle2D.Double(0, 0, 1, 1). Obviously it is accounting for the point (0, 0) two more times than I want it to, and I am confused as to why that is. Is it a result of the PathIterator.isDone() method? Am I using it incorrectly? What would solve my problem if PathIterator can't?
As it was already pointed out, the PathIterator returns different types of segments. When only considering the points that are involved in SEG_LINETO, you should already obtain satisfactory results. However, consider that there may also be SEG_QUADTO and SEG_CUBICTO in other shapes. These can easily be avoided by using a flattening PathIterator: When you create a PathIterator with
PathIterator pi = shape.getPathIterator(null, flatness);
with an appropriate flatness, then it will only contain straight line segments.
import java.awt.Shape;
import java.awt.geom.Ellipse2D;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
public class ShapeCenter
{
public static void main(String[] args)
{
System.out.println(computeCenter(new Ellipse2D.Double(-10,-10,20,20)));
System.out.println(computeCenter(new Rectangle2D.Double(0,0,1,1)));
}
public static Point2D computeCenter(Shape shape)
{
final double flatness = 0.1;
PathIterator pi = shape.getPathIterator(null, flatness);
double coords[] = new double[6];
double sumX = 0;
double sumY = 0;
int numPoints = 0;
while (!pi.isDone())
{
int s = pi.currentSegment(coords);
switch (s)
{
case PathIterator.SEG_MOVETO:
// Ignore
break;
case PathIterator.SEG_LINETO:
sumX += coords[0];
sumY += coords[1];
numPoints++;
break;
case PathIterator.SEG_CLOSE:
// Ignore
break;
case PathIterator.SEG_QUADTO:
throw new AssertionError(
"SEG_QUADTO in flattening path iterator");
case PathIterator.SEG_CUBICTO:
throw new AssertionError(
"SEG_CUBICTO in flattening path iterator");
}
pi.next();
}
double x = sumX / numPoints;
double y = sumY / numPoints;
return new Point2D.Double(x,y);
}
}
PathIterator defines different types of segments, you should pay attention to this fact. You get 6 segments in your example, because it returns additionally also the SEG_MOVETO segment, which defines the start of a subpath, and SEG_CLOSE at the end of the sub path. If you just want to get the endpoints of the lines of your shape, you should change your code like this:
for(PathIterator pi = shape.getPathIterator(null); !pi.isDone(); pi.next())
{
if(pi.currentSegment(arr) == PathIterator.SEG_LINETO) {
points.add(new Point2D.Double(arr[0], arr[1]));
}
}
I am not sure you're using it incorrectly but you aren't accounting for an aspect of PathIterator. PathIterator doesn't so much represent a geometric shape but rather a path that should be taken while drawing. So its points also represent the type of path the 'pen' should take. For example, for a Rectangle, the path makes the following segments:
SEG_MOVETO
SEG_LINETO
SEG_LINETO
SEG_LINETO
SEG_LINETO
SEG_CLOSE
Because obviously the path should:
Move, not draw, from wherever the pen was before.
Close off this path from whatever the pen draws next.
The type of segment is the return value of currentSegment. If you only want to capture points that are on the polygon you can check for the 'line to' segment:
if(pi.currentSegment(arr) == PathIterator.SEG_LINETO) {
points.add(new Point2D.Double(arr[0], arr[1]));
}
That will work for simple polygons like Rectangle. For the given Rectangle, it will return [0.5, 0.5] which is I assume the result you're interested in.
On the other hand, there are Shapes that are not polygons so I'd be careful with this approach.

game collision check when rectangle moves from one position to another if it misses collision in the distance travelled

I know this question is similar to others, but if I have a rectangle bounded game object. Which moves position. How can I check along the line if it intersects with any items in between?
In an extreme scenario. [x = 2, x = 1, width = 1, height = 1]A moves to [x = 4, y = 1, width = 1, height = 1]. Where the rectangle B exists at [3,1,0.5,0.5] it would get missed out.
I have read about scalar and cross product but they are single lines if i read correctly. This is due to Android game development on slow devices with low frame rate. I am getting it falling into objects. I check intersects using this code below.
public boolean testIntersection(GameVector lowerLeftMain, float mainWidth, float mainHeight, GameVector lowerLeftCollider,
float colliderWidth, float colliderHeight){
boolean intersect = false;
if(lowerLeftMain.x < lowerLeftCollider.x + colliderWidth+0.08f && //checks left collision
lowerLeftMain.x + mainWidth > lowerLeftCollider.x-0.08f && //checks right collision
lowerLeftMain.y < lowerLeftCollider.y + colliderHeight+0.08f &&//checks top collision
lowerLeftMain.y + mainHeight > lowerLeftCollider.y-0.08f )//checks bottom collision
intersect = true;
return intersect;
}
Please can someone point me in the right direction should I give up on rectangles and concentrate on ray cast line collision style?
Thanks in advance.
Thanks for the links great links will post my code to help others in the future.
My Separating Axis Theorem in java. Only to test if overlaps. I went for this algorithm due to efficiency and potential to see the min and max overlap vectors.
public GameVector[] getVertices(GameObject obj){
final GameVector topLeft = new GameVector( obj.mPosition.x-0.06f - (obj.mWidth/2), obj.mPosition.y+0.06f +(obj.mHeight/2) );
final GameVector topRight = new GameVector( obj.mPosition.x+0.06f + (obj.mWidth/2),obj.mPosition.y+0.06f +(obj.mHeight/2) );
final GameVector bottomLeft = new GameVector( obj.mPosition.x-0.06f - (obj.mWidth/2), obj.mPosition.y-0.06f -(obj.mHeight/2));
final GameVector bottomRight = new GameVector( obj.mPosition.x+0.06f + (obj.mWidth/2), obj.mPosition.y-0.06f -(obj.mHeight/2));
//order here matters
GameVector[] vertices = { topLeft, topRight, bottomRight, bottomLeft };
return vertices;
}
public GameVector[] getAxis(GameObject shape){
GameVector[] vertices = getVertices(shape);
GameVector[] axes = new GameVector[vertices.length];
// loop over the vertices
for (int i = 0; i < vertices.length; i++) {
// get the current vertex
GameVector p1 = vertices[i];
// get the next vertex if i+1 == vertices length set back to vertices [0]
GameVector p2 = vertices[i + 1 == vertices.length ? 0 : i + 1];
// subtract the two to get the edge vector
GameVector edge = p1.subtract(p2.x, p2.y);
// get either perpendicular vector
GameVector normal;
//get the left side normal of the vector due to clock wise positions
normal = new GameVector(edge.y, -edge.x);//edge.perp();
axes[i] = normal;
}
return axes;
}
public float dotProduct(GameVector a, GameVector b){
float dp = a.x*b.x + a.y*b.y;
return dp;
}
public class Projection {
private final float min;
private final float max;
public Projection(float min, float max) {
this.min = min;
this.max = max;
}
public boolean doesOverlap(final Projection other) {
return !(this.min > other.max || other.min > this.max);
}
}

Java: Object moving on a path, ignores certain coordinates. How to fix?

I have a circle that moves from point A to a random point B. When the object nears point B, a new random target location gets chosen. If the circle is moving parallel to the X-axis or Y-axis the object goes through all the pixels in the way and leaves a solid trace. But if the circle moves diagonally, it skips pixels and shakes slightly, making the animation not smooth and leaves a trace with unpainted pixels.
My algorithm is:
calculate the X and Y distances
check if the circle is near
if so, choose the new destination
if 2. is true, find the real distance using Pythagoras' theorem
if 2. is true, calculate the X and Y speed (the change of the coordinates)
set the new coordinates (no matter if 2. is true or not)
And here is the code:
public void move ()//движение
{
//finds the X and Y distance to the destination
int triangleX = nextLocationX - coorX;
int triangleY = nextLocationY - coorY;
//if too near the coordinates of the destination changes
if (Math.abs(triangleX) <= Math.abs(speedX) || Math.abs(triangleY) <= Math.abs(speedY))//setting the new target
{
//setting the new destinatio
int randInt;
for (;;)//I don't want the the new destination to be that same spot
{
randInt= randGen.nextInt(appletX);
if (randInt != nextLocationX)
{
nextLocationX = randInt + radius;
break;
}
}
for (;;)
{
randInt = randGen.nextInt(appletY);
if (randInt != nextLocationY)
{
nextLocationY = randInt + radius;
break;
}
}
//calculating the change of the circle's X and Y coordinates
triangleX = nextLocationX - coorX;
triangleY = nextLocationY - coorY;
speedX = ((double)(speed * triangleX) / (Math.sqrt (Math.pow(triangleX, 2) + Math.pow(triangleY, 2))));
speedY = ((double)(speed * triangleY) / (Math.sqrt (Math.pow(triangleX, 2) + Math.pow(triangleY, 2))));
}
//the realCoor variables are from type double
//they are the exact coordinates of the circle
//If I only use integers, the circle almost
//never reaches it's destination
//unless the change of the coordinates gets calculated
//after every time they change
realCoorX = realCoorX + speedX;
realCoorY = realCoorY + speedY;
coorX = (int)Math.round(realCoorX);
coorY = (int)Math.round(realCoorY);
}
I suspect that the problem is in the calculation of the change of the coordinates.
For me this sounds like a Aliasing problem. You would have the same problem if you draw(!) a line that is not aligned with the coordinate axis. As you know, i.e. diagonal lines need "half filled" pixels to look smooth.
Solution for you would be (depending on the technology for rendering) to use floating point position calculation.

Categories