Potter
Potter

Reputation: 643

webgl - how do i declare a float variable

super simple question: how do i properly declare a float variable in webgl?

Background:

I'm playing with this codepen: http://codepen.io/jlfwong/pen/Wxjkxv

the point of this codepen is to allow you set the color of each pixel in a shader based on a render function.

I get the basics and I got things working pretty well, but then I tried to get "fancy".

I'm focussing on this section:

var fragmentShader = compileShader('                           \n\
  void main(){                                                 \n\
    gl_FragColor = vec4(step(25.0, mod(gl_FragCoord.x, 50.0)), \n\
                        step(25.0, mod(gl_FragCoord.x, 50.0)), \n\
                        step(25.0, mod(gl_FragCoord.x, 50.0)), \n\
                        1.0);                                  \n\
  }                                                            \n\
', context.FRAGMENT_SHADER);

All I want to do is save step(25.0, mod(gl_FragCoord.x, 50.0)) off to a variable so i tried this:

var fragmentShader = compileShader('                           \n\
  void main(){                                                 \n\
    float x_thing = step(25.0, mod(gl_FragCoord.x, 50.0));     \n\
                                                               \n\
    gl_FragColor = vec4(x_thing, x_thing, x_thing, 1.0);       \n\
  }                                                            \n\
', context.FRAGMENT_SHADER);

This doesn't work because it seems to be missing a precision declaration for float. here is the error:

uncaught exception: Shader compile failed with: ERROR: 0:3: '' : No precision specified for (float)

I have tried a few things to remedy this:

Also i've been googling and fiddling with this for a while and I'm just annoyed with having issues declaring a variable :P

TL;DR

how do i properly declare a float variable in webgl? / what am i doing wrong?

Upvotes: 1

Views: 1451

Answers (1)

Potter
Potter

Reputation: 643

I found the secret! looks like float precision needs to be declared outside functions...

var fragmentShader = compileShader('                       \n\
  precision highp float;                                   \n\
                                                           \n\
  void main(){                                             \n\
    float x_thing = step(25.0, mod(gl_FragCoord.x, 50.0)); \n\
    gl_FragColor = vec4(x_thing,                           \n\
                        x_thing,                           \n\
                        x_thing,                           \n\
                        1.0);                              \n\
  }                                                        \n\
', context.FRAGMENT_SHADER);

Upvotes: 2

Related Questions