How to check if VERTEX ARRAY is clockwise? - java

Solved, used this code:
if ( !isClockwise(TempVectArray) ) { Collections.reverse(TempVectArray); }
...
private boolean isClockwise(ArrayList<Vec2> arl){
Iterator<Vec2> it = arl.iterator();
Vec2 pt1 = (Vec2)it.next();
Vec2 firstPt = pt1;
Vec2 lastPt = null;
double area = 0.0;
while(it.hasNext()){
Vec2 pt2 = (Vec2) it.next();
area += (((pt2.x - pt1.x) * (pt2.y + pt1.y)) / 2);
pt1 = pt2;
lastPt = pt1;
}
area += (((firstPt.x - lastPt.x) * (firstPt.y + lastPt.y)) / 2);
return area < 0;
}
Suppose I get a vertex array from the user tapping on the screen, but need it to be clockwise.
Maybe you know of some standard methods to check if it is clockwise and if it's not, then make it clockwise?
Thanks!

One way to do it is to first calculate the average point, and then sort everything around it by angle. Should be something like this:
public static void sortPointsClockwise(ArrayList<PointF> points) {
float averageX = 0;
float averageY = 0;
for (PointF point : points) {
averageX += point.x;
averageY += point.y;
}
final float finalAverageX = averageX / points.size();
final float finalAverageY = averageY / points.size();
Comparator<PointF> comparator = new Comparator<PointF>() {
public int compare(PointF lhs, PointF rhs) {
double lhsAngle = Math.atan2(lhs.y - finalAverageY, lhs.x - finalAverageX);
double rhsAngle = Math.atan2(rhs.y - finalAverageY, rhs.x - finalAverageX);
// Depending on the coordinate system, you might need to reverse these two conditions
if (lhsAngle < rhsAngle) return -1;
if (lhsAngle > rhsAngle) return 1;
return 0;
}
};
Collections.sort(points, comparator);
}
public static void sortPointsCounterClockwise(ArrayList<PointF> points) {
sortPointsClockwise(points);
Collections.reverse(points);
}

You have the sequence numbers and positions of the nodes. Get the movements which hold x and y changes in the move. All left to do is define a control structure such as:
if(movement_before is "up")
movement should-be "up" or "up-right"
if(movement_before is "up-left")
movement should-be "up" or "up-left" or "up-right"
etc..

Related

Eccentricity Vector in Java not accurate as orbit moves along

I am writing a small libgdx program in java that was inspired by Kerbal Space Program and I am now writing the class that controls objects that will have forces acted on them. Each of these objects have a velocity vector that is changed by a forces vector.
The program runs around 60 frames per second and every frame the calculations done on the force to change velocity are done 1000 times. ( I have played with this number a lot however). Right now the program is incredibly simple and the only force that is exerted and calculated every iteration is from the planet.
forcedub = ((gravConstanat*parentBody.getMass())/Math.pow(loc.distance(parentBody.getLoc()),2));
force = new Point2D(((-1)*forcedub*Math.cos(a)),((-1)*forcedub*Math.sin(a)));
This changes the velocity sightly, the position is adjusted and the loop continues. The process works very well and seems stable. I haven't run it for days on end, but the orbit even at relatively high eccentricities seems stable. UNFORTUNATELY I need to be able to speed this process up so it doesn't take 2 days real time to get to the moon. So I needed a system that puts the orbit "on rails" and doesn't need to recalculate the forces each iterations. Once the multiplier value there gets set too high the orbit falls apart.
Good news is I already have this system in place, I just can't switch between the two.
I need a few values from the orbit to do this in my system. (I know some values are a bit redundant but it is what it is).
The semi major axis
the semi minor axis
the eccentricity vector
eccentricity
true anomaly
focus information.
To cut to the chase, the biggest issue is the eccentricity vector / eccentricity. My 'bake' function is the one that attempts to compute the values from the state vectors of the orbit every iteration and the value of the eccentricity varies drastically where it should stay the same in a standard orbit.The direction the vector is all over the place as well.
I have hard coded a single object that should have an eccentricity of about .62 and the eccentricity vector should point to pi, but the value wanders between .25 and .88 and the direction wanders between pi and pi / 3 ish.
Here are two versions of how to get the eccvecc from the state vectors, and I have tried them both. They both give the exact same results:
https://space.stackexchange.com/questions/37331/why-does-the-eccentricity-vector-equation-always-equal-1
https://en.wikipedia.org/wiki/Eccentricity_vector
public void bake(){
double velSq = Math.pow(vel.distance(0,0),2);
double r = loc.distance(parentBody.getLoc());
double gm = gravConstanat*parentBody.getMass();
Point2D posr = new Point2D(loc.getX()-parentBody.getX(), loc.getY()-parentBody.getY());
Point2D calc1 = posr.scale((velSq/gm));
Point2D calc2 = vel.scale((dotProd(posr,vel)/gm));
Point2D calc3 = posr.scale(1/r);
Point2D eccVecc = (calc1.minus(calc2)).minus(calc3);
ecc = eccVecc.distance(0,0);
w = Math.toRadians(90)-(Math.atan2(eccVecc.x(),eccVecc.y()));
semiA = (gm*r)/(2*gm - r*velSq);
semiB = semiA*(Math.sqrt((1-Math.pow(ecc,2))));
focus = findFocus(semiA,semiB);
System.out.println("ecc " + ecc + " W " + w + " SEMI A " + semiA);
System.out.println();
}
Here is the entire class:
**initial distance is about 900,000 to the left of the parent body
**parent mass is 5.3*Math.pow(10,22)
public class Klobject {
String name;
TextureAtlas textureAtlas;
Sprite sprite;
Cbody parentBody;
Point2D loc;
Point2D vel;
public boolean acceleration;
double MULTIPLIER;
static double gravConstanat = 6.67*Math.pow(10,-11);
double semiA, semiB, ecc, w;
protected double t;
protected double mass;
protected double rotateRate;
protected double focus;
public Klobject(Cbody cb){
mass = 1;
MULTIPLIER = 1;
rotateRate = 0;
parentBody = cb;
acceleration = false;
cb.addKlob(this);
loc = new Point2D((parentBody.getX() - 900_000f ),
(parentBody.getY()));
vel = new Point2D(0,2526.733);
sprite = textureAtlas.createSprite(name);
sprite.setOrigin(sprite.getWidth()/2, sprite.getHeight()/2);
bake();
}
public void update(float dt){
oneXupdate(dt);
bake();
}
private void oneXupdate(float dt){
int timesLooped = 1000;
double a;
double forcedub;
Point2D force;
Point2D velout;
double dx;
double dy;
dt = dt/timesLooped;
for (int i = 0; i < timesLooped; i++){
velout = vel.scale(MULTIPLIER);
dx = (dt*velout.getX());
dy = (dt*velout.getY());
loc = new Point2D(loc.getX()+dx, loc.getY()+dy);
a = Math.atan2(loc.getX()-parentBody.getX(), loc.getY()-parentBody.getY());
a = Math.toRadians(90)-a;
forcedub = ((gravConstanat*parentBody.getMass())/Math.pow(loc.distance(parentBody.getLoc()),2));
force = new Point2D(((-1)*forcedub*Math.cos(a)),((-1)*forcedub*Math.sin(a)));
force = force.scale(MULTIPLIER*MULTIPLIER);
velout = velout.plus(new Point2D(force.getX()*dt,force.getY()*dt));
vel = velout.scale(1/MULTIPLIER);
}
}
public void bake(){
double velSq = Math.pow(vel.distance(0,0),2);
double r = loc.distance(parentBody.getLoc());
double gm = gravConstanat*parentBody.getMass();
Point2D posr = new Point2D(loc.getX()-parentBody.getX(), loc.getY()-parentBody.getY());
Point2D calc1 = posr.scale((velSq/gm));
Point2D calc2 = vel.scale((dotProd(posr,vel)/gm));
Point2D calc3 = posr.scale(1/r);
Point2D eccVecc = (calc1.minus(calc2)).minus(calc3);
ecc = eccVecc.distance(0,0);
w = Math.toRadians(90)-(Math.atan2(eccVecc.x(),eccVecc.y()));
semiA = (gm*r)/(2*gm - r*velSq);
semiB = semiA*(Math.sqrt((1-Math.pow(ecc,2))));
focus = findFocus(semiA,semiB);
System.out.println("ecc " + ecc + " W " + w + " SEMI A " + semiA);
System.out.println();
}
public double findFocus(double a, double b){
return Math.sqrt(a*a - b*b);
}
public double getX(){
return loc.getX();
}
public double getY(){
return loc.getY();
}
public void setRotateRate(double rr){rotateRate = rr;}
public String getName(){
return name;
}
public Sprite getSprite(){
return sprite;
}
public void setMultiplier(double mult){
MULTIPLIER = mult;
}
public Point2D getLoc(){
return loc;
}
public void setLoc(Point2D newLoc){
loc = newLoc;
}
public double dotProd(Point2D a, Point2D b){
return a.x()*b.x() + a.y()+b.y();
}
}

Reading through an array 2d from center to corners

So for this java project I´m working on I need a loop that reads trough an 2d array from center first then 4 adjecent values then the corners of that and keep doing that till it reaches and completes the most outer layer. I need it to work on all odd sizes of square 2d arrays. I made this image to clarify my goal: http://gyazo.com/80ed4502cb16795d37b75a14ee57f565 . I personally was not able to achieve this. Thank you for your time! any piece of pseudo code or java code is welcome!
You could logically redefine the grid so that the center is 0,0.
Then, sort each grid coordinate according to distance from the center.
This assumes that the grid is an odd width.
For example:
class Point
{
int x;
int y;
}
Point gridCenter;
Comparator<Point> comparator = new Comparator<Point>()
{
#Override
public int compare(Point arg0, Point arg1)
{
int x = arg0.x - gridCenter.x;
int y = arg0.y - gridCenter.y;
int distance0 = x*x + y*y;
x = arg1.x - gridCenter.x;
y = arg1.y - gridCenter.y;
int distance1 = x*x + y*y;
return distance0 - distance1;
}
};
void test()
{
int width = 11;
int height = 13;
gridCenter = new Point();
gridCenter.x = width/2;
gridCenter.y = height/2;
List<Point> points = new ArrayList<>();
for(int x=0;x<width;x++)
{
for(int y=0;y<height;y++)
{
Point p = new Point();
p.x = x;
p.y = y;
points.add(p);
}
}
Collections.sort(points, comparator);
for(Point p : points)
{
System.out.println(p.x + "," + p.y);
}
}
You could bias center slightly if you want to guarantee that it chooses left,top before right,bottom in the sort.

My method scale isn't working, what may be the issue?

I have been trying to scale a Shape in java, but I'm having some problems. When i try it the Shape simple dissapears... This method receives 2 points, toScale is the point that i want the shape to extend to, and p1 is the point that I clicked in the rectangle that is around the shape to select (there's a rectangle(boundingBox) surrounding the shape wheter is a polygone or a rectangle or just polylines)
Here's the scale method code:
public void scale(Point toScale, Point p1) {
Graphics g = parent.getGraphics();
int distanceToClicked = 0;
int distanceToBoundingBox = 0;
int scaleFactor = 0;
Vector<Point> pointsAux = new Vector<Point>();
Iterator<Point> it = points.iterator();
while (it.hasNext()){
Point p = it.next();
distanceToClicked = (int) Math.sqrt(Math.pow(getCentroid().getX()-p1.getX(), 2)+Math.pow(getCentroid().getY()-p1.getY(),2));
distanceToBoundingBox = (int) Math.sqrt(Math.pow(getCentroid().getX()-toScale.getX(),2)+Math.pow(getCentroid().getY()-toScale.getY(),2));
scaleFactor = distanceToClicked/distanceToBoundingBox;
p = new Point((int)p.getX()*scaleFactor,(int) p.getY()*scaleFactor);
pointsAux.add(p);
}
points.clear();
points.addAll(pointsAux);
}
public Point getCentroid(){
int sumx = 0;
int sumy = 0;
for(int i = 0; i<points.size();i++){
sumx+=points.get(i).getX();
sumy+=points.get(i).getY();
}
Point centroid = new Point(sumx/points.size(), sumy/points.size());
return centroid;
}
Any help would be appreciated
Thanks in advance, and eventually I'm sorry for the misunderstanding code
Something like that would do the trick:
public Collection<Point> scaleShape(float scale, Collection<Point> shape) {
Point centroid = getCentroid();
Collection<Point> scaledShape = new ArrayList<>(shape.size());
for (Point point : shape) {
Point diff = new Point(point.x() - centroid.x(), point.y() - centroid.y());
Point scaledPoint = new Point(
(int) (centroid.x() + scale * diff.x()),
(int) (centroid.y() + scale * diff.y()));
scaledShape.add(scaledPoint);
}
return scaledShape;
}
Basically, every points make a linear function with the centroid. Centroid's relative x = 0, while the current computed point is at relative x = 1. You want to find the point if it were at relative x = scale.

Point Outside of Area Which is Closest to Point Inside?

I have a program where an entity moves around in two-dimensional space. To move one step, the entity picks its next point, and then sets it as his current point.
Sometimes, however, the entity's next point lies in an Area (java.awt.geom.Area) that is forbidden (the "forbidden area" is actually a velocity obstacle).
How can the entity pick the point outside the Area which is closest to the entity's preferred point?
The Area is composed of different shapes (sometimes, the shapes are not touching).
My initial plan was to simply draw a line to the preferred point. Wherever the line intersected the Area first, this would be the next-best point. However, finding the intersection between a line and an Area turns out to be quite complex.
EDIT: This wouldn't necessarily find the closest point. This would just find the closet point on the same trajectory. I'm looking for the closest possible point.
Perhaps Area isn't the best class to use. All I require is something that can add multiple shapes, even when the shapes aren't touching.
I've solved the problem:
First, find all the line segments that constrain the Area. I've written code to do that on a different answer.
Then, it's just a matter of iterating through each line segment, and recording the point on the segment that's closest to the entity's desired point. Store these in the data structure of your choice (e.g., an ArrayList).
See: Shortest distance between a point and a line segment
Lastly, determine which of the points is closest to the desired point. Voilà!
Here's a demonstration:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Path2D;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JFrame;
public class AreaTest extends JFrame{
private static final long serialVersionUID = -2221432546854106311L;
Area area = new Area();
ArrayList<Line2D.Double> areaSegments = new ArrayList<Line2D.Double>();
Point2D.Double insidePoint = new Point2D.Double(225, 225);
Point2D.Double closestPoint = new Point2D.Double(-1, -1);
Point2D.Double bestPoint = new Point2D.Double(-1, -1);
ArrayList<Point2D.Double> closestPointList = new ArrayList<Point2D.Double>();
AreaTest() {
Path2D.Double triangle = new Path2D.Double();
Random random = new Random();
// Draw three random triangles
for (int i = 0; i < 3; i++) {
triangle.moveTo(random.nextInt(400) + 50, random.nextInt(400) + 50);
triangle.lineTo(random.nextInt(400) + 50, random.nextInt(400) + 50);
triangle.lineTo(random.nextInt(400) + 50, random.nextInt(400) + 50);
triangle.closePath();
area.add(new Area(triangle));
triangle.reset();
}
// Place a point inside the area
if (!area.contains(insidePoint)); {
while (!area.contains(insidePoint)) {
insidePoint.setLocation(random.nextInt(400) + 50, random.nextInt(400) + 50);
}
}
// Note: we're storing double[] and not Point2D.Double
ArrayList<double[]> areaPoints = new ArrayList<double[]>();
double[] coords = new double[6];
for (PathIterator pi = area.getPathIterator(null); !pi.isDone(); pi.next()) {
// Because the Area is composed of straight lines
int type = pi.currentSegment(coords);
// We record a double array of {segment type, x coord, y coord}
double[] pathIteratorCoords = {type, coords[0], coords[1]};
areaPoints.add(pathIteratorCoords);
}
double[] start = new double[3]; // To record where each polygon starts
for (int i = 0; i < areaPoints.size(); i++) {
// If we're not on the last point, return a line from this point to the next
double[] currentElement = areaPoints.get(i);
// We need a default value in case we've reached the end of the ArrayList
double[] nextElement = {-1, -1, -1};
if (i < areaPoints.size() - 1) {
nextElement = areaPoints.get(i + 1);
}
// Make the lines
if (currentElement[0] == PathIterator.SEG_MOVETO) {
start = currentElement; // Record where the polygon started to close it later
}
if (nextElement[0] == PathIterator.SEG_LINETO) {
areaSegments.add(
new Line2D.Double(
currentElement[1], currentElement[2],
nextElement[1], nextElement[2]
)
);
} else if (nextElement[0] == PathIterator.SEG_CLOSE) {
areaSegments.add(
new Line2D.Double(
currentElement[1], currentElement[2],
start[1], start[2]
)
);
}
}
// Calculate the nearest point on the edge
for (Line2D.Double line : areaSegments) {
// From: https://stackoverflow.com/questions/6176227
double u =
((insidePoint.getX() - line.x1) * (line.x2 - line.x1) + (insidePoint.getY() - line.y1) * (line.y2 - line.y1))
/ ((line.x2 - line.x1) * (line.x2 - line.x1) + (line.y2 - line.y1) * (line.y2 - line.y1));
double xu = line.x1 + u * (line.x2 - line.x1);
double yu = line.y1 + u * (line.y2 - line.y1);
if (u < 0) {
closestPoint.setLocation(line.getP1());
} else if (u > 1) {
closestPoint.setLocation(line.getP2());
} else {
closestPoint.setLocation(xu, yu);
}
closestPointList.add((Point2D.Double) closestPoint.clone());
if (closestPoint.distance(insidePoint) < bestPoint.distance(insidePoint)) {
bestPoint.setLocation(closestPoint);
}
}
setSize(new Dimension(500, 500));
setLocationRelativeTo(null); // To center the JFrame on screen
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
setVisible(true);
}
public void paint(Graphics g) {
// Fill the area
Graphics2D g2d = (Graphics2D) g;
g.setColor(Color.lightGray);
g2d.fill(area);
// Draw the border line by line
g.setColor(Color.black);
for (Line2D.Double line : areaSegments) {
g2d.draw(line);
}
// Draw the inside point
g.setColor(Color.red);
g2d.fill(
new Ellipse2D.Double(
insidePoint.getX() - 3,
insidePoint.getY() - 3,
6,
6
)
);
// Draw the other close points
for (Point2D.Double point : closestPointList) {
g.setColor(Color.black);
g2d.fill(
new Ellipse2D.Double(
point.getX() - 3,
point.getY() - 3,
6,
6
)
);
}
// Draw the outside point
g.setColor(Color.green);
g2d.fill(
new Ellipse2D.Double(
bestPoint.getX() - 3,
bestPoint.getY() - 3,
6,
6
)
);
}
public static void main(String[] args) {
new AreaTest();
}
}
Here's the result:
And again:
View my answer on this post
You can get the closest point outside of a polygon with a simple and lightweight approach:
Simply find the closest line segment, and find the perpendicular angle to that segment that intercepts the input point.
Example Code:
Vector2 is 2 doubles, x and y (Like Unity)
public class PolyCollisions {
// Call this function...
public static Vector2 doCollisions (Vector2[] polygon, Vector2 point) {
if(!pointIsInPoly(polygon, point)) {
// The point is not colliding with the polygon, so it does not need to change location
return point;
}
// Get the closest point off the polygon
return closestPointOutsidePolygon(polygon, point);
}
// Check if the given point is within the given polygon (Vertexes)
//
// If so, call on collision if required, and move the point to the
// closest point outside of the polygon
public static boolean pointIsInPoly(Vector2[] verts, Vector2 p) {
int nvert = verts.length;
double[] vertx = new double[nvert];
double[] verty = new double[nvert];
for(int i = 0; i < nvert; i++) {
Vector2 vert = verts[i];
vertx[i] = vert.x;
verty[i] = vert.y;
}
double testx = p.x;
double testy = p.y;
int i, j;
boolean c = false;
for (i = 0, j = nvert-1; i < nvert; j = i++) {
if ( ((verty[i]>testy) != (verty[j]>testy)) &&
(testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) )
c = !c;
}
return c;
}
// Gets the closed point that isn't inside the polygon...
public static Vector2 closestPointOutsidePolygon (Vector2[] poly, Vector2 point) {
return getClosestPointInSegment(closestSegment(poly, point), point);
}
public static Vector2 getClosestPointInSegment (Vector2[] segment, Vector2 point) {
return newPointFromCollision(segment[0], segment[1], point);
}
public static Vector2 newPointFromCollision (Vector2 aLine, Vector2 bLine, Vector2 p) {
return nearestPointOnLine(aLine.x, aLine.y, bLine.x, bLine.y, p.x, p.y);
}
public static Vector2 nearestPointOnLine(double ax, double ay, double bx, double by, double px, double py) {
// https://stackoverflow.com/questions/1459368/snap-point-to-a-line-java
double apx = px - ax;
double apy = py - ay;
double abx = bx - ax;
double aby = by - ay;
double ab2 = abx * abx + aby * aby;
double ap_ab = apx * abx + apy * aby;
double t = ap_ab / ab2;
if (t < 0) {
t = 0;
} else if (t > 1) {
t = 1;
}
return new Vector2(ax + abx * t, ay + aby * t);
}
public static Vector2[] closestSegment (Vector2[] points, Vector2 point) {
Vector2[] returns = new Vector2[2];
int index = closestPointIndex(points, point);
returns[0] = points[index];
Vector2[] neighbors = new Vector2[] {
points[(index+1+points.length)%points.length],
points[(index-1+points.length)%points.length]
};
double[] neighborAngles = new double[] {
getAngle(new Vector2[] {point, returns[0], neighbors[0]}),
getAngle(new Vector2[] {point, returns[0], neighbors[1]})
};
if(neighborAngles[0] < neighborAngles[1]) {
returns[1] = neighbors[0];
} else {
returns[1] = neighbors[0];
}
return returns;
}
public static double getAngle (Vector2[] abc) {
// https://stackoverflow.com/questions/1211212/how-to-calculate-an-angle-from-three-points
// atan2(P2.y - P1.y, P2.x - P1.x) - atan2(P3.y - P1.y, P3.x - P1.x)
return Math.atan2(abc[2].y - abc[0].y, abc[2].x - abc[0].x) - Math.atan2(abc[1].y - abc[0].y, abc[1].x - abc[0].x);
}
//public static Vector2 lerp (Vector2 a, Vector2 b, double c) {
//
// return new Vector2(c*(a.x-b.x)+b.x, c*(a.y-b.y)+b.y);
//
//}
/*public static Vector2 closestPoint (Vector2[] points, Vector2 point) {
int leastDistanceIndex = 0;
double leastDistance = Double.MAX_VALUE;
for(int i = 0; i < points.length; i++) {
double dist = distance(points[i], point);
if(dist < leastDistance) {
leastDistanceIndex = i;
leastDistance = dist;
}
}
return points[leastDistanceIndex];
}*/
public static int closestPointIndex (Vector2[] points, Vector2 point) {
int leastDistanceIndex = 0;
double leastDistance = Double.MAX_VALUE;
for(int i = 0; i < points.length; i++) {
double dist = distance(points[i], point);
if(dist < leastDistance) {
leastDistanceIndex = i;
leastDistance = dist;
}
}
return leastDistanceIndex;
}
public static double distance (Vector2 a, Vector2 b) {
return Math.sqrt(Math.pow(Math.abs(a.x-b.x), 2)+Math.pow(Math.abs(a.y-b.y), 2));
}
}
Useful Links / Answers
Snap Point to Line
How to calculate an angle from 3 points
The most easy (and most inefficient) approach would be a brute force.
You have a preferred point inside an area. to find the closest point to it: hold two variables, one for minimal distance and one for current closest point. now simply step over every other point in your two dimensional space: if that point is not inside the forbidden area (or any forbidden area if there are many), then calculate the distance between it and the preferred point. If that distance is less than the current minimal distance, then make it become the current minimal distance and make the point become the current closest point.
when you finish, you will have the closest point outside the area and if none was found, you stay on your original point.
I am not specialist in geometry algorithms, but if the two dimensional space is very big and the calculation is not finishing fast enough, maybe you can try to improve it with the following: the Area class has a contains method that "tests if the interior of the Shape entirely contains the specified rectangular area". therefore, start creating rectangles(or squares) around the preferred point. you start with the minimal rectangle surrounding the point and on every loop you increase it by one point in each direction. for every rectangle that you create, check if it is contained in the area. you stop calculating rectangles when you hit the first rectangle that is not entirely contained in the area. then, you use the above algorithm (the brute force) but only on points contained in this rectangle and that are not inside the area.
The formula for distance between two points is (javascript):
var xDiff = ( point1x - point2x ),
yDiff = ( point1y - point2y ),
distance = Math.sqrt( ( xDiff * xDiff ) + ( yDiff * yDiff ) );
Loop around your "proposed new point", starting at one x-1, y-1 to x+1, y+1. At each point check to see that it's not a forbidden point, not the point you just came from, and not off the boundaries of the map. If it meets all those criteria, use the above formula to measure the distance and add it to an array. At the end of your "1-point out" loop, check if there are any distances in that array. If so, take the smallest one and you're done. If there aren't any, move onto x-2, y-2 to x+2, y+2 (2 points out).
This will be extremely fast for the small area you are referring to.
Demo: http://jsfiddle.net/ThinkingStiff/V7Bqm/
var X = 0,
Y = 1,
currentPoint = [5,5],
proposedPoint = [5,6],
forbiddenPoints = [[5,6],[6,6],[4,7],[5,7],[6,7],[4,8],[5,8]],
map = { left:1, top:1, right:10, bottom:10 };
function closestSafePoint( point ) {
var x = point[X], y = point[Y], safePoints = [];
for( var left = x - 1, top = y - 1, right = x + 1, bottom = y + 1;
left <= map.left || top <= map.top || right <= map.right || bottom <= map.bottom;
left--, top--, right++, bottom++) {
checkHorizontalPoints( safePoints, point, left, right, top );
checkHorizontalPoints( safePoints, point, left, right, bottom );
checkVerticalPoints( safePoints, point, top + 1, bottom - 1, left );
checkVerticalPoints( safePoints, point, top + 1, bottom - 1, right );
safePoints.sort( function( a, b ){ return a[1] - b[1] } );
return safePoints.length ? safePoints[0] : point;
};
};
function checkHorizontalPoints( points, fromPoint, startX, endX, y ) {
for( var x = startX; x <= endX ; x++ ) {
var toPoint = [x, y];
if( !isForbidden( toPoint ) && !isCurrent( toPoint) && onMap( toPoint ) ) {
points.push( [toPoint, distance( fromPoint, toPoint )] );
};
};
};
function checkVerticalPoints( points, fromPoint, startY, endY, x ) {
for( var y = startY; y <= endY ; y++ ) {
var toPoint = [x, y];
if( !isForbidden( toPoint ) && !isCurrent( toPoint) && onMap( toPoint ) ) {
points.push( [toPoint, distance( fromPoint, toPoint )] );
};
};
};
function isForbidden( point ) {
for( var index = 0; index < forbiddenPoints.length; index++ ) {
if( forbiddenPoints[index].toString() == point.toString() ) return true;
};
};
function isCurrent( point ) {
return currentPoint.toString() == point.toString() ? true : false;
};
function onMap( point ) {
var x = point[X], y = point[Y];
return x >= map.left && y >= map.top && x <= map.right && y <= map.bottom;
};
function distance( pointA, pointB ) {
var xDiff = ( pointA[X] - pointB[X] ),
yDiff = ( pointA[Y] - pointB[Y] );
return Math.sqrt( ( xDiff * xDiff ) + ( yDiff * yDiff ) );
};
console.log(
'current: ' + currentPoint + ', '
+ 'proposed: ' + proposedPoint + ', '
+ 'closest: ' + closestSafePoint( proposedPoint )[0]
);
One optimization you could make to this, if you're fairly sure most of your safe spots will be one or two points away is to break out as soon as you get to a point thats distance is the same as the level you're on. So if you're on loop one, and you get a point that is distance = 1, stop, since you'll never get closer than that.
UPDATE: I noticed you added "same trajectory" to your question. But in one of the comments, you also say it can't jump over the forbidden area. Those statements seem to conflict.
Same trajectory is a little more tricky and requires some trig. Check out my demo of circular divs at http://jsfiddle.net/ThinkingStiff/uLu7v/. There is a "point on ray" function halfway down at:
$this.siblings( ".circle" ).each( function()
This calculates the distance to move the surrounding circles on a ray away from the selected circle. This could be used to calculate a point on your trajectory. But, I think my original function is actually what you're looking for and you didn't mean same trajectory.

How to calculate the area of a java.awt.geom.Area?

I am looking for a way to calculate the area, in pixels, of an arbitrary instance of java.awt.geom.Area.
The background: I have Shapes in my applications that may overlap. I want to know how much one Shape overlaps another. The Shapes may be skewed, rotated, etc. If I had a function area(Shape) (or Area), I could use the intersection of two Shapes like so:
double fractionObscured(Shape bottom, Shape top) {
Area intersection = new Area(bottom);
intersection.intersect(new Area(top));
return area(intersection) / area(bottom);
}
To find the area of a polygon using the following snippet:
int sum = 0;
for (int i = 0; i < n -1; i++)
{
sum = sum + x[i]*y[i+1] - y[i]*x[i+1];
}
// (sum / 2) is your area.
System.out.println("The area is : " + (sum / 2));
Here n is the total number of vertices and x[i] and y[i] are the x and y coordinates of a vertex i.
Note that for this algorithm to work, the polygon must be closed. It doesent work on open polygons.
You can find mathematical alogrithms related to polygons here. You need to convert it to code yourself:)
I've used this class to approximate the area of a shape in one of my projects. It's slow but at high resolution it may still be faster than counting pixels (because the cost of counting pixels grows quadratically with resolution, but the number of line segments on the perimeter grows linearly.)
import static java.lang.Double.NaN;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.awt.geom.FlatteningPathIterator;
import java.awt.geom.Line2D;
import java.awt.geom.PathIterator;
public abstract class Areas {
public static double approxArea(Area area, double flatness, int limit) {
PathIterator i =
new FlatteningPathIterator(area.getPathIterator(identity),
flatness,
limit);
return approxArea(i);
}
public static double approxArea(Area area, double flatness) {
PathIterator i = area.getPathIterator(identity, flatness);
return approxArea(i);
}
public static double approxArea(PathIterator i) {
double a = 0.0;
double[] coords = new double[6];
double startX = NaN, startY = NaN;
Line2D segment = new Line2D.Double(NaN, NaN, NaN, NaN);
while (! i.isDone()) {
int segType = i.currentSegment(coords);
double x = coords[0], y = coords[1];
switch (segType) {
case PathIterator.SEG_CLOSE:
segment.setLine(segment.getX2(), segment.getY2(), startX, startY);
a += hexArea(segment);
startX = startY = NaN;
segment.setLine(NaN, NaN, NaN, NaN);
break;
case PathIterator.SEG_LINETO:
segment.setLine(segment.getX2(), segment.getY2(), x, y);
a += hexArea(segment);
break;
case PathIterator.SEG_MOVETO:
startX = x;
startY = y;
segment.setLine(NaN, NaN, x, y);
break;
default:
throw new IllegalArgumentException("PathIterator contains curved segments");
}
i.next();
}
if (Double.isNaN(a)) {
throw new IllegalArgumentException("PathIterator contains an open path");
} else {
return 0.5 * Math.abs(a);
}
}
private static double hexArea(Line2D seg) {
return seg.getX1() * seg.getY2() - seg.getX2() * seg.getY1();
}
private static final AffineTransform identity =
AffineTransform.getQuadrantRotateInstance(0);
}
One approach would be to fill() each scaled and transformed Shape with a different color using a suitable AlphaComposite and count the overlapping pixels in the underlying Raster.
Addendum 1: Using this calculator to see the effect of AlphaComposite.Xor shows that the intersetion of any two opaque colors is zero.
Addendum 2: Counting pixels may have performance problems; sampling may help. If each Shape is reasonably convex, it may be possible to estimate the overlap from the ratio of the intersect() area to the sum of the areas of the Shapes' getBounds2D(). For example,
Shape s1, s2 ...
Rectangle2D r1 = s1.getBounds2D();
Rectangle2D r2 = s2.getBounds2D();
Rectangle2D r3 = new Rectangle2D.Double();
Rectangle2D.intersect(r1, r2, r3);
double overlap = area(r3) / (area(r1) + area(r2));
...
private double area(Rectangle2D r) {
return r.getWidth() * r.getHeight();
}
You may need to validate the results empirically.
I would comment if I could. Suraj, your algorithm is correct, but the code should be
int sum = 0;
for (int i = 0; i < npoints ; i++)
{
sum = sum + Xs[i]*Ys[(i+1)%npoints] - Ys[i]*Xs[(i+1)%npoints];
}
return Math.abs(sum / 2);
In your code last vertice is not taken into account. Just a small edit :)
The given answer is not accurate , I have found that following solution gives much better results
private int calcAreaSize(Area area){
int sum = 0;
float xBegin=0, yBegin=0, xPrev=0, yPrev=0, coords[] = new float[6];
for (PathIterator iterator1 = area.getPathIterator(null, 0.1); !iterator1.isDone(); iterator1.next()){
switch (iterator1.currentSegment(coords))
{
case PathIterator.SEG_MOVETO:
xBegin = coords[0]; yBegin = coords[1];
break;
case PathIterator.SEG_LINETO:
// the well-known trapez-formula
sum += (coords[0] - xPrev) * (coords[1] + yPrev) / 2.0;
break;
case PathIterator.SEG_CLOSE:
sum += (xBegin - xPrev) * (yBegin + yPrev) / 2.0;
break;
default:
// curved segments cannot occur, because we have a flattened ath
throw new InternalError();
}
xPrev = coords[0]; yPrev = coords[1];
}
return sum;
}

Categories

Resources