#include "camera.h"

Camera::Camera(bool persp)
{
    this->persp = persp;
    setHome(new QQuaternion(), new QVector3D(0.0,0.0,-4.0));
}

void Camera::home()
{
    this->rotation = homeRotation;
    this->translation = homeTranslation;

}

void Camera::setHome(QQuaternion *rotation, QVector3D *translation)
{
    //qDebug()<<*rotation<<" trans:"<<*translation;
    this->homeRotation = rotation;
    this->homeTranslation = translation;
    home();
}

void Camera::rotate(QQuaternion newPos )
{
    if(persp){
        QQuaternion newRot = newPos * *rotation;
        rotation = new QQuaternion(newRot.toVector4D());
    }
}

void Camera::move(QVector3D newPos)
{

    QVector3D newTrans = newPos + *translation;
    translation = new QVector3D(newTrans);
}


void Camera::setupCamera(GLdouble aspect )
{
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    if(persp){
        perspective(45.0,aspect,0.01,100.0);
    } else {
        int size = 4;
        glOrtho(-size*aspect,size*aspect,-size,size,0.01,100.0);
    }

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    //Camera Tranforations
    QMatrix4x4 mat = QMatrix4x4();
    mat.translate(*translation);
    glMultMatrixf(mat.data());

    mat = QMatrix4x4();
    mat.rotate(*rotation);
    glMultMatrixf(mat.data());
}


void Camera::perspective(GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar)
{
    GLdouble xmin, xmax, ymin, ymax;

    ymax = zNear * tan( fovy * M_PI / 360.0 );
    ymin = -ymax;
    xmin = ymin * aspect;
    xmax = ymax * aspect;

    glFrustum( xmin, xmax, ymin, ymax, zNear, zFar );
}
