Such as gl_FragColor = v1 * v2
, i can't really get how does it multiplies and it seems that the reference give the explanation of vector multiply matrix.
ps: The type of v1
and v2
are both vec4
.
1 Answer
The *
operator works component-wise for vectors like vec4
.
vec4 a = vec4(1.0, 2.0, 3.0, 4.0);
vec4 b = vec4(0.1, 0.2, 0.3, 0.4);
vec4 c = a * b; // vec4(0.1, 0.4, 0.9, 1.6)
The GLSL Language Specification says under section 5.10 Vector and Matrix Operations:
With a few exceptions, operations are component-wise. Usually, when an operator operates on a vector or matrix, it is operating independently on each component of the vector or matrix, in a component-wise fashion. [...] The exceptions are matrix multiplied by vector, vector multiplied by matrix, and matrix multiplied by matrix. These do not operate component-wise, but rather perform the correct linear algebraic multiply.
-
-
18@user674199: No, the result of a scalar (=dot) product is a scalar. The result of the
*
GLSL operator on vectors is a vector again. You can make a scalar product out of it, by adding the vector components after the componentwise multiplication. But if you actually need a scalar product, GLSL offers the builtin functiondot
. Dec 16, 2012 at 12:29 -
2Here is a ShaderToy program that illustrates that the multiplication is indeed component-wise.– wipFeb 5, 2014 at 7:38
-
2@FrankCheng In GLSL, doing
vec4 c = a * b;
is the same as doingvec4 c; c.x = a.x * b.x; c.y = a.y * b.y; c.z = a.z * b.z; c.w = a.w * b.w;
. That's what component-wise means— each component of the vector is treated as an algebraic value, ignoring the other components. It may be easier to rationalize if you consider what happens on silicon— a vec4 * vec4 multiplication isn't a mathematical or geometric vector; its simply 4 float values that are independently multiplied by 4 other float values, computed in parallel. Jun 1, 2017 at 23:56 -
2@FrankCheng Because of this, people doing extreme shader optimizations will sometimes lump unrelated data into
vec4
s just so they can get parallelization speedup when doing algebraic operations. TL;DR: To GLSL and the GPU, avec4
doesn't mean anything specific mathematically/geometrically; it's just 4 floats one right after the other in memory. (In programming environments where vectors have intrinsic mathematic meanings, you instead see types likepoint3
,normal3
,offset3
,velocity3
,accel3
, etc.) Jun 1, 2017 at 23:59
vecN * vecN
is NOT scalar dot product.