#include<glad/glad.h>#include<GLFW/glfw3.h>#include<C:/Users/qian.cheng/source\repos/openGl/openGl/stb_image.h>#include<C:/Users/qian.cheng/source/repos/openGl/openGl/shader.h>#include<iostream>voidframebuffer_size_callback(GLFWwindow* window,int width,int height);voidprocessInput(GLFWwindow* window);// settingsconstunsignedint SCR_WIDTH =800;constunsignedint SCR_HEIGHT =600;intmain(){// 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)){
std::cout <<"Failed to initialize GLAD"<< std::endl;return-1;}// build and compile our shader program// ------------------------------------
Shader ourShader("3.3.shader.vs","3.3.shader.fs");// you can name your shader files however you like// set up vertex data (and buffer(s)) and configure vertex attributes// ------------------------------------------------------------------float vertices[]={// positions // colors0.5f,-0.5f,0.0f,1.0f,0.0f,0.0f,// bottom right-0.5f,-0.5f,0.0f,0.0f,1.0f,0.0f,// bottom left0.0f,0.5f,0.0f,0.0f,0.0f,1.0f// top };unsignedint 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);// position attributeglVertexAttribPointer(0,3, GL_FLOAT, GL_FALSE,6*sizeof(float),(void*)0);glEnableVertexAttribArray(0);// color attributeglVertexAttribPointer(1,3, GL_FLOAT, GL_FALSE,6*sizeof(float),(void*)(3*sizeof(float)));glEnableVertexAttribArray(1);// 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);// render loop// -----------while(!glfwWindowShouldClose(window)){// input// -----processInput(window);// render// ------glClearColor(0.2f,0.3f,0.3f,1.0f);glClear(GL_COLOR_BUFFER_BIT);// render the triangle
ourShader.use();glBindVertexArray(VAO);glDrawArrays(GL_TRIANGLES,0,3);// 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);// glfw: terminate, clearing all previously allocated GLFW resources.// ------------------------------------------------------------------glfwTerminate();return0;}// process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly// ---------------------------------------------------------------------------------------------------------voidprocessInput(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// ---------------------------------------------------------------------------------------------voidframebuffer_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);}
#pragma once#ifndef SHADER_H#define SHADER_H#include<glad/glad.h>#include<string>#include<fstream>#include<sstream>#include<iostream>classShader{public:unsignedint ID;// constructor generates the shader on the fly// ------------------------------------------------------------------------Shader(constchar* vertexPath,constchar* fragmentPath){// 1. retrieve the vertex/fragment source code from filePath
std::string vertexCode;
std::string fragmentCode;
std::ifstream vShaderFile;
std::ifstream fShaderFile;// ensure ifstream objects can throw exceptions:
vShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
fShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit);try{// open files
vShaderFile.open(vertexPath);
fShaderFile.open(fragmentPath);
std::stringstream vShaderStream, fShaderStream;// read file's buffer contents into streams
vShaderStream << vShaderFile.rdbuf();
fShaderStream << fShaderFile.rdbuf();// close file handlers
vShaderFile.close();
fShaderFile.close();// convert stream into string
vertexCode = vShaderStream.str();
fragmentCode = fShaderStream.str();}catch(std::ifstream::failure& e){
std::cout <<"ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ"<< std::endl;}constchar* vShaderCode ="#version 330 core\n""layout (location = 0) in vec3 aPos;\n""layout (location = 1) in vec3 aColor;\n""layout (location = 2) in vec2 aTexCoord;\n""out vec3 ourColor;\n""out vec2 TexCoord;\n""void main()\n""{\n""gl_Position = vec4(aPos, 1.0);\n""ourColor = aColor;\n""TexCoord = aTexCoord;""}\0";//vertexCode.c_str();constchar* fShaderCode ="#version 330 core\n""out vec4 FragColor;\n""in vec3 ourColor;\n""in vec2 TexCoord;\n""uniform sampler2D ourTexture;""uniform sampler2D texture1;""uniform sampler2D texture2;""void main()\n""{\n"//" FragColor = vec4(ourColor, 1.0f);\n"//"FragColor = texture(ourTexture, TexCoord);"//"FragColor = texture(ourTexture, TexCoord) * vec4(ourColor, 1.0);\n""FragColor = mix(texture(texture1, TexCoord), texture(texture2, TexCoord), 0.2);""}\n\0";//fragmentCode.c_str();// 2. compile shadersunsignedint vertex, fragment;// vertex shader
vertex =glCreateShader(GL_VERTEX_SHADER);glShaderSource(vertex,1,&vShaderCode,NULL);glCompileShader(vertex);checkCompileErrors(vertex,"VERTEX");// fragment Shader
fragment =glCreateShader(GL_FRAGMENT_SHADER);glShaderSource(fragment,1,&fShaderCode,NULL);glCompileShader(fragment);checkCompileErrors(fragment,"FRAGMENT");// shader Program
ID =glCreateProgram();glAttachShader(ID, vertex);glAttachShader(ID, fragment);glLinkProgram(ID);checkCompileErrors(ID,"PROGRAM");// delete the shaders as they're linked into our program now and no longer necessaryglDeleteShader(vertex);glDeleteShader(fragment);}// activate the shader// ------------------------------------------------------------------------voiduse(){glUseProgram(ID);}// utility uniform functions// ------------------------------------------------------------------------voidsetBool(const std::string& name,bool value)const{glUniform1i(glGetUniformLocation(ID, name.c_str()),(int)value);}// ------------------------------------------------------------------------voidsetInt(const std::string& name,int value)const{glUniform1i(glGetUniformLocation(ID, name.c_str()), value);}// ------------------------------------------------------------------------voidsetFloat(const std::string& name,float value)const{glUniform1f(glGetUniformLocation(ID, name.c_str()), value);}private:// utility function for checking shader compilation/linking errors.// ------------------------------------------------------------------------voidcheckCompileErrors(unsignedint shader, std::string type){int success;char infoLog[1024];if(type !="PROGRAM"){glGetShaderiv(shader, GL_COMPILE_STATUS,&success);if(!success){glGetShaderInfoLog(shader,1024,NULL, infoLog);
std::cout <<"ERROR::SHADER_COMPILATION_ERROR of type: "<< type <<"\n"<< infoLog <<"\n -- --------------------------------------------------- -- "<< std::endl;}}else{glGetProgramiv(shader, GL_LINK_STATUS,&success);if(!success){glGetProgramInfoLog(shader,1024,NULL, infoLog);
std::cout <<"ERROR::PROGRAM_LINKING_ERROR of type: "<< type <<"\n"<< infoLog <<"\n -- --------------------------------------------------- -- "<< std::endl;}}}};#endif
渐变
```cpp
#include<glad/glad.h>#include<GLFW/glfw3.h>#include<iostream>voidframebuffer_size_callback(GLFWwindow* window,int width,int height);voidprocessInput(GLFWwindow* window);// settingsconstunsignedint SCR_WIDTH =800;constunsignedint SCR_HEIGHT =600;constchar* vertexShaderSource ="#version 330 core\n""layout (location = 0) in vec3 aPos;\n""layout (location = 1) in vec3 aColor;\n""out vec3 ourColor;\n""void main()\n""{\n"" gl_Position = vec4(aPos, 1.0);\n"" ourColor = aColor;\n""}\0";constchar* fragmentShaderSource ="#version 330 core\n""out vec4 FragColor;\n""in vec3 ourColor;\n""void main()\n""{\n"" FragColor = vec4(ourColor, 1.0f);\n""}\n\0";intmain(){// 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)){
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);// set up vertex data (and buffer(s)) and configure vertex attributes// ------------------------------------------------------------------float vertices[]={// positions // colors0.5f,-0.5f,0.0f,1.0f,0.0f,0.0f,// bottom right-0.5f,-0.5f,0.0f,0.0f,1.0f,0.0f,// bottom left0.0f,0.5f,0.0f,0.0f,0.0f,1.0f// top };unsignedint 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);// position attributeglVertexAttribPointer(0,3, GL_FLOAT, GL_FALSE,6*sizeof(float),(void*)0);glEnableVertexAttribArray(0);// color attributeglVertexAttribPointer(1,3, GL_FLOAT, GL_FALSE,6*sizeof(float),(void*)(3*sizeof(float)));glEnableVertexAttribArray(1);// 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);// as we only have a single shader, we could also just activate our shader once beforehand if we want to glUseProgram(shaderProgram);// render loop// -----------while(!glfwWindowShouldClose(window)){// input// -----processInput(window);// render// ------glClearColor(0.2f,0.3f,0.3f,1.0f);glClear(GL_COLOR_BUFFER_BIT);// render the triangleglBindVertexArray(VAO);glDrawArrays(GL_TRIANGLES,0,3);// 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();return0;}// process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly// ---------------------------------------------------------------------------------------------------------voidprocessInput(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// ---------------------------------------------------------------------------------------------voidframebuffer_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);}