Triangle with out vertex
Here is the code:
void main()
{
float x = -1.0 + float((gl_VertexID & 1) << 2);
float y = -1.0 + float((gl_VertexID & 2) << 1);
gl_Position = vec4(x, y, 0, 1);
}
This code allow us to draw a trangle without providing specific vertex coords.
Basics on rendering
Shaders are programs user wrote to run on some stage of the GPU.
The two most vital componenet shader are vertex and fragment.
vertex handles coordinates in the virtual space. fragment handles the color, depth and other stuff.
How does this programm work
Overview
through a method, we get x
and y
value, we then put them with the predetermined z
and w
value, which is set to 0 and 1, the standards for 2D graphics.
layer 1.
we get both calculations of x and y by minusing the output of float(things in here)
layer 2
we get the output of x
in float(things in here)
by bitshifting (gl_VertexID & 1)
to the left by 2. This means that we times the number we get from (gl_VertexID & 1)
by 4.
we get the output of y
in float(things in here)
by bitshifting (gl_VertexID & 2)
to the left by 1. This means thaht we times the number we get from (gl_VertexID & 2)
by 2.
layer 3
gl_VertexID
: This is a built-in variable in GLSL that provides the index of the currently processed vertex.
(gl_VertexID & 1)
extract the least significant bit(the big on the most right of the binary number). this is becuase it is comparing the binary number of gl_VertexID
with the binary number of 1, which is 0001
.
So if gl_VertexID
is 2, which is 0010
in binary, and we do an and operation with 0001
, we get 0000
, which is 0, which matches the least significant bit in 0010
.
The samee logic goes for (gl_VertexID & 2)
, but now we are getting the second least significant bit.
So..
if these logics are run for gl_VertexID
equals 1, 2, and 3, we will get the coordinates {-1, -1}, {3, -1}, and {-1, 3}, which is a triangle.