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
?
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With