LearnOpenGL笔记(2)三角形
这是学习LearnOpenGL CN教程的笔记,包括我遇到的问题和我的烂笔头。文章名与网站小节对应。
------------------------------------分割线--------------------------------------------------------------------------------------------
摆张重要的图先,蓝色的是可以编写着色器控制的部分。
着色器在C++字符串中的形式
"#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" "}\n";
绘制流程
//初始化缓冲数组对象 unsigned int VAO; //顶点数组对象VAO unsigned int VBO; //顶点缓冲对象VBO //创建VAO glGenVertexArrays(1, &VAO); //绑定VAO glBindVertexArray(VAO); //创建VBO glGenBuffers(1, &VBO); //生成vbo和缓冲ID //缓冲绑定 glBindBuffer(GL_ARRAY_BUFFER, VBO); //将数据传输到当前绑定缓冲 glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); //第四个参数:如何管理给定的数据 // GL_STATIC_DRAW :数据不会或几乎不会改变。 // GL_DYNAMIC_DRAW:数据会被改变很多。 // GL_STREAM_DRAW :数据每次绘制时都会改变。 //解析顶点数据,设置顶点属性指针 glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); //创建着色器程序 //顶点着色器 unsigned int vertexShader; vertexShader = glCreateShader(GL_VERTEX_SHADER); //附加 glShaderSource(vertexShader, 1, &vertexShaderSource, NULL); //编译 glCompileShader(vertexShader); //检测失败 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; } //片段着色器 unsigned int fragmentShader; fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL); glCompileShader(fragmentShader); //片段着色器 unsigned int fragmentShaderY; fragmentShaderY = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShaderY, 1, &fragmentShaderYellowSource, NULL); glCompileShader(fragmentShaderY); shaderProgram = glCreateProgram(); //附加 glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); //链接 glLinkProgram(shaderProgram); shaderYellowProram = glCreateProgram(); //附加 glAttachShader(shaderYellowProram, vertexShader); glAttachShader(shaderYellowProram, fragmentShaderY); //链接 glLinkProgram(shaderYellowProram); //链接成功后,释放着色器对象 glDeleteShader(vertexShader); glDeleteShader(fragmentShader); glDeleteShader(fragmentShaderY); //在循环渲染中绘制 //渲染循环 while (!glfwWindowShouldClose(window)) { //渲染指令 glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glUseProgram(shaderProgram); glBindVertexArray(VAO); glDrawArrays(GL_TRIANGLES, 0, 3); //交换颜色缓冲,绘制显示 glfwSwapBuffers(window); }