/*-
 *  Copyright 2020 Beuth Hochschule für Technik Berlin, Hochschule für Technik Stuttgart
 * 
 *  This file is part of CityDoctor2.
 *
 *  CityDoctor2 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 3 of the License, or
 *  (at your option) any later version.
 *
 *  CityDoctor2 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 CityDoctor2.  If not, see <https://www.gnu.org/licenses/>.
 */
package de.hft.stuttgart.citydoctor2.math;

import de.hft.stuttgart.citydoctor2.datastructure.Polygon;
import de.hft.stuttgart.citydoctor2.tesselation.TesselatedPolygon;
import de.hft.stuttgart.citydoctor2.tesselation.JoglTesselator;

/**
 * A ray constructed by a point and a direction. A ray has a starting point and
 * a direction, it does not go into the opposite direction unlike a line.
 * 
 * @author Matthias Betz
 *
 */
public class Ray {

	public static final double EPSILON = 0.0001;

	private Vector3d origin;
	private Vector3d direction;

	public Ray(Vector3d origin, Vector3d direction) {
		this.origin = origin;
		this.direction = direction.normalize();
	}

	public Vector3d getPointOnRay(double distanceFromOrigin) {
		return origin.plus(direction.mult(distanceFromOrigin));
	}

	public Vector3d intersectsPolygon(TesselatedPolygon p) {
		for (Triangle3d t : p.getTriangles()) {
			Vector3d intersection = intersectTriangle(t);
			if (intersection != null) {
				return intersection;
			}
		}
		return null;
	}

	public Vector3d intersectTriangle(Triangle3d t) {
		return intersectTriangle(t.getP1(), t.getP2(), t.getP3());
	}

	public Vector3d intersectTriangle(Vector3d v0, Vector3d v1, Vector3d v2) {
		Vector3d edge1 = v1.minus(v0);
		Vector3d edge2 = v2.minus(v0);

		Vector3d p = direction.cross(edge2);
		double det = edge1.dot(p);

		if (det > -EPSILON && det < EPSILON) {
			return null;
		}

		double invDet = 1 / det;

		Vector3d s = origin.minus(v0);

		double u = invDet * s.dot(p);
		if (u < 0.0 || u > 1.0) {
			return null;
		}

		Vector3d q = s.cross(edge1);

		double v = invDet * direction.dot(q);

		if (v < 0.0 || u + v > 1.0) {
			return null;
		}

		double t = edge2.dot(q) * invDet;
		if (t > EPSILON) {
			// ray intersection
			return getPointOnRay(t);
		} else {
			// line intersection, but not ray intersection
			return null;
		}
	}

	public Vector3d intersectsPolygon(Polygon p) {
		return intersectsPolygon(JoglTesselator.tesselatePolygon(p));
	}

}
