- OpenGL(全写Open Graphics Library),定义了一个跨编程语言、跨平台的编程接口规格的专业的图形程序接口。它用于三维、二维图形,是一个功能强大,调用方便的底层图形库。【更多细节:图形程序接口知多少| OpenGL、OpenCL、Vulkan、OpenGL ES、WebGL、Metal、Directx】
- OpenGL支持跨平台开发(如Windows、Unix、Linux、MacOS、OS/2),自动化构建的话首选 CMake,编辑器推荐个人很喜欢的微软的 VScode,插件丰富、轻量且开源,下面介绍在 Win10 系统下基于 VScode 和 CMake 搭建 OpenGL开发环境。
- 准备工作
- 需要软件:VScode 【下载】,Visual Studio 2017 【链接,提取码:lzkp 】
- OpenGL库介绍:
- opengl 的库在安装 Visual Studio 2017 过程中已经安装完毕
- GLEW: 对底层 OpenGL 接口进行封装
- GLAD: 可以看做是 GLEW 的进化版
- Freeglut :用于创建 OpenGL 上下文、鼠键事件响应等
- GLFW :可看做是 Freeglut 的进化版
- 配合使用: GLAD + GLFW (推荐,也是本文使用的库) | GLEW + Freeglut
- 先在 VScode 基础上跑通 CMake 例子,具体参考 [Win10下VScode+MSVC+CMake搭建C++开发环境(傻瓜式教程)]
- GLFW:针对 OpenGL 的 C 语言库,提供了渲染物体所需的最低限度的接口。允许用户创建 OpenGL 上下文,定义窗口参数以及处理用户输入
- 官网下载 [链接],可以直接下载官网编译好的二进制版本(建议下载32位版本),但因为本人下载后 cmake 编译过程中老是报错:error LNK2019: 无法解析的外部符号 glfwInit,所以这里我选择了用 Visual Studio 进行编译
- Visual Studio 进行编译过程:【glfw-3.3.3.zip, 链接:https://pan.baidu.com/s/1AIAGcvp_w6fuZNv60RluHg 提取码:sipv 】
- 该文件解压后,用 VScode 的 CMakeTools 进行 Build:
然后利用 Visual Studio 2017 进行生成:
在 glfw-3.3.3/build/src/Debug 和 glfw-3.3.3/build/src/Release 目录下有 glfw3.lib 文件;
- GLAD : 鉴于 OpenGL 驱动版本多,大多数函数的位置因无法在编译时确定,需要在运行时进行查询,该工作复杂又繁琐,对于开发者而言是个灾难,而 GLAD 库可以简化此过程。
获得 GLAD 前先确定下自己 opengl 库的版本,小工具 OpenGL Extensions Viewer [链接:https://pan.baidu.com/s/17v77pDjgd_5CPfNIbDNA0w 提取码:ofay ]
- 官网的在线生成 【链接】 【本教程的 glad.zip: 链接:https://pan.baidu.com/s/1LdPOIYE0Wgm9dAdy1iqgHQ 提取码:b72t 】
构建工程 (build 文件夹是 VScode Build 后自动生成的):
include 文件:
lib 文件:
其中 opengl32.dll 一般在 C:\Windows\System32 目录下, OpenGL32.Lib 在 C:\Program Files (x86)\Windows Kits\10\Lib\10.0.17763.0\um\x86 目录下,将其拷贝到 lib 目录下。
src 文件:
main.cpp
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <iostream>
using namespace std;
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void processInput(GLFWwindow* window);
// settings
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;
const char* vertexShaderSource = "#version 330 core\n"
"layout (location = 0) in vec3 aPos;\n"
"void main()\n"
"{\n"
" gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n"
"}\0";
const char* fragmentShaderSource = "#version 330 core\n"
"out vec4 FragColor;\n"
"void main()\n"
"{\n"
" FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n"
"}\n\0";
int main()
{
// glfw: initialize and configure
// ------------------------------
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#ifdef __APPLE__
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
// glfw window creation
// --------------------
GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
// glad: load all OpenGL function pointers
// ---------------------------------------
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
cout << "Failed to initialize GLAD" << endl;
return -1;
}
// build and compile our shader program
// ------------------------------------
// vertex shader
int vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
glCompileShader(vertexShader);
// check for shader compile errors
int success;
char infoLog[512];
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
}
// fragment shader
int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
glCompileShader(fragmentShader);
// check for shader compile errors
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl;
}
// link shaders
int shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
// check for linking errors
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
if (!success) {
glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl;
}
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
// set up vertex data (and buffer(s)) and configure vertex attributes
// ------------------------------------------------------------------
float vertices[] = {
-0.5f, -0.5f, 0.0f, // left
0.5f, -0.5f, 0.0f, // right
0.0f, 0.5f, 0.0f // top
};
unsigned int VBO, VAO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
// bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s).
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// note that this is allowed, the call to glVertexAttribPointer registered VBO as the vertex attribute's bound vertex buffer object so afterwards we can safely unbind
glBindBuffer(GL_ARRAY_BUFFER, 0);
// You can unbind the VAO afterwards so other VAO calls won't accidentally modify this VAO, but this rarely happens. Modifying other
// VAOs requires a call to glBindVertexArray anyways so we generally don't unbind VAOs (nor VBOs) when it's not directly necessary.
glBindVertexArray(0);
// uncomment this call to draw in wireframe polygons.
//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
// render loop
// -----------
while (!glfwWindowShouldClose(window))
{
// input
// -----
processInput(window);
// render
// ------
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
// draw our first triangle
glUseProgram(shaderProgram);
glBindVertexArray(VAO); // seeing as we only have a single VAO there's no need to bind it every time, but we'll do so to keep things a bit more organized
glDrawArrays(GL_TRIANGLES, 0, 3);
// glBindVertexArray(0); // no need to unbind it every time
// glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
// -------------------------------------------------------------------------------
glfwSwapBuffers(window);
glfwPollEvents();
}
// optional: de-allocate all resources once they've outlived their purpose:
// ------------------------------------------------------------------------
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
glDeleteProgram(shaderProgram);
// glfw: terminate, clearing all previously allocated GLFW resources.
// ------------------------------------------------------------------
glfwTerminate();
return 0;
}
// process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly
// ---------------------------------------------------------------------------------------------------------
void processInput(GLFWwindow* window)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
}
// glfw: whenever the window size changed (by OS or user resize) this callback function executes
// ---------------------------------------------------------------------------------------------
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
// make sure the viewport matches the new window dimensions; note that width and
// height will be significantly larger than specified on retina displays.
glViewport(0, 0, width, height);
}
CMakeLists.txt
cmake_minimum_required(VERSION 3.8)
project(HelloGL VERSION 0.1.0)
# 使用 C++ 11 标准
set(CMAKE_CXX_STANDARD 11)
# 添加头文件
set(THIRD_PARTY_H ${PROJECT_SOURCE_DIR}/include)
include_directories(${THIRD_PARTY_H})
# 添加目标链接
set(LIB_PATH ${PROJECT_SOURCE_DIR}/lib)
file(GLOB_RECURSE LIB_FILES
"${LIB_PATH}/*.lib"
)
message("............ LIB_PATH: ${LIB_PATH}")
message("............ LIB_FILES: ${LIB_FILES}")
link_directories(${LIB_PATH})
aux_source_directory(./src DIR_SRCS)
add_executable(HelloGL ${DIR_SRCS})
target_link_libraries(HelloGL ${LIB_FILES})
通过 VScode Build 和运行 (该工程的 include , lib, src 中涉及到第三方库的文件下载:链接:https://pan.baidu.com/s/1QGvtQm7LGRQz30BiTpCyKg 提取码:acf4 )