Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shader position vec4 or vec3

I have read some tutorials about GLSL. In certain position attribute is a vec4 in some vec3. I know that the matrix operations need a vec4, but is it worth to send an additional element? Isn't it better to send vec3 and later cast in the shader vec4(position, 1.0)? Less data in memory - it will be faster? Or we should pack an extra element to avoid casting?

Any tips what should be better?

layout(location = 0) in vec4 position;
MVP*position;

or

layout(location = 0) in vec3 position;
MVP*vec4(position,1.0);
like image 643
Skides Avatar asked Sep 21 '13 16:09

Skides


People also ask

Why is gl_Position a vec4?

gl_Position is of type vec4, requiring four numbers, because the coordinates are specified as homogeneous coordinates (Subsection 3.5. 3). The special variable gl_FragCoord in the fragment shader is also a vec4, giving the coordinates of the pixel as homogeneous coordinates.

What is vec4 in opengl?

vec4 is a floating point vector with four components. It can be initialized by: Providing a scalar value for each component. Providing one scalar value. This value is used for all components.

What is gl_ position?

gl_Position is a special variable that holds the position of the vertex in clip space. Since a vertex shader's main output is the position in clip space, it must always set gl_Position. This vertex shader just transforms each vertex position (by the VP matrix).

How many bytes is a vec4?

Any float value is stored in 4 consecutive bytes of memory. A sequence of 4 floats, in GLSL parlance a vec4, is exactly that: a sequence of four floating-point values. Therefore, a vec4 takes up 16 bytes, 4 floats times the size of a float. The vertexData variable is one large array of floats.


1 Answers

For vertex attributes, this will not matter. The 4th component is automatically expanded to 1.0 when it is absent.

That is to say, if you pass a 3-dimensional vertex attribute pointer to a 4-dimensional vector, GL will fill-in W with 1.0 for you. I always go with this route, it avoids having to explicitly write vec4 (...) when doing matrix multiplication on the position and it also avoids wasting memory storing the 4th component.

This works for 2D coordinates too, by the way. A 2D coordinate passed to a vec4 attribute becomes vec4 (x, y, 0.0, 1.0). The general rule is this: all missing components are replaced with 0.0 except for W, which is replaced with 1.0.

However, to people who are unaware of the behavior of GLSL in this circumstance, it can be confusing. I suppose this is why most tutorials never touch on this topic.

like image 123
Andon M. Coleman Avatar answered Dec 22 '22 22:12

Andon M. Coleman