int compile_and_link_shader(ShaderGLSL & shader, int typeMask, const char * sourceBuffer, int bufferSize) { // Create program object shader.program = glCreateProgram(); //Handle Vertex Shader GLuint vertexShaderObject ; if (typeMask & ShaderGLSL::VERTEX_SHADER) { // Create shader object for vertex shader vertexShaderObject = glCreateShader(GL_VERTEX_SHADER); // Add #define VERTEX to buffer const char * sc[3] = { "#version 150\n", "#define VERTEX\n", sourceBuffer}; glShaderSource(vertexShaderObject, 3, sc, NULL); // Compile shader glCompileShader(vertexShaderObject); // Get error log size and print it eventually int logLength; glGetShaderiv(vertexShaderObject, GL_INFO_LOG_LENGTH, &logLength); if (logLength > 1) { char * log = new char[logLength]; glGetShaderInfoLog(vertexShaderObject, logLength, &logLength, log); fprintf(stderr, "Error in compiling vertex shader : %s", log); fprintf(stderr, "%s\n%s\n%s", sc[0], sc[1], sc[2]); delete[] log; } // If an error happend quit int status; glGetShaderiv(vertexShaderObject, GL_COMPILE_STATUS, &status); if (status == GL_FALSE) return -1; //Attach shader to program glAttachShader(shader.program, vertexShaderObject); } // Handle Geometry shader GLuint geometryShaderObject ; if (typeMask & ShaderGLSL::GEOMETRY_SHADER) { // Create shader object for Geometry shader geometryShaderObject = glCreateShader(GL_GEOMETRY_SHADER); // Add #define Geometry to buffer const char * sc[3] = { "#version 150\n", "#define GEOMETRY\n", sourceBuffer}; glShaderSource(geometryShaderObject, 3, sc, NULL); // Compile shader glCompileShader(geometryShaderObject); // Get error log size and print it eventually int logLength; glGetShaderiv(geometryShaderObject, GL_INFO_LOG_LENGTH, &logLength); if (logLength > 1) { char * log = new char[logLength]; glGetShaderInfoLog(geometryShaderObject, logLength, &logLength, log); fprintf(stderr, "Error in compiling Geometry shader : %s \n", log); fprintf(stderr, "%s\n%s\n%s", sc[0], sc[1], sc[2]); delete[] log; } // If an error happend quit int status; glGetShaderiv(geometryShaderObject, GL_COMPILE_STATUS, &status); if (status == GL_FALSE) return -1; //Attach shader to program glAttachShader(shader.program, geometryShaderObject); } // Handle Fragment shader GLuint fragmentShaderObject ; if (typeMask && ShaderGLSL::FRAGMENT_SHADER) { // Create shader object for fragment shader fragmentShaderObject = glCreateShader(GL_FRAGMENT_SHADER); // Add #define fragment to buffer const char * sc[3] = { "#version 150\n", "#define FRAGMENT\n", sourceBuffer}; glShaderSource(fragmentShaderObject, 3, sc, NULL); // Compile shader glCompileShader(fragmentShaderObject); // Get error log size and print it eventually int logLength; glGetShaderiv(fragmentShaderObject, GL_INFO_LOG_LENGTH, &logLength); if (logLength > 1) { char * log = new char[logLength]; glGetShaderInfoLog(fragmentShaderObject, logLength, &logLength, log); fprintf(stderr, "Error in compiling fragment shader : %s \n", log); fprintf(stderr, "%s\n%s\n%s", sc[0], sc[1], sc[2]); delete[] log; } // If an error happend quit int status; glGetShaderiv(fragmentShaderObject, GL_COMPILE_STATUS, &status); if (status == GL_FALSE) return -1; //Attach shader to program glAttachShader(shader.program, fragmentShaderObject); } // Bind attribute location glBindAttribLocation(shader.program, 0, "VertexPosition"); glBindAttribLocation(shader.program, 1, "VertexNormal"); glBindAttribLocation(shader.program, 2, "VertexTexCoord"); glBindFragDataLocation(shader.program, 0, "Color"); glBindFragDataLocation(shader.program, 1, "Normal"); // Link attached shaders glLinkProgram(shader.program); // Clean if (typeMask & ShaderGLSL::VERTEX_SHADER) { glDeleteShader(vertexShaderObject); } if (typeMask && ShaderGLSL::GEOMETRY_SHADER) { glDeleteShader(fragmentShaderObject); } if (typeMask && ShaderGLSL::FRAGMENT_SHADER) { glDeleteShader(fragmentShaderObject); } // Get link error log size and print it eventually int logLength; glGetProgramiv(shader.program, GL_INFO_LOG_LENGTH, &logLength); if (logLength > 1) { char * log = new char[logLength]; glGetProgramInfoLog(shader.program, logLength, &logLength, log); fprintf(stderr, "Error in linking shaders : %s \n", log); delete[] log; } int status; glGetProgramiv(shader.program, GL_LINK_STATUS, &status); if (status == GL_FALSE) return -1; return 0; }
virtual void startup() { static const char * vs_source[] = { "#version 410 core \n" " \n" "in vec4 position; \n" " \n" "uniform mat4 mv_matrix; \n" "uniform mat4 proj_matrix; \n" " \n" "void main(void) \n" "{ \n" " gl_Position = proj_matrix * mv_matrix * position; \n" "} \n" }; static const char * fs_source[] = { "#version 410 core \n" " \n" "out vec4 color; \n" " \n" "void main(void) \n" "{ \n" " color = vec4(1.0) ; \n" "} \n" }; program = glCreateProgram(); GLuint fs = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fs, 1, fs_source, NULL); glCompileShader(fs); GLuint vs = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vs, 1, vs_source, NULL); glCompileShader(vs); glAttachShader(program, vs); glAttachShader(program, fs); glLinkProgram(program); mv_location = glGetUniformLocation(program, "mv_matrix"); proj_location = glGetUniformLocation(program, "proj_matrix"); glGenVertexArrays(1, &vao); glBindVertexArray(vao); static const GLushort vertex_indices[] = { 0, 1, 2, 2, 1, 3, 2, 3, 4, 4, 3, 5, 4, 5, 6, 6, 5, 7, 6, 7, 0, 0, 7, 1, 6, 0, 2, 2, 4, 6, 7, 5, 3, 7, 3, 1 }; static const GLfloat vertex_positions[] = { -0.25f, -0.25f, -0.25f, -0.25f, 0.25f, -0.25f, 0.25f, -0.25f, -0.25f, 0.25f, 0.25f, -0.25f, 0.25f, -0.25f, 0.25f, 0.25f, 0.25f, 0.25f, -0.25f, -0.25f, 0.25f, -0.25f, 0.25f, 0.25f, }; glGenBuffers(1, &position_buffer); glBindBuffer(GL_ARRAY_BUFFER, position_buffer); glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_positions), vertex_positions, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL); glEnableVertexAttribArray(0); glGenBuffers(1, &index_buffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_buffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(vertex_indices), vertex_indices, GL_STATIC_DRAW); glEnable(GL_CULL_FACE); }
/////////////////////////////////////////////////////// // // This routine creates the shader program, including the vertex shader and fragment shader objects // GLuint SetupGLSL(char *fileName){ GLuint programObject; GLuint vertexShaderObject; GLuint fragmentShaderObject; check_graphics(); // check the capability of the graphics card in use programObject = glCreateProgram(); // create an overall shader program if (programObject == 0) { // error checking printf(" Error creating shader program object.\n"); exit(1); } else printf(" Succeeded creating shader program object.\n"); vertexShaderObject = glCreateShader(GL_VERTEX_SHADER); if (vertexShaderObject == 0) { // error checking printf(" Error creating vertex shader object.\n"); exit(1); } else printf(" Succeeded creating vertex shader object.\n"); fragmentShaderObject = glCreateShader(GL_FRAGMENT_SHADER); if (fragmentShaderObject == 0) { // error checking printf(" Error creating fragment shader object.\n"); exit(1); } else printf(" Succeeded creating fragment shader object.\n"); // now input the vertex and fragment programs as ascii readShaderSource(fileName, &vertexShaderSource, &fragmentShaderSource); glShaderSource(vertexShaderObject,1,(const GLchar**)&vertexShaderSource,NULL); glShaderSource(fragmentShaderObject,1,(const GLchar**)&fragmentShaderSource,NULL); // now compile the shader code; vertex shader first, followed by fragment shader glCompileShader(vertexShaderObject); // error checking and printing out log if error GLint result; glGetShaderiv(vertexShaderObject, GL_COMPILE_STATUS, &result); if (result == GL_FALSE) { printf(" vertex shader compilation failed!\n"); GLint logLen; glGetShaderiv(vertexShaderObject, GL_INFO_LOG_LENGTH, &logLen); if (logLen > 0) { char *log = (char*) malloc(logLen); GLsizei written; glGetShaderInfoLog(vertexShaderObject, logLen, &written, log); printf("Sahder log: \n %s", log); free(log); } } glCompileShader(fragmentShaderObject); glGetShaderiv(fragmentShaderObject, GL_COMPILE_STATUS, &result); if (result == GL_FALSE) { printf(" fragment shader compilation failed!\n"); GLint logLen; glGetShaderiv(fragmentShaderObject, GL_INFO_LOG_LENGTH, &logLen); if (logLen > 0) { char *log = (char*) malloc(logLen); GLsizei written; glGetShaderInfoLog(fragmentShaderObject, logLen, &written, log); printf("Sahder log: \n %s", log); free(log); } } // insert compiler error checking code later glAttachShader(programObject, vertexShaderObject); glAttachShader(programObject, fragmentShaderObject); glLinkProgram(programObject); // insert linking error checking code later return(programObject); }
/* Inits the shader program for this object */ void GLSphere::initShader(void) { // Vertex shader source code. This draws the vertices in our window. We have 3 vertices since we're drawing an triangle. // Each vertex is represented by a vector of size 4 (x, y, z, w) coordinates. // static const string vertex_code = vs_string_CoordSystem; static const char * vs_source = vs_string_GLSphere_410.c_str(); // Fragment shader source code. This determines the colors in the fragment generated in the shader pipeline. In this case, it colors the inside of our triangle specified by our vertex shader. // static const string fragment_code = fs_string_CoordSystem; static const char * fs_source = fs_string_GLSphere_410.c_str(); // This next section we'll generate the OpenGL program and attach the shaders to it so that we can render our triangle. _program = glCreateProgram(); // We create a shader with our fragment shader source code and compile it. GLuint fs = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fs, 1, &fs_source, NULL); glCompileShader(fs); CheckShader(fs, GL_FRAGMENT_SHADER); // We create a shader with our vertex shader source code and compile it. GLuint vs = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vs, 1, &vs_source, NULL); glCompileShader(vs); CheckShader(vs, GL_VERTEX_SHADER); // We'll attach our two compiled shaders to the OpenGL program. glAttachShader(_program, vs); glAttachShader(_program, fs); glLinkProgram(_program); glUseProgram(_program); _modelMatrix = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, 0.0f)); // Create our model matrix which will halve the size of our model int projectionMatrixLocation = glGetUniformLocation(_program, "projectionMatrixBox"); // Get the location of our projection matrix in the shader _viewMatrixLocation = glGetUniformLocation(_program, "viewMatrixBox"); // Get the location of our view matrix in the shader _modelMatrixLocation = glGetUniformLocation(_program, "modelMatrixBox"); // Get the location of our model matrix in the shader _inverseViewMatrixLocation = glGetUniformLocation(_program, "inverseViewMatrix"); _light_source0._lightPosIdx = glGetUniformLocation(_program, "light_position"); glUniformMatrix4fv(projectionMatrixLocation, 1, GL_FALSE, &projectionMatrix()[0][0] ); // Send our projection matrix to the shader glUniformMatrix4fv(_viewMatrixLocation, 1, GL_FALSE, &viewMatrix()[0][0]); // Send our view matrix to the shader glUniformMatrix4fv(_modelMatrixLocation, 1, GL_FALSE, &_modelMatrix[0][0]); // Send our model matrix to the shader glUniformMatrix4fv(_inverseViewMatrixLocation, 1, GL_FALSE, &invRotatedViewMatrix()[0][0]); /////////////////////////////////////////////////////////////////////////////////////////////// // Material _material._diffuse_material = glm::vec3(1.0, 0.5, 0.0); _material._ambient_material = glm::vec3(1.0, 0.5, 0.0); _material._specular_material = glm::vec3(1.0, 1.0, 1.0); _material._shininess = 12.0; _material._ambientColorPos = glGetUniformLocation(_program, "ambient_color"); _material._diffuseColorPos = glGetUniformLocation(_program, "diffuse_color"); _material._specularColorPos = glGetUniformLocation(_program, "specular_color"); _material._shininessIdx = glGetUniformLocation(_program, "shininess"); // Send the material to your shader program glUniform3fv(_material._ambientColorPos, 1, &_material._ambient_material[0] ); glUniform3fv(_material._diffuseColorPos, 1, &_material._diffuse_material[0]); glUniform3fv(_material._specularColorPos, 1, &_material._specular_material[0]); glUniform1f(_material._shininessIdx, _material._shininess); /////////////////////////////////////////////////////////////////////////////////////////////// // Light // define the position of the light and send the light position to your shader program _light_source0._lightPos = glm::vec4(50.0,50.0,0.0,1.0); _light_source0._ambient_intensity = 0.5; _light_source0._specular_intensity = 1.0; _light_source0._diffuse_intensity = 1.0; _light_source0._ambientIdx = glGetUniformLocation(_program, "ambient_intensity"); _light_source0._diffuseIdx = glGetUniformLocation(_program, "diffuse_intensity"); _light_source0._specularIdx = glGetUniformLocation(_program, "specular_intensity"); // Send the light information to your shader program glUniform1f(_light_source0._ambientIdx, _light_source0._ambient_intensity ); glUniform1f(_light_source0._diffuseIdx, _light_source0._diffuse_intensity); glUniform1f(_light_source0._specularIdx, _light_source0._specular_intensity); glUniform4fv(_light_source0._lightPosIdx, 1, &_light_source0._lightPos[0]); /////////////////////////////////////////////////////////////////////////////////////////////// // Vertex information / names // bind the to the shader program glBindAttribLocation(_program, 0, "in_Position"); glBindAttribLocation(_program, 1, "in_Normal"); glBindAttribLocation(_program, 2, "in_Color"); glUseProgram(0); }
/** * Add a Vertex- / Fragment or a GeometryShader from file * @param type Type of shader - GL_VERTEX_SHADER, GL_FRAGMENT_SHADER or GL_GEOMETRY_SHADER * @param filename filename of the shader to be loaded */ bool SciIllLib::CGLShaderProgram::addShaderFromSourceFile(GLenum type, const char* filename) { if (m_hndProgram <= 0) { m_hndProgram = glCreateProgram(); } std::fstream shaderFile(filename, std::ios::in); std::string sShader; const char * szShader; if (shaderFile.is_open()) { std::stringstream buffer; buffer << shaderFile.rdbuf(); sShader = buffer.str(); } else { std::cout << "Failed to read file: " << filename << std::endl; return false; }; shaderFile.close(); // removeAllShaders(); //TODO cleanup shaders! GLuint hndShader = glCreateShader(type); szShader = sShader.c_str(); glShaderSource(hndShader, 1, (const char**) &szShader, NULL); glCompileShader(hndShader); // check result int compiled = 0, length = 0, laux = 0; glGetShaderiv(hndShader, GL_COMPILE_STATUS, &compiled); if (compiled == GL_TRUE) { if (type == GL_VERTEX_SHADER) { if (m_hndVertex > 0) { glDetachShader(m_hndProgram, m_hndVertex); glDeleteShader(m_hndVertex); } m_qstrVertex = filename; m_hndVertex = hndShader; glAttachShader(m_hndProgram, m_hndVertex); } else if (type == GL_FRAGMENT_SHADER) { if (m_hndFragment > 0) { glDetachShader(m_hndProgram, m_hndFragment); glDeleteShader(m_hndFragment); } m_qstrFragment = filename; m_hndFragment = hndShader; glAttachShader(m_hndProgram, m_hndFragment); } else if (type == GL_GEOMETRY_SHADER) { if (m_hndGeometry > 0) { glDetachShader(m_hndProgram, m_hndGeometry); glDeleteShader(m_hndGeometry); } m_qstrGeometry = filename; m_hndGeometry = hndShader; glAttachShader(m_hndProgram, m_hndGeometry); } return true; } else { glGetShaderiv(hndShader, GL_INFO_LOG_LENGTH, &length); char *logString = new char[length]; glGetShaderInfoLog(hndShader, length, &laux, logString); std::cout << "Couldn't compile shader - " << filename << std::endl; std::cout << logString << std::endl; return false; } }
const Shader& Shader::Compile() const { glCompileShader(mShader); assert(checkInfoLog(mShader, GL_COMPILE_STATUS, glGetShaderiv, glGetShaderInfoLog) == true); return (*this); }
void Label::Init(int winW, int winH, float posX, float posY, int fontsize, std::string textToDraw) { winWidth = winW; winHeight = winH; ix = posX; iy = posY; iwidth = fontsize; iheight = fontsize; x = posX; y = posY; width = fontsize; height = fontsize; labelText = textToDraw; x /= winWidth; y /= winHeight; width /= winWidth; height /= winHeight; static const GLfloat vertex_positions[] = { -0.5f, 0.5f, 0, -0.5f, -0.5f, 0, 0.5f, -0.5f, 0, 0.5f, -0.5f, 0, 0.5f, 0.5f, 0, -0.5f, 0.5f, 0, }; static const GLushort vertex_indices[] = { 0, 1, 2, 2, 4, 0 }; static const char * vs_source[] = { "#version 410 core \n" " \n" "in vec4 position2; \n" "in vec2 texPos; \n" "out VS_OUT \n" "{ \n" " vec4 color; \n" " vec2 tc; \n" "} vs_out; \n" " \n" "uniform mat4 mv_matrix; \n" "uniform mat4 proj_matrix; \n" "uniform vec4 btnColor; \n" " \n" "const vec2[6] texPos2 = vec2[6](vec2(0.0f, 1.0f), \n" " vec2(0.0f, 0.0f), \n" " vec2(1.0f, 0.0f), \n" " vec2(1.0f, 0.0f), \n" " vec2(1.0f, 1.0f), \n" " vec2(0.0f, 1.0f)); \n" "void main(void) \n" "{ \n" " gl_Position = mv_matrix*position2; \n" " vs_out.tc = texPos.xy; \n" " vs_out.color = btnColor; \n" "} \n" }; static const char * fs_source[] = { "#version 410 core \n" " \n" "out vec4 color; \n" "uniform sampler2D sss; \n" "in VS_OUT \n" "{ \n" " vec4 color; \n" " vec2 tc; \n" "} fs_in; \n" " \n" "void main(void) \n" "{ \n" " color = texture(sss, fs_in.tc )*fs_in.color; \n" "} \n" }; GLuint fs = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fs, 1, fs_source, NULL); glCompileShader(fs); GLuint vs = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vs, 1, vs_source, NULL); glCompileShader(vs); program = glCreateProgram(); glAttachShader(program, vs); glAttachShader(program, fs); glLinkProgram(program); glDeleteShader(vs); glDeleteShader(fs); mv_location = glGetUniformLocation(program, "mv_matrix"); proj_location = glGetUniformLocation(program, "proj_matrix"); btnColor = glGetUniformLocation(program, "btnColor"); glGenVertexArrays(1, &vao); glBindVertexArray(vao); //vertecies glGenBuffers(1, &positionBuffer); glBindBuffer(GL_ARRAY_BUFFER, positionBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_positions), vertex_positions, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL); //texture coordinates glGenBuffers(1, &texCoordBuffer); glBindBuffer(GL_ARRAY_BUFFER, texCoordBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(tex_coords_pos), tex_coords_pos, GL_STATIC_DRAW); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, NULL); LoadPNGTexture(); glBindVertexArray(0); }
// // Install our shader programs and tell GL to use them. // We also initialize the uniform variables. // void installShaders(void) { // // (1) Create shader objects // vertexShader = glCreateShader(GL_VERTEX_SHADER); fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); // // (2) Load source code into shader objects. // const GLchar *vertexShaderSource = getShaderSource("vertex.vs"); const GLchar *fragmentShaderSource = getShaderSource("fragment.fs"); glShaderSource(vertexShader, 1, &vertexShaderSource, NULL); glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL); // // (3) Compile shaders. // glCompileShader(vertexShader); GLint success; glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success); if (!success) { GLchar infoLog[200]; GLint charsWritten; glGetShaderInfoLog(vertexShader, sizeof(infoLog), &charsWritten, infoLog); fprintf(stderr, "vertex shader info log:\n%s\n\n", infoLog); } checkOpenGLError(__LINE__); glCompileShader(fragmentShader); glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success); if (!success) { GLchar infoLog[200]; GLint charsWritten; glGetShaderInfoLog(fragmentShader, sizeof(infoLog), &charsWritten, infoLog); fprintf(stderr, "fragment shader info log:\n%s\n\n", infoLog); } checkOpenGLError(__LINE__); // // (4) Create program object and attach vertex and fragment shader. // program = glCreateProgram(); glAttachShader(program, vertexShader); glAttachShader(program, fragmentShader); checkOpenGLError(__LINE__); // // (5) Link program. // glLinkProgram(program); glGetProgramiv(program, GL_LINK_STATUS, &success); if (!success) { GLchar infoLog[200]; GLint charsWritten; glGetProgramInfoLog(program, sizeof(infoLog), &charsWritten, infoLog); fprintf(stderr, "program info log:\n%s\n\n", infoLog); } checkOpenGLError(__LINE__); // // (7) Get vertex attribute locations // vertexPositionAttr = glGetAttribLocation(program, "vertexPosition"); vertexNormalAttr = glGetAttribLocation(program, "vertexNormal"); if (vertexPositionAttr == -1 || vertexNormalAttr == -1) { fprintf(stderr, "Error fetching vertex position or normal attribute!\n"); exit(-1); } // // (8) Fetch handles for uniform variables in program. // ModelViewProjectionUniform = glGetUniformLocation(program, "ModelViewProjection"); if (ModelViewProjectionUniform == -1) { fprintf(stderr, "Error fetching modelViewProjectionUniform !\n"); exit(-1); } ModelViewMatrixUniform = glGetUniformLocation(program, "ModelViewMatrix"); if (ModelViewMatrixUniform == -1) { fprintf(stderr, "Error fetching modelViewMatrixUniform!\n"); // exit(-1); } NormalMatrixUniform = glGetUniformLocation(program, "NormalMatrix"); if (NormalMatrixUniform == -1) { fprintf(stderr, "Error fetching normalMatrixUniform!\n"); // exit(-1); } ambientLightUniform = glGetUniformLocation(program, "ambientLight"); if (ambientLightUniform == -1) { fprintf(stderr, "Error fetching ambientLightUniform!\n"); exit(-1); } light0ColorUniform = glGetUniformLocation(program, "light0Color"); if (light0ColorUniform == -1) { fprintf(stderr, "Error fetching light0ColorUniform!\n"); // exit(-1); } light0PositionUniform = glGetUniformLocation(program, "light0Position"); if (light0PositionUniform == -1) { fprintf(stderr, "Error fetching light0PositionUniform!\n"); // exit(-1); } materialAmbientUniform = glGetUniformLocation(program, "materialAmbient"); if (materialAmbientUniform == -1) { fprintf(stderr, "Error fetching materialAmbientUniform!\n"); // exit(-1); } materialDiffuseUniform = glGetUniformLocation(program, "materialDiffuse"); if (materialDiffuseUniform == -1) { fprintf(stderr, "Error fetching materialDiffuseUniform!\n"); //exit(-1); } materialSpecularUniform = glGetUniformLocation(program, "materialSpecular"); materialShininessUniform = glGetUniformLocation(program, "materialShininess"); // // (9) Tell GL to use our program // glUseProgram(program); }
bool GLSLESProgram::compile(const bool checkErrors) { if (mCompiled == 1) { return true; } // Only create a shader object if glsl es is supported if (isSupported()) { GL_CHECK_ERROR // Create shader object GLenum shaderType = 0x0000; if (mType == GPT_VERTEX_PROGRAM) { shaderType = GL_VERTEX_SHADER; } else if (mType == GPT_FRAGMENT_PROGRAM) { shaderType = GL_FRAGMENT_SHADER; } mGLShaderHandle = glCreateShader(shaderType); GL_CHECK_ERROR #if GL_EXT_debug_label && OGRE_PLATFORM != OGRE_PLATFORM_NACL glLabelObjectEXT(GL_SHADER_OBJECT_EXT, mGLShaderHandle, 0, mName.c_str()); #endif if(Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_SEPARATE_SHADER_OBJECTS)) { mGLProgramHandle = glCreateProgram(); GL_CHECK_ERROR #if GL_EXT_debug_label && OGRE_PLATFORM != OGRE_PLATFORM_NACL glLabelObjectEXT(GL_PROGRAM_OBJECT_EXT, mGLProgramHandle, 0, mName.c_str()); #endif } } // Add preprocessor extras and main source if (!mSource.empty()) { const char *source = mSource.c_str(); glShaderSource(mGLShaderHandle, 1, &source, NULL); // Check for load errors GL_CHECK_ERROR } if (checkErrors) logObjectInfo("GLSL ES compiling: " + mName, mGLShaderHandle); glCompileShader(mGLShaderHandle); GL_CHECK_ERROR // Check for compile errors glGetShaderiv(mGLShaderHandle, GL_COMPILE_STATUS, &mCompiled); if(!mCompiled && checkErrors) { String message = logObjectInfo("GLSL ES compile log: " + mName, mGLShaderHandle); checkAndFixInvalidDefaultPrecisionError(message); } // Log a message that the shader compiled successfully. if (mCompiled && checkErrors) logObjectInfo("GLSL ES compiled: " + mName, mGLShaderHandle); if(!mCompiled) OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, ((mType == GPT_VERTEX_PROGRAM) ? "Vertex Program " : "Fragment Program ") + mName + " failed to compile. See compile log above for details.", "GLSLESProgram::compile"); return (mCompiled == 1); }
/////////////////////////////////////////////////////////////////////// //load, compile and set the shaders void setShaders() { char *vs,*fs,*gs; v = glCreateShader(GL_VERTEX_SHADER); f = glCreateShader(GL_FRAGMENT_SHADER); g = glCreateShader(GL_GEOMETRY_SHADER); vs = textFileRead(const_cast<char *>("./shader03.vert")); fs = textFileRead(const_cast<char *>("./shader03.frag")); gs = textFileRead(const_cast<char *>("./shader03.geom")); const char * ff = fs; const char * vv = vs; const char * gg = gs; glShaderSource(v, 1, &vv,NULL); glShaderSource(f, 1, &ff,NULL); glShaderSource(g, 1, &gg,NULL); free(vs);free(fs);free(gs); glCompileShader(v); glCompileShader(f); glCompileShader(g); GLint blen = 0; GLsizei slen = 0; glGetShaderiv(v, GL_INFO_LOG_LENGTH , &blen); if (blen > 1) { GLchar* compiler_log = (GLchar*)malloc(blen); glGetShaderInfoLog(v, blen, &slen, compiler_log); std::cout << "compiler_log vertex shader:\n" << compiler_log << std::endl; free (compiler_log); } blen = 0; slen = 0; glGetShaderiv(f, GL_INFO_LOG_LENGTH , &blen); if (blen > 1) { GLchar* compiler_log = (GLchar*)malloc(blen); glGetShaderInfoLog(f, blen, &slen, compiler_log); std::cout << "compiler_log fragment shader:\n" << compiler_log << std::endl; free (compiler_log); } blen = 0; slen = 0; glGetShaderiv(g, GL_INFO_LOG_LENGTH , &blen); if (blen > 1) { GLchar* compiler_log = (GLchar*)malloc(blen); glGetShaderInfoLog(g, blen, &slen, compiler_log); std::cout << "compiler_log geometry shader:\n" << compiler_log << std::endl; free (compiler_log); } p = glCreateProgram(); glAttachShader(p,f); glAttachShader(p,v); glAttachShader(p,g); glLinkProgram(p); // comment out this line to not use the shader glUseProgram(p); GLint loc = glGetUniformLocation(p, "ambientColor"); if (loc != -1) { GL_CHECK(glUniform4f(loc, 1.0,0.0,0.0,1.0)); } loc = glGetUniformLocation(p, "diffuseColor"); if (loc != -1) { GL_CHECK(glUniform4f(loc, 1.0,1.0,1.0,1.0)); } loc = glGetUniformLocation(p, "specularColor"); if (loc != -1) { GL_CHECK(glUniform4f(loc, 1.0,1.0,1.0,1.0)); } loc = glGetUniformLocation(p, "specularExponent"); if (loc != -1) { GL_CHECK(glUniform1f(loc, 25.0)); } }
///////////////////////////////////////////////////////////////// // Load a pair of shaders, compile, and link together. Specify the complete // file path for each shader. Note, there is no support for // just loading say a vertex program... you have to do both. GLuint gltLoadShaderPair(const char *szVertexProg, const char *szFragmentProg, bool loadFromFile) { // Temporary Shader objects GLuint hVertexShader; GLuint hFragmentShader; GLuint hReturn = 0; GLint testVal; // Create shader objects hVertexShader = glCreateShader(GL_VERTEX_SHADER); hFragmentShader = glCreateShader(GL_FRAGMENT_SHADER); if (loadFromFile) { if(gltLoadShaderFile(szVertexProg, hVertexShader) == false) { glDeleteShader(hVertexShader); glDeleteShader(hFragmentShader); return (GLuint)NULL; } if(gltLoadShaderFile(szFragmentProg, hFragmentShader) == false) { glDeleteShader(hVertexShader); glDeleteShader(hFragmentShader); return (GLuint)NULL; } } else { gltLoadShaderSrc(vertexShader, hVertexShader); gltLoadShaderSrc(fragmentShader, hFragmentShader); } // Compile them glCompileShader(hVertexShader); glCompileShader(hFragmentShader); // Check for errors glGetShaderiv(hVertexShader, GL_COMPILE_STATUS, &testVal); if(testVal == GL_FALSE) { char temp[256] = ""; glGetShaderInfoLog( hVertexShader, 256, NULL, temp); fprintf( stderr, "Compile failed:\n%s\n", temp); assert(0); exit(0); glDeleteShader(hVertexShader); glDeleteShader(hFragmentShader); return (GLuint)NULL; } glGetShaderiv(hFragmentShader, GL_COMPILE_STATUS, &testVal); if(testVal == GL_FALSE) { char temp[256] = ""; glGetShaderInfoLog( hFragmentShader, 256, NULL, temp); fprintf( stderr, "Compile failed:\n%s\n", temp); assert(0); exit(0); glDeleteShader(hVertexShader); glDeleteShader(hFragmentShader); return (GLuint)NULL; } // Link them - assuming it works... hReturn = glCreateProgram(); glAttachShader(hReturn, hVertexShader); glAttachShader(hReturn, hFragmentShader); glLinkProgram(hReturn); // These are no longer needed glDeleteShader(hVertexShader); glDeleteShader(hFragmentShader); // Make sure link worked too glGetProgramiv(hReturn, GL_LINK_STATUS, &testVal); if(testVal == GL_FALSE) { glDeleteProgram(hReturn); return (GLuint)NULL; } return hReturn; }
int main(int argc, char *argv[]) { SDL_Surface *screen; if ( SDL_Init(SDL_INIT_VIDEO) != 0 ) { printf("Unable to initialize SDL: %s\n", SDL_GetError()); return 1; } SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); screen = SDL_SetVideoMode( 640, 480, 24, SDL_OPENGL ); if ( !screen ) { printf("Unable to set video mode: %s\n", SDL_GetError()); return 1; } glClearColor( 0, 0, 0, 0 ); glClear( GL_COLOR_BUFFER_BIT ); // Fog glEnable(GL_FOG); glFogf(GL_FOG_START, 100); glFogf(GL_FOG_END, 2000); glFogi(GL_FOG_MODE, GL_LINEAR); GLfloat fogcolor[4] = { 0.9, 0.1, 0.35, 0 }; glFogfv(GL_FOG_COLOR, fogcolor); // Create a texture GLuint texture; glGenTextures( 1, &texture ); glBindTexture( GL_TEXTURE_2D, texture ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); GLubyte textureData[16*16*4]; for (int x = 0; x < 16; x++) { for (int y = 0; y < 16; y++) { *((int*)&textureData[(x*16 + y) * 4]) = x*16 + ((y*16) << 8); } } glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, 16, 16, 0, GL_RGBA, GL_UNSIGNED_BYTE, textureData ); // Create a second texture GLuint texture2; glGenTextures( 1, &texture2 ); glBindTexture( GL_TEXTURE_2D, texture2 ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); GLubyte texture2Data[] = { 0xff, 0, 0, 0xff, 0, 0xff, 0, 0xaa, 0, 0, 0xff, 0x55, 0x80, 0x90, 0x70, 0 }; glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, 2, 2, 0, GL_RGBA, GL_UNSIGNED_BYTE, texture2Data ); // BEGIN #if USE_GLEW glewInit(); #endif glMatrixMode(GL_PROJECTION); glLoadIdentity(); // original: glFrustum(-0.6435469817188064, 0.6435469817188064 ,-0.48266022190470925, 0.48266022190470925 ,0.5400000214576721, 2048); glFrustum(-0.6435469817188064, 0.1435469817188064 ,-0.48266022190470925, 0.88266022190470925 ,0.5400000214576721, 2048); glRotatef(-30, 1, 1, 1); //GLfloat pm[] = { 1.372136116027832, 0, 0, 0, 0, 0.7910231351852417, 0, 0, -0.6352481842041016, 0.29297152161598206, -1.0005275011062622, -1, 0, 0, -1.080284833908081, 0 }; //glLoadMatrixf(pm); glMatrixMode(GL_MODELVIEW); GLfloat matrixData[] = { -1, 0, 0, 0, 0, 0,-1, 0, 0, 1, 0, 0, 0, 0, 0, 1 }; glLoadMatrixf(matrixData); //glTranslated(-512,-512,-527); // XXX this should be uncommented, but if it is then nothing is shown glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glClear(GL_DEPTH_BUFFER_BIT); glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glActiveTexture(GL_TEXTURE0); glEnableClientState(GL_VERTEX_ARRAY); GLuint arrayBuffer, elementBuffer; glGenBuffers(1, &arrayBuffer); glGenBuffers(1, &elementBuffer); GLubyte arrayData[] = { /* [0, 0, 0, 67] ==> 128 float [0, 0, 128, 67] ==> 256 float [0, 0, 0, 68] ==> 512 float [0, 0, 128, 68] ==> 1024 float [vertex x ] [vertex y ] [vertex z ] [nr] [texture u ] [texture v ] [lm u ] [lm v ] [color r,g,b,a ] */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 68, 11, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, // 0 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 68, 23, 20, 0, 0, 0, 0, 0, 67, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, // 1 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 35, 30, 0, 0, 0, 0, 0, 67, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 2 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 68, 47, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 3 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 68, 51, 50, 0, 0, 0, 0, 0, 67, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, // 4 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 68, 64, 60, 0, 0, 0, 0, 128, 67, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, // 5 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 68, 70, 70, 0, 0, 0, 0, 128, 67, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 6 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 89, 80, 0, 0, 0, 0, 0, 67, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 7 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 68, 94, 90, 0, 0, 0, 0, 0, 0, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 8 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 20, 10, 0, 0, 0, 0, 0, 67, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 9 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 68, 31, 20, 0, 0, 0, 0, 0, 67, 0, 0, 128, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 10 0, 0, 0, 0, 0, 0, 128, 68, 0, 0, 0, 68, 42, 30, 0, 0, 0, 0, 0, 0, 0, 0, 128, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 11 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 53, 40, 0, 0, 0, 0, 0, 67, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 12 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 68, 64, 50, 0, 0, 0, 0, 128, 67, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 13 0, 0, 128, 68, 0, 0, 128, 68, 0, 0, 0, 68, 75, 60, 0, 0, 0, 0, 128, 67, 0, 0, 128, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 14 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 68, 86, 70, 0, 0, 0, 0, 0, 67, 0, 0, 128, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 15 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 128, 68, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128 }; assert(sizeof(arrayData) == 1408); glBindBuffer(GL_ARRAY_BUFFER, arrayBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(arrayData), arrayData, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); GLushort elementData[] = { 1, 2, 0, 2, 3, 0, 5, 6, 4, 6, 7, 4, 9, 10, 8, 10, 11, 8, 13, 14, 12, 14, 15, 12 }; assert(sizeof(elementData) == 48); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementBuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elementData), elementData, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, arrayBuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementBuffer); // sauer vertex data is apparently 0-12: V3F, 12: N1B, 16-24: T2F, 24-28: T2S, 28-32: C4B glVertexPointer(3, GL_FLOAT, 32, (void*)0); // all these apply to the ARRAY_BUFFER that is bound glTexCoordPointer(2, GL_FLOAT, 32, (void*)16); glClientActiveTexture(GL_TEXTURE1); // XXX seems to be ignored in native build glTexCoordPointer(2, GL_SHORT, 32, (void*)24); glClientActiveTexture(GL_TEXTURE0); // likely not needed, it is a cleanup glNormalPointer(GL_BYTE, 32, (void*)12); glColorPointer(4, GL_UNSIGNED_BYTE, 32, (void*)28); glBindTexture(GL_TEXTURE_2D, texture); // diffuse? glActiveTexture(GL_TEXTURE0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, texture2); // lightmap? glActiveTexture(GL_TEXTURE0); GLint ok; const char *vertexShader = "uniform vec4 texgenscroll;\n" "void main(void)\n" "{\n" " gl_Position = ftransform();\n" " gl_TexCoord[0].xy = gl_MultiTexCoord0.xy/10000.0 + (0.001*texgenscroll.xy) + gl_Normal.xy;\n" // added /100 here " gl_TexCoord[1].xy = gl_MultiTexCoord1.xy/100.0 * 3.051851e-05;\n" " gl_FogFragCoord = gl_Position.z;\n" "}\n"; const char *fragmentShader = "uniform vec4 colorparams;\n" "uniform sampler2D diffusemap, lightmap;\n" "void main(void)\n" "{\n" " vec4 diffuse = texture2D(diffusemap, gl_TexCoord[0].xy);\n" " vec4 lm = texture2D(lightmap, gl_TexCoord[1].xy);\n" " diffuse *= colorparams;\n" " vec4 color = diffuse * lm;\n" " gl_FragColor.rgb = mix((gl_Fog.color).rgb, color.rgb, clamp((gl_Fog.end - gl_FogFragCoord) * gl_Fog.scale, 0.0, 1.0));\n" //" gl_FragColor.rgb = 0.0001 * color.rgb + ((gl_Fog.color).rgb * (1.0-clamp((gl_FogFragCoord)* 1.0/1000.0, 0.0, 1.0)));\n" "}\n"; GLuint vs = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vs, 1, &vertexShader, NULL); glCompileShader(vs); glGetShaderiv(vs, GL_COMPILE_STATUS, &ok); assert(ok); GLuint fs = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fs, 1, &fragmentShader, NULL); glCompileShader(fs); glGetShaderiv(fs, GL_COMPILE_STATUS, &ok); assert(ok); GLuint program = glCreateProgram(); glAttachShader(program, vs); glAttachShader(program, fs); glLinkProgram(program); glGetProgramiv(program, GL_LINK_STATUS, &ok); assert(ok); glUseProgram(program); GLint lightmapLocation = glGetUniformLocation(program, "lightmap"); assert(lightmapLocation >= 0); glUniform1i(lightmapLocation, 1); // sampler2D? Is it the texture unit? GLint diffusemapLocation = glGetUniformLocation(program, "diffusemap"); assert(diffusemapLocation >= 0); glUniform1i(diffusemapLocation, 0); GLint texgenscrollLocation = glGetUniformLocation(program, "texgenscroll"); assert(texgenscrollLocation >= 0); GLint colorparamsLocation = glGetUniformLocation(program, "colorparams"); assert(colorparamsLocation >= 0); GLfloat texgenscrollData[] = { 0, 0, 0, 0 }; glUniform4fv(texgenscrollLocation, 1, texgenscrollData); GLfloat colorparamsData[] = { 2, 2, 2, 1 }; glUniform4fv(colorparamsLocation, 1, colorparamsData); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*)12); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*) 0); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*)24); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*)36); // END SDL_GL_SwapBuffers(); verify(); #if !EMSCRIPTEN SDL_Delay(1500); #endif SDL_Quit(); return 0; }
/*! adds a shader object */ shader_object* shader::add_shader_src(const string& identifier, const string& option, ext::GLSL_VERSION glsl_version, const char* vs_text, const char* gs_text, const char* fs_text) { // success flag (if it's 1 (true), we successfully created a shader object) int success; GLchar info_log[A2E_SHADER_LOG_SIZE]; if(gs_text != nullptr && strcmp(gs_text, "") == 0) gs_text = nullptr; // create a new shader object if none exists for this identifier if(shaders.count(identifier) == 0) { shaders[identifier] = new shader_object(identifier); } // add a new program object to this shader shaders[identifier]->programs.push_back(new shader_object::internal_shader_object()); if(option != "") { shaders[identifier]->options[option] = shaders[identifier]->programs.back(); } shader_object::internal_shader_object& shd_obj = *shaders[identifier]->programs.back(); shaders[identifier]->glsl_version = std::max(shaders[identifier]->glsl_version, glsl_version); // create the vertex shader object shd_obj.vertex_shader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(shd_obj.vertex_shader, 1, (GLchar const**)&vs_text, nullptr); glCompileShader(shd_obj.vertex_shader); glGetShaderiv(shd_obj.vertex_shader, GL_COMPILE_STATUS, &success); if(!success) { glGetShaderInfoLog(shd_obj.vertex_shader, A2E_SHADER_LOG_SIZE, nullptr, info_log); log_error("Error in vertex shader \"%s/%s\" compilation!", identifier, option); log_pretty_print(info_log, vs_text); return 0; } #if !defined(FLOOR_IOS) // create the geometry shader object if(gs_text != nullptr && strcmp(gs_text, "") != 0) { shd_obj.geometry_shader = glCreateShader(GL_GEOMETRY_SHADER); glShaderSource(shd_obj.geometry_shader, 1, (GLchar const**)&gs_text, nullptr); glCompileShader(shd_obj.geometry_shader); glGetShaderiv(shd_obj.geometry_shader, GL_COMPILE_STATUS, &success); if(!success) { glGetShaderInfoLog(shd_obj.geometry_shader, A2E_SHADER_LOG_SIZE, nullptr, info_log); log_error("Error in geometry shader \"%s/%s\" compilation!", identifier, option); log_pretty_print(info_log, gs_text); return 0; } } else shd_obj.geometry_shader = 0; #else if(gs_text != nullptr && strcmp(gs_text, "") != 0) { log_error("geometry shaders are not supported in OpenGL ES 2.0 or 3.0!"); } shd_obj.geometry_shader = 0; #endif // create the fragment shader object shd_obj.fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(shd_obj.fragment_shader, 1, (GLchar const**)&fs_text, nullptr); glCompileShader(shd_obj.fragment_shader); glGetShaderiv(shd_obj.fragment_shader, GL_COMPILE_STATUS, &success); if(!success) { glGetShaderInfoLog(shd_obj.fragment_shader, A2E_SHADER_LOG_SIZE, nullptr, info_log); log_error("Error in fragment shader \"%s/%s\" compilation!", identifier, option); log_pretty_print(info_log, fs_text); return 0; } // create the program object shd_obj.program = glCreateProgram(); // attach the vertex and fragment shader progam to it glAttachShader(shd_obj.program, shd_obj.vertex_shader); glAttachShader(shd_obj.program, shd_obj.fragment_shader); if(gs_text != nullptr) { glAttachShader(shd_obj.program, shd_obj.geometry_shader); } // WIP: program binary #if defined(A2E_DEBUG_PROGRAM_BINARY) #if defined(__APPLE__) { fstream progcode_vs("/tmp/a2e_shd_code_vs.glsl", fstream::out); progcode_vs << vs_text << endl; progcode_vs.close(); if(shd_obj.geometry_shader != 0) { fstream progcode_gs("/tmp/a2e_shd_code_gs.glsl", fstream::out); progcode_gs << gs_text << endl; progcode_gs.close(); } fstream progcode_fs("/tmp/a2e_shd_code_fs.glsl", fstream::out); progcode_fs << fs_text << endl; progcode_fs.close(); string output_vs = "", output_gs = "", output_fs = ""; core::system("cgc -profile gp4vp -strict -oglsl /tmp/a2e_shd_code_vs.glsl 2>&1", output_vs); if(shd_obj.geometry_shader != 0) { core::system("cgc -profile gp4gp -strict -oglsl -po POINT /tmp/a2e_shd_code_gs.glsl 2>&1", output_gs); } core::system("cgc -profile gp4fp -strict -oglsl /tmp/a2e_shd_code_fs.glsl 2>&1", output_fs); system("rm /tmp/a2e_shd_code_vs.glsl"); if(shd_obj.geometry_shader != 0) { system("rm /tmp/a2e_shd_code_gs.glsl"); } system("rm /tmp/a2e_shd_code_fs.glsl"); // shader_debug::add(identifier, option, output_vs, output_gs, output_fs); } #else if(exts->is_ext_supported("GL_ARB_get_program_binary")) glProgramParameteri(shd_obj.program, GL_PROGRAM_BINARY_RETRIEVABLE_HINT, GL_TRUE); #endif #endif // now link the program object glLinkProgram(shd_obj.program); glGetProgramiv(shd_obj.program, GL_LINK_STATUS, &success); if(!success) { glGetProgramInfoLog(shd_obj.program, A2E_SHADER_LOG_SIZE, nullptr, info_log); log_error("Error in program \"%s/%s\" linkage!\nInfo log: %s", identifier, option, info_log); return 0; } glUseProgram(shd_obj.program); // bind frag data locations (frag_color, frag_color_2, frag_color_3, ...) bool fd_relink = false; #if !defined(FLOOR_IOS) const unsigned int max_draw_buffers = exts->get_max_draw_buffers(); for(unsigned int i = 0; i < max_draw_buffers; i++) { string name = "frag_color"; if(i >= 1) name += "_"+to_string(i+1); const GLint location = glGetFragDataLocation(shd_obj.program, name.c_str()); // check if the frag color exists and must be bound to a different location if(location >= 0 && i != (GLuint)location) { // if so, bind it to the correct location glBindFragDataLocation(shd_obj.program, i, name.c_str()); fd_relink = true; } } #else // NOTE: MRTs are not support in OpenGL ES 2.0 // in OpenGL ES 3.0 the locations are already set in the shader #endif if(fd_relink) { // program must be linked again after the frag data locations were modified // (double-linkage sucks, but there's no other way in opengl 3.2 ...) glLinkProgram(shd_obj.program); } // WIP: program binary #if defined(A2E_DEBUG_PROGRAM_BINARY) #if !defined(__APPLE__) if(exts->is_ext_supported("GL_ARB_get_program_binary")) { GLint binary_length = 0; glGetProgramiv(shd_obj.program, GL_PROGRAM_BINARY_LENGTH, &binary_length); unsigned char* binary = new unsigned char[binary_length]; GLenum binary_format = 0; glGetProgramBinary(shd_obj.program, binary_length, nullptr, &binary_format, binary); string binary_fname = "shader_binary_"+identifier+"_"+to_string(shaders[identifier]->programs.size()-1)+".dat"; f->open_file(binary_fname.c_str(), file_io::OT_WRITE_BINARY); f->write_block((const char*)binary, binary_length, false); f->close_file(); delete [] binary; } #endif #endif // grab number and names of all attributes and uniforms and get their locations (needs to be done before validation, b/c we have to set sampler locations) GLint attr_count = 0, uni_count = 0, max_attr_len = 0, max_uni_len = 0; GLint var_location = 0; GLint var_size = 0; GLenum var_type = 0; glGetProgramiv(shd_obj.program, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &max_attr_len); glGetProgramiv(shd_obj.program, GL_ACTIVE_UNIFORM_MAX_LENGTH, &max_uni_len); glGetProgramiv(shd_obj.program, GL_ACTIVE_ATTRIBUTES, &attr_count); glGetProgramiv(shd_obj.program, GL_ACTIVE_UNIFORMS, &uni_count); max_attr_len+=2; max_uni_len+=2; #if !defined(FLOOR_IOS) || defined(PLATFORM_X64) GLint uni_block_count = 0, max_uni_block_len = 0; glGetProgramiv(shd_obj.program, GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH, &max_uni_block_len); glGetProgramiv(shd_obj.program, GL_ACTIVE_UNIFORM_BLOCKS, &uni_block_count); max_uni_block_len+=2; #endif // note: this may report weird attribute/uniform names (and locations), if uniforms/attributes are optimized away by the compiler bool print_debug_info = false; //if(identifier == "SIMPLE") { /*if(identifier == "FONT") { print_debug_info = true; cout << endl << "## " << identifier << "::" << option << endl; }*/ GLchar* attr_name = new GLchar[(size_t)max_attr_len]; if(print_debug_info) log_undecorated("## shader: %s", identifier); if(print_debug_info) log_undecorated("GL_ACTIVE_ATTRIBUTES: %u", attr_count); for(GLuint attr = 0; attr < (GLuint)attr_count; attr++) { memset(attr_name, 0, (size_t)max_attr_len); glGetActiveAttrib(shd_obj.program, attr, max_attr_len-1, nullptr, &var_size, &var_type, attr_name); var_location = glGetAttribLocation(shd_obj.program, attr_name); if(var_location < 0) { if(print_debug_info) log_error("Warning: could not get location for attribute \"%s\" in shader #%s/%s!", attr_name, identifier, option); continue; } if(print_debug_info) log_undecorated("attribute #%u: %s", var_location, attr_name); string attribute_name = attr_name; if(attribute_name.find("[") != string::npos) attribute_name = attribute_name.substr(0, attribute_name.find("[")); shd_obj.attributes.insert(make_pair(attribute_name, shader_object::internal_shader_object::shader_variable((size_t)var_location, (size_t)var_size, var_type))); } delete [] attr_name; GLchar* uni_name = new GLchar[(size_t)max_uni_len]; if(print_debug_info) log_undecorated("GL_ACTIVE_UNIFORMS: %u", uni_count); for(GLuint uniform = 0; uniform < (GLuint)uni_count; uniform++) { memset(uni_name, 0, (size_t)max_uni_len); glGetActiveUniform(shd_obj.program, uniform, max_uni_len-1, nullptr, &var_size, &var_type, uni_name); var_location = glGetUniformLocation(shd_obj.program, uni_name); if(var_location < 0) { if(print_debug_info) log_error("Warning: could not get location for uniform \"%s\" in shader #%s/%s!", uni_name, identifier, option); continue; } if(print_debug_info) log_undecorated("uniform #%u: %s", var_location, uni_name); string uniform_name = uni_name; if(uniform_name.find("[") != string::npos) uniform_name = uniform_name.substr(0, uniform_name.find("[")); shd_obj.uniforms.insert(make_pair(uniform_name, shader_object::internal_shader_object::shader_variable((size_t)var_location, (size_t)var_size, var_type))); // if the uniform is a sampler, add it to the sampler mapping (with increasing id/num) if(shader_class::is_gl_sampler_type(var_type)) { shd_obj.samplers.insert(make_pair(uniform_name, shd_obj.samplers.size())); // while we are at it, also set the sampler location to a dummy value (this has to be done to satisfy program validation) glUniform1i(var_location, (GLint)shd_obj.samplers.size()-1); } } delete [] uni_name; #if !defined(FLOOR_IOS) || defined(PLATFORM_X64) GLchar* uni_block_name = new GLchar[(size_t)max_uni_block_len]; if(print_debug_info) log_undecorated("GL_ACTIVE_UNIFORM_BLOCKS: %u", uni_block_count); for(GLuint block = 0; block < (GLuint)uni_block_count; block++) { memset(uni_block_name, 0, (size_t)max_uni_block_len); glGetActiveUniformBlockName(shd_obj.program, (GLuint)block, max_uni_block_len-1, nullptr, uni_block_name); GLuint block_index = glGetUniformBlockIndex(shd_obj.program, uni_block_name); if(block_index == GL_INVALID_INDEX) { if(print_debug_info) log_error("Warning: could not get index for uniform block \"%s\" in shader #%s/%s!", uni_block_name, identifier, option); continue; } GLint data_size = 0; glGetActiveUniformBlockiv(shd_obj.program, block_index, GL_UNIFORM_BLOCK_DATA_SIZE, &data_size); if(print_debug_info) log_undecorated("uniform block #%u (size: %u): %s", block_index, data_size, uni_block_name); const string uniform_block_name = uni_block_name; shd_obj.blocks.insert(make_pair(uniform_block_name, shader_object::internal_shader_object::shader_variable(block_index, (size_t)data_size, GL_UNIFORM_BUFFER))); // TODO: handle samplers? } delete [] uni_block_name; #endif // validate the program object glValidateProgram(shd_obj.program); glGetProgramiv(shd_obj.program, GL_VALIDATE_STATUS, &success); if(!success) { glGetProgramInfoLog(shd_obj.program, A2E_SHADER_LOG_SIZE, nullptr, info_log); log_error("Error in program \"%s/%s\" validation!\nInfo log: %s", identifier, option, info_log); return 0; } else { glGetProgramInfoLog(shd_obj.program, A2E_SHADER_LOG_SIZE, nullptr, info_log); // check if shader will run in software (if so, print out a debug message) if(strstr((const char*)info_log, (const char*)"software") != nullptr) { log_debug("program \"%s/%s\" validation: %s", identifier, option, info_log); } } // glUseProgram(0); return shaders[identifier]; }
void mGLES2ShaderInit(struct mGLES2Shader* shader, const char* vs, const char* fs, int width, int height, bool integerScaling, struct mGLES2Uniform* uniforms, size_t nUniforms) { shader->width = width; shader->height = height; shader->integerScaling = integerScaling; shader->filter = false; shader->blend = false; shader->uniforms = uniforms; shader->nUniforms = nUniforms; glGenFramebuffers(1, &shader->fbo); glBindFramebuffer(GL_FRAMEBUFFER, shader->fbo); glGenTextures(1, &shader->tex); glBindTexture(GL_TEXTURE_2D, shader->tex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); if (shader->width > 0 && shader->height > 0) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, shader->width, shader->height, 0, GL_RGB, GL_UNSIGNED_BYTE, 0); } glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, shader->tex, 0); shader->program = glCreateProgram(); shader->vertexShader = glCreateShader(GL_VERTEX_SHADER); shader->fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); const GLchar* shaderBuffer[2]; const GLubyte* version = glGetString(GL_VERSION); if (strncmp((const char*) version, "OpenGL ES ", strlen("OpenGL ES "))) { shaderBuffer[0] = _gl3Header; } else { shaderBuffer[0] = _gles2Header; } if (vs) { shaderBuffer[1] = vs; } else { shaderBuffer[1] = _nullVertexShader; } glShaderSource(shader->vertexShader, 2, shaderBuffer, 0); if (fs) { shaderBuffer[1] = fs; } else { shaderBuffer[1] = _nullFragmentShader; } glShaderSource(shader->fragmentShader, 2, shaderBuffer, 0); glAttachShader(shader->program, shader->vertexShader); glAttachShader(shader->program, shader->fragmentShader); char log[1024]; glCompileShader(shader->fragmentShader); glGetShaderInfoLog(shader->fragmentShader, 1024, 0, log); if (log[0]) { mLOG(OPENGL, ERROR, "%s\n", log); } glCompileShader(shader->vertexShader); glGetShaderInfoLog(shader->vertexShader, 1024, 0, log); if (log[0]) { mLOG(OPENGL, ERROR, "%s\n", log); } glLinkProgram(shader->program); glGetProgramInfoLog(shader->program, 1024, 0, log); if (log[0]) { mLOG(OPENGL, ERROR, "%s\n", log); } shader->texLocation = glGetUniformLocation(shader->program, "tex"); shader->texSizeLocation = glGetUniformLocation(shader->program, "texSize"); shader->positionLocation = glGetAttribLocation(shader->program, "position"); size_t i; for (i = 0; i < shader->nUniforms; ++i) { shader->uniforms[i].location = glGetUniformLocation(shader->program, shader->uniforms[i].name); } glBindFramebuffer(GL_FRAMEBUFFER, 0); }
// Create a GLSL program object from vertex and fragment shader files GLuint InitShader(const char* vShaderFile, const char* fShaderFile) { struct Shader { const char* filename; GLenum type; GLchar* source; } shaders[2] = { { vShaderFile, GL_VERTEX_SHADER, NULL }, { fShaderFile, GL_FRAGMENT_SHADER, NULL } }; GLuint program = glCreateProgram(); for ( int i = 0; i < 2; ++i ) { Shader& s = shaders[i]; s.source = readShaderSource( s.filename ); if ( shaders[i].source == NULL ) { std::cerr << "Failed to read " << s.filename << std::endl; exit( EXIT_FAILURE ); } GLuint shader = glCreateShader( s.type ); glShaderSource( shader, 1, (const GLchar**) &s.source, NULL ); glCompileShader( shader ); GLint compiled; glGetShaderiv( shader, GL_COMPILE_STATUS, &compiled ); if ( !compiled ) { std::cerr << s.filename << " failed to compile:" << std::endl; GLint logSize; glGetShaderiv( shader, GL_INFO_LOG_LENGTH, &logSize ); char* logMsg = new char[logSize]; glGetShaderInfoLog( shader, logSize, NULL, logMsg ); std::cerr << logMsg << std::endl; delete [] logMsg; exit( EXIT_FAILURE ); } delete [] s.source; glAttachShader( program, shader ); } /* link and error check */ glLinkProgram(program); GLint linked; glGetProgramiv( program, GL_LINK_STATUS, &linked ); if ( !linked ) { std::cerr << "Shader program failed to link" << std::endl; GLint logSize; glGetProgramiv( program, GL_INFO_LOG_LENGTH, &logSize); char* logMsg = new char[logSize]; glGetProgramInfoLog( program, logSize, NULL, logMsg ); std::cerr << logMsg << std::endl; delete [] logMsg; exit( EXIT_FAILURE ); } /* use program object */ glUseProgram(program); return program; }
GLuint GLShaderManager::LoadShaderPairSrcWithAttributes( const char* _name, const char* _vertexShader, const char* _pixelShader, ... ) { // Check for duplicate GLuint uiShader = LookupShader( _name, _name ); if( uiShader != 0 ) return uiShader; SHADERLOOKUPETRY shaderEntry; // Temporary Shader objects GLuint hVertexShader; GLuint hPixelShader; GLint testVal; // Create shader objects hVertexShader = glCreateShader(GL_VERTEX_SHADER); hPixelShader = glCreateShader(GL_FRAGMENT_SHADER); // Load them. glsLoadShaderSrc( _vertexShader, hVertexShader ); glsLoadShaderSrc( _pixelShader, hPixelShader ); // Compile them glCompileShader( hVertexShader ); glCompileShader( hPixelShader ); // Check for errors glGetShaderiv( hVertexShader, GL_COMPILE_STATUS, &testVal ); if( testVal == GL_FALSE ) { glDeleteShader( hVertexShader ); glDeleteShader( hPixelShader ); return 0; } glGetShaderiv( hPixelShader, GL_COMPILE_STATUS, &testVal ); if( testVal == GL_FALSE ) { glDeleteShader( hVertexShader ); glDeleteShader( hPixelShader ); return 0; } // Link them - assuming it works... shaderEntry.shaderID = glCreateProgram(); glAttachShader( shaderEntry.shaderID, hVertexShader ); glAttachShader( shaderEntry.shaderID, hPixelShader ); // List of attributes va_list attributeList; va_start( attributeList, _pixelShader ); char *szNextArg; int iArgCount = va_arg( attributeList, int ); // Number of attributes for( int i = 0; i < iArgCount; i++ ) { int index = va_arg( attributeList, int ); szNextArg = va_arg( attributeList, char* ); glBindAttribLocation( shaderEntry.shaderID, index, szNextArg ); } va_end( attributeList ); glLinkProgram( shaderEntry.shaderID ); // These are no longer needed glDeleteShader( hVertexShader ); glDeleteShader( hPixelShader ); // Make sure link worked too glGetProgramiv( shaderEntry.shaderID, GL_LINK_STATUS, &testVal ); if( testVal == GL_FALSE ) { glDeleteProgram( shaderEntry.shaderID ); return 0; } // Add it... strncpy_s( shaderEntry.vertexShaderName, _name, MAX_SHADER_NAME_LENGTH ); strncpy_s( shaderEntry.pixelShaderName, _name, MAX_SHADER_NAME_LENGTH ); // shaderTable.push_back(shaderEntry); return shaderEntry.shaderID; }
bool GLES2Shader::LoadShaderFromString( ShaderContextPtr context, const str_type::string& shaderName, const std::string& codeAsciiString, const Shader::SHADER_FOCUS focus, const Shader::SHADER_PROFILE profile, const char *entry) { if (m_shader != 0) return false; // pVideo->Message(codeAsciiString, GSMT_INFO); const GLuint shader = glCreateShader(GetGLShaderType(focus)); if (shader) { if (m_shaderName == "") m_shaderName = shaderName; m_shaderFocus = focus; m_logger = boost::shared_ptr<Platform::FileLogger>( new Platform::FileLogger(Platform::FileLogger::GetLogDirectory() + Platform::GetFileName(shaderName) + ".log.txt")); m_shader = shader; const char *pSource = codeAsciiString.c_str(); glShaderSource(shader, 1, &pSource, NULL); glCompileShader(shader); GLint compiled = 0; glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled); if (!compiled) { m_context->Log(str_type::string("couldn't compile ") + Platform::GetFileName(shaderName), Platform::FileLogger::ERROR); GLint infoLen = 0; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLen); if (infoLen) { char* buf = new char [infoLen]; if (buf) { glGetShaderInfoLog(shader, infoLen, NULL, buf); std::stringstream ss; ss << "Error: could not compile shader " << shaderName << " (" << buf << ")"; m_logger->Log(ss.str(), Platform::FileLogger::ERROR); m_context->Log(ss.str(), Platform::FileLogger::ERROR); delete [] buf; } glDeleteShader(shader); m_shader = 0; return false; } } else { m_context->Log(shaderName + " successfully created", Platform::FileLogger::INFO); // TODO glReleaseShaderCompiler() ? } } else { std::stringstream ss; ss << "Error: could not create shader " << shaderName; m_logger->Log(ss.str(), Platform::FileLogger::ERROR); } return true; }
ShaderProgram *ShaderCombiner_Compile(DecodedMux *dmux, int flags) { GLint success; char frag[4096]; char *buffer = frag; ShaderProgram *prog = (ShaderProgram*) malloc(sizeof(ShaderProgram)); prog->left = prog->right = NULL; prog->usesT0 = prog->usesT1 = prog->usesCol = prog->usesNoise = 0; prog->combine = dmux->combine; prog->flags = flags; prog->vertex = _vertex_shader; for(int i=0; i < ((flags & SC_2CYCLE) ? 4 : 2); i++) { //make sure were not ignoring cycle: if ((dmux->flags&(1<<i)) == 0) { for(int j=0;j<4;j++) { prog->usesT0 |= (dmux->decode[i][j] == TEXEL0 || dmux->decode[i][j] == TEXEL0_ALPHA); prog->usesT1 |= (dmux->decode[i][j] == TEXEL1 || dmux->decode[i][j] == TEXEL1_ALPHA); prog->usesCol |= (dmux->decode[i][j] == SHADE || dmux->decode[i][j] == SHADE_ALPHA); prog->usesNoise |= (dmux->decode[i][j] == NOISE); } } } buffer += sprintf(buffer, "%s", _frag_header); if (prog->usesT0) buffer += sprintf(buffer, "lowp vec4 lTex0 = texture2D(uTex0, vTexCoord0); \n"); if (prog->usesT1) buffer += sprintf(buffer, "lowp vec4 lTex1 = texture2D(uTex1, vTexCoord1); \n"); if (prog->usesNoise) buffer += sprintf(buffer, "lowp vec4 lNoise = texture2D(uNoise, (1.0 / 1024.0) * gl_FragCoord.st); \n"); for(int i = 0; i < ((flags & SC_2CYCLE) ? 2 : 1); i++) { if ((dmux->flags&(1<<(i*2))) == 0) { buffer += sprintf(buffer, "lFragColor.rgb = (%s - %s) * %s + %s; \n", _color_param_str(dmux->decode[i*2][0]), _color_param_str(dmux->decode[i*2][1]), _color_param_str(dmux->decode[i*2][2]), _color_param_str(dmux->decode[i*2][3]) ); } if ((dmux->flags&(1<<(i*2+1))) == 0) { buffer += sprintf(buffer, "lFragColor.a = (%s - %s) * %s + %s; \n", _alpha_param_str(dmux->decode[i*2+1][0]), _alpha_param_str(dmux->decode[i*2+1][1]), _alpha_param_str(dmux->decode[i*2+1][2]), _alpha_param_str(dmux->decode[i*2+1][3]) ); } buffer += sprintf(buffer, "gl_FragColor = lFragColor; \n"); }; //fog if (flags&SC_FOGENABLED) { buffer += sprintf(buffer, "gl_FragColor = mix(gl_FragColor, uFogColor, vFactor); \n"); } //alpha function if (flags&SC_ALPHAENABLED) { if (flags&SC_ALPHAGREATER) buffer += sprintf(buffer, "if (gl_FragColor.a < uAlphaRef) %s;\n", config.hackAlpha ? "gl_FragColor.a = 0" : "discard"); else buffer += sprintf(buffer, "if (gl_FragColor.a <= uAlphaRef) %s;\n", config.hackAlpha ? "gl_FragColor.a = 0" : "discard"); } buffer += sprintf(buffer, "} \n\n"); *buffer = 0; #ifdef PRINT_SHADER LOG(LOG_VERBOSE, "=============================================================\n"); LOG(LOG_VERBOSE, "Combine=0x%llx flags=0x%x dmux flags=0x%x\n", prog->combine.mux, flags, dmux->flags); LOG(LOG_VERBOSE, "Num=%i \t usesT0=%i usesT1=%i usesCol=%i usesNoise=%i\n", scProgramCount, prog->usesT0, prog->usesT1, prog->usesCol, prog->usesNoise); LOG(LOG_VERBOSE, "=============================================================\n"); LOG(LOG_VERBOSE, "%s", frag); LOG(LOG_VERBOSE, "=============================================================\n"); #endif prog->program = glCreateProgram(); //Compile: char *src[1]; src[0] = frag; GLint len[1]; len[0] = min(4096, strlen(frag)); prog->fragment = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(prog->fragment, 1, (const char**) src, len); glCompileShader(prog->fragment); glGetShaderiv(prog->fragment, GL_COMPILE_STATUS, &success); if (!success) { _glcompiler_error(prog->fragment); } //link _locate_attributes(prog); glAttachShader(prog->program, prog->fragment); glAttachShader(prog->program, prog->vertex); glLinkProgram(prog->program); glGetProgramiv(prog->program, GL_LINK_STATUS, &success); if (!success) { _gllinker_error(prog->program); } //remove fragment shader: glDeleteShader(prog->fragment); _locate_uniforms(prog); return prog; }
void init_shaders(CUBE_STATE_T *state) { const GLchar *vShaderStr = "attribute vec3 vPosition;\n" "attribute vec2 TexCoordIn;\n" "varying vec2 TexCoordOut;\n" "uniform mat4 umvmatrix;\n" "uniform mat4 upmatrix;\n" "void main() \n" "{ \n" " TexCoordOut = TexCoordIn;\n" " gl_Position = upmatrix * umvmatrix * vec4(vPosition, 1.0); \n" "} \n"; const GLchar *fShaderStr = "precision mediump float; \n" "varying vec2 TexCoordOut;\n" "uniform sampler2D texture;\n" "void main() \n" "{ \n" " vec4 tex = texture2D(texture, TexCoordOut);\n" " gl_FragColor = tex;\n" "} \n"; const GLchar *fShaderStrY = "precision highp float; \n" "varying vec2 TexCoordOut;\n" "uniform sampler2D texture;\n" "vec4 conversion_factor = vec4(0.257, 0.504, .098, 0.0625);\n" "void main() \n" "{ \n" " vec4 tex1 = texture2D(texture, TexCoordOut - vec2(.00234375, 0));\n" " vec4 tex2 = texture2D(texture, TexCoordOut - vec2(.00078125, 0));\n" " vec4 tex3 = texture2D(texture, TexCoordOut + vec2(.00078123, 0));\n" " vec4 tex4 = texture2D(texture, TexCoordOut + vec2(.00234375, 0));\n" " float Y1 = dot(conversion_factor, vec4(tex1.rgb, 1.0));\n" " float Y2 = dot(conversion_factor, vec4(tex2.rgb, 1.0));\n" " float Y3 = dot(conversion_factor, vec4(tex3.rgb, 1.0));\n" " float Y4 = dot(conversion_factor, vec4(tex4.rgb, 1.0));\n" " gl_FragColor = vec4(Y1, Y2, Y3, Y4);\n" "} \n"; const GLchar *fShaderStrU = "precision highp float; \n" "varying vec2 TexCoordOut;\n" "uniform sampler2D texture;\n" "vec4 conversion_factor = vec4(-0.148, -0.291, .439, 0.5);\n" "void main() \n" "{ \n" " vec4 tex1 = texture2D(texture, TexCoordOut - vec2(.0046875, 0));\n" " vec4 tex2 = texture2D(texture, TexCoordOut - vec2(.0015625, 0));\n" " vec4 tex3 = texture2D(texture, TexCoordOut + vec2(.0015625, 0));\n" " vec4 tex4 = texture2D(texture, TexCoordOut + vec2(.0046875, 0));\n" " float Y1 = dot(conversion_factor, vec4(tex1.rgb, 1.0));\n" " float Y2 = dot(conversion_factor, vec4(tex2.rgb, 1.0));\n" " float Y3 = dot(conversion_factor, vec4(tex3.rgb, 1.0));\n" " float Y4 = dot(conversion_factor, vec4(tex4.rgb, 1.0));\n" " gl_FragColor = vec4(Y1, Y2, Y3, Y4);\n" "} \n"; const GLchar *fShaderStrV = "precision highp float; \n" "varying vec2 TexCoordOut;\n" "uniform sampler2D texture;\n" "vec4 conversion_factor = vec4(0.439, -0.368, -0.071, 0.5);\n" "void main() \n" "{ \n" " vec4 tex1 = texture2D(texture, TexCoordOut - vec2(.0046875, 0));\n" " vec4 tex2 = texture2D(texture, TexCoordOut - vec2(.0015625, 0));\n" " vec4 tex3 = texture2D(texture, TexCoordOut + vec2(.0015625, 0));\n" " vec4 tex4 = texture2D(texture, TexCoordOut + vec2(.0046875, 0));\n" " float Y1 = dot(conversion_factor, vec4(tex1.rgb, 1.0));\n" " float Y2 = dot(conversion_factor, vec4(tex2.rgb, 1.0));\n" " float Y3 = dot(conversion_factor, vec4(tex3.rgb, 1.0));\n" " float Y4 = dot(conversion_factor, vec4(tex4.rgb, 1.0));\n" " gl_FragColor = vec4(Y1, Y2, Y3, Y4);\n" "} \n"; GLuint vertexShader; GLuint fragmentShader; GLint compiled; vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &vShaderStr, NULL); glCompileShader(vertexShader); glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &compiled); if (!compiled) printf("It didn't compile\n"); fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &fShaderStr, NULL); glCompileShader(fragmentShader); glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &compiled); if (!compiled) printf("It didn't compile\n"); state->render_program = glCreateProgram(); glAttachShader(state->render_program, vertexShader); glAttachShader(state->render_program, fragmentShader); glBindAttribLocation(state->render_program, 0, "vPosition"); glBindAttribLocation(state->render_program, 1, "TexCoordIn"); glLinkProgram(state->render_program); GLint linked; state->unif_pmatrix = glGetUniformLocation(state->render_program, "upmatrix"); glGetError(); state->unif_mvmatrix = glGetUniformLocation(state->render_program, "umvmatrix"); state->unif_tex = glGetUniformLocation(state->render_program, "texture"); glGetError(); glGetProgramiv(state->render_program, GL_LINK_STATUS, &linked); if(!linked) { GLint infoLen = 0; glGetProgramiv(state->render_program, GL_INFO_LOG_LENGTH, &infoLen); if(infoLen > 1) { char* infoLog = malloc(sizeof(char) * infoLen); glGetProgramInfoLog(state->render_program, infoLen, NULL, infoLog); printf("%s\n", infoLog); free(infoLog); } glDeleteProgram(state->render_program); } fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &fShaderStrY, NULL); glCompileShader(fragmentShader); glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &compiled); if (!compiled) printf("It didn't compile\n"); state->y_program = glCreateProgram(); glAttachShader(state->y_program, vertexShader); glAttachShader(state->y_program, fragmentShader); glBindAttribLocation(state->y_program, 0, "vPosition"); glBindAttribLocation(state->y_program, 1, "TexCoordIn"); glLinkProgram(state->y_program); state->y_pmatrix = glGetUniformLocation(state->y_program, "upmatrix"); glGetError(); state->y_mvmatrix = glGetUniformLocation(state->y_program, "umvmatrix"); state->y_tex = glGetUniformLocation(state->y_program, "texture"); glGetError(); glGetProgramiv(state->y_program, GL_LINK_STATUS, &linked); if(!linked) { GLint infoLen = 0; glGetProgramiv(state->y_program, GL_INFO_LOG_LENGTH, &infoLen); if(infoLen > 1) { char* infoLog = malloc(sizeof(char) * infoLen); glGetProgramInfoLog(state->y_program, infoLen, NULL, infoLog); printf("%s\n", infoLog); free(infoLog); } glDeleteProgram(state->y_program); } fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &fShaderStrU, NULL); glCompileShader(fragmentShader); glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &compiled); if (!compiled) printf("It didn't compile\n"); state->u_program = glCreateProgram(); glAttachShader(state->u_program, vertexShader); glAttachShader(state->u_program, fragmentShader); glBindAttribLocation(state->u_program, 0, "vPosition"); glBindAttribLocation(state->u_program, 1, "TexCoordIn"); glLinkProgram(state->u_program); state->u_pmatrix = glGetUniformLocation(state->u_program, "upmatrix"); glGetError(); state->u_mvmatrix = glGetUniformLocation(state->u_program, "umvmatrix"); state->u_tex = glGetUniformLocation(state->u_program, "texture"); glGetError(); glGetProgramiv(state->u_program, GL_LINK_STATUS, &linked); if(!linked) { GLint infoLen = 0; glGetProgramiv(state->u_program, GL_INFO_LOG_LENGTH, &infoLen); if(infoLen > 1) { char* infoLog = malloc(sizeof(char) * infoLen); glGetProgramInfoLog(state->u_program, infoLen, NULL, infoLog); printf("%s\n", infoLog); free(infoLog); } glDeleteProgram(state->u_program); } fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &fShaderStrV, NULL); glCompileShader(fragmentShader); glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &compiled); if (!compiled) printf("It didn't compile\n"); state->v_program = glCreateProgram(); glAttachShader(state->v_program, vertexShader); glAttachShader(state->v_program, fragmentShader); glBindAttribLocation(state->v_program, 0, "vPosition"); glBindAttribLocation(state->v_program, 1, "TexCoordIn"); glLinkProgram(state->v_program); state->v_pmatrix = glGetUniformLocation(state->v_program, "upmatrix"); glGetError(); state->v_mvmatrix = glGetUniformLocation(state->v_program, "umvmatrix"); state->v_tex = glGetUniformLocation(state->v_program, "texture"); glGetError(); glGetProgramiv(state->v_program, GL_LINK_STATUS, &linked); if(!linked) { GLint infoLen = 0; glGetProgramiv(state->v_program, GL_INFO_LOG_LENGTH, &infoLen); if(infoLen > 1) { char* infoLog = malloc(sizeof(char) * infoLen); glGetProgramInfoLog(state->v_program, infoLen, NULL, infoLog); printf("%s\n", infoLog); free(infoLog); } glDeleteProgram(state->v_program); } }
GLuint CreateProgram(const char* vsKey, const char* gsKey, const char* fsKey) { static int first = 1; if (first) { glswInit(); glswAddPath("../", ".glsl"); glswAddPath("./", ".glsl"); char qualifiedPath[128]; strcpy(qualifiedPath, PezResourcePath()); strcat(qualifiedPath, "/"); glswAddPath(qualifiedPath, ".glsl"); glswAddDirective("*", "#version 150"); first = 0; } const char* vsSource = glswGetShader(vsKey); const char* gsSource = glswGetShader(gsKey); const char* fsSource = glswGetShader(fsKey); const char* msg = "Can't find %s shader: '%s'.\n"; PezCheckCondition(vsSource != 0, msg, "vertex", vsKey); PezCheckCondition(gsKey == 0 || gsSource != 0, msg, "geometry", gsKey); PezCheckCondition(fsKey == 0 || fsSource != 0, msg, "fragment", fsKey); GLint compileSuccess; GLchar compilerSpew[256]; GLuint programHandle = glCreateProgram(); GLuint vsHandle = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vsHandle, 1, &vsSource, 0); glCompileShader(vsHandle); glGetShaderiv(vsHandle, GL_COMPILE_STATUS, &compileSuccess); glGetShaderInfoLog(vsHandle, sizeof(compilerSpew), 0, compilerSpew); PezCheckCondition(compileSuccess, "Can't compile %s:\n%s", vsKey, compilerSpew); glAttachShader(programHandle, vsHandle); GLuint gsHandle; if (gsKey) { gsHandle = glCreateShader(GL_GEOMETRY_SHADER); glShaderSource(gsHandle, 1, &gsSource, 0); glCompileShader(gsHandle); glGetShaderiv(gsHandle, GL_COMPILE_STATUS, &compileSuccess); glGetShaderInfoLog(gsHandle, sizeof(compilerSpew), 0, compilerSpew); PezCheckCondition(compileSuccess, "Can't compile %s:\n%s", gsKey, compilerSpew); glAttachShader(programHandle, gsHandle); } GLuint fsHandle; if (fsKey) { fsHandle = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fsHandle, 1, &fsSource, 0); glCompileShader(fsHandle); glGetShaderiv(fsHandle, GL_COMPILE_STATUS, &compileSuccess); glGetShaderInfoLog(fsHandle, sizeof(compilerSpew), 0, compilerSpew); PezCheckCondition(compileSuccess, "Can't compile %s:\n%s", fsKey, compilerSpew); glAttachShader(programHandle, fsHandle); } glLinkProgram(programHandle); GLint linkSuccess; glGetProgramiv(programHandle, GL_LINK_STATUS, &linkSuccess); glGetProgramInfoLog(programHandle, sizeof(compilerSpew), 0, compilerSpew); if (!linkSuccess) { PezDebugString("Link error.\n"); if (vsKey) PezDebugString("Vertex Shader: %s\n", vsKey); if (gsKey) PezDebugString("Geometry Shader: %s\n", gsKey); if (fsKey) PezDebugString("Fragment Shader: %s\n", fsKey); PezDebugString("%s\n", compilerSpew); } return programHandle; }
int Shader :: init() { GLint status, len; GLuint shader; const char* body; GLchar buffer[1024]; if(num_init > 0) return 1; if(vsh && fsh) { program = glCreateProgram(); shader = glCreateShader(GL_VERTEX_SHADER); body = (const char*)vsh->getPtr(0); len = (GLint)vsh->getLength(); glShaderSource(shader, 1, &body, &len); glCompileShader(shader); glGetShaderiv(shader, GL_COMPILE_STATUS, &status); if(status != GL_TRUE) { glGetShaderInfoLog(shader, 1024, &len, buffer); LOG_WARNING("GLSL(vert): %s.", (const char*)buffer); return 0; } glAttachShader(program, shader); glBindAttribLocation(program, 0, "in_vert"); glBindAttribLocation(program, 1, "in_norm"); glBindAttribLocation(program, 2, "in_coord"); glBindAttribLocation(program, 3, "in_color"); glBindAttribLocation(program, 4, "in_tangent"); glBindAttribLocation(program, 5, "in_binormal"); glDeleteShader(shader); shader = glCreateShader(GL_FRAGMENT_SHADER); body = (const char*)fsh->getPtr(0); len = (GLint)fsh->getLength(); glShaderSource(shader, 1, &body, &len); glCompileShader(shader); glGetShaderiv(shader, GL_COMPILE_STATUS, &status); if(status != GL_TRUE) { glGetShaderInfoLog(shader, 1024, &len, buffer); LOG_WARNING("GLSL(frag): %s.", (const char*)buffer); return 0; } glAttachShader(program, shader); glDeleteShader(shader); } else return 0; glLinkProgram(program); glGetProgramiv(program, GL_LINK_STATUS, &status); if(status != GL_TRUE) { glGetProgramInfoLog(program, 1024, &len, buffer); LOG_WARNING("GLSL(link): %s.", (const char*)buffer); return 0; } glValidateProgram(program); glGetProgramiv(program, GL_VALIDATE_STATUS, &status); if(status != GL_TRUE) { glGetProgramInfoLog(program, 1024, &len, buffer); LOG_WARNING("GLSL(valid): %s.", (const char*)buffer); return 0; } num_init ++; LOG_INFO("Shader: Linking shader programs \"%s\" complete.", getName()); return 1; }
int main(int argc, char **argv) { wrt = (struct warp_runtime *)malloc(sizeof(struct warp_runtime)); assert(NULL != wrt); memset(wrt, 0, sizeof(struct warp_runtime)); create_warp_runtime(wrt); glViewport(0, 0, 500, 500); /* setup shader & program */ GLchar message[512]; GLint status; GLchar *source = NULL; GLuint vertex_shader = glCreateShader(GL_VERTEX_SHADER); load_shader_from_file("shaders/es3_ubo.vert", &source); glShaderSource(vertex_shader, 1, (const GLchar * const*)&source, NULL); glCompileShader(vertex_shader); glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &status); if (!status) { glGetShaderInfoLog(vertex_shader, 512, NULL, message); printf("%s\n", message); } GLuint fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); free(source); load_shader_from_file("shaders/es3_ubo.frag", &source); glShaderSource(fragment_shader, 1, (const GLchar * const*)&source, NULL); glCompileShader(fragment_shader); glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &status); if (!status) { glGetShaderInfoLog(fragment_shader, 512, NULL, message); printf("%s\n", message); } GLuint prog = glCreateProgram(); glAttachShader(prog, vertex_shader); glAttachShader(prog, fragment_shader); glLinkProgram(prog); glGetProgramiv(prog, GL_LINK_STATUS, &status); if (!status) { glGetProgramInfoLog(prog, 512, NULL, message); printf("%s\n", message); } glUseProgram(prog); /* set up resource */ GLfloat pos_buf[] = { -0.25f, 0.25f, 0.0f, 0.25f, -0.25f, 0.0f, -0.25f, -0.25f, 0.0f, 0.25f, 0.25f, 0.0f }; GLfloat color_buf[] = { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, }; GLushort index_buf[] = { 2, 0, 1, 3 }; GLuint vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); /* setup array buffer for position and color */ GLuint vbo_pos; glGenBuffers(1, &vbo_pos); glBindBuffer(GL_ARRAY_BUFFER, vbo_pos); glBufferData(GL_ARRAY_BUFFER, sizeof(pos_buf), pos_buf, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid *)0); GLuint vbo_color; glGenBuffers(1, &vbo_color); glBindBuffer(GL_ARRAY_BUFFER, vbo_color); glBufferData(GL_ARRAY_BUFFER, sizeof(color_buf), color_buf, GL_STATIC_DRAW); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid *)0); /* setup index buffer for index */ GLuint vbo_index; glGenBuffers(1, &vbo_index); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_index); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(index_buf), index_buf, GL_STATIC_DRAW); /* updating uniform block */ glm::mat4 model_mat = glm::mat4(1.0f); glm::mat4 view_mat = glm::lookAt( glm::vec3(-2, 1, 2), glm::vec3(0, 0, 0), glm::vec3(0, 1, 0) ); glm::mat4 proj_mat = glm::perspective(glm::radians(45.0f), 1.0f, 0.1f, 100.0f); GLuint ubo_blk_idx = glGetUniformBlockIndex(prog, "MVP"); GLint ubo_sz; glGetActiveUniformBlockiv(prog, ubo_blk_idx, GL_UNIFORM_BLOCK_DATA_SIZE, &ubo_sz); const char *names[3] = {"uModel", "uView", "uProj"}; GLuint indices[3]; GLint size[3]; GLint offset[3]; GLint type[3]; glGetUniformIndices(prog, 3, names, indices); glGetActiveUniformsiv(prog, 3, indices, GL_UNIFORM_OFFSET, offset); glGetActiveUniformsiv(prog, 3, indices, GL_UNIFORM_SIZE, size); glGetActiveUniformsiv(prog, 3, indices, GL_UNIFORM_TYPE, type); /* mat4 here is 4x4=16 GLfloat */ GLubyte *buffer = (GLubyte *)malloc(ubo_sz); memcpy(buffer + offset[0], &model_mat[0][0], size[0] * sizeof(GLfloat) * 16); memcpy(buffer + offset[1], &view_mat[0][0], size[1] * sizeof(GLfloat) * 16); memcpy(buffer + offset[2], &proj_mat[0][0], size[2] * sizeof(GLfloat) * 16); GLuint ubo; glGenBuffers(1, &ubo); glBindBuffer(GL_UNIFORM_BUFFER, ubo); glBufferData(GL_UNIFORM_BUFFER, ubo_sz, buffer, GL_STATIC_DRAW); glBindBufferBase(GL_UNIFORM_BUFFER, ubo_blk_idx, ubo); /* game loop */ while (1) { XNextEvent(wrt->x11_display, &(wrt->event)); switch(wrt->event.type) { case Expose: /* do the render */ glClearColor(0.3f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glBindVertexArray(vao); glDrawElements(GL_TRIANGLE_STRIP, 4, GL_UNSIGNED_SHORT, (void*)0); glBindVertexArray(0); eglSwapBuffers(wrt->egl_display, wrt->egl_surface); break; case ButtonPress: case KeyPress: goto finish; default: break; } } finish: glDeleteBuffers(1, &vbo_pos); glDeleteBuffers(1, &vbo_color); glDeleteBuffers(1, &vbo_index); glDeleteBuffers(1, &ubo); glDeleteVertexArrays(1, &vao); glDeleteShader(vertex_shader); glDeleteShader(fragment_shader); glDeleteProgram(prog); destroy_warp_runtime(wrt); return 0; }
// Read/compile/link shaders GLuint pie_LoadShader(const char *programName, const char *vertexPath, const char *fragmentPath) { SHADER_PROGRAM program; GLint status; bool success = true; // Assume overall success char *buffer[2]; memset(&program, 0, sizeof(program)); program.program = glCreateProgram(); ASSERT_OR_RETURN(false, program.program, "Could not create shader program!"); *buffer = (char *)""; if (vertexPath) { success = false; // Assume failure before reading shader file if ((*(buffer + 1) = readShaderBuf(vertexPath))) { GLuint shader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(shader, 2, (const char **)buffer, NULL); glCompileShader(shader); // Check for compilation errors glGetShaderiv(shader, GL_COMPILE_STATUS, &status); if (!status) { debug(LOG_ERROR, "Vertex shader compilation has failed [%s]", vertexPath); printShaderInfoLog(LOG_ERROR, shader); } else { printShaderInfoLog(LOG_3D, shader); glAttachShader(program.program, shader); success = true; } if (GLEW_VERSION_4_3 || GLEW_KHR_debug) { glObjectLabel(GL_SHADER, shader, -1, vertexPath); } free(*(buffer + 1)); } } if (success && fragmentPath) { success = false; // Assume failure before reading shader file if ((*(buffer + 1) = readShaderBuf(fragmentPath))) { GLuint shader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(shader, 2, (const char **)buffer, NULL); glCompileShader(shader); // Check for compilation errors glGetShaderiv(shader, GL_COMPILE_STATUS, &status); if (!status) { debug(LOG_ERROR, "Fragment shader compilation has failed [%s]", fragmentPath); printShaderInfoLog(LOG_ERROR, shader); } else { printShaderInfoLog(LOG_3D, shader); glAttachShader(program.program, shader); success = true; } if (GLEW_VERSION_4_3 || GLEW_KHR_debug) { glObjectLabel(GL_SHADER, shader, -1, fragmentPath); } free(*(buffer + 1)); } } if (success) { glLinkProgram(program.program); // Check for linkage errors glGetProgramiv(program.program, GL_LINK_STATUS, &status); if (!status) { debug(LOG_ERROR, "Shader program linkage has failed [%s, %s]", vertexPath, fragmentPath); printProgramInfoLog(LOG_ERROR, program.program); success = false; } else { printProgramInfoLog(LOG_3D, program.program); } if (GLEW_VERSION_4_3 || GLEW_KHR_debug) { glObjectLabel(GL_PROGRAM, program.program, -1, programName); } } getLocs(&program); glUseProgram(0); shaderProgram.append(program); return shaderProgram.size() - 1; }
void setup() { // 3. Define and compile vertex and fragment shaders GLuint vs; GLuint fs; GLint compileSuccess, linkSuccess; GLchar compilerSpew[256]; glswInit(); glswSetPath("../shader/", ".glsl"); glswAddDirectiveToken("GL3", "#version 150"); const char *vss = glswGetShader("test.Vertex.GL3"); const char *fss = glswGetShader("test.Fragment.GL3"); PezCheckCondition((void *)vss, "Can't find vertex shader.\n"); PezCheckCondition((void *)fss, "Can't find fragment shader.\n"); vs = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vs, 1, &vss, NULL); glCompileShader(vs); glGetShaderiv(vs, GL_COMPILE_STATUS, &compileSuccess); glGetShaderInfoLog(vs, sizeof(compilerSpew), 0, compilerSpew); PezCheckCondition((void*)compileSuccess, compilerSpew); fs = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fs, 1, &fss, NULL); glCompileShader(fs); glGetShaderiv(fs, GL_COMPILE_STATUS, &compileSuccess); glGetShaderInfoLog(fs, sizeof(compilerSpew), 0, compilerSpew); PezCheckCondition((void*)compileSuccess, compilerSpew); shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vs); glAttachShader(shaderProgram, fs); glBindFragDataLocation(shaderProgram, 0, "fragColour"); glLinkProgram(shaderProgram); glGetProgramiv(shaderProgram, GL_LINK_STATUS, &linkSuccess); glGetProgramInfoLog(shaderProgram, sizeof(compilerSpew), 0, compilerSpew); PezCheckCondition((void*)linkSuccess, compilerSpew); positionUniform = glGetUniformLocation(shaderProgram, "p"); colourAttribute = glGetAttribLocation(shaderProgram, "colour"); positionAttribute = glGetAttribLocation(shaderProgram, "position"); glDeleteShader(vs); glDeleteShader(fs); GLfloat vertexData[]= { -0.5,-0.5,0.0,1.0, 1.0,0.0,0.0,1.0, -0.5, 0.5,0.0,1.0, 0.0,1.0,0.0,1.0, 0.5, 0.5,0.0,1.0, 0.0,0.0,1.0,1.0, 0.5,-0.5,0.0,1.0, 1.0,1.0,1.0,1.0}; glGenVertexArrays(1, &vertexArrayObject); glBindVertexArray(vertexArrayObject); glGenBuffers(1, &vertexBuffer); glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer); glBufferData(GL_ARRAY_BUFFER, 4*8*sizeof(GLfloat), vertexData, GL_STATIC_DRAW); glEnableVertexAttribArray((GLuint)positionAttribute); glEnableVertexAttribArray((GLuint)colourAttribute ); glVertexAttribPointer((GLuint)positionAttribute, 4, GL_FLOAT, GL_FALSE, 8*sizeof(GLfloat), 0); glVertexAttribPointer((GLuint)colourAttribute , 4, GL_FLOAT, GL_FALSE, 8*sizeof(GLfloat), (char*)0+4*sizeof(GLfloat)); }
/** * Vraci program (zkompilovane shadery) pro renderovani nahledoveho krize */ GLuint Shaders::getPreviewProgram() { const char *p_s_vertex_shader = "#version 330\n" "in vec3 v_pos;\n" // atributy - vstup z dat vrcholu "in vec2 v_tex;\n" // souradnice textury "\n" "uniform mat4 t_modelview_projection_matrix;\n" // parametr shaderu - transformacni matice "\n" "out vec2 v_texcoord, v_normal_tex;\n" "\n" "void main()\n" "{\n" " gl_Position = t_modelview_projection_matrix * vec4(v_pos, 1.0);\n" // musime zapsat pozici " v_texcoord = v_tex;\n" " v_normal_tex = v_tex * 2.0 - 1.0;\n" "}\n"; const char *p_s_fragment_shader = "#version 330\n" "in vec2 v_texcoord, v_normal_tex;\n" "\n" "out vec4 frag_color;\n" // vystup do framebufferu "\n" "uniform sampler2D n_tex;\n" "\n" "void main()\n" "{\n" /* " vec4 tex_color = vec4(0.0);" " if(v_texcoord.y >= 0.25 && v_texcoord.y <= 0.75) {" " if(v_texcoord.x < 0.25)" " tex_color = texture(n_tex, (v_texcoord + vec2(0, -.25)) * vec2(0.25/0.25, 0.66667/0.5));" " else if(v_texcoord.x < 0.75)" " tex_color = texture(n_tex, (v_texcoord + vec2(0, -.25)) * vec2(0.5/0.5, 0.66667/0.5));" " else" " tex_color = texture(n_tex, (v_texcoord + vec2(0, -.25)) * vec2(0.25/0.25, 0.66667/0.5));" " } else if(v_texcoord.y < 0.25 && v_texcoord.x >= 0.25 && v_texcoord.x <= 0.75)" " tex_color = texture(n_tex, (v_texcoord + vec2(-.25, 0)) * vec2(0.5/0.5, 0.33333/0.25) + vec2(0.5, 0.66667));" " else if(v_texcoord.y > 0.75 && v_texcoord.x >= 0.25 && v_texcoord.x <= 0.75)" " tex_color = texture(n_tex, (v_texcoord + vec2(-0.25, -.75)) * vec2(0.5/0.5, 0.33333/0.25) + vec2(0.0, 0.66667));" " else discard;" */ " vec4 tex_color = texture(n_tex, v_texcoord);\n" /* " vec4 tex_color = texture(n_tex, v_texcoord) * .5;//vec4(0.0);\n" // precte texturu krabice " float f_tex_length = length(v_normal_tex);\n" " vec3 v_ray = vec3(v_normal_tex, sqrt(1 - f_tex_length));\n" " if(f_tex_length > 1.0)\n" " discard;\n" " vec3 v_ray_abs = abs(v_ray);\n" " if(v_ray.z > v_ray_abs.x && v_ray.z > v_ray_abs.y)\n" // dopredu " tex_color = texture(n_tex, ((v_ray.xy / v_ray.z) * .5 + .5) * vec2(0.5, 0.66667) + vec2(0.25, 0.0));\n" " else if(v_ray_abs.x > v_ray_abs.y) {\n" " if(v_ray.x < 0)\n" // vlevo " tex_color = texture(n_tex, ((v_ray.yz / v_ray.x) * vec2(0.5, 0.5) + vec2(0.5, 0.5)) * vec2(-0.25, -0.66667) + vec2(0.25, 0.66667));\n" " else\n" // vpravo " tex_color = texture(n_tex, ((v_ray.yz / v_ray.x) * vec2(-0.5, 0.5) + vec2(0.5, 0.5)) * vec2(0.25, 0.66667) + vec2(0.75, 0.0));\n" " } else {\n" " if(v_ray.y < 0)\n" // nahoru " tex_color = texture(n_tex, ((v_ray.xz / v_ray.y) * vec2(0.5, 0.5) + vec2(0.5, 0.5)) * vec2(-0.5, -0.33333) + vec2(1.0, 1.0));\n" " else\n" // dolu " tex_color = texture(n_tex, ((v_ray.xz / v_ray.y) * vec2(0.5, -0.5) + vec2(0.5, 0.5)) * vec2(0.5, 0.33333) + vec2(0, 0.66667));\n" " }\n" */ " frag_color = tex_color;\n" "}\n"; // zkompiluje vertex / fragment shader, pripoji je k programu n_preview_vertex_shader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(n_preview_vertex_shader, 1, &p_s_vertex_shader, NULL); glCompileShader(n_preview_vertex_shader); if(!CheckShader(n_preview_vertex_shader, "vertex shader")) return false; n_preview_fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(n_preview_fragment_shader, 1, &p_s_fragment_shader, NULL); glCompileShader(n_preview_fragment_shader); if(!CheckShader(n_preview_fragment_shader, "fragment shader")) return false; n_preview_program_object = glCreateProgram(); glAttachShader(n_preview_program_object, n_preview_vertex_shader); glAttachShader(n_preview_program_object, n_preview_fragment_shader); // nabinduje atributy (propojeni mezi obsahem VBO a vstupem do vertex shaderu) glBindAttribLocation(n_preview_program_object, 0, "v_pos"); glBindAttribLocation(n_preview_program_object, 2, "v_tex"); // nabinduje vystupni promenou (propojeni mezi framebufferem a vystupem fragment shaderu) glBindFragDataLocation(n_preview_program_object, 0, "frag_color"); // slinkuje program glLinkProgram(n_preview_program_object); if(!CheckProgram(n_preview_program_object, "program")) return false; else return n_preview_program_object; }
bool ImGui_ImplSdl_CreateDeviceObjects() { // Backup GL state GLint last_texture, last_array_buffer, last_vertex_array; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array); // Specify version 140 shaders because some trash drivers fail otherwise const GLchar *vertex_shader = "#version 120\n" "uniform mat4 ProjMtx;\n" "attribute vec2 Position;\n" "attribute vec2 UV;\n" "attribute vec4 Color;\n" "varying vec2 Frag_UV;\n" "varying vec4 Frag_Color;\n" "void main()\n" "{\n" " Frag_UV = UV;\n" " Frag_Color = Color;\n" " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" "}\n"; const GLchar* fragment_shader = "#version 120\n" "uniform sampler2D Texture;\n" "varying vec2 Frag_UV;\n" "varying vec4 Frag_Color;\n" "varying vec4 Out_Color;\n" "void main()\n" "{\n" " gl_FragColor = Frag_Color * texture2D( Texture, Frag_UV.st);\n" "}\n"; g_ShaderHandle = glCreateProgram(); g_VertHandle = glCreateShader(GL_VERTEX_SHADER); g_FragHandle = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(g_VertHandle, 1, &vertex_shader, 0); glShaderSource(g_FragHandle, 1, &fragment_shader, 0); glCompileShader(g_VertHandle); glCompileShader(g_FragHandle); glAttachShader(g_ShaderHandle, g_VertHandle); glAttachShader(g_ShaderHandle, g_FragHandle); glLinkProgram(g_ShaderHandle); g_AttribLocationTex = glGetUniformLocation(g_ShaderHandle, "Texture"); g_AttribLocationProjMtx = glGetUniformLocation(g_ShaderHandle, "ProjMtx"); g_AttribLocationPosition = glGetAttribLocation(g_ShaderHandle, "Position"); g_AttribLocationUV = glGetAttribLocation(g_ShaderHandle, "UV"); g_AttribLocationColor = glGetAttribLocation(g_ShaderHandle, "Color"); glGenBuffers(1, &g_VboHandle); glGenBuffers(1, &g_ElementsHandle); glGenVertexArrays(1, &g_VaoHandle); glBindVertexArray(g_VaoHandle); glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle); glEnableVertexAttribArray(g_AttribLocationPosition); glEnableVertexAttribArray(g_AttribLocationUV); glEnableVertexAttribArray(g_AttribLocationColor); #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT)) glVertexAttribPointer(g_AttribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, pos)); glVertexAttribPointer(g_AttribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, uv)); glVertexAttribPointer(g_AttribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, col)); #undef OFFSETOF ImGui_ImplSdl_CreateFontsTexture(); // Restore modified GL state glBindTexture(GL_TEXTURE_2D, last_texture); glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); glBindVertexArray(last_vertex_array); return true; }
int main(int argc, char** argv) { int ch, samples = 4; GLFWwindow* window; GLuint vertex_buffer, vertex_shader, fragment_shader, program; GLint mvp_location, vpos_location; while ((ch = getopt(argc, argv, "hs:")) != -1) { switch (ch) { case 'h': usage(); exit(EXIT_SUCCESS); case 's': samples = atoi(optarg); break; default: usage(); exit(EXIT_FAILURE); } } glfwSetErrorCallback(error_callback); if (!glfwInit()) exit(EXIT_FAILURE); if (samples) printf("Requesting MSAA with %i samples\n", samples); else printf("Requesting that MSAA not be available\n"); glfwWindowHint(GLFW_SAMPLES, samples); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); window = glfwCreateWindow(800, 400, "Aliasing Detector", NULL, NULL); if (!window) { glfwTerminate(); exit(EXIT_FAILURE); } glfwSetKeyCallback(window, key_callback); glfwMakeContextCurrent(window); gladLoadGLLoader((GLADloadproc) glfwGetProcAddress); glfwSwapInterval(1); glGetIntegerv(GL_SAMPLES, &samples); if (samples) printf("Context reports MSAA is available with %i samples\n", samples); else printf("Context reports MSAA is unavailable\n"); glGenBuffers(1, &vertex_buffer); glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); vertex_shader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex_shader, 1, &vertex_shader_text, NULL); glCompileShader(vertex_shader); fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment_shader, 1, &fragment_shader_text, NULL); glCompileShader(fragment_shader); program = glCreateProgram(); glAttachShader(program, vertex_shader); glAttachShader(program, fragment_shader); glLinkProgram(program); mvp_location = glGetUniformLocation(program, "MVP"); vpos_location = glGetAttribLocation(program, "vPos"); glEnableVertexAttribArray(vpos_location); glVertexAttribPointer(vpos_location, 2, GL_FLOAT, GL_FALSE, sizeof(vertices[0]), (void*) 0); while (!glfwWindowShouldClose(window)) { float ratio; int width, height; mat4x4 m, p, mvp; const double angle = glfwGetTime() * M_PI / 180.0; glfwGetFramebufferSize(window, &width, &height); ratio = width / (float) height; glViewport(0, 0, width, height); glClear(GL_COLOR_BUFFER_BIT); glUseProgram(program); mat4x4_ortho(p, -ratio, ratio, -1.f, 1.f, 0.f, 1.f); mat4x4_translate(m, -1.f, 0.f, 0.f); mat4x4_rotate_Z(m, m, (float) angle); mat4x4_mul(mvp, p, m); glUniformMatrix4fv(mvp_location, 1, GL_FALSE, (const GLfloat*) mvp); glDisable(GL_MULTISAMPLE); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); mat4x4_translate(m, 1.f, 0.f, 0.f); mat4x4_rotate_Z(m, m, (float) angle); mat4x4_mul(mvp, p, m); glUniformMatrix4fv(mvp_location, 1, GL_FALSE, (const GLfloat*) mvp); glEnable(GL_MULTISAMPLE); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); glfwSwapBuffers(window); glfwPollEvents(); } glfwDestroyWindow(window); glfwTerminate(); exit(EXIT_SUCCESS); }
/*!**************************************************************************** @Function InitView @Return bool true if no error occured @Description Code in InitView() will be called by PVRShell upon initialization or after a change in the rendering context. Used to initialize variables that are dependant on the rendering context (e.g. textures, vertex buffers, etc.) ******************************************************************************/ bool OGLES2BinaryShader::InitView() { // Initialise a colour to draw our triangle // (For this training course, binary loaded shaders use a different colour // To show which is being used. Red means it had to compile the shaders, // green shows that it retrieved the binary from memory. float afColour[]={0.0,0.0,0.0}; // Filename and path strings. char* pWritePath = (char*)PVRShellGet(prefWritePath); char* shaderPath = new char[strlen(pWritePath) + 13]; sprintf(shaderPath, "%sShaderBinary", pWritePath); //Checks if the program binary handling extension is supported. m_bBinaryShaderSupported=IsGLExtensionSupported("GL_OES_get_program_binary"); #if !defined (TARGET_OS_IPHONE) glGetProgramBinaryOES=0; glProgramBinaryOES=0; // Retrieves the functions needed to use the extension. if (m_bBinaryShaderSupported) { glGetProgramBinaryOES = (PFNGLGETPROGRAMBINARYOESPROC) PVRGetProcAddress(glGetProgramBinaryOES); glProgramBinaryOES = (PFNGLPROGRAMBINARYOESPROC) PVRGetProcAddress(glProgramBinaryOES); } #endif // If binary shaders are not supported or there isn't a valid binary shader stored, recompile the shaders. if (!m_bBinaryShaderSupported || !loadBinaryProgram(shaderPath,m_uiProgramObject)) { { // Fragment shader code const char* pszFragShader = "\ uniform lowp vec3 myColour;\ void main (void)\ {\ gl_FragColor = vec4(myColour, 1.0);\ }"; // Create the fragment shader object m_uiFragShader = glCreateShader(GL_FRAGMENT_SHADER); // Load the source code into it glShaderSource(m_uiFragShader, 1, (const char**)&pszFragShader, NULL); // Compile the source code glCompileShader(m_uiFragShader); // Check if compilation succeeded GLint bShaderCompiled; glGetShaderiv(m_uiFragShader, GL_COMPILE_STATUS, &bShaderCompiled); if (!bShaderCompiled) { // An error happened, first retrieve the length of the log message int i32InfoLogLength, i32CharsWritten; glGetShaderiv(m_uiFragShader, GL_INFO_LOG_LENGTH, &i32InfoLogLength); // Allocate enough space for the message and retrieve it char* pszInfoLog = new char[i32InfoLogLength]; glGetShaderInfoLog(m_uiFragShader, i32InfoLogLength, &i32CharsWritten, pszInfoLog); /* Displays the message in a dialog box when the application quits using the shell PVRShellSet function with first parameter prefExitMessage. */ char* pszMsg = new char[i32InfoLogLength+256]; strcpy(pszMsg, "Failed to compile fragment shader: "); strcat(pszMsg, pszInfoLog); PVRShellSet(prefExitMessage, pszMsg); delete [] pszMsg; delete [] pszInfoLog; delete [] shaderPath; return false; } }
int main(int argc, char * argv[]) { // Load GLFW and Create a Window glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); auto mWindow = glfwCreateWindow(mWidth, mHeight, "OpenGL", nullptr, nullptr); // Check for Valid Context if (mWindow == nullptr) { fprintf(stderr, "Failed to Create OpenGL Context"); return EXIT_FAILURE; } // Create Context and Load OpenGL Functions glfwMakeContextCurrent(mWindow); gladLoadGL(); fprintf(stderr, "OpenGL %s\n", glGetString(GL_VERSION)); glfwSetErrorCallback(&errorCallback); float vertices[] = { 0.0f, 0.5f, 0.5f, -0.5f, -0.5f, -0.5f, }; // Create Vertex Array Object GLuint vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); // Create a Vertex Buffer Object and copy the vertex data to it GLuint vbo; glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); std::ifstream vertexShaderFile(PROJECT_SOURCE_DIR "/Glitter/Shaders/main.vert"); std::string vertexShaderStr((std::istreambuf_iterator<char>(vertexShaderFile)), std::istreambuf_iterator<char>()); auto vertexSource = vertexShaderStr.c_str(); // Create and compile the vertex shader GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &vertexSource, NULL); glCompileShader(vertexShader); assertShaderCompile(vertexShader); std::ifstream fragmentShaderFile(PROJECT_SOURCE_DIR "/Glitter/Shaders/main.frag"); std::string fragmentShaderStr((std::istreambuf_iterator<char>(fragmentShaderFile)), std::istreambuf_iterator<char>()); auto fragmentSource = fragmentShaderStr.c_str(); // Create and compile the fragment shader GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &fragmentSource, NULL); glCompileShader(fragmentShader); assertShaderCompile(fragmentShader); // Link the vertex and fragment shader into a shader program GLuint shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glBindFragDataLocation(shaderProgram, 0, "outColor"); glLinkProgram(shaderProgram); std::cout << glGetError() << std::endl; glUseProgram(shaderProgram); std::cout << glGetError() << std::endl; std::cout << glGetError() << std::endl; // Specify the layout of the vertex data GLint posAttrib = glGetAttribLocation(shaderProgram, "position"); glEnableVertexAttribArray(posAttrib); glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 0, 0); std::cout << glGetError() << std::endl; // Rendering Loop while (glfwWindowShouldClose(mWindow) == false) { if (glfwGetKey(mWindow, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(mWindow, true); // Background Fill Color glClearColor(0.25f, 0.25f, 0.25f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); // Draw a triangle from the 3 vertices glDrawArrays(GL_TRIANGLES, 0, 3); // Flip Buffers and Draw glfwSwapBuffers(mWindow); glfwPollEvents(); } glfwTerminate(); glDeleteProgram(shaderProgram); glDeleteShader(fragmentShader); glDeleteShader(vertexShader); glDeleteBuffers(1, &vbo); glDeleteVertexArrays(1, &vao); return EXIT_SUCCESS; }
bool Material::LoadShader(std::string filepath, ShaderType type) { if (!program) program = glCreateProgram(); const char* shaderCode = FileSystem::LoadTextFile(filepath.c_str()); if (!shaderCode) return 0; uint* index = 0; GLenum t; switch (type) { case ShaderType::Vertex: index = &vertex; t = GL_VERTEX_SHADER; break; case ShaderType::TessControl: index = &tessControl; t = GL_TESS_CONTROL_SHADER; break; case ShaderType::TessEval: index = &tessEval; t = GL_TESS_EVALUATION_SHADER; break; case ShaderType::Geometry: index = &geometry; t = GL_GEOMETRY_SHADER; break; case ShaderType::Fragment: index = &fragment; t = GL_FRAGMENT_SHADER; break; case ShaderType::Compute: index = &compute; t = GL_COMPUTE_SHADER; break; default: return 0; } *index = glCreateShader(t); glShaderSource(*index, 1, &shaderCode, 0); glCompileShader(*index); #if LUMINA_DEBUG GLint check; glGetShaderiv(*index, GL_COMPILE_STATUS, &check); if (!check) { char log[1000] = { 0 }; int length; glGetShaderiv(*index, GL_INFO_LOG_LENGTH, &length); glGetShaderInfoLog(*index, length, 0, log); std::cout << log << std::endl; return 0; } glAttachShader(program, *index); glLinkProgram(program); glGetProgramiv(program, GL_LINK_STATUS, &check); if (!check) { char log[1000] = { 0 }; int length; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &length); glGetShaderInfoLog(program, length, 0, log); std::cout << log << std::endl; glDeleteProgram(program); return 0; } #endif return true; }