SparrowRenderer/camera.cpp
2015-06-22 01:57:02 +02:00

113 lines
2.3 KiB
C++

#include "camera.h"
#include <glm/ext.hpp>
#include <cmath>
#define _USE_MATH_DEFINES
Camera::Camera(int width, int height, float fov_y, float near, float far, glm::vec3 pos) :
m_projectionHasChanged(true),
m_viewHasChanged(true),
m_fov(fov_y),
m_width(width),
m_height(height),
m_near(near),
m_far(far),
m_position(pos),
m_rotation(glm::vec2())
{
computeProjectionMatrix();
computeViewMatrix();
}
void Camera::computeProjectionMatrix()
{
m_projectionMatrix = glm::perspectiveFov(m_fov, (float)m_width, (float)m_height, m_near, m_far);
m_projectionHasChanged = false;
}
void Camera::computeViewMatrix()
{
m_viewMatrix = glm::rotate(glm::mat4(), m_rotation.y, glm::vec3(0, 1, 0));
m_viewMatrix = glm::rotate(m_viewMatrix, m_rotation.x, glm::vec3(1, 0, 0));
m_viewMatrix = glm::translate(m_viewMatrix, -m_position);
m_viewHasChanged = false;
}
void Camera::translate(glm::vec3 vector)
{
m_viewHasChanged = true;
m_position += vector;
}
void Camera::rotate(glm::vec2 rad_vector)
{
m_viewHasChanged = true;
m_rotation += rad_vector;
if(m_rotation.y > M_PI/2)
m_rotation.y = M_PI/2;
if(m_rotation.y < -M_PI/2)
m_rotation.y = -M_PI/2;
}
void Camera::zoom(float new_fov_y)
{
m_projectionHasChanged = true;
m_fov = new_fov_y;
}
void Camera::resize(int width, int height)
{
m_projectionHasChanged = true;
m_width = width;
m_height = height;
}
void Camera::setNear(float near)
{
m_projectionHasChanged = true;
m_near = near;
}
void Camera::setFar(float far)
{
m_projectionHasChanged = true;
m_far = far;
}
void Camera::moveTo(glm::vec3 position)
{
m_viewHasChanged = true;
m_position = position;
}
void Camera::lookAt(glm::vec3 position)
{
m_viewHasChanged = true;
glm::vec3 delta = position - m_position;
glm::normalize(delta);
m_rotation.y = std::asin(delta.y);
m_rotation.x = std::acos(delta.z/std::acos(delta.y));
if(delta.z < 0) m_rotation.x += M_PI;
}
void Camera::lookAt(glm::vec2 rotation)
{
m_viewHasChanged = true;
m_rotation = rotation;
}
glm::mat4 Camera::getProjectionMatrix()
{
if(m_projectionHasChanged)
computeProjectionMatrix();
return m_projectionMatrix;
}
glm::mat4 Camera::getViewMatrix()
{
if(m_viewHasChanged)
computeViewMatrix();
return m_viewMatrix;
}