Search code examples
openglattributesglslvertex-shaderpixel-shader

What happens if Vertex Attributes not match Vertex Shader Input


As I know, if the vertex buffer has an attribute that shader does not use, there will be no problem.

What happens if the vertex buffer does not have an attribute that the vertex shader uses for OpenGL?

I know for DirectX11, nothing will draw if the attribute needed in shader is not provided in vertex buffer.

Example

vb only has: position

vertex shader:

attribute vec3 position;
attribute vec4 color;
varying vec4 out_color;
void main()
{
  gl_Position = vec4(position, 1.0);
  out_color = color;
}

pixel shader:

varying vec4 out_color;
void main()
{
  gl_FragColor = vertex_color;
}

What is the pixel color after the shaders executed?


Solution

  • There are two scenarios:

    1. If the attribute array is enabled (i.e. glEnableVertexAttribArray() was called for the attribute), but you didn't make a glVertexAttribPointer() call that specifies the data to be in a valid VBO, bad things can happen. I believe it can be implementation dependent what exactly the outcome is. For example, the draw call could crash, or there could be garbage rendering. The best thing I can find in the spec, which still sounds somewhat vague to me, is:

      Most, but not all GL commands operating on buffer objects will detect attempts to read from or write to a location in a bound buffer object at an offset less than zero, or greater than or equal to the buffer’s size. When such an attempt is detected, a GL error will be generated. Any command which does not detect these attempts, and performs such an invalid read or write, has undefined results, and may result in GL interruption or termination.

    2. If the attribute array is not enabled, the current attribute value is used for all vertices. This is the value set with glVertexAttrib4fv() and similar calls. If no such call was made, the default for the current attribute value is (0.0, 0.0, 0.0, 1.0).