6
$\begingroup$

EDIT: This is a duplicate of a question from stack overflow: https://stackoverflow.com/questions/9222217/how-does-the-fragment-shader-know-what-variable-to-use-for-the-color-of-a-pixel

If you want to send a value from vertex shader to fragment shader, the vertex shader should declare one variable as out, the fragment shader should declare other variable as in and both variables must have their names and types equal. But this doesn't happen when you want to send the color value from the fragment shader. In fact, you can call the output variable as you want. Why? In older version there was one variable called gl_FragColor
How the program links your output fragment variable with gl_FragColor?

$\endgroup$
2

1 Answer 1

7
$\begingroup$

It works almost exactly the same way as vertex shader inputs.

In vertex shaders, you have inputs. And these inputs represent vertex attribute indices, the numbers you pass to glVertexAttribPointer and glEnableVertexAttribArray and so forth. You set up which input pulls from which attribute. In GLSL 3.30, you use this syntax:

layout(location = 2) in color;

This sets the color vertex shader input to come from attribute location 2. Before 3.30 (or without ARB_explicit_attrib_location), you would have to either set this up explicitly with glBindAttrbLocation before linking or query the program for the attribute index with glGetAttribLocation. If you don't explicitly provide an attribute location, GLSL will assign a location arbitrarily (ie: in an implementation-defined manner).

Setting it in the shader is almost always the better option.

In any case, fragment shader outputs work almost exactly the same way. Fragment shaders can write to multiple output colors, which themselves get mapped to multiple buffers in the framebuffer. Therefore, you need to indicate which output goes to which fragment output color.

This process begins with the fragment output location value. It's set very similarly to vertex shader input locations:

layout(location = 1) out secColor;

There are also the API functions glBindFragDataLocation and glGetFragDataLocation, which are analogous to glBindAttribLocation and glGetAttribLocation.

If you don't do any explicit assignments, implementations usually will assign one of your output variables to location 0. However, the OpenGL standard does not require this behavior, so you should not depend on it either.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.