Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 245
Iter Ator Avatar asked Oct 21 '15 23:10

Iter Ator


People also ask

Does WebGL use GLSL?

Shaders in WebGL are expressed directly in GLSL and passed to the WebGL API as textual strings. The WebGL implementation compiles these shader instructions to GPU code. This code is executed for each and every vertex sent through the API and for each pixel rasterized to the screen.

What is gl_Position in WebGL?

gl_Position is the predefined variable which is available only in the vertex shader program. It contains the vertex position. In the above code, the coordinates attribute is passed in the form of a vector. As vertex shader is a per-vertex operation, the gl_position value is calculated for each vertex.

How do I optimize GLSL?

One way to speed up GLSL code, is by marking some variables constant at compile-time. This way the compiler may optimize code (e.g. unroll loops) and remove unused code (e.g. if hard shadows are disabled). The drawback is that changing these constant variables requires that the GLSL code is compiled again.


1 Answers

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)

like image 91
maddouri Avatar answered Sep 29 '22 23:09

maddouri