Checks whether there is intersection of the line and the quad curve - Java java.lang

Java examples for java.lang:Math Curve

Description

Checks whether there is intersection of the line and the quad curve

Demo Code



public class Main{
    /**//  ww w. j av  a 2  s .  co m
     * Checks whether there is intersection of the line (x1, y1) - (x2, y2) and the quad curve
     * (qx1, qy1) - (qx2, qy2) - (qx3, qy3). The parameters of the intersection area saved to
     * {@code params}. Therefore {@code params} must be of length at least 4.
     *
     * @return the number of roots that lie in the defined interval.
     */
    public static int intersectLineAndQuad(float x1, float y1, float x2,
            float y2, float qx1, float qy1, float qx2, float qy2,
            float qx3, float qy3, float[] params) {
        float[] eqn = new float[3];
        float[] t = new float[2];
        float[] s = new float[2];
        float dy = y2 - y1;
        float dx = x2 - x1;
        int quantity = 0;
        int count = 0;

        eqn[0] = dy * (qx1 - x1) - dx * (qy1 - y1);
        eqn[1] = 2 * dy * (qx2 - qx1) - 2 * dx * (qy2 - qy1);
        eqn[2] = dy * (qx1 - 2 * qx2 + qx3) - dx * (qy1 - 2 * qy2 + qy3);

        if ((count = Crossing.solveQuad(eqn, t)) == 0) {
            return 0;
        }

        for (int i = 0; i < count; i++) {
            if (dx != 0) {
                s[i] = (quad(t[i], qx1, qx2, qx3) - x1) / dx;
            } else if (dy != 0) {
                s[i] = (quad(t[i], qy1, qy2, qy3) - y1) / dy;
            } else {
                s[i] = 0f;
            }
            if (t[i] >= 0 && t[i] <= 1 && s[i] >= 0 && s[i] <= 1) {
                params[2 * quantity] = t[i];
                params[2 * quantity + 1] = s[i];
                ++quantity;
            }
        }

        return quantity;
    }
    public static float quad(float t, float x1, float x2, float x3) {
        return x1 * (1f - t) * (1f - t) + 2f * x2 * t * (1f - t) + x3 * t
                * t;
    }
}

Related Tutorials