In summary, I have the following vertices buffer:
GLfloat _vertices[] = {
-1.0f, -1.0f,
1.0f, -1.0f,
-1.0f, 1.0f,
1.0f, -1.0f,
1.0f, 1.0f,
-1.0f, 1.0f };
I then set the vertices and call draw like this:
glViewport(0, 0, w, h);
glEnableVertexAttribArray(0);
glDisable(GL_BLEND);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, _vertices);
glDrawArrays(GL_TRIANGLES, 0, 6);
My Vertex shader is as:
#version 320 es
layout(location = 0) in vec2 vertPos;
out vec2 fragPos;
out float theLength;
void main()
{
fragPos = vertPos;
theLength = length(fragPos);
gl_Position = vec4(vertPos.xy, 1.0, 1.0);
}
And the fragment is:
#version 320 es
precision mediump float;
in vec2 fragPos;
in float theLength;
out vec4 fragColor;
void main()
{
vec4 color = vec4(0.0);
float d = length(fragPos);
fragColor = vec4(d, 0.0, 0.0, 1.0);
}
With the fragment like the one above I have the following image:
If I change the line fragColor = vec4(d, 0.0, 0.0, 1.0);
to fragColor = vec4(theLength, 0.0, 0.0, 1.0);
I got:
Why do I obtain different results? I was expecting to have a red square. I'm using glsl shaders within SDL. Maybe SDL is implementing a Geometry Shader in the background?
Thank you.
With fragColor = vec4(theLength, 0.0, 0.0, 1.0);
, the length is only calculated on each vertex, then the length results for the vertices are interpolated.
Since all vertices have the same length (probably sqrt(2)), all interpolations between those values yield the same result.
In the original version, the length is calculated for each pixel (fragment) separately. This leads to having smaller values towards the center.
The important difference is which values get interpolated. In the first version, it's the position (which varies between vertices). Example for the first pixel row: fragPos.x is interpolated from -1 to 1 (with all values inbetween). fragPos.y is constant -1. When you then calculate the distance, you get different value for each fragment.
In the second version, it's the length which doesn't vary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With