1
0
Fork 0
Univerxel/src/control/Camera.cpp

95 lines
2.7 KiB
C++

#include "Camera.hpp"
#include <glm/gtc/matrix_transform.hpp>
#include "../render/window.hpp"
Camera::Camera(GLFWwindow *window, const InputMap& inputs): window(window), inputs(inputs) {
updateProjection();
}
Camera::~Camera() { }
void Camera::updateProjection() {
ProjectionMatrix = glm::perspective(FoV, RATIO, Near, Far);
}
void Camera::update(bool captureMouse, bool captureKeys) {
// glfwGetTime is called only once, the first time this function is called
static double lastTime = glfwGetTime();
// Compute time difference between current and last frame
double currentTime = glfwGetTime();
float deltaTime = float(currentTime - lastTime);
// Get mouse position
if(captureMouse) {
int viewportX, viewportY;
glfwGetWindowSize(window, &viewportX, &viewportY);
if(capturingMouse) {
double xPos, yPos;
glfwGetCursorPos(window, &xPos, &yPos);
// Compute new orientation
HorizontalAngle += Sensibility * 0.0001f * float(viewportX / 2 - xPos);
VerticalAngle += Sensibility * 0.0001f * float(viewportY / 2 - yPos);
} else {
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
capturingMouse = true;
}
// Reset mouse position for next frame
glfwSetCursorPos(window, viewportX / 2, viewportY / 2);
} else if (capturingMouse) {
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
capturingMouse = false;
}
// Direction : Spherical coordinates to Cartesian coordinates conversion
glm::vec3 direction = getDirection();
// Right vector
glm::vec3 right = glm::vec3(
sin(HorizontalAngle - 3.14f / 2.0f),
0,
cos(HorizontalAngle - 3.14f / 2.0f));
// Up vector
glm::vec3 up = glm::cross(right, direction);
if(captureKeys) {
// Move forward
if (inputs.isDown(Input::Forward)) {
Position += direction * deltaTime * Speed;
}
// Move backward
if (inputs.isDown(Input::Backward)) {
Position -= direction * deltaTime * Speed;
}
// Strafe right
if (inputs.isDown(Input::Right)) {
Position += right * deltaTime * Speed;
}
// Strafe left
if (inputs.isDown(Input::Left)) {
Position -= right * deltaTime * Speed;
}
// Move up
if (inputs.isDown(Input::Up)) {
Position += up * deltaTime * Speed;
}
// Move down
if (inputs.isDown(Input::Down)) {
Position -= up * deltaTime * Speed;
}
}
// MAYBE: only if moved
// MAYBE: save frustum
// Camera matrix
ViewMatrix = glm::lookAt(
Position, // Camera is here
Position + direction, // and looks here : at the same position, plus "direction"
up // Head is up (set to 0,-1,0 to look upside-down)
);
// For the next frame, the "last time" will be "now"
lastTime = currentTime;
}