参考文章: https://learnopengl-cn.readthedocs.io/zh/latest/
上一节:https://blog.csdn.net/qq_40515692/article/details/106950901
演示视频: https://www.bilibili.com/video/BV1bZ4y1u7my/
代码1存在两个问题。代码2解决了问题2。代码3解决了问题1、2。想看最终代码的直接代码3问题1: GLSL现阶段貌似只有float类型,貌似4.0有更高的精度,这会导致放大一些后就出现模糊的情况。 问题2: 按键我暂时没管了,需要连续按,如果不喜欢可以用标志位解决。但是我发现貌似glfw的鼠标键盘事件貌似都不怎么灵敏,不知道是不是使用方式有误。
等待更新一些代码的解释。
更新:
经过评论提醒,确实可以只传递6个顶点(两个三角形绘制),然后让GPU插值。这样不用每次渲染传入WIDTH*HEIGHT*3的数组了。
但是我开始一直把处理写到了Vertex Shader,一直不行就一张渐变图,后来才想到渲染管线的过程,Vertex Shader只有刚传入的顶点,还没有光栅化!
Fragment Shader是在光栅化之后。在Vertex Shader阶段,我们要处理的数据只是3个顶点,而在Fragment Shader阶段,我们要处理的则是(大致上)被这三个顶点围住的所有像素对应的Fragments。Vertex的数量远远少于Fragment。
现在帧率又一次爆炸了,大概1000-1500(配色1)、500-1200帧(配色2)左右了(我已经麻木了 ○| ̄|_)
然后就是键盘的操作确实是我没写好,应该在循环里面再添加一个专门处理按键的函数,问题2解决,不过问题1的float精度问题还没解决。
main.cpp #include <iostream> #include <ctime> #define GLEW_STATIC #include <GL/glew.h> #include <GLFW/glfw3.h> #include "Shader.h" // Function prototypes void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode); void handle_input(); // Window dimensions const GLuint WIDTH = 1000, HEIGHT = 1000; GLfloat alphax, alphay; GLfloat rateZoom = 1.5f; GLfloat cx = -1, cy = -1; bool stop = false; void func(float rate) { if (stop) return; static bool flag = true; if (flag) cx += rate; else cx -= rate; if (cx > 1) { cy += rate; flag = false; } if (cx < -1) { cy += rate; flag = true; } if (cy == 0) { cx += rate; } } double CalFrequency() { static int count; static double save; static clock_t last, current; double timegap; ++count; if (count <= 50) return save; count = 0; last = current; current = clock(); timegap = (current - last) / (double)CLK_TCK; save = 50.0 / timegap; return save; } int main() { // Init GLFW glfwInit(); // Set all the required options for GLFW glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // Create a GLFWwindow object that we can use for GLFW's functions GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr); glfwMakeContextCurrent(window); // Set the required callback functions glfwSetKeyCallback(window, key_callback); // Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions glewExperimental = GL_TRUE; // Initialize GLEW to setup the OpenGL Function pointers glewInit(); // Define the viewport dimensions glViewport(0, 0, WIDTH, HEIGHT); GLfloat vertices[] = { 1, 1, 0.0f, // Top Right 1, -1, 0.0f, // Bottom Right -1, -1, 0.0f, // Bottom Left -1, 1, 0.0f // Top Left }; GLuint indices[] = { // Note that we start from 0! 0, 1, 3, // First Triangle 1, 2, 3 // Second Triangle }; // Build and compile our shader program Shader ourShader("default.vs", "default.frag"); GLuint VBO, VAO, EBO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); // Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s). glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); // Note that this is allowed, the call to glVertexAttribPointer registered VBO as the currently bound vertex buffer object so afterwards we can safely unbind glBindVertexArray(0); // Unbind VAO (it's always a good thing to unbind any buffer/array to prevent strange bugs), remember: do NOT unbind the EBO, keep it bound to this VAO // Game loop while (!glfwWindowShouldClose(window)) { double FPS = CalFrequency(); printf("FPS = %f\n", FPS); handle_input(); // Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions glfwPollEvents(); // Render // Clear the colorbuffer glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); GLint alphaLoc = glGetUniformLocation(ourShader.Program, "alpha"); GLint rateZoomLoc = glGetUniformLocation(ourShader.Program, "rateZoom"); GLint cLoc = glGetUniformLocation(ourShader.Program, "C"); glUniform2f(alphaLoc, alphax, alphay); glUniform1f(rateZoomLoc, rateZoom); glUniform2f(cLoc, cx, cy); // Draw the triangle ourShader.Use(); glBindVertexArray(VAO); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); glBindVertexArray(0); // Swap the screen buffers glfwSwapBuffers(window); // 这么高的FPS,只能调小步长了 func(0.01); } // Properly de-allocate all resources once they've outlived their purpose glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); // Terminate GLFW, clearing any resources allocated by GLFW. glfwTerminate(); return 0; } bool keypressed[349]; // max key num in glfw : 348 // Is called whenever a key is pressed/released via GLFW void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) { if (action == GLFW_PRESS) { if (key >= 0) keypressed[key] = 1; } else if (action == GLFW_RELEASE) { if (key >= 0) keypressed[key] = 0; if (key == GLFW_KEY_SPACE) stop = !stop; } } void handle_input() { // 移动速度调节 double addRate = 0.005 * std::abs(std::exp(rateZoom) - 1); if (keypressed[GLFW_KEY_UP]) alphay += addRate; if (keypressed[GLFW_KEY_DOWN]) alphay -= addRate; if (keypressed[GLFW_KEY_LEFT]) alphax -= addRate; if (keypressed[GLFW_KEY_RIGHT]) alphax += addRate; if (keypressed[GLFW_KEY_PAGE_UP]) rateZoom -= addRate; if (keypressed[GLFW_KEY_PAGE_DOWN]) rateZoom = (rateZoom + addRate) > 2 ? 2 : rateZoom + addRate; }Shader.h文件未变
default.vs
#version 330 core layout (location = 0) in vec3 position; out vec3 color; void main() { color = position; gl_Position = vec4(position, 1.0f); } default.frag #version 330 core in vec3 color; out vec4 colorF; uniform float rateZoom; uniform vec2 alpha; uniform vec2 C; // (-0.8,0.156) void main() { const int N = 100; const float M = 1000; vec2 X = vec2(color.x*rateZoom, color.y*rateZoom); X += alpha; vec3 color; for(int k=0;k<N;k++){ // X = X*X; X = X+C; X = vec2(X.x*X.x - X.y*X.y , 2*X.x*X.y); X = vec2(X.x*X.x - X.y*X.y , 2*X.x*X.y); X += C; if(X.x*X.x+X.y*X.y > M){ // 配色2 int x = k + k; int y = k * k; int z = int(exp(k)); // 必须加上int()强制类型转化,GLSL没有隐式转换,左右类型必须一致; color.x = float(x%255)/255.0; color.y = float(y%255)/255.0; color.z = float(z%255)/255.0; break; } } colorF = vec4(color, 1.0f); }更新,问题1解决:
首先是使用了OpenGL扩展功能,然后就可以使用double了,然后发现帧率虚高(double运算很慢)。然后才发现一直用的是核显(怪不得一直是左边风扇叫,因为我的CPU在左边,GPU在右边)。你竟然告诉我我的GTX1050一直没用上!所以先介绍如何配置显卡,我的显卡是英伟达的,AMD的需要自己再百度百度。
首先是查看GPU使用情况,打开cmd输入下面的命令查看:
cd C:\Program Files\NVIDIA Corporation\NVSMI nvidia-smi.exe运行代码时,出现这个才表示使用了GPU(PID3628那个进程),虽然GTX1050的帧数不会爆炸,但是超级稳(所以我说核显帧率虚高):
那么如何使用独显呢?桌面右键,然后进入NVIDA控制面板
然后就是修改全局设置:
最终代码:
main.cpp #include <iostream> #include <ctime> #define GLEW_STATIC #include <GL/glew.h> #include <GLFW/glfw3.h> #include "Shader.h" // Function prototypes void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode); void handle_input(); // Window dimensions const GLuint WIDTH = 1000, HEIGHT = 1000; GLdouble alphax, alphay; GLdouble rateZoom = 1.5f; GLdouble cx = -1, cy = -1; bool stop = false; void func(float rate) { if (stop) return; static bool flag = true; if (flag) cx += rate; else cx -= rate; if (cx > 1) { cy += rate; flag = false; } if (cx < -1) { cy += rate; flag = true; } if (cy == 0) { cx += rate; } } double CalFrequency() { static int count; static double save; static clock_t last, current; double timegap; ++count; if (count <= 50) return save; count = 0; last = current; current = clock(); timegap = (current - last) / (double)CLK_TCK; save = 50.0 / timegap; return save; } int main() { // Init GLFW glfwInit(); // Set all the required options for GLFW glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // Create a GLFWwindow object that we can use for GLFW's functions GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr); glfwMakeContextCurrent(window); // Set the required callback functions glfwSetKeyCallback(window, key_callback); // Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions glewExperimental = GL_TRUE; // Initialize GLEW to setup the OpenGL Function pointers glewInit(); // Define the viewport dimensions glViewport(0, 0, WIDTH, HEIGHT); GLfloat vertices[] = { 1, 1, 0.0f, // Top Right 1, -1, 0.0f, // Bottom Right -1, -1, 0.0f, // Bottom Left -1, 1, 0.0f // Top Left }; GLuint indices[] = { // Note that we start from 0! 0, 1, 3, // First Triangle 1, 2, 3 // Second Triangle }; // Build and compile our shader program Shader ourShader("default.vs", "default.frag"); GLuint VBO, VAO, EBO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); // Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s). glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); // Note that this is allowed, the call to glVertexAttribPointer registered VBO as the currently bound vertex buffer object so afterwards we can safely unbind glBindVertexArray(0); // Unbind VAO (it's always a good thing to unbind any buffer/array to prevent strange bugs), remember: do NOT unbind the EBO, keep it bound to this VAO // Game loop while (!glfwWindowShouldClose(window)) { double FPS = CalFrequency(); printf("FPS = %f\n", FPS); handle_input(); // Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions glfwPollEvents(); // Render // Clear the colorbuffer glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); GLint alphaLoc = glGetUniformLocation(ourShader.Program, "alpha"); GLint rateZoomLoc = glGetUniformLocation(ourShader.Program, "rateZoom"); GLint cLoc = glGetUniformLocation(ourShader.Program, "C"); glUniform2d(alphaLoc, alphax, alphay); glUniform1d(rateZoomLoc, rateZoom); glUniform2d(cLoc, cx, cy); // Draw the triangle ourShader.Use(); glBindVertexArray(VAO); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); glBindVertexArray(0); // Swap the screen buffers glfwSwapBuffers(window); func(0.05); } // Properly de-allocate all resources once they've outlived their purpose glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); // Terminate GLFW, clearing any resources allocated by GLFW. glfwTerminate(); return 0; } bool keypressed[349]; // max key num in glfw : 348 // Is called whenever a key is pressed/released via GLFW void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) { if (action == GLFW_PRESS) { if (key >= 0) keypressed[key] = 1; } else if (action == GLFW_RELEASE) { if (key >= 0) keypressed[key] = 0; if (key == GLFW_KEY_SPACE) stop = !stop; } } void handle_input() { // 移动速度调节 double addRate = 0.1 * std::abs(std::exp(rateZoom) - 1); if (keypressed[GLFW_KEY_UP]) alphay += addRate; if (keypressed[GLFW_KEY_DOWN]) alphay -= addRate; if (keypressed[GLFW_KEY_LEFT]) alphax -= addRate; if (keypressed[GLFW_KEY_RIGHT]) alphax += addRate; if (keypressed[GLFW_KEY_PAGE_UP]) rateZoom -= addRate; if (keypressed[GLFW_KEY_PAGE_DOWN]) rateZoom = (rateZoom + addRate) > 2 ? 2 : rateZoom + addRate; }Shader.h文件未变
default.vs
#version 330 core layout (location = 0) in vec3 position; out vec3 color; void main() { color = position; gl_Position = vec4(position, 1.0f); } default.frag #version 330 core #extension GL_ARB_gpu_shader_fp64 : enable in vec3 color; out vec4 colorF; uniform double rateZoom; uniform dvec2 alpha; uniform dvec2 C; void main() { const uint N = 200; const float M = 1000.0; dvec2 X = dvec2(color.x*rateZoom, color.y*rateZoom) + alpha; vec3 color; for(uint k=0;k<N;k++){ dvec2 X2 = X*X; if(X2.x + X2.y > M){ uint x = k + k; uint y = k * k; uint z = uint(exp(k)); // a % (2^n) 等价于 a & (2^n - 1) eg: x % 256 ----> x & 255 color.x = float(x&255)/256.0; color.y = float(y&255)/256.0; color.z = float(z&255)/256.0; break; } X = dvec2(X2.x - X2.y , 2.0*X.x*X.y); X = dvec2(X.x*X.x - X.y*X.y , 2.0*X.x*X.y); X += C; } colorF = vec4(color, 1.0f); }