#ifndef MAP_HELPER_H
#define MAP_HELPER_H

#include <Indoor/geo/Point3.h>
#include <QOpenGLFunctions>

class GLHelper {

public:

	static QVector3D getNormal(const QVector3D& v1, const QVector3D& v2, const QVector3D& v3) {

		// get two of the triangle's edges
		const QVector4D v21 = v2-v1;
		const QVector4D v31 = v3-v1;

		const QVector3D n = QVector3D::crossProduct(v21.toVector3D(), v31.toVector3D()).normalized();

		return isCCW(v1, v2, v3) ? (n) : (-n);

	}

	/**
	 * is the triangle given by p1,p2,p3 CCW?
	 * NOTE: uses OUR coordinate system (x,y,z) where z is the floor-height
	 */
	static bool isCCW(const Point3 p1, const Point3 p2, const Point3 p3) {
		const QVector3D v1(p1.x, p1.z, p1.y);
		const QVector3D v2(p2.x, p2.z, p2.y);
		const QVector3D v3(p3.x, p3.z, p3.y);
		return isCCW(v1, v2, v3);
	}

	/**
	 * is the triangle given by p1,p2,p3 CCW?
	 * NOTE: uses OpenGL coordinate system (x,z,y) (our z is the floor-height)
	 */
	static bool isCCW(const QVector3D& p1, const QVector3D& p2, const QVector3D& p3) {

		// camera position
		QMatrix4x4 proj; proj.lookAt(QVector3D(-1,20,-1), QVector3D(0,0,0), QVector3D(0,1,0));

		// to camera space
		QVector4D v1(p1.x(), p1.y(), p1.z(), 1);
		QVector4D v2(p2.x(), p2.y(), p2.z(), 1);
		QVector4D v3(p3.x(), p3.y(), p3.z(), 1);
		v1 = proj * v1;
		v2 = proj * v2;
		v3 = proj * v3;

		// get two of the triangle's edges
		const QVector4D v21 = v2-v1;
		const QVector4D v31 = v3-v1;

		// check the angle between both
		const float angle = QVector2D::dotProduct(v21.toVector2D(), v31.toVector2D());
		return angle > 0;

//		const QVector3D n = QVector3D::crossProduct(v21.toVector3D(), v31.toVector3D());
//		return n.z() > 0;

	}


};

#endif // MAP_HELPER_H
