Example usage for java.awt.geom Line2D getP2

List of usage examples for java.awt.geom Line2D getP2

Introduction

In this page you can find the example usage for java.awt.geom Line2D getP2.

Prototype

public abstract Point2D getP2();

Source Link

Document

Returns the end Point2D of this Line2D .

Usage

From source file:graticules2wld.Main.java

/**
 * @param args//from w w  w  . j  ava2  s .  c o  m
 * @throws Exception
 */
public static void main(String[] args) throws Exception {

    /* parse the command line arguments */
    // create the command line parser
    CommandLineParser parser = new PosixParser();

    // create the Options
    Options options = new Options();
    options.addOption("x", "originx", true, "x component of projected coordinates of upper left pixel");
    options.addOption("y", "originy", true, "y component of projected coordinates of upper left pixel");
    options.addOption("u", "tometers", true, "multiplication factor to get source units into meters");
    options.addOption("h", "help", false, "prints this usage page");
    options.addOption("d", "debug", false, "prints debugging information to stdout");

    double originNorthing = 0;
    double originEasting = 0;

    String inputFileName = null;
    String outputFileName = null;

    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("help"))
            printUsage(0); // print usage then exit using a non error exit status

        if (line.hasOption("debug"))
            debug = true;

        // these arguments are required
        if (!line.hasOption("originy") || !line.hasOption("originx"))
            printUsage(1);

        originNorthing = Double.parseDouble(line.getOptionValue("originy"));
        originEasting = Double.parseDouble(line.getOptionValue("originx"));

        if (line.hasOption("tometers"))
            unitsToMeters = Double.parseDouble(line.getOptionValue("tometers"));

        // two args should be left. the input csv file name and the output wld file name.
        String[] iofiles = line.getArgs();
        if (iofiles.length < 2) {
            printUsage(1);
        }

        inputFileName = iofiles[0];
        outputFileName = iofiles[1];
    } catch (ParseException exp) {
        System.err.println("Unexpected exception:" + exp.getMessage());
        System.exit(1);
    }

    // try to open the input file for reading and the output file for writing
    File graticulesCsvFile;
    BufferedReader csvReader = null;

    File wldFile;
    BufferedWriter wldWriter = null;

    try {
        graticulesCsvFile = new File(inputFileName);
        csvReader = new BufferedReader(new FileReader(graticulesCsvFile));
    } catch (IOException exp) {
        System.err.println("Could not open input file for reading: " + inputFileName);
        System.exit(1);
    }

    try {
        wldFile = new File(outputFileName);
        wldWriter = new BufferedWriter(new FileWriter(wldFile));
    } catch (IOException exp) {
        System.err.println("Could not open output file for writing: " + outputFileName);
        System.exit(1);
    }

    // list of lon graticules and lat graticules
    ArrayList<Graticule> lonGrats = new ArrayList<Graticule>();
    ArrayList<Graticule> latGrats = new ArrayList<Graticule>();

    // read the source CSV and convert its information into the two ArrayList<Graticule> data structures
    readCSV(csvReader, lonGrats, latGrats);

    // we now need to start finding the world file paramaters
    DescriptiveStatistics stats = new DescriptiveStatistics();

    // find theta and phi
    for (Graticule g : latGrats) {
        stats.addValue(g.angle());
    }

    double theta = stats.getMean(); // we use the mean of the lat angles as theta
    if (debug)
        System.out.println("theta range = " + Math.toDegrees(stats.getMax() - stats.getMin()));
    stats.clear();

    for (Graticule g : lonGrats) {
        stats.addValue(g.angle());
    }

    double phi = stats.getMean(); // ... and the mean of the lon angles for phi
    if (debug)
        System.out.println("phi range = " + Math.toDegrees(stats.getMax() - stats.getMin()));
    stats.clear();

    // print these if in debug mode
    if (debug) {
        System.out.println("theta = " + Math.toDegrees(theta) + "deg");
        System.out.println("phi = " + Math.toDegrees(phi) + "deg");
    }

    // find x and y (distance beteen pixels in map units)
    Collections.sort(latGrats);
    Collections.sort(lonGrats);
    int prevMapValue = 0; //fixme: how to stop warning about not being initilised?
    Line2D prevGratPixelSys = new Line2D.Double();

    boolean first = true;
    for (Graticule g : latGrats) {
        if (!first) {
            int deltaMapValue = Math.abs(g.realValue() - prevMapValue);
            double deltaPixelValue = (g.l.ptLineDist(prevGratPixelSys.getP1())
                    + (g.l.ptLineDist(prevGratPixelSys.getP2()))) / 2;

            double delta = deltaMapValue / deltaPixelValue;
            stats.addValue(delta);
        } else {
            first = false;
            prevMapValue = g.realValue();
            prevGratPixelSys = (Line2D) g.l.clone();
        }
    }

    double y = stats.getMean();
    if (debug)
        System.out.println("y range = " + (stats.getMax() - stats.getMin()));
    stats.clear();

    first = true;
    for (Graticule g : lonGrats) {
        if (!first) {
            int deltaMapValue = g.realValue() - prevMapValue;
            double deltaPixelValue = (g.l.ptLineDist(prevGratPixelSys.getP1())
                    + (g.l.ptLineDist(prevGratPixelSys.getP2()))) / 2;

            double delta = deltaMapValue / deltaPixelValue;
            stats.addValue(delta);
        } else {
            first = false;
            prevMapValue = g.realValue();
            prevGratPixelSys = (Line2D) g.l.clone();
        }
    }

    double x = stats.getMean();
    if (debug)
        System.out.println("x range = " + (stats.getMax() - stats.getMin()));
    stats.clear();

    if (debug) {
        System.out.println("x = " + x);
        System.out.println("y = " + y);
    }

    SimpleRegression regression = new SimpleRegression();

    // C, F are translation terms: x, y map coordinates of the center of the upper-left pixel
    for (Graticule g : latGrats) {
        // find perp dist to pixel space 0,0
        Double perpPixelDist = g.l.ptLineDist(new Point2D.Double(0, 0));

        // find the map space distance from this graticule to the center of the 0,0 pixel
        Double perpMapDist = perpPixelDist * y; // perpMapDist / perpPixelDist = y

        regression.addData(perpMapDist, g.realValue());
    }

    double F = regression.getIntercept();
    regression.clear();

    for (Graticule g : lonGrats) {
        // find perp dist to pixel space 0,0
        Double perpPixelDist = g.l.ptLineDist(new Point2D.Double(0, 0));

        // find the map space distance from this graticule to the center of the 0,0 pixel
        Double perpMapDist = perpPixelDist * x; // perpMapDist / perpPixelDist = x

        regression.addData(perpMapDist, g.realValue());
    }

    double C = regression.getIntercept();
    regression.clear();

    if (debug) {
        System.out.println("Upper Left pixel has coordinates " + C + ", " + F);
    }

    // convert to meters
    C *= unitsToMeters;
    F *= unitsToMeters;

    // C,F store the projected (in map units) coordinates of the upper left pixel.
    // originNorthing,originEasting is the offset we need to apply to 0,0 to push the offsets into our global coordinate system 
    C = originEasting + C;
    F = originNorthing + F;

    // calculate the affine transformation matrix elements
    double D = -1 * x * unitsToMeters * Math.sin(theta);
    double A = x * unitsToMeters * Math.cos(theta);
    double B = y * unitsToMeters * Math.sin(phi); // if should be negative, it'll formed by negative sin
    double E = -1 * y * unitsToMeters * Math.cos(phi);

    /*
     * Line 1: A: pixel size in the x-direction in map units/pixel
     * Line 2: D: rotation about y-axis
     * Line 3: B: rotation about x-axis
     * Line 4: E: pixel size in the y-direction in map units, almost always negative[3]
     * Line 5: C: x-coordinate of the center of the upper left pixel
     * Line 6: F: y-coordinate of the center of the upper left pixel
     */
    if (debug) {
        System.out.println("A = " + A);
        System.out.println("D = " + D);
        System.out.println("B = " + B);
        System.out.println("E = " + E);
        System.out.println("C = " + C);
        System.out.println("F = " + F);

        // write the world file
        System.out.println();
        System.out.println("World File:");
        System.out.println(A);
        System.out.println(D);
        System.out.println(B);
        System.out.println(E);
        System.out.println(C);
        System.out.println(F);
    }

    // write to the .wld file
    wldWriter.write(A + "\n");
    wldWriter.write(D + "\n");
    wldWriter.write(B + "\n");
    wldWriter.write(E + "\n");
    wldWriter.write(C + "\n");
    wldWriter.write(F + "\n");

    wldWriter.close();
}

From source file:Main.java

/** Computes the intersection between two lines. The calculated point is approximate, 
 * since integers are used. If you need a more precise result, use doubles everywhere.
 * Modified from original version (by Alexander Hristov) by Eric Eaton. 
 * (c) 2007 Alexander Hristov. Use Freely (LGPL license). http://www.ahristov.com
 *
 * @param lineA the first line/*from   w  ww .  jav  a 2 s .  c  om*/
 * @param lineB the second line
 * @return point where the segments intersect, or null if they don't
 */
public static Point2D intersection(Line2D lineA, Line2D lineB) {

    Point2D lineAPt1 = lineA.getP1();
    Point2D lineAPt2 = lineA.getP2();
    Point2D lineBPt1 = lineB.getP1();
    Point2D lineBPt2 = lineB.getP2();

    double x1 = lineAPt1.getX();
    double y1 = lineAPt1.getY();
    double x2 = lineAPt2.getX();
    double y2 = lineAPt2.getY();
    double x3 = lineBPt1.getX();
    double y3 = lineBPt1.getY();
    double x4 = lineBPt2.getX();
    double y4 = lineBPt2.getY();

    double d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
    if (d == 0)
        return null;

    double xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d;
    double yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d;

    return new Point2D.Double(xi, yi);
}

From source file:Main.java

/**
 * Compares two lines are returns <code>true</code> if they are equal or
 * both <code>null</code>.//from w  w w  .  j  a  v a 2  s . c o m
 *
 * @param l1  the first line (<code>null</code> permitted).
 * @param l2  the second line (<code>null</code> permitted).
 *
 * @return A boolean.
 */
public static boolean equal(final Line2D l1, final Line2D l2) {
    if (l1 == null) {
        return (l2 == null);
    }
    if (l2 == null) {
        return false;
    }
    if (!l1.getP1().equals(l2.getP1())) {
        return false;
    }
    if (!l1.getP2().equals(l2.getP2())) {
        return false;
    }
    return true;
}

From source file:org.gumtree.vis.mask.ChartMaskingUtilities.java

public static Shape translateChartShape(Shape shape, Rectangle2D imageArea, JFreeChart chart) {
    if (shape instanceof Line2D) {
        Line2D line = (Line2D) shape;
        double length = line.getP1().distance(line.getP2());
        if (length == 0) {
            Point2D point = line.getP1();
            Point2D newPoint = ChartMaskingUtilities.translateChartPoint(point, imageArea, chart);
            Shape oShape = ShapeUtilities.createDiagonalCross(5f, 0.2f);
            //             Shape oShape = ShapeUtilities.createRegularCross(3f, 0.5f);
            Shape newShape = ShapeUtilities.createTranslatedShape(oShape, newPoint.getX(), newPoint.getY());
            return newShape;
        } else if (length < 1e-6) {
            if (line.getP1().getX() == line.getP2().getX()) {
                double newX = ChartMaskingUtilities.translateChartPoint(line.getP1(), imageArea, chart).getX();
                Line2D newLine = new Line2D.Double(newX, imageArea.getMinY(), newX, imageArea.getMaxY());
                return newLine;
            } else {
                double newY = ChartMaskingUtilities.translateChartPoint(line.getP1(), imageArea, chart).getY();
                Line2D newLine = new Line2D.Double(imageArea.getMinX(), newY, imageArea.getMaxX(), newY);
                return newLine;
            }/*from   w w w  . ja  v  a 2s.  c o  m*/
        }
        Line2D newShape = (Line2D) line.clone();
        Point2D newP1 = translateChartPoint(line.getP1(), imageArea, chart);
        Point2D newP2 = translateChartPoint(line.getP2(), imageArea, chart);
        newShape.setLine(newP1, newP2);
        return newShape;
    } else if (shape instanceof RectangularShape) {
        RectangularShape rect = (RectangularShape) shape;
        RectangularShape newShape = (RectangularShape) rect.clone();
        Rectangle2D bound = rect.getBounds2D();
        Point2D start = new Point2D.Double(bound.getMinX(), bound.getMinY());
        Point2D end = new Point2D.Double(bound.getMaxX(), bound.getMaxY());
        Point2D screenStart = translateChartPoint(start, imageArea, chart);
        Point2D screenEnd = translateChartPoint(end, imageArea, chart);
        newShape.setFrame(new Rectangle2D.Double(Math.min(screenStart.getX(), screenEnd.getX()),
                Math.min(screenStart.getY(), screenEnd.getY()), Math.abs(screenStart.getX() - screenEnd.getX()),
                Math.abs(screenStart.getY() - screenEnd.getY())));
        return newShape;
    } else {
        return shape;
    }
}

From source file:ShapeTransform.java

/**
 * Resizes a line. Instead of creating a GeneralPath (as AffineTransform's
 * scale would do) we modify the line itself.
 * // w  w  w .  j  a va2  s  .c o m
 * @param line
 *          the line that should be scaled
 * @param width
 *          the new width of the line bounds
 * @param height
 *          the new height of the line bounds
 * @return the scale Line2D object.
 */
private static Line2D resizeLine(final Line2D line, final double width, final double height) {
    final Line2D newLine = getNormalizedLine(line);
    final Point2D p1 = newLine.getP1();
    final Point2D p2 = newLine.getP2();
    final double normPointX = (p1.getX() - p2.getX());
    final double normPointY = (p1.getY() - p2.getY());
    final double scaleX = (normPointX == 0) ? 1 : width / Math.abs(normPointX);
    final double scaleY = (normPointY == 0) ? 1 : height / Math.abs(normPointY);
    p2.setLocation((p2.getX() - p1.getX()) * scaleX + p1.getX(), (p2.getY() - p1.getY()) * scaleY + p1.getY());
    newLine.setLine(p1, p2);
    return newLine;
}

From source file:ShapeTransform.java

/**
 * Normalize the line; the point with the lowest X is the primary point, if
 * both points have the same X, that point with the lowest Y value wins.
 * //from   w  ww  .  ja v  a 2  s  .c  o  m
 * @param line
 *          the original line
 * @return the normalized line
 */
private static Line2D getNormalizedLine(final Line2D line) {
    final Line2D lineClone = (Line2D) line.clone();

    final Point2D p1 = line.getP1();
    final Point2D p2 = line.getP2();
    if (p1.getX() < p2.getX()) {
        return lineClone;
    }
    if (p1.getX() > p2.getX()) {
        lineClone.setLine(p2, p1);
        return lineClone;
    }
    if (p1.getY() < p2.getY()) {
        return lineClone;
    }
    lineClone.setLine(p2, p1);
    return lineClone;
}

From source file:com.wasteofplastic.beaconz.Register.java

/**
 * Deletes any links that starts/*  w  ww. ja v  a 2 s. co  m*/
 * @param faction
 * @param point
 * NOTE: THIS ISN'T USED ANYWHERE *****************************
 */
public void deleteBeaconLinks(Team team, Point2D point) {
    Set<Line2D> linkSet = new HashSet<Line2D>();
    if (links.containsKey(team)) {
        linkSet = links.get(team);
    }
    Iterator<Line2D> it = linkSet.iterator();
    while (it.hasNext()) {
        Line2D line = it.next();
        if (line.getP1().equals(point) || line.getP2().equals(point)) {
            // Devisualize - TODO: make async or something
            for (Iterator<Point2D> lineIt = new LineIterator(line); lineIt.hasNext();) {
                Point2D current = lineIt.next();
                Block b = getBeaconzWorld().getBlockAt((int) current.getX(),
                        getBeaconzWorld().getMaxHeight() - 1, (int) current.getY());
                b.setType(Material.AIR);
            }
            it.remove();
            getScorecard().refreshScores(team, "links");
        }
    }
}

From source file:com.wasteofplastic.beaconz.Register.java

/**
 * Removes this beacon from team ownership and makes it unowned
 * @param beacon//from w ww.  j  a v  a 2 s .  com
 */
public void removeBeaconOwnership(BeaconObj beacon) {
    Team oldOwner = beacon.getOwnership();
    beacon.setOwnership(null);

    // Remove links to the beacon (and back)
    Iterator<BeaconObj> beaconIterator = beacon.getLinks().iterator();
    while (beaconIterator.hasNext()) {
        beaconIterator.next().removeLink(beacon);
    }

    // Remove links from this register 
    if (links.get(oldOwner) != null) {
        Iterator<Line2D> linkIterator = links.get(oldOwner).iterator();
        int linkLossCount = 0;
        while (linkIterator.hasNext()) {
            Line2D link = linkIterator.next();
            if (link.getP1().equals(beacon.getLocation()) || link.getP2().equals(beacon.getLocation())) {
                linkLossCount++;
                linkIterator.remove();
            }
        }
        if (linkLossCount == 1) {
            // Tell folks what's going on
            getMessages().tellTeam(oldOwner, ChatColor.RED + "Your team lost a link!");
            getMessages().tellOtherTeams(oldOwner,
                    ChatColor.GREEN + oldOwner.getDisplayName() + ChatColor.GREEN + " lost a link!");
        } else if (linkLossCount > 1) {
            getMessages().tellTeam(oldOwner, ChatColor.RED + "Your team lost " + linkLossCount + " links!");
            getMessages().tellOtherTeams(oldOwner, ChatColor.GREEN + oldOwner.getDisplayName() + ChatColor.GREEN
                    + " lost " + linkLossCount + " links!");
        }
    }

    beacon.removeLinks();

    // Get any control triangles that have been removed because of this
    Iterator<TriangleField> it = triangleFields.iterator();
    while (it.hasNext()) {
        TriangleField triangle = it.next();
        if (triangle.hasVertex(beacon.getLocation())) {
            //getLogger().info("DEBUG: this beacon was part of a triangle");
            // Tell folks what's going on
            getMessages().tellTeam(triangle.getOwner(),
                    ChatColor.RED + "Your team lost a triangle worth " + triangle.getArea() + "!");
            getMessages().tellOtherTeams(triangle.getOwner(),
                    ChatColor.GREEN + triangle.getOwner().getDisplayName() + ChatColor.GREEN
                            + " lost a triangle worth " + triangle.getArea() + "!");
            // Remove triangle
            it.remove();
        }
    }
    // Refresh the scores
    getScorecard().refreshScores(oldOwner);
}

From source file:edu.uci.ics.jung.visualization.PluggableRenderer.java

/**
 * Passed Line's point2 must be inside the passed shape or
 * an IllegalArgumentException is thrown
 * @param line line to subdivide/* w  ww .j a va  2  s.c o  m*/
 * @param shape shape to compare with line
 * @return a line that intersects the shape boundary
 * @throws IllegalArgumentException if the passed line's point1 is not inside the shape
 */
protected Line2D getLastOutsideSegment(Line2D line, Shape shape) {
    if (shape.contains(line.getP2()) == false) {
        String errorString = "line end point: " + line.getP2() + " is not contained in shape: "
                + shape.getBounds2D();
        throw new IllegalArgumentException(errorString);
        //return null;
    }
    Line2D left = new Line2D.Double();
    Line2D right = new Line2D.Double();
    // subdivide the line until its left segment intersects
    // the shape boundary
    int iterations = 0;
    do {
        subdivide(line, left, right);
        line = right;
    } while (shape.contains(line.getP1()) == false && iterations++ < MAX_ITERATIONS);
    // now that right is completely inside shape,
    // return left, which must be partially outside
    return left;
}

From source file:edu.uci.ics.jung.visualization.PluggableRenderer.java

/**
 * Passed Line's point1 must be inside the passed shape or
 * an IllegalArgumentException is thrown
 * @param line line to subdivide//from   w ww .  jav a2  s . com
 * @param shape shape to compare with line
 * @return a line that intersects the shape boundary
 * @throws IllegalArgumentException if the passed line's point1 is not inside the shape
 */
protected Line2D getFirstOutsideSegment(Line2D line, Shape shape) {

    if (shape.contains(line.getP1()) == false) {
        String errorString = "line start point: " + line.getP1() + " is not contained in shape: "
                + shape.getBounds2D();
        throw new IllegalArgumentException(errorString);
    }
    Line2D left = new Line2D.Float();
    Line2D right = new Line2D.Float();
    // subdivide the line until its right side intersects the
    // shape boundary
    do {
        subdivide(line, left, right);
        line = left;
    } while (shape.contains(line.getP2()) == false);
    // now that left is completely inside shape,
    // return right, which must be partially outside
    return right;
}