/* * Moonlight|3D Copyright (C) 2006 The Moonlight|3D team * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library 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 Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Created on Oct 31, 2006 */ package ml.math; public class Ray2D { public Vector2D start, direction; public Ray2D() { start=new Vector2D(); direction=new Vector2D(); } public Ray2D(Vector2D start, Vector2D direction) { this.start=start.clone(); this.direction=direction.clone(); } public Vector2D getIntersectionPoint(Line2D line) { Vector2D otherDirection; double lambda, tau; otherDirection=line.end2.sub(line.end1); double denominator=(-direction.X1*otherDirection.X2+direction.X2*otherDirection.X1); if(denominator==0) { return null; // lines are parallel - no intersection possible } tau = (-direction.X1*start.X2+direction.X1*line.end1.X2+direction.X2*start.X1-direction.X2*line.end1.X1)/denominator; lambda = -(-start.X1*otherDirection.X2+line.end1.X1*otherDirection.X2+otherDirection.X1*start.X2-otherDirection.X1*line.end1.X2)/denominator; if(!(0 <= tau && tau <=1) || !(0 <= lambda)) { // calculated intersection point is outside of at least one line - so no intersection return null; } Vector2D intersectionPoint=start.add(direction.multiply(lambda)); return intersectionPoint; } public Vector2D getIntersectionPoint(Ray2D ray) { Vector2D otherDirection; double lambda, tau; otherDirection=ray.direction; double denominator=(-direction.X1*otherDirection.X2+direction.X2*otherDirection.X1); if(denominator==0) { return null; // lines are parallel - no intersection possible } tau = (-direction.X1*start.X2+direction.X1*ray.start.X2+direction.X2*start.X1-direction.X2*ray.start.X1)/denominator; lambda = -(-start.X1*otherDirection.X2+ray.start.X1*otherDirection.X2+otherDirection.X1*start.X2-otherDirection.X1*ray.start.X2)/denominator; if(!(0 <= tau) || !(0 <= lambda)) { // calculated intersection point is outside of at least one ray - so no intersection return null; } Vector2D intersectionPoint=start.add(direction.multiply(lambda)); return intersectionPoint; } }