Heightmap Generation

Shader Class

Language: C++

This class wrap an OpenGL shader and provide some functionalities for its creation. Logic for its utilisation is implemented in the shader program class.

Code sample

Header

class Shader
{
public:
    //Create an unitialized OpenGL shader
    Shader();
 
    //Create and compile an OpenGL shader from a string buffer
    void createFromString(char *str);
 
    //Create and compile an OpenGL shader from a file
    void createFromFile(char *file);
 
    //Output the content of this shader's log
    void printInfoLog();
 
    //Return the shader handle
    GLuint getShaderHandle();
 
protected:
    //This shader handle
    GLuint m_handle;
 
    //Call the OpenGL API to create the shader accordingly with its type
    virtual void createShader()=0;
 
    //Compile the shader after it has been loaded
    void compileShader();
};

Implementation

//Create an unitialized OpenGL shader
Shader::Shader()
{
    m_handle = 0;
}
 
//Return the shader handle
GLuint Shader::getShaderHandle(){
    return m_handle;
}
 
//Create and compile an OpenGL shader from a string buffer
void Shader::createFromString(char *str){
    const char *pstr = str;
 
    //Obtain a shader hadle from OpenGL
    createShader();
    //Load its source
    glShaderSource(m_handle, 1, &pstr,NULL);
    //And compile it
    glCompileShader(m_handle);
}
 
//Create and compile an OpenGL shader from a file
void Shader::createFromFile(char *file){
    FILE *fp;
    char *content = NULL;
    int count=0;
 
    if (file != NULL) 
    {
        fp = fopen(file,"rt");
        if (fp != NULL)
        {      
            fseek(fp, 0, SEEK_END);
            count = ftell(fp);
            rewind(fp);
 
            if (count > 0) {
                content = new char[(count+1)];
                count = fread(content,sizeof(char),count,fp);
                content[count] = '\0';
            }
            fclose(fp);
        }
    }
 
    //Use the file content to create the shader
    createFromString(content);
 
    delete content;
}
 
//Output the content of this shader's log
void Shader::printInfoLog(){
    int infologLength = 0;
    int charsWritten = 0;
    char *infoLog;
 
    glGetShaderiv(m_handle, GL_INFO_LOG_LENGTH, &infologLength);
 
    if (infologLength > 0)
    {
        infoLog = new char[infologLength];
        glGetShaderInfoLog(m_handle, infologLength, &charsWritten, infoLog);
        printf("%s\n",infoLog);
        delete infoLog;
    }
}
 
//Compile the shader after it has been loaded    
void Shader::compileShader(){
    glCompileShader(m_handle);
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License