0
votes

I'm finding the way to create some noise in WEBGL shaders. Some noise for vertex displacement or colors randomization inside shader itself. I want to have it inside a shader in order to not consider what i'm rendering. Just to make current fragment color randomized or vertex position moved a bit.

You can see my shaders code here: https://github.com/rantiev/webgl-learning/blob/master/stars/index.html

It's plain simple shaders:

<script id="shader-fs" type="x-shader/x-fragment">
    precision mediump float;    
    varying vec2 vTextureCoord;    
    uniform sampler2D uSampler;    
    uniform vec3 uColor;    
    void main(void) {
        vec4 textureColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t));
        gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
    }   
</script>
1
A quick google for "GLSL noise" brings up lots of them. These ones on stackoverflow for example. This article from the Book of Shaders. Searching shadertoy.com also brings up lots of examples - gman
Here is a great repository with several kinds of noise functions which do not require an textures or other uniform inputs. Each file is fully self-sufficient. Just copy-paste the entire file into your shader and enjoy. - Sergey
Thanks guys. I'm talking about WEBGL, looking to these links you proposed (which i saw before) i got even more questions. What is .glsl files etc. I want to add noise into shader script in HTML. I think it's possible without any .glsl files c++ samples and other crazy stuff. I might be wrong - novice to WEBGL. - Rantiev
Thanks, Ah now i see that i can use .glsl, thought it has nothing to do with WEBGL. - Rantiev

1 Answers

1
votes

Here is one way to do it:

First, we calculate a screen space uv by dividing gl_Position.xy by gl_Position.ww and remap it from (-1, +1) to (0 to 1).

vec4 projCoords = projection * view * model * attr_pos;

vec2 screenUV = projCoords.xy/projCoords.ww; // (from -1 to 1)
screenUV = screenUV * 0.5 + 0.5; // remap to (0 to 1)

Then with this uv we can apply a screen space noise via either a random texture or some math calculation in the shader. Assuming that you generated a random texture, then noise is simply:

vec4 noise = texture2D(u_randomTexture, screenUV);

If you want to use calculations in the shader, look into implementing something like perlin2D noise or perhaps search in shadertoy.