Search code examples
openglglsl

What is the correct way to set a bool vec uniform in OpenGL?


In my shader I have a bvec4 uniform defined like so:

uniform bvec4 Flags;

What is the correct way to set this from my code?

I initially assumed I would set it with glUniform1i(location, bits), but that did not work.


Solution

  • From the OpenGL specification section 2.2.1:

    When the type of internal state is boolean, zero integer or floating-point values are converted to FALSE and non-zero values are converted to TRUE

    So you can use glUniform4iv and pass it a buffer of 4 integers where bits[I] occupies ints[I]. The values will be converted to false if zero, and true otherwise.

    Similarly, you can use glUniform3iv to set a bvec3, glUniform2iv to set a bvec2, and glUniform1iv or glUniform1i to set a bool.

    Here is an example in Java using LWJGL 3:

    GL20.glUniform4iv(location, new int[]{bits & 0b1, bits & 0b10, bits & 0b100, bits & 0b1000});
    

    You should probably create an int[] or an IntBuffer once and reuse it though.