When constructing your shaders, I notice sometimes a void function named main is constructed is used to define the shader. It seems like main
is added to the shader when an attributed is iterated on.
I wanted to get some clarity for when it is appropriate to define the shader inside main
as opposed to just within the top-level definition space of the shader.
Example code from the regl tutorial.
var drawTriangle = regl({
//
// First we define a vertex shader. This is a program which tells the GPU
// where to draw the vertices.
//
vert: `
// This is a simple vertex shader that just passes the position through
attribute vec2 position;
void main () {
gl_Position = vec4(position, 0, 1);
}
`,
//
// Next, we define a fragment shader to tell the GPU what color to draw.
//
frag: `
// This is program just colors the triangle white
void main () {
gl_FragColor = vec4(1, 1, 1, 1);
}
`,
// Finally we need to give the vertices to the GPU
attributes: {
position: [
[1, 0],
[0, 1],
[-1, -1]
]
},
// And also tell it how many vertices to draw
count: 3
})
I'm not familiar with regl, but a main()
function is always required for GLSL shaders. It is the shader's entry point. For example in the case of the vertex shader, the shader's main()
function will be executed for each vertex. In your tutorial code, gl_Position
is a builtin (as opposed to user-defined) output of the vertex shader. attribute vec2 position;
defines an input variable for the vertex shader which gives access to the position
attribute.