Monday, February 07, 2011

Ripple effect in WebGL




There is really nothing special to the ripple effect, in essence it is just an evaluation of the sombrero function. This is just a 2D version of the sinc function.




Below is a graph of the sin function, followed by sinc.
Left: sin(x);   Right: sin(x) / x

Extending this to 2D we have:
r = sqrt (x*x + y*y);
z = sin (r) / r;

Plotting this as (x,y,z) we have the sombrero function:

To turn it into a ripple-like looking effect we just need to scale down the "height" of the function, and animate it by adding time into the sin term to generate a repeating pulse. The complete GLSL code is:

#ifdef GL_ES
precision highp float;
#endif

uniform float time;
uniform vec2 resolution;
uniform sampler2D tex;

void main(void) {
vec2 cPos = -1.0 + 2.0 * gl_FragCoord.xy / resolution.xy;
float cLength = length(cPos);

vec2 uv = gl_FragCoord.xy/resolution.xy+(cPos/cLength)*cos(cLength*12.0-time*4.0)*0.03;
vec3 col = texture2D(tex,uv).xyz;

gl_FragColor = vec4(col,1.0);
}

Your browser doesn't appear to support the HTML5 <canvas> element.

3 comments:

Simon Wittber said...

Awesome. I was inspired to recreate this in Unity. Thanks for these awesome posts!

Krish said...

Not working any more inChrome and Firefox. Here is the error:
Warning: WebGL: It is forbidden to load a WebGL texture from a cross-domain element. See https://developer.mozilla.org/en/WebGL/Cross-Domain_Textures
Source File: http://adrianboeing.blogspot.com/2011/02/ripple-effect-in-webgl.html
Line: 626

But thanks for the explanation of the math. Looking forward to more.

Unknown said...

Problem seems to be new restrictions on cross site content.
If you but the image file to same place as the script, everything works nice and dandy :)

http://dl.dropbox.com/u/35529986/kokokakku/Mika.html

BTW. Thanks for excellent tutorials, this is the first place i have found, that you can start learning WebGL without any additional scripts that aren't explained.

Cheers,
Jussi