在openGL里写一个Shader

Posted Pudding

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在openGL里写一个Shader相关的知识,希望对你有一定的参考价值。

1、总体代码

draw一个三角形,自写vertex着色器和fregment着色器,三角形染红色。

#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>

static unsigned int CompileShader( unsigned int type, const std::string& source)
{
    unsigned int id = glCreateShader(type);
    const char* src = source.c_str();
    glShaderSource(id, 1, &src,nullptr);
    glCompileShader(id);

    //TODO:Error handling
    int result;
    glGetShaderiv(id, GL_COMPILE_STATUS, &result);
    if (result == GL_FALSE)
    {
        int length;
        glGetShaderiv(id, GL_INFO_LOG_LENGTH, &length);
        char* message = (char*)alloca(length * sizeof(char));

        glGetShaderInfoLog(id, length, &length, message);
        std::cout << "Failed to compile " <<(type == GL_VERTEX_SHADER ? "vertex" : "fragment") << "shader!" 
            << std::endl;
        std::cout << message << std::endl;
        glDeleteShader(id);
    }

    return id;
}

static unsigned int CreateShader(const std::string& vectexShader, const std::string& fragmentShader)
{
   unsigned int program = glCreateProgram();
   unsigned int vs = CompileShader(GL_VERTEX_SHADER, vectexShader);
   unsigned int fs = CompileShader(GL_FRAGMENT_SHADER, fragmentShader);

   glAttachShader(program, vs);
   glAttachShader(program, fs);
   glLinkProgram(program);
   glValidateProgram(program);

   glDeleteShader(vs);
   glDeleteShader(fs);

   return program;
}

int main(void)
{
    GLFWwindow* window;

    /* Initialize the library */
    if (!glfwInit())
        return -1;
    
    /* Create a windowed mode window and its OpenGL context */
    window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }

    /* Make the window‘s context current */
    glfwMakeContextCurrent(window);

    if (glewInit() != GLEW_OK)
        std::cout << "GLEW INIT ERR" << std::endl;

    std::cout << glGetString(GL_VERSION) << std::endl;

    float position[6] = {
        -0.5f, -0.5f,
         0.0f,  0.5f,
         0.5f, -0.5f,
    };

    unsigned int buffer;
    glGenBuffers(1, &buffer);
    glBindBuffer(GL_ARRAY_BUFFER, buffer);
    glBufferData(GL_ARRAY_BUFFER, 6 * sizeof(float), position, GL_STATIC_DRAW);

    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, 0);

    std::string vertexShader =
        "#version 330 core\n"
        "\n"
        "layout(location = 0) in vec4 position;\n"
        "void main()\n"
        "{\n"
        "    gl_Position = position;\n"
        "}\n";

    std::string fragmentShader =
        "#version 330 core\n"
        "\n"
        "layout(location = 0) out vec4 color;\n"
        "void main()\n"
        "{\n"
        "    color = vec4(1.0, 0.0, 0.0, 1.0);\n" //RGB
        "}\n";

    unsigned int shader = CreateShader(vertexShader, fragmentShader);
    glUseProgram(shader);


    /* Loop until the user closes the window */
    while (!glfwWindowShouldClose(window))
    {
        /* Render here */
        glClear(GL_COLOR_BUFFER_BIT);

        glDrawArrays(GL_TRIANGLES, 0, 3);

        /* Swap front and back buffers */
        glfwSwapBuffers(window);

        /* Poll for and process events */
        glfwPollEvents();
    }

    glDeleteProgram(shader);

    glfwTerminate();
    return 0;
}

2、解析

具体的gl函数文档可以见这个网站: opengl文档.
一个十分好用的中文网站:learnOpenGL-CN

  • glGenBuffers glGenBuffers:生成缓冲区对象名称

    • 声明:void glGenBuffers( GLsizei n,
      GLuint * buffers);
    • 参数:
      • n :Specifies the number of buffer object names to be generated.指定要生成的缓冲区对象名称的数目。
      • buffers :Specifies an array in which the generated buffer object names are stored. 指定存储生成的缓冲区对象名称的数组。
    • 说明:
      glGenBuffers returns n buffer object names in buffers. There is no guarantee that the names form a contiguous set of integers; however, it is guaranteed that none of the returned names was in use immediately before the call to glGenBuffers.
      unsigned int objectId = 0;
      glGenObject(1, &objectId);//我们首先创建一个对象,然后用一个id保存它的引用(实际数据被储存在后台)
      
      返回n个缓冲对象名称,不能保证名字会组成一个连续的整数集,但是能保证在调用glGenBuffers前没有被立即使用过。
  • glBindBuffer glBindBuffer

以上是关于在openGL里写一个Shader的主要内容,如果未能解决你的问题,请参考以下文章

初识OpenGL 片段着色器(Fragment Shader)

Visual Studio 2012 和 2010 中基于 Opengl Sierpinski Shader 的 C 代码

OpenGL 之 Compute Shader(通用计算并行加速)

片段着色器中未使用纹理数据 - OpenGL

Shader2.0的顶点着色器和片段着色器

着色器在 Opengl Shader Builder 上工作,但不在我的 OpenGL 应用程序中