Example usage for java.lang Math atan2

List of usage examples for java.lang Math atan2

Introduction

In this page you can find the example usage for java.lang Math atan2.

Prototype

@HotSpotIntrinsicCandidate
public static double atan2(double y, double x) 

Source Link

Document

Returns the angle theta from the conversion of rectangular coordinates ( x ,  y ) to polar coordinates (r, theta).

Usage

From source file:com.diozero.sandpit.imu.invensense.MPU9150DriverTest.java

public void run() {
    try (MPU9150Driver mpu = new MPU9150Driver(I2CConstants.BUS_1, I2CConstants.ADDR_SIZE_7,
            MPU9150Constants.I2C_CLOCK_FREQUENCY_FAST)) {
        mpuInit(mpu);//w w  w. j  av a2  s.  com
        System.err.println("Ready.");

        do {
            ImuData imu_data = update(mpu);
            System.out.print("Got IMU data: compass=[" + imu_data.getCompass() + "], temp="
                    + imu_data.getTemperature() + ", gyro=[" + imu_data.getGyro() + "], accel=["
                    + imu_data.getAccel() + "], quat=[" + imu_data.getQuaternion().getQ0() + ", "
                    + imu_data.getQuaternion().getQ1() + ", " + imu_data.getQuaternion().getQ2() + ", "
                    + imu_data.getQuaternion().getQ3() + "], timestamp=" + imu_data.getTimestamp() + ", ");

            Quaternion q = imu_data.getQuaternion();
            //double[] ypr = q.toEuler();
            //double[] ypr = quat.getYawPitchRoll();
            Rotation r = new Rotation(q.getQ0(), q.getQ1(), q.getQ2(), q.getQ3(), true);
            double[] ypr = null;
            try {
                ypr = r.getAngles(RotationOrder.XYZ, RotationConvention.VECTOR_OPERATOR);
            } catch (CardanEulerSingularityException e) {
                ypr = new double[] { 2 * Math.atan2(q.getQ1(), q.getQ0()), Math.PI / 2, 0 };
                System.out.print("Singularity detected, ");
            }
            Logger.info("ypr=[{}, {}, {}]", Double.valueOf(ypr[0]), Double.valueOf(ypr[1]),
                    Double.valueOf(ypr[2]));
        } while (true);

    } catch (RuntimeIOException ioe) {
        Logger.error(ioe, "Error: {}", ioe);
    }
}

From source file:org.knowrob.vis.model.util.algorithm.ACCUM.java

/**
 * Calculate hue and saturation for curvature properties.
 * /* w w w. ja  va  2 s . co m*/
 * @param curvatures
 *            maps curvatures to vertices
 * @param smoothSigma
 *            sigma value for smoothing the curvature. Set to 0 to disable smoothing.
 * @param m
 *            model needed to calculate hue saturation scale
 */
public static void setCurvatureHueSaturation(HashMap<Vertex, Curvature> curvatures, Model m,
        float smoothSigma) {
    if (smoothSigma > 0.0f) {
        float scaledSigma = smoothSigma * m.feature_size();
        diffuse_curv(m, curvatures, scaledSigma);
    }

    float cscale = 120.0f * typical_scale(curvatures, m);
    cscale = cscale * cscale;
    int nv = m.getVertices().size();
    for (int i = 0; i < nv; i++) {
        Curvature c = curvatures.get(m.getVertices().get(i));
        float H = 0.5f * (c.getCurvatureMax() + c.getCurvatureMin());
        // mean curvature -> don't set the mean curvature here as we want only the initial one to be stored and this method is public
        float K = c.getCurvatureMax() * c.getCurvatureMin();
        // Gaussian curvature -> don't set the Gaussian curvature here as we want only the initial one to be stored and this method is public
        float h = (float) (4.0f / 3.0f * Math.abs(Math.atan2(H * H - K, H * H * Math.signum(H))));
        float s = (float) ((2 / Math.PI) * Math.atan((2.0f * H * H - K) * cscale));
        c.setHue(h);
        c.setSaturation(s);
    }
}

From source file:syncleus.dann.math.ComplexNumber.java

/**
 * Argument of this Complex number (the angle in radians with the x-axis in
 * polar coordinates)./* w w w  .  j  a v a2  s. c o  m*/
 *
 * @return arg(z) where z is this Complex number.
 */
public double arg() {
    return Math.atan2(getImaginary(), getReal());
}

From source file:geogebra.common.kernel.geos.GeoVec2D.java

/**
 * @return phase (polar)
 */
final public double getPhi() {
    return Math.atan2(y, x);
}

From source file:de.biomedical_imaging.traj.math.TrajectorySplineFit.java

/**
 * Calculates a spline to a trajectory. Attention: The spline is fitted through a rotated version of the trajectory.
 * To fit the spline the trajectory is rotated into its main direction. You can access this rotated trajectory by 
 * {@link #getRotatedTrajectory() getRotatedTrajectory}.
 * @return The fitted spline/*from   www  .  ja  v  a 2s  .co  m*/
 */
public PolynomialSplineFunction calculateSpline() {

    successfull = false;
    /*
     * 1.Calculate the minimum bounding rectangle
     */
    ArrayList<Point2D.Double> points = new ArrayList<Point2D.Double>();
    for (int i = 0; i < t.size(); i++) {
        Point2D.Double p = new Point2D.Double();
        p.setLocation(t.get(i).x, t.get(i).y);
        points.add(p);
    }

    /*
     * 1.1 Rotate that the major axis is parallel with the xaxis
     */

    Array2DRowRealMatrix gyr = RadiusGyrationTensor2D.getRadiusOfGyrationTensor(t);
    EigenDecomposition eigdec = new EigenDecomposition(gyr);

    double inRad = -1 * Math.atan2(eigdec.getEigenvector(0).getEntry(1), eigdec.getEigenvector(0).getEntry(0));
    boolean doTransform = (Math.abs(Math.abs(inRad) - Math.PI) > 0.001);

    if (doTransform) {
        angleRotated = inRad;
        for (int i = 0; i < t.size(); i++) {
            double x = t.get(i).x;
            double y = t.get(i).y;
            double newX = x * Math.cos(inRad) - y * Math.sin(inRad);
            double newY = x * Math.sin(inRad) + y * Math.cos(inRad);
            rotatedTrajectory.add(newX, newY, 0);
            points.get(i).setLocation(newX, newY);
        }
        //for(int i = 0; i < rect.length; i++){
        //   rect[i].setLocation(rect[i].x*Math.cos(inRad)-rect[i].y*Math.sin(inRad), rect[i].x*Math.sin(inRad)+rect[i].y*Math.cos(inRad));
        //}
    } else {
        angleRotated = 0;
        rotatedTrajectory = t;
    }

    /*
     * 2. Divide the rectangle in n equal segments
     * 2.1 Calculate line in main direction
     * 2.2 Project the points in onto this line
     * 2.3 Calculate the distance between the start of the line and the projected point
     * 2.4 Assign point to segment according to distance of (2.3)
     */
    List<List<Point2D.Double>> pointsInSegments = null;
    boolean allSegmentsContainingAtLeastTwoPoints = true;
    int indexSmallestX = 0;

    double segmentWidth = 0;
    do {
        double smallestX = Double.MAX_VALUE;
        double largestX = Double.MIN_VALUE;

        for (int i = 0; i < points.size(); i++) {
            if (points.get(i).x < smallestX) {
                smallestX = points.get(i).x;
                indexSmallestX = i;
            }
            if (points.get(i).x > largestX) {
                largestX = points.get(i).x;
            }
        }

        allSegmentsContainingAtLeastTwoPoints = true;
        segmentWidth = (largestX - smallestX) / nSegments;
        pointsInSegments = new ArrayList<List<Point2D.Double>>(nSegments);
        for (int i = 0; i < nSegments; i++) {
            pointsInSegments.add(new ArrayList<Point2D.Double>());
        }
        for (int i = 0; i < points.size(); i++) {

            int index = (int) Math.abs((points.get(i).x / segmentWidth));

            if (index > (nSegments - 1)) {
                index = (nSegments - 1);
            }
            pointsInSegments.get(index).add(points.get(i));
        }

        for (int i = 0; i < pointsInSegments.size(); i++) {
            if (pointsInSegments.get(i).size() < 2) {
                if (nSegments > 2) {
                    nSegments--;
                    i = pointsInSegments.size();
                    allSegmentsContainingAtLeastTwoPoints = false;

                }
            }
        }

    } while (allSegmentsContainingAtLeastTwoPoints == false);

    /*
     * 3. Calculate the mean standard deviation over each segment: <s>
     */
    //Point2D.Double eMajorP1 = new Point2D.Double(p1.x - (p3.x-p1.x)/2.0,p1.y - (p3.y-p1.y)/2.0); 
    //   Point2D.Double eMajorP2 = new Point2D.Double(p2.x - (p3.x-p1.x)/2.0,p2.y - (p3.y-p1.y)/2.0); 
    double sumSDOrthogonal = 0;
    int Nsum = 0;
    CenterOfGravityFeature cogf = new CenterOfGravityFeature(rotatedTrajectory);
    Point2D.Double cog = new Point2D.Double(cogf.evaluate()[0], cogf.evaluate()[1]);
    Point2D.Double eMajorP1 = cog;
    Point2D.Double eMajorP2 = new Point2D.Double(cog.getX() + 1, cog.getY());
    for (int i = 0; i < nSegments; i++) {
        StandardDeviation sd = new StandardDeviation();
        double[] distances = new double[pointsInSegments.get(i).size()];
        for (int j = 0; j < pointsInSegments.get(i).size(); j++) {
            int factor = 1;
            if (isLeft(eMajorP1, eMajorP2, pointsInSegments.get(i).get(j))) {
                factor = -1;
            }
            distances[j] = factor * distancePointLine(eMajorP1, eMajorP2, pointsInSegments.get(i).get(j));
        }
        if (distances.length > 0) {
            sd.setData(distances);

            sumSDOrthogonal += sd.evaluate();
            Nsum++;
        }
    }
    double s = sumSDOrthogonal / Nsum;
    if (segmentWidth < Math.pow(10, -15)) {
        return null;
    }
    if (s < Math.pow(10, -15)) {
        //If standard deviation is zero, replace it with the half of the segment width

        s = segmentWidth / 2;
    }
    //rotatedTrajectory.showTrajectory("rot");
    /*
     * 4. Build a kd-tree
     */
    KDTree<Point2D.Double> kdtree = new KDTree<Point2D.Double>(2);

    for (int i = 0; i < points.size(); i++) {
        try {
            //To ensure that all points have a different key, add small random number

            kdtree.insert(new double[] { points.get(i).x, points.get(i).y }, points.get(i));
        } catch (KeySizeException e) {
            e.printStackTrace();
        } catch (KeyDuplicateException e) {
            //Do nothing! It is not important
        }

    }

    /*
     * 5. Using the first point f in trajectory and calculate the center of mass
     * of all points around f (radius: 3*<s>))
     */
    List<Point2D.Double> near = null;

    Point2D.Double first = points.get(indexSmallestX);//minDistancePointToLine(p1, p3, points);
    double r1 = 3 * s;
    try {

        near = kdtree.nearestEuclidean(new double[] { first.x, first.y }, r1);

    } catch (KeySizeException e) {
        e.printStackTrace();
    }

    double cx = 0;
    double cy = 0;
    for (int i = 0; i < near.size(); i++) {
        cx += near.get(i).x;
        cy += near.get(i).y;
    }
    cx /= near.size();
    cy /= near.size();

    splineSupportPoints = new ArrayList<Point2D.Double>();
    splineSupportPoints.add(new Point2D.Double(cx, cy));

    /* 
     * 6. The second point is determined by finding the center-of-mass of particles in the p/2 radian 
     * section of an annulus, r1 < r < 2r1, that is directed toward the angle with the highest number 
     * of particles within p/2 radians.
     * 7. This second point is then used as the center of the annulus for choosing the third point, and the process is repeated (6. & 7.).
     */

    /*
     * 6.1 Find all points in the annolous
     */

    /*
     * 6.2 Write each point in a coordinate system centered at the center of the sphere, calculate direction and
     * check if it in the allowed bounds
     */
    int nCircleSegments = 100;
    double deltaRad = 2 * Math.PI / nCircleSegments;
    boolean stop = false;
    int minN = 7;
    double tempr1 = r1;
    double allowedDeltaDirection = 0.5 * Math.PI;

    while (stop == false) {
        List<Point2D.Double> nearestr1 = null;
        List<Point2D.Double> nearest2xr1 = null;
        try {
            nearestr1 = kdtree
                    .nearestEuclidean(new double[] { splineSupportPoints.get(splineSupportPoints.size() - 1).x,
                            splineSupportPoints.get(splineSupportPoints.size() - 1).y }, tempr1);
            nearest2xr1 = kdtree
                    .nearestEuclidean(new double[] { splineSupportPoints.get(splineSupportPoints.size() - 1).x,
                            splineSupportPoints.get(splineSupportPoints.size() - 1).y }, 2 * tempr1);
        } catch (KeySizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        nearest2xr1.removeAll(nearestr1);

        double lThreshRad = 0;
        double hThreshRad = Math.PI / 2;
        double stopThresh = 2 * Math.PI;
        if (splineSupportPoints.size() > 1) {
            double directionInRad = Math.atan2(
                    splineSupportPoints.get(splineSupportPoints.size() - 1).y
                            - splineSupportPoints.get(splineSupportPoints.size() - 2).y,
                    splineSupportPoints.get(splineSupportPoints.size() - 1).x
                            - splineSupportPoints.get(splineSupportPoints.size() - 2).x)
                    + Math.PI;
            lThreshRad = directionInRad - allowedDeltaDirection / 2 - Math.PI / 4;
            if (lThreshRad < 0) {
                lThreshRad = 2 * Math.PI + lThreshRad;
            }
            if (lThreshRad > 2 * Math.PI) {
                lThreshRad = lThreshRad - 2 * Math.PI;
            }
            hThreshRad = directionInRad + allowedDeltaDirection / 2 + Math.PI / 4;
            if (hThreshRad < 0) {
                hThreshRad = 2 * Math.PI + hThreshRad;
            }
            if (hThreshRad > 2 * Math.PI) {
                hThreshRad = hThreshRad - 2 * Math.PI;
            }
            stopThresh = directionInRad + allowedDeltaDirection / 2 - Math.PI / 4;
            if (stopThresh > 2 * Math.PI) {
                stopThresh = stopThresh - 2 * Math.PI;
            }

        }

        double newCx = 0;
        double newCy = 0;
        int newCN = 0;
        int candN = 0;

        //Find center with highest density of points
        double lastDist = 0;
        double newDist = 0;
        do {
            lastDist = Math.min(Math.abs(lThreshRad - stopThresh),
                    2 * Math.PI - Math.abs(lThreshRad - stopThresh));

            candN = 0;
            double candCx = 0;
            double candCy = 0;

            for (int i = 0; i < nearest2xr1.size(); i++) {
                Point2D.Double centerOfCircle = splineSupportPoints.get(splineSupportPoints.size() - 1);
                Vector2d relativeToCircle = new Vector2d(nearest2xr1.get(i).x - centerOfCircle.x,
                        nearest2xr1.get(i).y - centerOfCircle.y);
                relativeToCircle.normalize();
                double angleInRadians = Math.atan2(relativeToCircle.y, relativeToCircle.x) + Math.PI;

                if (lThreshRad < hThreshRad) {
                    if (angleInRadians > lThreshRad && angleInRadians < hThreshRad) {
                        candCx += nearest2xr1.get(i).x;
                        candCy += nearest2xr1.get(i).y;
                        candN++;
                    }
                } else {
                    if (angleInRadians > lThreshRad || angleInRadians < hThreshRad) {
                        candCx += nearest2xr1.get(i).x;
                        candCy += nearest2xr1.get(i).y;
                        candN++;
                    }
                }

            }

            if (candN > 0 && candN > newCN) {
                candCx /= candN;
                candCy /= candN;
                newCx = candCx;
                newCy = candCy;
                newCN = candN;
            }
            lThreshRad += deltaRad;
            hThreshRad += deltaRad;
            if (lThreshRad > 2 * Math.PI) {
                lThreshRad = lThreshRad - 2 * Math.PI;
            }
            if (hThreshRad > 2 * Math.PI) {
                hThreshRad = hThreshRad - 2 * Math.PI;
            }
            newDist = Math.min(Math.abs(lThreshRad - stopThresh),
                    2 * Math.PI - Math.abs(lThreshRad - stopThresh));

        } while ((newDist - lastDist) > 0);

        //Check if the new center is valid
        if (splineSupportPoints.size() > 1) {
            double currentDirectionInRad = Math.atan2(
                    splineSupportPoints.get(splineSupportPoints.size() - 1).y
                            - splineSupportPoints.get(splineSupportPoints.size() - 2).y,
                    splineSupportPoints.get(splineSupportPoints.size() - 1).x
                            - splineSupportPoints.get(splineSupportPoints.size() - 2).x)
                    + Math.PI;
            double candDirectionInRad = Math.atan2(
                    newCy - splineSupportPoints.get(splineSupportPoints.size() - 1).y,
                    newCx - splineSupportPoints.get(splineSupportPoints.size() - 1).x) + Math.PI;
            double dDir = Math.max(currentDirectionInRad, candDirectionInRad)
                    - Math.min(currentDirectionInRad, candDirectionInRad);
            if (dDir > 2 * Math.PI) {
                dDir = 2 * Math.PI - dDir;
            }
            if (dDir > allowedDeltaDirection) {

                stop = true;
            }
        }
        boolean enoughPoints = (newCN < minN);
        boolean isNormalRadius = Math.abs(tempr1 - r1) < Math.pow(10, -18);
        boolean isExtendedRadius = Math.abs(tempr1 - 3 * r1) < Math.pow(10, -18);

        if (enoughPoints && isNormalRadius) {
            //Not enough points, extend search radius
            tempr1 = 3 * r1;
        } else if (enoughPoints && isExtendedRadius) {
            //Despite radius extension: Not enough points!
            stop = true;
        } else if (stop == false) {
            splineSupportPoints.add(new Point2D.Double(newCx, newCy));
            tempr1 = r1;
        }

    }

    //Sort
    Collections.sort(splineSupportPoints, new Comparator<Point2D.Double>() {

        public int compare(Point2D.Double o1, Point2D.Double o2) {
            if (o1.x < o2.x) {
                return -1;
            }
            if (o1.x > o2.x) {
                return 1;
            }
            return 0;
        }
    });

    //Add endpoints
    if (splineSupportPoints.size() > 1) {
        Vector2d start = new Vector2d(splineSupportPoints.get(0).x - splineSupportPoints.get(1).x,
                splineSupportPoints.get(0).y - splineSupportPoints.get(1).y);
        start.normalize();
        start.scale(r1 * 8);
        splineSupportPoints.add(0, new Point2D.Double(splineSupportPoints.get(0).x + start.x,
                splineSupportPoints.get(0).y + start.y));

        Vector2d end = new Vector2d(
                splineSupportPoints.get(splineSupportPoints.size() - 1).x
                        - splineSupportPoints.get(splineSupportPoints.size() - 2).x,
                splineSupportPoints.get(splineSupportPoints.size() - 1).y
                        - splineSupportPoints.get(splineSupportPoints.size() - 2).y);
        end.normalize();
        end.scale(r1 * 6);
        splineSupportPoints
                .add(new Point2D.Double(splineSupportPoints.get(splineSupportPoints.size() - 1).x + end.x,
                        splineSupportPoints.get(splineSupportPoints.size() - 1).y + end.y));
    } else {
        Vector2d majordir = new Vector2d(-1, 0);
        majordir.normalize();
        majordir.scale(r1 * 8);
        splineSupportPoints.add(0, new Point2D.Double(splineSupportPoints.get(0).x + majordir.x,
                splineSupportPoints.get(0).y + majordir.y));
        majordir.scale(-1);
        splineSupportPoints
                .add(new Point2D.Double(splineSupportPoints.get(splineSupportPoints.size() - 1).x + majordir.x,
                        splineSupportPoints.get(splineSupportPoints.size() - 1).y + majordir.y));

    }

    //Interpolate spline
    double[] supX = new double[splineSupportPoints.size()];
    double[] supY = new double[splineSupportPoints.size()];
    for (int i = 0; i < splineSupportPoints.size(); i++) {
        supX[i] = splineSupportPoints.get(i).x;
        supY[i] = splineSupportPoints.get(i).y;
    }

    SplineInterpolator sIinter = new SplineInterpolator();
    spline = sIinter.interpolate(supX, supY);
    successfull = true;
    return spline;
}

From source file:org.gearvrf.controls.util.MathUtils.java

public static float getYAngleEuler(GVRSceneObject object) {

    // xAngle = atan2(2*y*w - 2*x*z, 1 - 2*y*y - 2*z*z) //GVRF y
    // yAngle = atan2(2*x*w - 2*y*z, 1 - 2*x*x - 2*z*z) //GVRF x
    // zAngle = asin(2*x*y + 2*z*w) //GVRF

    // http://www.tinkerforge.com/en/doc/Software/Bricks/IMU_Brick_CSharp.html

    float xq = object.getTransform().getRotationX();
    float yq = object.getTransform().getRotationY();
    float zq = object.getTransform().getRotationZ();
    float wq = object.getTransform().getRotationW();

    double yAngle = Math.atan2(2 * yq * wq - 2 * xq * zq, 1 - 2 * yq * yq - 2 * zq * zq);

    return (float) yAngle;
}

From source file:uk.ac.diamond.scisoft.analysis.diffraction.powder.PixelIntegrationUtils.java

public static Dataset[] generateMinMaxAzimuthalArray(double[] beamCentre, int[] shape, boolean radians) {

    Dataset aMax = DatasetFactory.zeros(shape, Dataset.FLOAT64);
    Dataset aMin = DatasetFactory.zeros(shape, Dataset.FLOAT64);

    PositionIterator iter = aMax.getPositionIterator();
    int[] pos = iter.getPos();
    double[] vals = new double[4];

    while (iter.hasNext()) {
        //find vals at pixel corners
        vals[0] = Math.atan2(pos[0] - beamCentre[1], pos[1] - beamCentre[0]);
        vals[1] = Math.atan2(pos[0] - beamCentre[1] + 1, pos[1] - beamCentre[0]);
        vals[2] = Math.atan2(pos[0] - beamCentre[1], pos[1] - beamCentre[0] + 1);
        vals[3] = Math.atan2(pos[0] - beamCentre[1] + 1, pos[1] - beamCentre[0] + 1);

        Arrays.sort(vals);//  w  w w.  j  a va 2 s  .  co  m

        if (vals[0] < -Math.PI / 2 && vals[3] > Math.PI / 2) {
            //FIXME do best to handle discontinuity here - saves changing the integration routine
            //may not be as accurate - might need to make the integration aware.
            //currently just squeeze all the signal in one side

            if (Math.PI - vals[3] > Math.PI + vals[0]) {
                vals[3] = Math.PI;
                vals[0] = vals[2];
            } else {
                vals[0] = -Math.PI;
                vals[3] = vals[1];
            }
        }

        if (radians) {
            aMax.set(vals[3], pos);
            aMin.set(vals[0], pos);
        } else {
            aMax.set(Math.toDegrees(vals[3]), pos);
            aMin.set(Math.toDegrees(vals[0]), pos);
        }
    }

    return new Dataset[] { aMin, aMax };
}

From source file:com.inc.playground.playground.utils.NetworkUtilities.java

public static Double calculateDistance(double lon1, double lat1, double lon2, double lat2) {
    //calculate air distance
    double R = 6371; // Radius of the earth in km
    double dLat = deg2rad(lat2 - lat1); // deg2rad below
    double dLon = deg2rad(lon2 - lon1);
    double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
            + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    double d = R * c; // Distance in km
    return Math.round(d * 10d) / 10d; //round 1 point after digit
}

From source file:de.bund.bfr.jung.JungUtils.java

static <V, E> Shape getTransformedEdgeShape(RenderContext<V, E> rc, Layout<V, E> layout, E e) {
    Graph<V, E> graph = layout.getGraph();
    edu.uci.ics.jung.graph.util.Pair<V> endpoints = graph.getEndpoints(e);
    V v1 = endpoints.getFirst();//w w  w .j a v a 2  s .c  o m
    V v2 = endpoints.getSecond();

    if (!rc.getEdgeIncludePredicate().evaluate(Context.<Graph<V, E>, E>getInstance(graph, e))
            || !rc.getVertexIncludePredicate().evaluate(Context.<Graph<V, E>, V>getInstance(graph, v1))
            || !rc.getVertexIncludePredicate().evaluate(Context.<Graph<V, E>, V>getInstance(graph, v2))) {
        return null;
    }

    Point2D p1 = rc.getMultiLayerTransformer().transform(Layer.LAYOUT, layout.transform(v1));
    Point2D p2 = rc.getMultiLayerTransformer().transform(Layer.LAYOUT, layout.transform(v2));
    float x1 = (float) p1.getX();
    float y1 = (float) p1.getY();
    float x2 = (float) p2.getX();
    float y2 = (float) p2.getY();
    Shape edgeShape = rc.getEdgeShapeTransformer().transform(Context.getInstance(graph, e));
    AffineTransform edgeShapeTransform = AffineTransform.getTranslateInstance(x1, y1);

    if (v1.equals(v2)) {
        Rectangle2D bounds = rc.getVertexShapeTransformer().transform(v1).getBounds2D();

        edgeShapeTransform.scale(bounds.getWidth(), bounds.getHeight());
        edgeShapeTransform.translate(0, -edgeShape.getBounds2D().getWidth() / 2);
    } else {
        float dx = x2 - x1;
        float dy = y2 - y1;

        edgeShapeTransform.rotate(Math.atan2(dy, dx));
        edgeShapeTransform.scale(Math.sqrt(dx * dx + dy * dy), 1.0);
    }

    return edgeShapeTransform.createTransformedShape(edgeShape);
}

From source file:org.gearvrf.viewmanager.controls.gestures.TouchPadGesturesDetector.java

@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {

    Log.d(TouchPadGesturesDetector.DEBUG_TAG, "onFling()");

    if (mDetector == null) {
        return false;
    }/*from   w  w w . j ava2 s. co m*/

    double distance = Math.sqrt(Math.pow(e2.getX() - e1.getX(), 2) + Math.pow(e2.getY() - e1.getY(), 2));

    saveSwipeDistanceValue((float) distance);

    if (distance > SWIPE_MIN_DISTANCE) {
        try {

            double deltaY = e2.getY() - e1.getY();
            double deltaX = e2.getX() - e1.getX();

            double angle = Math.toDegrees(Math.atan2(deltaY, deltaX)) + 180 + 45;

            if (angle > 360)
                angle -= 360;

            if (angle < 90) {
                return gestureListener.onSwipe(e1, SwipeDirection.Forward, velocityX, velocityY);
            } else if (angle < 180) {
                return gestureListener.onSwipe(e1, SwipeDirection.Up, velocityX, velocityY);
            } else if (angle < 270) {
                return gestureListener.onSwipe(e1, SwipeDirection.Backward, velocityX, velocityY);
            } else {
                return gestureListener.onSwipe(e1, SwipeDirection.Down, velocityX, velocityY);
            }

        } catch (Exception e) {
            // Ignore
        }

    } else if (distance >= ONTAP_MIN_DISTANCE) {
        /*
         * The gesture listener filters out dirty taps that look like swipes
         * altogether. This reduces usability as it's hard to get a clean
         * tap on the tracker
         */
        gestureListener.onSingleTap(e1);
        return true;
    }

    return false;
}