How to cast int to float in GLSL (WebGL)?

35,474

It seems that you're not allowed to cast in GLSL. Therefore, "you have to use a constructor".

Try this:

// http://www.shaderific.com/glsl-types/
// "Implicit type conversions are not supported.
// Type conversions can be done using constructors..."
float i_float = float(i);
res = i_float / 15.0;

PS: If you have a look at the documentation, it says that "... Either integer type can be converted into floats, and integers and floats can be converted into doubles." ... I find it odd that your code is not accepted by the GLSL compiler. (cf. Reto Koradi's comment)

Share:
35,474
Iter Ator
Author by

Iter Ator

Hobby programmer

Updated on July 09, 2022

Comments

  • Iter Ator
    Iter Ator almost 2 years

    My code is (inside the void main):

    float res;
    
    for(int i=0; i<15; i++) {
    
        res = float(i)/15.0;
    
        //...
    
    }
    

    Unfortunately I get a syntax error at float(i)/15.0

    If I just write i/15.0, then the error is:

    wrong operand types  no operation '/' exists that takes a left-hand operand of type 'mediump int' and a right operand of type 'const float' (or there is no acceptable conversion)
    

    If I just try i/15 then the result is an integer, but I would like to get a float.

    How is it possible to cast int to float?