OpenGL 是一個強大的跨平臺圖形 API,用于渲染 2D 和 3D 圖形。以下是 OpenGL 3D 編程的入門基礎。
一. 環境設置
安裝必要的庫
-
GLFW: 用于創建窗口和處理輸入
-
GLEW 或 GLAD: 用于加載 OpenGL 函數
-
GLM: 數學庫,用于 3D 變換
// 基本 OpenGL 程序結構示例
#include <GL/glew.h>
#include <GLFW/glfw3.h>int main() {// 初始化 GLFWif (!glfwInit()) return -1;// 創建窗口GLFWwindow* window = glfwCreateWindow(800, 600, "OpenGL 3D", NULL, NULL);if (!window) {glfwTerminate();return -1;}// 設置當前上下文glfwMakeContextCurrent(window);// 初始化 GLEWif (glewInit() != GLEW_OK) return -1;// 主循環while (!glfwWindowShouldClose(window)) {// 清屏glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);// 渲染代碼// 交換緩沖區glfwSwapBuffers(window);// 處理事件glfwPollEvents();}glfwTerminate();return 0;
}
二. 3D 基礎概念
坐標系
-
OpenGL 使用右手坐標系
-
X軸向右,Y軸向上,Z軸向外(朝向觀察者)
變換矩陣
-
模型矩陣(Model): 物體從局部空間到世界空間的變換
-
視圖矩陣(View): 世界空間到相機空間的變換
-
投影矩陣(Projection): 從相機空間到裁剪空間的變換
// 使用 GLM 創建變換矩陣示例
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>glm::mat4 model = glm::mat4(1.0f); // 單位矩陣
model = glm::rotate(model, glm::radians(45.0f), glm::vec3(0.0f, 1.0f, 0.0f)); // 繞Y軸旋轉45度
model = glm::translate(model, glm::vec3(1.0f, 0.0f, 0.0f)); // 沿X軸平移glm::mat4 view = glm::lookAt(glm::vec3(0.0f, 0.0f, 3.0f), // 相機位置glm::vec3(0.0f, 0.0f, 0.0f), // 觀察目標glm::vec3(0.0f, 1.0f, 0.0f) // 上向量
);glm::mat4 projection = glm::perspective(glm::radians(45.0f), // 視野角度800.0f / 600.0f, // 寬高比0.1f, 100.0f // 近平面和遠平面
);
三. 渲染3D物體
頂點數據
// 立方體頂點數據示例
float vertices[] = {// 位置 // 顏色-0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f,0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.0f,// ... 其他頂點
};
頂點緩沖對象(VBO)和頂點數組對象(VAO)
unsigned int VBO, VAO;
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, 6 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);// 顏色屬性
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
著色器程序
頂點著色器示例:
glsl
#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aColor;uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;out vec3 ourColor;void main() {gl_Position = projection * view * model * vec4(aPos, 1.0);ourColor = aColor;
}
片段著色器示例:
glsl
#version 330 core
in vec3 ourColor;
out vec4 FragColor;void main() {FragColor = vec4(ourColor, 1.0);
}