Java examples for 2D Graphics:Curve
Solves the quadratic curve giving parameterized t values at points where the curve has an y value matching the given value.
/*/* ww w .j a v a2 s. c om*/ * Copyright (C) 2005 Jordan Kiang * jordan-at-kiang.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ //package com.java2s; import java.awt.geom.QuadCurve2D; public class Main { /** * Solves the quadratic curve giving parameterized t values at * points where the curve has an y value matching the given value. * Writes as many solutions into the given array as will fit. * * @param curve the curve * @param y the value of y to solve for * @param solutions an array to write solutions into * @return the number of solutions */ static public int solveQuadCurveForY(QuadCurve2D curve, double y, double[] solutions) { double a = getQuadAy(curve); double b = getQuadBy(curve); double c = curve.getY1() - y; double[] eqn = new double[] { c, b, a }; int roots = QuadCurve2D.solveQuadratic(eqn, solutions); return copyValidSolutions(roots, eqn, solutions); } static private double getQuadAy(QuadCurve2D curve) { return curve.getY1() - (2.0 * curve.getCtrlY()) + curve.getY2(); } static private double getQuadBy(QuadCurve2D curve) { return 2.0 * (-curve.getY1() + curve.getCtrlY()); } static private int copyValidSolutions(int rootCount, double[] roots, double[] solutions) { int solutionCount = 0; for (int i = 0; i < rootCount; i++) { if (roots[i] >= 0 && roots[i] <= 1.0) { // The solve functions can give multiple roots. // We only want unique roots, so we check the next solution against the previous roots. boolean unique = true; for (int j = 0; j < solutionCount; j++) { if (roots[i] == roots[j]) { unique = false; break; } } if (unique) { // If the given solution array is too small, then just write as many as will fit. if (solutionCount < solutions.length) { solutions[solutionCount] = roots[i]; } solutionCount++; } } } return solutionCount; } }