文章目录
- 1、简介
- 1.1 OpenGL简介
- 1.2 glfw简介
- 2、安装glfw
- 2.1 直接命令二进制安装
- 2.2 源码安装
- 3、测试glfw
- 3.1 测试1,glfw+glew
- 3.2 测试2,glfw+glad
- 3.3 测试3
- 结语
1、简介
1.1 OpenGL简介
OpenGL作为图形界的工业标准,其仅仅定义了一组2D和3D图形接口API,而对于窗口管理、IO消息响应等并没有规定。也就是说,OpenGL依赖各平台提供用于渲染的context以及具体实现方式,而各平台提供的实现不尽相同。这些实现主要有:Windows平台下的WGL、Linux下的Mesa/GLX、Mac OS X下的Cocoa/NSGL,以及跨平台的GLUT、GLFW、SDL等等。
安装OpenGL库:
sudo apt-get install build-essential
sudo apt-get install libgl1-mesa-dev
使用如下的命令来查看对应显卡的OpenGL版本:
glxinfo | grep -i opengl
1.2 glfw简介
GLFW 是一个开源的多平台库,适用于 OpenGL、OpenGL ES 和 桌面上的 Vulkan 开发。它提供了一个简单的 API 来创建 窗口、上下文和表面,接收输入和事件。
GLFW 是用 C 语言编写的,支持 Windows、macOS、Wayland 和 X11。
GLFW 根据 zlib/libpng 许可证获得许可。
https://www.glfw.org/
查看glfw安装情况如下:
locate glfw
2、安装glfw
2.1 直接命令二进制安装
使用包管理器安装。
- 安装glfw:
sudo apt-get update
sudo apt-get -y install libglfw3# 或者
sudo apt-get install libglfw3
sudo apt-get install libglfw3-dev# 或者
sudo apt update
sudo apt -y install libglfw3
- 卸载glfw
# 要仅卸载包libglfw3
sudo apt-get remove libglfw3# 卸载 libglfw3 及其依赖项
sudo apt-get -y autoremove libglfw3# 删除 libglfw3 配置和数据
sudo apt-get -y purge libglfw3
2.2 源码安装
官方地址:
https://github.com/glfw/glfw
从 GLFW 的官方网站下载源代码并编译安装,依次执行如下命令:
# git clone git@github.com:glfw/glfw.git
# wget https://github.com/glfw/glfw/archive/refs/tags/3.4.tar.gz
wget http://github.com/glfw/glfw/releases/download/3.4/glfw-3.4.zip
cd glfw-3.4
mkdir build && cd build
sudo apt-get install libxrandr-dev
sudo apt-get install libxinerama-dev
sudo apt-get install libxcursor-dev
sudo apt-get install libxi-dev
cmake .. -DGLFW_BUILD_WAYLAND:BOOL=OFF
make -j4
sudo make install
通过wget下载glfw源码。
通过cmake编译glfw代码。
通过make install安装glfw库文件。
3、测试glfw
3.1 测试1,glfw+glew
要在 Linux 系统上配置 OpenGL 开发环境并使用 GLFW 和 GLEW,你可以按照以下步骤操作。
使用 GLEW 加载所有 OpenGL 函数指针。通过cmake构建测试工程。
- CMakeLists.txt
cmake_minimum_required(VERSION 2.8.1)project(my_project)find_package(OpenGL REQUIRED)
find_package(GLEW REQUIRED)
find_package(glfw3 REQUIRED)add_executable(main main.cpp)
target_link_libraries(main OpenGL::GL GLEW::GLEW glfw)
- main.cpp
#include <GL/glew.h>
#include <GLFW/glfw3.h>int main(void)
{GLFWwindow* window;/* Initialize the library */if (!glfwInit())return -1;/* Create a windowed mode window and its OpenGL context */window = glfwCreateWindow(640, 480, "Hello World, yxy", NULL, NULL);if (!window){glfwTerminate();return -1;}/* Make the window's context current */glfwMakeContextCurrent(window);if(glewInit() != GLEW_OK){std::cerr << "Failed to initalize GLEW" << std::endl;return -1;}/* Loop until the user closes the window */while (!glfwWindowShouldClose(window)){/* Render here */glClear(GL_COLOR_BUFFER_BIT);glClearColor(0, 1, 0, 1);/* Swap front and back buffers */glfwSwapBuffers(window);/* Poll for and process events */glfwPollEvents();}glfwTerminate();return 0;
}
编译如下:
3.2 测试2,glfw+glad
GLAD 是一个用于加载 OpenGL 函数指针的库,它简化了 OpenGL 函数的调用。你可以从 GLAD 的官方网站下载并生成适合你需求的 GLAD 配置。通常,你需要指定 OpenGL 的版本和配置文件类型(通常是核心模式)。生成后,将包含的头文件和源文件添加到你的项目中。
在你的项目中,你需要包含 GLAD 和 GLFW 的头文件,并链接到相应的库。如果你使用 CMake,你可能需要在你的 CMakeLists.txt 文件中添加相应的链接指令。
- CMakeLists.txt
cmake_minimum_required(VERSION 2.8.1)project(my_project)
set(CMAKE_C_STANDARD 11)
set(CMAKE_CXX_STANDARD 14)find_package(glfw3 REQUIRED)file(GLOB SOURCE_FILES glad.c main.cpp)
add_executable(${PROJECT_NAME} ${SOURCE_FILES})target_link_libraries(${PROJECT_NAME} glfw)
- main.cpp
#include <iostream>
#include <glad/glad.h>
#include <GLFW/glfw3.h>void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void processInput(GLFWwindow *window);int main() {// Intialize GLFWglfwInit();// Configure GLFW (v3.3)glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);// Create a window objectGLFWwindow* window = glfwCreateWindow(800, 600, "LearnOpenGL, yxy", NULL, NULL);if (window == NULL) {std::cout << "Failed to create GLFW window" << std::endl;glfwTerminate();return -1;}// Make our window the main context on the current threadglfwMakeContextCurrent(window);// Initialize GLADif (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {std::cout << "Failed to initialize GLAD" << std::endl;return -1;}// Set size of the rendering window (dimensions)glViewport(0, 0, 800, 600);// Register a callback function on the window that gets called// each time the window is resizedglfwSetFramebufferSizeCallback(window, framebuffer_size_callback);// Render loop that keeps on running until we tell GLFW to stopwhile(!glfwWindowShouldClose(window)) {// Check input close window if it is the escape keyprocessInput(window);// Rendering commands here// Set a color to clear the screen with (state-setting function)glClearColor(0.2f, 0.3f, 0.3f, 1.0f);// Clear the screen with the color (state-using function)glClear(GL_COLOR_BUFFER_BIT);// Swap the color buffer and show output to the screenglfwSwapBuffers(window);// Check if any events are triggeredglfwPollEvents();}// Clean/delete all GLFW's resourcesglfwTerminate();return 0;
}void framebuffer_size_callback(GLFWwindow* window, int width, int height) {// Update width and heightglViewport(0, 0, width, height);
}void processInput(GLFWwindow *window) {// Check whether the user has pressed the escape key and close GLFWif (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)glfwSetWindowShouldClose(window, true);
}
编译如下:
3.3 测试3
- CMakeLists.txt
cmake_minimum_required(VERSION 2.8.1)project(my_project)
set(CMAKE_C_STANDARD 11)
set(CMAKE_CXX_STANDARD 14)find_package(glfw3 REQUIRED)file(GLOB SOURCE_FILES glad.c main.cpp)
add_executable(${PROJECT_NAME} ${SOURCE_FILES})target_link_libraries(${PROJECT_NAME} glfw)
- main.cpp
#include <glad/glad.h>
#include <GLFW/glfw3.h>#include <iostream>void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void processInput(GLFWwindow *window);
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;// 顶点着色器,GLSL语言
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 configureglfwInit();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 creationGLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL, yxy", 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 pointersif (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)){std::cout << "Failed to initialize GLAD" << std::endl;return -1;}// build and compile our shader program// ------------------------------------// vertex shaderint vertexShader = glCreateShader(GL_VERTEX_SHADER);glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);glCompileShader(vertexShader);// check for shader compile errorsint 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 shaderint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);glCompileShader(fragmentShader);// check for shader compile errorsglGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);if (!success){glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl;}// link shadersint shaderProgram = glCreateProgram();glAttachShader(shaderProgram, vertexShader);glAttachShader(shaderProgram, fragmentShader);glLinkProgram(shaderProgram);// check for linking errorsglGetProgramiv(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);float vertices[] = {-0.5f, -0.5f, 0.0f, // left0.5f, -0.5f, 0.0f, // right0.0f, 0.5f, 0.0f // top};unsigned int VBO, VAO;//创建VAO对象glGenVertexArrays(1, &VAO);glBindVertexArray(VAO);//创建VBO对象,把顶点数组复制到一个顶点缓冲中,供OpenGL使用glGenBuffers(1, &VBO);glBindBuffer(GL_ARRAY_BUFFER, VBO); // 缓冲绑定到GL_ARRAY_BUFFERglBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // 顶点数据复制到缓冲的内存中//解释顶点数据方式glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); // 顶点数据的解释glEnableVertexAttribArray(0);// 解绑VAOglBindVertexArray(0);// 解绑VBOglBindBuffer(GL_ARRAY_BUFFER, 0);// 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 triangleglUseProgram(shaderProgram);glBindVertexArray(VAO);glDrawArrays(GL_TRIANGLES, 0, 3);glfwSwapBuffers(window);glfwPollEvents();}// optional: de-allocate all resourcesglDeleteVertexArrays(1, &VAO);glDeleteBuffers(1, &VBO);glDeleteProgram(shaderProgram);glfwTerminate();return 0;
}//键盘按键回调函数
void processInput(GLFWwindow *window)
{if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)glfwSetWindowShouldClose(window, true);
}//调整窗口大小回调函数
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{glViewport(0, 0, width, height);
}
结语
如果您觉得该方法或代码有一点点用处,可以给作者点个赞,或打赏杯咖啡;
╮( ̄▽ ̄)╭
如果您感觉方法或代码不咋地//(ㄒoㄒ)//,就在评论处留言,作者继续改进;
o_O???
如果您需要相关功能的代码定制化开发,可以留言私信作者;
(✿◡‿◡)
感谢各位大佬童鞋们的支持!
( ´ ▽´ )ノ ( ´ ▽´)っ!!!