Camera类
Notes
- 欧拉角相机 物体世界坐标->观察空间坐标
相机的参数包括:相机位置Position,目标位置指向相机Direction,以及Up方向
相机变换的目的是得到物体与相机(相机为原点)的相对位置,通过将相机坐标系(Right,UP,Front)平移和旋转至世界坐标系(X,Y,Z轴)重合,平移矩阵和旋转矩阵的组合就是所求的相机变换。
平移矩阵:
[ 1 0 0 -Position . x 0 1 0 -Position . y 0 0 1 - P o s i t i o n . z 0 0 0 1 ] \left[ \begin{matrix} 1 & 0 & 0 & \text{-Position}.x \\ 0 & 1 & 0 & \text{-Position}.y \\ 0 & 0 & 1 & \text-{Position}.z \\ 0 & 0 & 0 & 1 \\ \end{matrix} \right] ⎣⎢⎢⎡100001000010-Position.x-Position.y-Position.z1⎦⎥⎥⎤
旋转矩阵: 相机相对于世界坐标系
[ cameraRight . x cameraUP . x -cameraDirection . x 0 cameraRight . y cameraUP . y -cameraDirection . y 0 cameraRight . z cameraUP . z -cameraDirection . z 0 0 0 0 1 ] \left[ \begin{matrix} \text{cameraRight}.x & \text{cameraUP}.x & \text{-cameraDirection}.x & 0 \\ \text{cameraRight}.y & \text{cameraUP}.y & \text{-cameraDirection}.y & 0 \\ \text{cameraRight}.z & \text{cameraUP}.z & \text{-cameraDirection}.z & 0 \\ 0 & 0 & 0 & 1 \\ \end{matrix} \right] ⎣⎢⎢⎡cameraRight.xcameraRight.ycameraRight.z0cameraUP.xcameraUP.ycameraUP.z0-cameraDirection.x-cameraDirection.y-cameraDirection.z00001⎦⎥⎥⎤
因此变换矩阵为
旋转矩阵 − ^{-} − * 平移矩阵
[ cameraRight . x cameraRight. y cameraRight . z -glm::dot(cameraRight,cameraPosition) cameraUP . x cameraUP . y cameraUP . z -glm::dot(cameraUp,cameraPosition) -cameraDirection . x -cameraDirection . y -cameraDirection . z glm::dot(cameraDirection,cameraPosition) 0 0 0 1 ] \left[ \begin{matrix} \text{cameraRight}.x & \text{cameraRight}\text{.}y & \text{cameraRight}.z & \text{-glm::dot(cameraRight,cameraPosition)} \\ \text{cameraUP}.x & \text{cameraUP}.y & \text{cameraUP}.z & \text{-glm::dot(cameraUp,cameraPosition)} \\ \text{-cameraDirection}.x & \text{-cameraDirection}.y & \text{-cameraDirection}.z & \text{glm::dot(cameraDirection,cameraPosition)} \\ 0 & 0 & 0 & 1 \\ \end{matrix} \right] ⎣⎢⎢⎡cameraRight.xcameraUP.x-cameraDirection.x0cameraRight.ycameraUP.y-cameraDirection.y0cameraRight.zcameraUP.z-cameraDirection.z0-glm::dot(cameraRight,cameraPosition)-glm::dot(cameraUp,cameraPosition)glm::dot(cameraDirection,cameraPosition)1⎦⎥⎥⎤
glm::mat4 CameraLookAt(glm::vec3 cameraPosition, glm::vec3 cameraTarget, glm::vec3 cameraUp)
{
auto cameraDirection = glm::normalize(cameraTarget - cameraPosition);
auto cameraRight = glm::normalize(glm::cross(cameraDirection, cameraUp));
auto cameraUP = glm::cross(cameraRight, cameraDirection);
glm::mat4 Result(1.0f);
Result[0][0] = cameraRight.x;
Result[1][0] = cameraRight.y;
Result[2][0] = cameraRight.z;
Result[0][1] = cameraUP.x;
Result[1][1] = cameraUP.y;
Result[2][1] = cameraUP.z;
Result[0][2] = -cameraDirection.x;
Result[1][2] = -cameraDirection.y;
Result[2][2] = -cameraDirection.z;
Result[3][0] = -glm::dot(cameraRight, cameraPosition);
Result[3][1] = -glm::dot(cameraUP, cameraPosition);
Result[3][2] = glm::dot(cameraDirection, cameraPosition);
return Result;
}
- 变换相机方向Direction:俯仰角(pitch描述往上或往下看的角度)&偏航角(Yaw描述往左或往右看的角)
xoffset *= MouseSensitivity;
yoffset *= MouseSensitivity;
Yaw += xoffset;
Pitch += yoffset;
if (constrainPitch)
{
if (Pitch > 89.0f)
Pitch = 89.0f;
if (Pitch < -89.0f)
Pitch = -89.0f;
}
glm::vec3 front;
front.x = cos(glm::radians(Yaw)) * cos(glm::radians(Pitch));
front.y = sin(glm::radians(Pitch));
front.z = sin(glm::radians(Yaw)) * cos(glm::radians(Pitch));
Front = glm::normalize(front);
Right = glm::normalize(glm::cross(Front, WorldUp));
Up = glm::normalize(glm::cross(Right, Front));
- 变换相机位置Position,
float velocity = MovementSpeed * deltaTime;
if (direction == FORWARD)
Position += Front * velocity;
if (direction == BACKWARD)
Position -= Front * velocity;
if (direction == LEFT)
Position -= Right * velocity;
if (direction == RIGHT)
Position += Right * velocity;
- 裁剪矩阵 观察空间坐标->裁剪空间坐标
Zoom -= (float)yoffset;
if (Zoom < 1.0f)
Zoom = 1.0f;
if (Zoom > 45.0f)
Zoom = 45.0f;
- 注册键盘回调函数,使用鼠标操作相机方向和键盘操作相机位置
void processinput_callback(GLFWwindow* window)
{
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
{
camera.ProcessKeyboard(FORWARD, deltaTime);
}
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
{
camera.ProcessKeyboard(LEFT, deltaTime);
}
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
{
camera.ProcessKeyboard(BACKWARD, deltaTime);
}
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
{
camera.ProcessKeyboard(RIGHT, deltaTime);
}
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
{
glfwSetWindowShouldClose(window, true);
}
}
void mouse_callback(GLFWwindow* window, double xpose,double ypose)
{
if (firstMouse)
{
lastX = xpose;
lastY = ypose;
firstMouse = false;
}
auto xoffset = xpose - lastX;
lastX = xpose;
auto yoffset = lastY - ypose;
lastY = ypose;
camera.ProcessMouseMovement(xoffset, yoffset);
}
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
camera.ProcessMouseScroll(yoffset);
}
- 为了计算灵敏度和让立方体旋转起来,使用glfwGetTime()获得一个累计的时间
代码示例
https://gitee.com/NiMiKiss/opengl-notes.git
camera.h
#ifndef CAMERA_H
#define CAMERA_H
#include <glad/glad.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
// Defines several possible options for camera movement. Used as abstraction to stay away from window-system specific input methods
enum Camera_Movement {
FORWARD,
BACKWARD,
LEFT,
RIGHT
};
// Default camera values
const float YAW = -90.0f;
const float PITCH = 0.0f;
const float SPEED = 2.5f;
const float SENSITIVITY = 0.1f;
const float ZOOM = 45.0f;
// An abstract camera class that processes input and calculates the corresponding Euler Angles, Vectors and Matrices for use in OpenGL
class Camera
{
public:
// camera Attributes
glm::vec3 Position;
glm::vec3 Front;
glm::vec3 Up;
glm::vec3 Right;
glm::vec3 WorldUp;
// euler Angles
float Yaw;
float Pitch;
// camera options
float MovementSpeed;
float MouseSensitivity;
float Zoom;
// constructor with vectors
Camera(glm::vec3 position = glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f), float yaw = YAW, float pitch = PITCH) : Front(glm::vec3(0.0f, 0.0f, -1.0f)), MovementSpeed(SPEED), MouseSensitivity(SENSITIVITY), Zoom(ZOOM)
{
Position = position;
WorldUp = up;
Yaw = yaw;
Pitch = pitch;
updateCameraVectors();
}
// constructor with scalar values
Camera(float posX, float posY, float posZ, float upX, float upY, float upZ, float yaw, float pitch) : Front(glm::vec3(0.0f, 0.0f, -1.0f)), MovementSpeed(SPEED), MouseSensitivity(SENSITIVITY), Zoom(ZOOM)
{
Position = glm::vec3(posX, posY, posZ);
WorldUp = glm::vec3(upX, upY, upZ);
Yaw = yaw;
Pitch = pitch;
updateCameraVectors();
}
// returns the view matrix calculated using Euler Angles and the LookAt Matrix
glm::mat4 GetViewMatrix()
{
return glm::lookAt(Position, Position + Front, Up);
}
// processes input received from any keyboard-like input system. Accepts input parameter in the form of camera defined ENUM (to abstract it from windowing systems)
void ProcessKeyboard(Camera_Movement direction, float deltaTime)
{
float velocity = MovementSpeed * deltaTime;
if (direction == FORWARD)
Position += Front * velocity;
if (direction == BACKWARD)
Position -= Front * velocity;
if (direction == LEFT)
Position -= Right * velocity;
if (direction == RIGHT)
Position += Right * velocity;
}
// processes input received from a mouse input system. Expects the offset value in both the x and y direction.
void ProcessMouseMovement(float xoffset, float yoffset, GLboolean constrainPitch = true)
{
xoffset *= MouseSensitivity;
yoffset *= MouseSensitivity;
Yaw += xoffset;
Pitch += yoffset;
// make sure that when pitch is out of bounds, screen doesn't get flipped
if (constrainPitch)
{
if (Pitch > 89.0f)
Pitch = 89.0f;
if (Pitch < -89.0f)
Pitch = -89.0f;
}
// update Front, Right and Up Vectors using the updated Euler angles
updateCameraVectors();
}
// processes input received from a mouse scroll-wheel event. Only requires input on the vertical wheel-axis
void ProcessMouseScroll(float yoffset)
{
Zoom -= (float)yoffset;
if (Zoom < 1.0f)
Zoom = 1.0f;
if (Zoom > 45.0f)
Zoom = 45.0f;
}
private:
// calculates the front vector from the Camera's (updated) Euler Angles
void updateCameraVectors()
{
// calculate the new Front vector
glm::vec3 front;
front.x = cos(glm::radians(Yaw)) * cos(glm::radians(Pitch));
front.y = sin(glm::radians(Pitch));
front.z = sin(glm::radians(Yaw)) * cos(glm::radians(Pitch));
Front = glm::normalize(front);
// also re-calculate the Right and Up vector
Right = glm::normalize(glm::cross(Front, WorldUp)); // normalize the vectors, because their length gets closer to 0 the more you look up or down which results in slower movement.
Up = glm::normalize(glm::cross(Right, Front));
}
};
#endif
shader.h
#ifndef _SHADER_H_
#define _SHADER_H_
#include<glad/glad.h>
#include<GLFW/glfw3.h>
#include <iostream>
class Shader
{
public:
Shader();
~Shader();
void UseShader() const;
void InitShader();
int GetShaderProgramID() const;
private:
int m_iShaderProgramID;
};
#endif // !_SHADER_H_
shader.cpp
#include "Shader.h"
Shader::Shader(){}
Shader::~Shader(){}
void Shader::InitShader()
{
const char* vertexShaderSource = "#version 400 core\n"
"layout (location = 0) in vec3 aPos;\n"
"layout (location = 1) in vec2 aTexCoord;\n"
"out vec2 TexCoord;\n"
"uniform mat4 transform;\n"
"void main()\n"
"{\n"
" gl_Position =transform * vec4(aPos.x, aPos.y, aPos.z, 1.0f);\n"
" TexCoord = aTexCoord;\n"
"}\0";
const char* fragmentShaderSource = "#version 400 core\n"
"out vec4 FragColor;\n"
"in vec2 TexCoord;\n"
"uniform sampler2D ourTexture1;\n"
"uniform sampler2D ourTexture2;\n"
"void main()\n"
"{\n"
" FragColor = mix(texture(ourTexture1,TexCoord),texture(ourTexture2,TexCoord),0.2);\n"
"}\n\0";
int vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
glCompileShader(vertexShader);
int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
glCompileShader(fragmentShader);
m_iShaderProgramID = glCreateProgram();
glAttachShader(m_iShaderProgramID, vertexShader);
glAttachShader(m_iShaderProgramID, fragmentShader);
glLinkProgram(m_iShaderProgramID);
}
void Shader::UseShader() const
{
glUseProgram(m_iShaderProgramID);
}
int Shader::GetShaderProgramID()const
{
return m_iShaderProgramID;
}
OpenGL.cpp
#include "Shader.h"
#include "stb_image.h"
#include <camera.h>
#pragma region 顶点数据
float vertices[] = {
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 1.0f, 1.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 1.0f, 1.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f
};
glm::vec3 cubePositions[] = {
glm::vec3(0.0f, 0.0f, 0.0f),
glm::vec3(2.0f, 5.0f, -15.0f),
glm::vec3(-1.5f, -2.2f, -2.5f),
glm::vec3(-3.8f, -2.0f, -12.3f),
glm::vec3(2.4f, -0.4f, -3.5f),
glm::vec3(-1.7f, 3.0f, -7.5f),
glm::vec3(1.3f, -2.0f, -2.5f),
glm::vec3(1.5f, 2.0f, -2.5f),
glm::vec3(1.5f, 0.2f, -1.5f),
glm::vec3(-1.3f, 1.0f, -1.5f)
};
#pragma endregion
GLFWwindow* Init();
void SetVAO();
void SetTexture();
void processinput_callback(GLFWwindow* window);
void mouse_callback(GLFWwindow* window, double xpose, double ypose);
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset);
Shader shader;
Camera camera(glm::vec3(0.0f,0.0f,3.0f));
unsigned int VAO;
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;
bool firstMouse = true;
static float lastX = 0.0f, lastY = 0.0f;
float deltaTime = 0.0f;
float lastFrame = 0.0f;
GLFWwindow* Init()
{
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 4);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
auto window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
}
glfwMakeContextCurrent(window);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
}
shader.InitShader();
return window;
}
void SetVAO()
{
unsigned int VBO, EBO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
}
void SetTexture()
{
int width(0), height(0), nrChannels(0);
unsigned char* data;
stbi_set_flip_vertically_on_load(true);
unsigned int texture[2];
glGenTextures(2, texture);
glBindTexture(GL_TEXTURE_2D, texture[0]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
data = stbi_load("../OpenGL/resources/textures/container.jpg", &width, &height, &nrChannels, 0);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
stbi_image_free(data);
glBindTexture(GL_TEXTURE_2D, texture[1]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
data = stbi_load("../OpenGL/resources/textures/awesomeface.png", &width, &height, &nrChannels, 0);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
stbi_image_free(data);
glActiveTexture(GL_TEXTURE0); //先激活再绑定
glBindTexture(GL_TEXTURE_2D, texture[0]);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, texture[1]);
shader.UseShader();
glUniform1i(glGetUniformLocation(shader.GetShaderProgramID(), "ourTexture1"), 0);
glUniform1i(glGetUniformLocation(shader.GetShaderProgramID(), "ourTexture2"), 1);
}
void processinput_callback(GLFWwindow* window)
{
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
{
camera.ProcessKeyboard(FORWARD, deltaTime);
}
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
{
camera.ProcessKeyboard(LEFT, deltaTime);
}
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
{
camera.ProcessKeyboard(BACKWARD, deltaTime);
}
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
{
camera.ProcessKeyboard(RIGHT, deltaTime);
}
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
{
glfwSetWindowShouldClose(window, true);
}
}
void mouse_callback(GLFWwindow* window, double xpose,double ypose)
{
if (firstMouse)
{
lastX = xpose;
lastY = ypose;
firstMouse = false;
}
auto xoffset = xpose - lastX;
lastX = xpose;
auto yoffset = lastY - ypose;
lastY = ypose;
camera.ProcessMouseMovement(xoffset, yoffset);
}
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
camera.ProcessMouseScroll(yoffset);
}
int main()
{
auto window = Init();
SetVAO();
SetTexture();
glfwSetCursorPosCallback(window, mouse_callback);
glfwSetScrollCallback(window, scroll_callback);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
glEnable(GL_DEPTH_TEST);
while (!glfwWindowShouldClose(window))
{
float currentFrame = glfwGetTime();
deltaTime = currentFrame - lastFrame;
lastFrame = currentFrame;
processinput_callback(window);
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
float radius = 10.0f;
for (size_t i = 0; i < 10; ++i)
{
glm::mat4 trans(glm::mat4(1.0f)), model(glm::mat4(1.0f)), view(glm::mat4(1.0f)), projection(glm::mat4(1.0f));
model = glm::translate(model, glm::vec3(cubePositions[i]));
model = glm::rotate(model, currentFrame, glm::vec3(1.0f, 2.0f, 0.0f));
view = camera.GetViewMatrix();
projection = glm::perspective(glm::radians(camera.Zoom), 800.0f / 600.0f, 0.1f, 100.0f);
trans = projection * view * model;
glUniformMatrix4fv(glGetUniformLocation(shader.GetShaderProgramID(), "transform"),
1, GL_FALSE, glm::value_ptr(trans));
glBindVertexArray(VAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
}
glfwSwapBuffers(window);
glfwPollEvents();
}
}
输出效果
鼠标键盘可操作的10个旋转立方体