Check if two points are on the same side of a given line. - Java java.lang

Java examples for java.lang:Math Geometry Line

Description

Check if two points are on the same side of a given line.

Demo Code


//package com.java2s;

public class Main {
    /**//from   w  w w.j  ava 2  s .c o  m
     * Check if two points are on the same side of a given line. Algorithm from
     * Sedgewick page 350.
     *
     * @param x0, y0, x1, y1 The line.
     * @param px0, py0 First point.
     * @param px1, py1 Second point.
     * @return <0 if points on opposite sides. =0 if one of the points is
     * exactly on the line >0 if points on same side.
     */
    private static int sameSide(double x0, double y0, double x1, double y1,
            double px0, double py0, double px1, double py1) {
        int sameSide = 0;

        double dx = x1 - x0;
        double dy = y1 - y0;
        double dx1 = px0 - x0;
        double dy1 = py0 - y0;
        double dx2 = px1 - x1;
        double dy2 = py1 - y1;

        // Cross product of the vector from the endpoint of the line to the point
        double c1 = dx * dy1 - dy * dx1;
        double c2 = dx * dy2 - dy * dx2;

        if (c1 != 0 && c2 != 0) {
            sameSide = c1 < 0 != c2 < 0 ? -1 : 1;
        } else if (dx == 0 && dx1 == 0 && dx2 == 0) {
            sameSide = !isBetween(y0, y1, py0) && !isBetween(y0, y1, py1) ? 1
                    : 0;
        } else if (dy == 0 && dy1 == 0 && dy2 == 0) {
            sameSide = !isBetween(x0, x1, px0) && !isBetween(x0, x1, px1) ? 1
                    : 0;
        }

        return sameSide;
    }

    /**
     * Check if two points are on the same side of a given line. Integer domain.
     *
     * @param x0, y0, x1, y1 The line.
     * @param px0, py0 First point.
     * @param px1, py1 Second point.
     * @return <0 if points on opposite sides. =0 if one of the points is
     * exactly on the line >0 if points on same side.
     */
    private static int sameSide(int x0, int y0, int x1, int y1, int px0,
            int py0, int px1, int py1) {
        return sameSide((double) x0, (double) y0, (double) x1, (double) y1,
                (double) px0, (double) py0, (double) px1, (double) py1);
    }

    /**
     * Return true if c is between a and b.
     */
    private static boolean isBetween(int a, int b, int c) {
        return b > a ? c >= a && c <= b : c >= b && c <= a;
    }

    /**
     * Return true if c is between a and b.
     */
    private static boolean isBetween(double a, double b, double c) {
        return b > a ? c >= a && c <= b : c >= b && c <= a;
    }
}

Related Tutorials