# 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]
旋转矩阵: 相机相对于世界坐标系
[ 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 . 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]
    glm::mat4 CameraLookAt(glm::vec3 cameraPosition, glm::vec3 cameraTarget, glm::vec3 cameraUp)
{
auto cameraDirection = glm::normalize(cameraTarget - cameraPosition);

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[3][0] = -glm::dot(cameraRight, cameraPosition);
Result[3][1] = -glm::dot(cameraUP, 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 = 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()获得一个累计的时间

## 代码示例

#ifndef CAMERA_H
#define CAMERA_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 = 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


#ifndef _SHADER_H_
#include<GLFW/glfw3.h>
#include <iostream>
{
public:
private:
};



#include "Shader.h"

{
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";

}

{
}

{
}


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);

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);

{
std::cout << "Failed to initialize GLAD" << std::endl;
}

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;
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]);
}

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);

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;

1, GL_FALSE, glm::value_ptr(trans));

glBindVertexArray(VAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
}

glfwSwapBuffers(window);
glfwPollEvents();
}
}


• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 手机看

分享到微信朋友圈

x

扫一扫，手机阅读

• 打赏

打赏

NiMiKiss

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文

06-30 7187
08-27 207
08-21 1万+