Arrays in GLSL
You can use arrays in GLSL to store more than one object.
You can declare an array outside of your
main()
function something like this:
const int ns = 2; // MUST BE CONSTANT
vec4 Sph[ns]; // YOU CANNOT ASSIGN VALUES TO ARRAY ELEMENTS HERE
For now, we assign values inside the
main()
function,
something like this:
main() {
...
Sph[0] = vec4(....);
Sph[1] = vec4(....);
...
}
This is wasteful, because we are assigning values
for every call to
main()
.
In the next class we will
learn how to send values down from the CPU to the
GPU, so that array values can be assigned just once per
animation frame.
Also, when you loop over the values of an array,
the number of times you will be looping must be
known at compile time (since loops are actually
unrolled by the compiler).
So this, for example, is valid, because we have declared
ns
to be a constant:
for (int is = 0 ; is < ns ; is++) {
...
vec4 sph = Sph[is];
...
}
In contrast, the following code is not valid,
because the number of iterations of the loop
cannot be known at compile time:
void function myFunction(int n) {
for (int is = 0 ; is < n ; is++) {
...
vec4 sph = Sph[is];
...
}
}
In fact, the above code will produce the following compiler error:
Loop index cannot be compared with non-constant expression
Storing values in matrices
We also learned in class that we can use the
mat4
data type to store up to 16 values. For example,
we might store the ambient, diffuse and
specular values for a surface within a
mat4
as follows:
mat4 M = mat4(.1,.0,.0,.0, .5,.0,.0,.0, 1.,1.,1.,20., .0,.0,.0,.0);
Note that the
mat4(...)
constructor needs to have exactly 16 floating point arguments,
which is why we pad it on the end with zeroes.
We can access the columns of a
mat4
as
M[0],M[1],M[2],M[3]
.
So, for example, to retrieve the ambient, diffuse
and specular rgb color values,
as well as the specular power,
we could specify:
vec3 ambient = M[0].rgb;
vec3 diffuse = M[1].rgb;
vec3 specular = M[2].rgb;
float p = M[2].a ; // get the 4th element of column 2 of the matrix.