-OPENGL7-
Posted gearslogy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了-OPENGL7-相关的知识,希望对你有一定的参考价值。
CP24: GeometryShader
教程中的一开始初始化的点是在NDC设备,我的同样一样,在shader中,教程中vert 不包含projection * view *model,我的依然存在。
如果在Geometry绘制的线段依然要满足透视关系,所以也得把projection * view * model带入
在这里修改了LoaderShader.h
#ifndef LOADSHADER_H #define LOADSHADER_H #include <GL/glew.h> #include <iostream> #include <fstream> #include <string> #include <sstream> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <vector> #include "ALG_TextureDelegate.h" namespace AlgebraMaster { using namespace std; // Shaders const char* vertexShaderSource = "#version 450 core " "layout (location = 0) in vec4 v_position; " "layout ( location = 1 ) in vec3 v_normal; " "layout ( location = 2 ) in vec2 v_texCoord; " "out vec2 myTexCoord; " "uniform mat4 model; " "uniform mat4 view; " "uniform mat4 projection; " "void main() " "{ " "gl_Position = projection * view * model * v_position; " "myTexCoord = v_texCoord; " "} "; const char* fragmentShaderSource = "#version 450 core " "out vec4 fColor; " "void main() " "{ " "fColor = vec4(1.0f, 1.0f, 1.0f , 1.0f); " "} "; // this have texture const char* fragmentShaderSource2 = "#version 450 core " "out vec4 fColor; " "in vec2 myTexCoord; " "struct Material " "{ " "float Kd; // diffuse mult " "float kS; // specular mult " "float shininess; // phong pow(,shine) " "sampler2D diffuse_map; " "sampler2D specular_map; " "sampler2D emission_map; " "}; " "uniform Material material; " "void main() " "{ " "vec4 df_tex=texture(material.diffuse_map, myTexCoord); ;" "fColor = vec4(df_tex.r,df_tex.g,df_tex.b,1.0f) ; " "} "; struct LoadShader { enum ShaderIOType{FILE,INLINE_DEFAULT_PROJECTION,INLINE_TEXTURE_PROJECTION}; void compileShaderProgram(bool needGeometryShader = false){ // create shader program and check it GLint success; GLchar infoLog[512]; shaderProgram = glCreateProgram(); glAttachShader(shaderProgram,vertexShader); glAttachShader(shaderProgram,fragmentShader); // if we need attach geometry shader if (needGeometryShader){ glAttachShader(shaderProgram,geometryShader); } glLinkProgram(shaderProgram ); glGetProgramiv( shaderProgram, GL_LINK_STATUS, &success ); // Get Link Status if (!success) { glGetProgramInfoLog( shaderProgram, 512, NULL, infoLog ); std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED " << infoLog << std::endl; } // Delete the allShaders as they‘re linked into our program now and no longer necessery glDeleteShader( vertexShader ); glDeleteShader( fragmentShader ); } void compileVertexShader(const string& code){ vertexShader = glCreateShader( GL_VERTEX_SHADER ); const char * src = code.c_str(); glShaderSource( vertexShader, 1, &(src), NULL ); glCompileShader( vertexShader ); GLint success; GLchar infoLog[512]; glGetShaderiv( vertexShader, GL_COMPILE_STATUS, &success ); if ( !success ) { glGetShaderInfoLog( vertexShader, 512, NULL, infoLog ); std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED " << infoLog << std::endl; } } void compileGeometryShader(const string& code){ const char *src = code.c_str(); GLint success; GLchar infoLog[512]; geometryShader = glCreateShader( GL_GEOMETRY_SHADER ); glShaderSource( geometryShader, 1, &src, NULL ); glCompileShader( geometryShader ); glGetShaderiv( geometryShader, GL_COMPILE_STATUS, &success ); // Get Compile status if ( !success ) { glGetShaderInfoLog( geometryShader, 512, NULL, infoLog ); std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED " << infoLog << std::endl; } } void compileFragmentShader(const string& code){ const char * src = code.c_str(); GLint success; GLchar infoLog[512]; fragmentShader = glCreateShader( GL_FRAGMENT_SHADER ); glShaderSource( fragmentShader, 1, &src, NULL ); glCompileShader( fragmentShader ); glGetShaderiv( fragmentShader, GL_COMPILE_STATUS, &success ); // Get Compile status if ( !success ) { glGetShaderInfoLog( fragmentShader, 512, NULL, infoLog ); std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED " << infoLog << std::endl; } } void fromSrc(const string &vertCode, const string &fragCode){ compileVertexShader(vertCode); compileFragmentShader(fragCode); compileShaderProgram(); } void fromSrc(const string &vertCode, const string &fragCode, const string&geometryCode){ compileVertexShader(vertCode); compileFragmentShader(fragCode); compileGeometryShader(geometryCode); compileShaderProgram(true); } LoadShader(){ } ~LoadShader(){ } // ------------ this method do not compile the geometry shader ----------------------- void asSimpleTextureShader(){ shaderName = "simpleTex"; shaderIOType = INLINE_TEXTURE_PROJECTION; compileVertexShader(vertexShaderSource); compileFragmentShader(fragmentShaderSource2); compileShaderProgram(); } void asSimpleShader() { shaderName = "simpleCol"; shaderIOType = INLINE_DEFAULT_PROJECTION; compileVertexShader(vertexShaderSource); compileFragmentShader(fragmentShaderSource); compileShaderProgram(); } // ------------ this method do not compile the geometry shader ----------------------- void setShaderName(const string &name){ shaderName = name; } // ------------ read text file ----------------------- string _readFile(const char *path){ ifstream stream; stringstream ss; stream.exceptions(ifstream::badbit); try { stream.open(path); // open file ss << stream.rdbuf(); // get strings from file } catch (ifstream::failure e) { cout << "ERROR::OPEN FILE:" << path << endl; } // close file handle stream.close(); // get str() from stringstream string shaderCode = ss.str(); return shaderCode; } // ------------ load a vertex shader from a path ---------------------------------- void _loadVertexShader(const char *path){ // read shader code auto handle = _readFile(path); compileVertexShader(handle); } // ------------ load a fragment shader from a path ---------------------------------- void _loadFragmentShader(const char *path){ // read shader code auto handle = _readFile(path); compileFragmentShader(handle); } // ------------ load a geometry shader from a path ---------------------------------- void _loadGeometryShader(const char *path){ auto handle = _readFile(path); compileGeometryShader(handle); } // ------------ only load two shader : vert & frag ---------------------------------- void load(const char* vertShaderPath, const char* fragShaderPath){ shaderIOType = FILE; _loadVertexShader(vertShaderPath); _loadFragmentShader(fragShaderPath); // create shader program and check it compileShaderProgram(); } // ------------ shader program have 3 shader: vert&frag&geometry ---------------------------------- void load(const char* vertShaderPath, const char* fragShaderPath, const char* geometryShaderPath){ shaderIOType = FILE; _loadVertexShader(vertShaderPath); _loadFragmentShader(fragShaderPath); _loadGeometryShader(geometryShaderPath); // create shader program and check it compileShaderProgram(true); } // ------------ active current shader program ---------------------------------- void use(){ glUseProgram(shaderProgram); } // ------------ set shader method ---------------------------------- void setBool(const char *name, bool value) const { glUniform1i(glGetUniformLocation(shaderProgram, name), (int)value); } void setInt(const char *name, int value) const { glUniform1i(glGetUniformLocation(shaderProgram,name), value); } // ------------------------------------------------------------------------ void setFloat(const char *name, float value) const { glUniform1f(glGetUniformLocation(shaderProgram, name), value); } // ------------------------------------------------------------------------ void setVec2(const char *name, const glm::vec2 &value) const { glUniform2fv(glGetUniformLocation(shaderProgram,name), 1, &value[0]); } void setVec2(const char *name, float x, float y) const { glUniform2f(glGetUniformLocation(shaderProgram,name), x, y); } // ------------------------------------------------------------------------ void setVec3(const char *name, const glm::vec3 &value) const { glUniform3fv(glGetUniformLocation(shaderProgram,name), 1, &value[0]); } void setVec3(const char *name, float x, float y, float z) const { glUniform3f(glGetUniformLocation(shaderProgram,name), x, y, z); } // ------------------------------------------------------------------------ void setVec4(const char *name, const glm::vec4 &value) const { glUniform4fv(glGetUniformLocation(shaderProgram,name), 1, &value[0]); } void setVec4(const char *name, float x, float y, float z, float w) { glUniform4f(glGetUniformLocation(shaderProgram,name), x, y, z, w); } void setMat2(const char*name, const glm::mat2 &mat) const { glUniformMatrix2fv(glGetUniformLocation(shaderProgram, name), 1, GL_FALSE,glm::value_ptr(mat)); } void setMat3(const char*name, const glm::mat3 &mat){ GLuint location = glGetUniformLocation(shaderProgram, name); glUniformMatrix3fv(location,1, GL_FALSE, &mat[0][0]); } void setMat4(const char *name , const glm::mat4 &mat){ GLuint location = glGetUniformLocation(shaderProgram, name); glUniformMatrix4fv(location,1, GL_FALSE, glm::value_ptr(mat)); } GLuint shaderProgram; GLuint vertexShader; GLuint fragmentShader; GLuint geometryShader; ShaderIOType shaderIOType; string shaderName; vector <Texture*> textures; // do not release this memory, scene will manipulate this mem glm::mat4 model; glm::mat4 view; glm::mat4 projection; // ------------ direct set shader projection,view,model ---------------------------------- void setMatrix(const glm::mat4 &matModel , const glm::mat4 &matView , const glm::mat4 &matProjection){ model = matModel; view = matView; projection = matProjection; setMat4("projection", projection); setMat4("view", view); setMat4("model", model); } }; } #endif // LOADSHADER_H
集合体shader->GeometryShader.geom:
#version 450 core layout (points) in; layout (line_strip, max_vertices = 2) out; uniform mat4 model; uniform mat4 view; uniform mat4 projection; void main() { gl_Position = gl_in[0].gl_Position + projection*view*model*vec4(-.2, 0.0, 0.0, 0.0); EmitVertex(); gl_Position = gl_in[0].gl_Position + projection*view*model*vec4( 0.2, 0.0, 0.0, 0.0); EmitVertex(); EndPrimitive(); }
#version 450 core // Final Color To export out vec4 FragColor; void main() { FragColor = vec4(1,0,1,1); }
#version 450 core // INCOMING DATA layout ( location = 0 ) in vec4 v_position; // pos //layout ( location = 1 ) in vec2 v_texCoord; // st //layout ( location = 2 ) in vec3 v_normal; // st // define out data out vec2 f_TexCoord; // normal at world matrix, we direct from C++ calcalation out vec3 f_Normal; // to world matrix : mat3( transpose(inverse(model)) ) * v_normal; out vec3 f_Pos; // INCOMING THE MATRIX FROM CLIENT to transform the gl point position uniform mat4 model; uniform mat4 view; uniform mat4 projection; void main(){ // Transform the world matrix to view matrix //f_Normal = mat3(transpose(inverse(model))) * v_normal; // f_Normal at world matrix //f_TexCoord = v_texCoord; // out TexCoord //f_Pos = vec3(model *v_position); // out fragment position gl_Position = projection * view * model * v_position; }
#define GLEW_STATIC // GLEW #include <GL/glew.h> #include <cstdlib> #undef GLFW_DLL // GLFW #include <GLFW/glfw3.h> #include <iostream> #include "ALG_LoadShader.h" #include "ALG_LoadTexture.h" #include "ALG_GLFWCamera.h" #include "ALG_FrameWindow.h" #include "ALG_ModelDelegate.h" #include "ALG_SceneDelegate.h" #include "ALG_DrawGrid.h" #include <cmath> #include "ALG_OGLHelper.h" #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <map> #include "ALG_DrawEnvBox.h" using namespace AlgebraMaster; const unsigned int SRC_WIDTH = 1400; const unsigned int SRC_HEIGHT = 720; static LoadShader SurfaceShader; void init(); void display(); void processInput(GLFWwindow *window); void framebuffer_size_callback(GLFWwindow* window, int width, int height); // framezize void mouse_callback(GLFWwindow* window, double xpos, double ypos); // Maya Alt+LeftMouse void scroll_callback(GLFWwindow *window, double xoffset, double yoffset); static float lastX = float(SRC_WIDTH) / 2.0f; static float lastY = float(SRC_HEIGHT) / 2.0f; static bool firstMouse = true; static bool firstMiddowMouse = true; // timing static float deltaTime = 0.0f; // time between current frame and last frame static float lastFrame = 0.0f; // cube vao vbo static unsigned int VAO,VBO; // camera static GLFWCamera *camera; // light define static glm::vec3 lightPos(0.0f, 4.0f,-2.0f); static DrawGrid grid; static DrawEnvBox envBox; static LoadTexture cubeTex; static LoadTexture groundTex; static float testPoints[] = { -0.5f, 0.5f, // 左上 0.5f, 0.5f, // 右上 0.5f, -0.5f, // 右下 -0.5f, -0.5f // 左下 }; void init(){ camera = new GLFWCamera; camera->pos.y = 1.0f; camera->pos.z = 4.0f; // GL depth zbuffer glEnable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); SurfaceShader.load( "shaders/SurfaceShader.vert", "shaders/SurfaceShader.frag", "shaders/GeometryShader.geom"); CreateGeometryBuffer(VAO,VBO); glBufferData(GL_ARRAY_BUFFER,sizeof(testPoints),&testPoints,GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), 0); grid.initialize(); } // ----------- Render Loop ---------- void display(){ // per-frame time logic // -------------------- float currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // object .vert settings glm::mat4 projection = glm::perspective(glm::radians(camera->fov),float(SRC_WIDTH) / float(SRC_HEIGHT),0.1f, 1000.0f); glm::mat4 view = camera->GetViewMatrix(); // object world transformation glm::mat4 model = glm::mat4(1.0f); grid.draw(projection,view); SurfaceShader.use(); SurfaceShader.setMatrix(model,view,projection); glBindVertexArray(VAO); glDrawArrays(GL_POINTS,0,4); } int main() { cout << sizeof(float) << endl; glfwInit(); FrameWindow FrameWindow(SRC_WIDTH,SRC_HEIGHT); glfwSetFramebufferSizeCallback(FrameWindow.getWindow(), framebuffer_size_callback); glfwSetCursorPosCallback(FrameWindow.getWindow(),mouse_callback); glfwSetScrollCallback(FrameWindow.getWindow(), scroll_callback); init(); // RENDER-------------- //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); while(!glfwWindowShouldClose(FrameWindow.getWindow())){ processInput(FrameWindow.getWindow()); display(); glfwSwapBuffers(FrameWindow.getWindow()); glfwPollEvents(); } delete camera; return 0; } 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); } void processInput(GLFWwindow *window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) camera->processKeyboardMove(deltaTime,GLFWCamera::FORWARD); if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) camera->processKeyboardMove(deltaTime,GLFWCamera::BACKWARD); if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) camera->processKeyboardMove(deltaTime,GLFWCamera::LEFT); if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) camera->processKeyboardMove(deltaTime,GLFWCamera::RIGHT); } // ROTATE VIEW DIR void mouse_callback(GLFWwindow* window, double xpos, double ypos){ int middow_mouse_state = glfwGetMouseButton(window,GLFW_MOUSE_BUTTON_MIDDLE); int mouse_state = glfwGetMouseButton(window,GLFW_MOUSE_BUTTON_LEFT); int key_state = glfwGetKey(window,GLFW_KEY_LEFT_ALT); // set up the camera view if( mouse_state == GLFW_PRESS && key_state== GLFW_PRESS) { if (firstMouse){ lastX = xpos; lastY = ypos; firstMouse = false; } float xoffset = xpos - lastX; float yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top lastX = xpos; lastY = ypos; camera->processMouseMove(xoffset,yoffset); } if (key_state == GLFW_RELEASE || mouse_state == GLFW_RELEASE){ firstMouse = true; } // Move Camera Position if( middow_mouse_state == GLFW_PRESS) { if (firstMiddowMouse){ lastX = xpos; lastY = ypos; firstMiddowMouse = false; } float xoffset = xpos - lastX; float yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top lastX = xpos; lastY = ypos; camera->pos.x += xoffset*0.01f; camera->pos.y += yoffset*0.01f; } if ( middow_mouse_state == GLFW_RELEASE){ firstMiddowMouse = true; } } void scroll_callback(GLFWwindow *window, double xoffset, double yoffset){ camera->processFov(yoffset); }
以上是关于-OPENGL7-的主要内容,如果未能解决你的问题,请参考以下文章