GoofyBall
GoofyBall

Reputation: 411

Acessing VBO/VAO Data in GLSL Shader

In a vertex shader how can a function within the shader be made to access a specific attribute array value after buffering its vertex data to a VBO?

In the shader below the cmp() function is supposed to compare a uniform variable with vertex i.

#version 150 core

in vec2 vertices;
in vec3 color;
out vec3 Color;

uniform mat4 projection;
uniform mat4 view;
uniform mat4 model;

uniform vec2 cmp_vertex; // Vertex to compare
out int isEqual;         // Output variable for cmp()

// Comparator 
vec2 cmp(){
  int i = 3; 
  return (cmp_vertex == vertices[i]); 
}

void main() {
    Color = color;
    gl_Position = projection * view * model * vec4(vertices, 0.0, 1.0);
    isEqual = cmp();
}

Also, can cmp() be modified so that it does the comparison in parallel?

Upvotes: 1

Views: 719

Answers (1)

Reto Koradi
Reto Koradi

Reputation: 54572

Based on the naming in your shader code, and the wording of your question, it looks like you misunderstood the concept of vertex shaders.

The vertex shader is invoked once for each vertex. So when your vertex shader code executes, it always operates on a single vertex. This means that the name of your in variable is misleading:

in vec2 vertices;

This variable gives you the position of the one and only vertex your shader is working on. So it would probably be clearer if you used a name in singular form:

in vec2 vertex;

Once you realize that you're operating on a single vertex, the rest becomes easy. For the comparison:

bool cmp() {
    return (cmp_vertex == vertex); 
}

Vertex shaders are typically already invoked in parallel, meaning that many instances can execute at the same time, each one on its own vertex. So there is no need for parallelism within a single shader instance.

You'll probably have more issues achieving what you're after. But I hope that this gets you at least over the initial hurdle.

For example, the following out variable is problematic:

out int isEqual;

out variables of the vertex shader have matching in variables in the fragment shader. By default, the value written by the vertex shader is linearly interpolated across triangles, and the fragment shader gets the interpolated values. This is not supported for variables of type int. They only support flat interpolation:

flat out int isEqual;

But this will probably not give you what you're after, since the value you see in the fragment shader will always be the same across an entire triangle.

Upvotes: 1

Related Questions