Reputation: 45
My code compiled without errors, but did not work until I added the vec3 in front of the brackets. The contents were vec3 components, so I would have assumed that GLSL is treating it like a vector or give me an error if it can't but it just accepted it. The error message (cannot convert from float to highp 3-component vector of float) only appears if I remove the "-vec3(0.)".
So what is the meaning of just (...) in GLSL and why is it silently accepted when subtracting a vec3?
Examples:
//this works:
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 uv = fragCoord.xy/iResolution.xy;
vec3 col = vec3(uv.x, uv.y, 0.)-vec3(0.);
fragColor = vec4(vec3(col), 1.);
}
.
//this doesn't:
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 uv = fragCoord.xy/iResolution.xy;
vec3 col = (uv.x, uv.y, 0.)-vec3(0.);
fragColor = vec4(vec3(col), 1.);
}
.
//this gives the helpful error message
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 uv = fragCoord.xy/iResolution.xy;
vec3 col = (uv.x, uv.y, 0.);
fragColor = vec4(vec3(col), 1.);
}
Upvotes: 0
Views: 1005
Reputation: 8123
This is not exclusive to GLSL but actually a lot of C style languages.
vec3
is a constructor, an expression like vec3(1,2,3)
passes the arguments 1
2
and 3
separated by the comma to the constructor function which will in turn construct a vector with three componenets initialized to the given parameters and return it.
In the case of (1,2,3)
the comma does not act as a separator but as an operator, making it a list of instructions where the result of the last instruction is propagated to the outside, in this specific case 3
. If you were to write (1,2,3) + 5
the result would be 8
. You can read more about the comma operator and some common use cases on wikipedia.
Now comes the GLSL specific part:
(1.,2.,3.)-vec3(0)
results in 3.-vec3(0)
, as GLSL is all about vector math this is a valid vector-scalar operation, resulting in the scalar operation being applied to the individual components of the vector. in this case this is the same as writing vec3(3.-0.,3.-0.,3.-0.)
. Another example would be 5.*vec3(2,3,4)
which results in vec3(2*5,3*5,4*5)
=> vec3(10,15,20)
. This is not a type cast since scalar on vector operations are defined as such, just like transforming a vector by a matrix does not require one to be cast to the other.
Upvotes: 3