Why does my OpenGL Phong shader behave like a flat shader?

后端 未结 2 1618
青春惊慌失措
青春惊慌失措 2020-12-07 11:30

I\'ve been learning OpenGL for the past couple of weeks and I\'ve run into some trouble implementing a Phong shader. It appears to do no interpolation between vertexes despi

2条回答
  •  孤城傲影
    2020-12-07 12:04

    As an addition to this answer, here is a simple geometry shader which will let you visualize your normals. Modify the accompanying vertex shader as needed based on your attribute locations and how you send your matrices.

    But first, a picture of a giant bunny head from our friend the Stanford bunny as an example of the result !

    normals for the Stanford bunny

    Major warning: do note that I get away with transforming the normals with the modelview matrix instead of a proper normal matrix. This won't work correctly if your modelview contains non uniform scaling. Also, the length of your normals won't be correct but that matters little if you just want to check their direction.

    Vertex shader:

    #version 330
    
    layout(location = 0) in vec4 position;
    layout(location = 1) in vec4 normal;
    layout(location = 2) in mat4 mv;
    
    out Data
    {
        vec4 position;
        vec4 normal;
        vec4 color;
        mat4 mvp;
    } vdata;
    
    uniform mat4 projection;
    
    void main()
    {
        vdata.mvp = projection * mv;
        vdata.position = position;
        vdata.normal = normal;
    }
    

    Geometry shader:

    #version 330
    layout(triangles) in;
    layout(line_strip, max_vertices = 6) out;
    
    in Data
    {
        vec4 position;
        vec4 normal;
        vec4 color;
        mat4 mvp;
    } vdata[3];
    
    out Data
    {
        vec4 color;
    } gdata;
    
    void main()
    {
        const vec4 green = vec4(0.0f, 1.0f, 0.0f, 1.0f);
        const vec4 blue = vec4(0.0f, 0.0f, 1.0f, 1.0f);
    
        for (int i = 0; i < 3; i++)
        {
            gl_Position = vdata[i].mvp * vdata[i].position;
            gdata.color = green;
            EmitVertex();
    
            gl_Position = vdata[i].mvp * (vdata[i].position + vdata[i].normal);
            gdata.color = blue;
            EmitVertex();
    
            EndPrimitive();
        }
    }
    

    Fragment shader:

    #version 330
    
    in Data
    {
        vec4 color;
    } gdata;
    
    out vec4 outputColor;
    
    void main()
    {
        outputColor = gdata.color;
    }
    

提交回复
热议问题