Writing a Shader in OpenGL - hls333555/OpenGL GitHub Wiki

Here are the main steps on how to create a vertex shader:

Shader Part

  • Construct a shader source, here we use C++11 raw string literals:

    std::string vertexShaderSource = R"(
    	#version 330 core
    	
    	// The location of the position vertex attribute data is 0
    	layout(location = 0) in vec4 position;
    	void main()
    	{
    		gl_Position = position;
    	}
    )";
    
  • Create a shader object:

    unsigned int vsId = glCreateShader(GL_VERTEX_SHADER);
    
  • Load the shader source into the shader object:

    const char* src = vertexShaderSource.c_str();
    glShaderSource(vsId, 1, &src, nullptr);
    
  • Compile the shader object:

    glCompileShader(vsId);
    
    int result;
    glGetShaderiv(vsId, GL_COMPILE_STATUS, &result);
    if(result == GL_FALSE)
    {
        int length;
        glGetShaderiv(vsId, GL_INFO_LOG_LENGTH, &length);
        // Allocate on the stack dynamically
        char* message = (char*)_malloca(length * sizeof(char));
        // Return the information log for the shader object
        glGetShaderInfoLog(vsId,length, &length, message);
        std::cout << "Failed to compile vertex shader!" << std::endl;
        std::cout << message << std::endl;
        glDeleteShader(vsId);
        return 0;
    }
    

Program Part

  • Create the program object:

    unsigned int program = glCreateProgram();
    
  • Attach shaders to the program object:

    glAttachShader(program, vsId);
    
  • Link the program:

    glLinkProgram(program);
    
  • Validate the program object:

    // Check to see whether the executables contained in program can execute given the current OpenGL state
    glValidateProgram(program);
    
    int result;
    glGetProgramiv(program, GL_VALIDATE_STATUS, &result);
    if(result == GL_FALSE)
    {
        std::cout << "Failed to validate program!" << std::endl;
        return 0;
    }
    
  • Use the program object:

    // Install the program object as part of current rendering state
    glUseProgram(program); // Do not forget this!
    
  • Delete the program object at last:

    glDeleteProgram(program);