faros initial commit
[faros-demo] / glsl-noise / classic / 2d.glsl
1 //
2 // GLSL textureless classic 2D noise "cnoise",
3 // with an RSL-style periodic variant "pnoise".
4 // Author:  Stefan Gustavson (stefan.gustavson@liu.se)
5 // Version: 2011-08-22
6 //
7 // Many thanks to Ian McEwan of Ashima Arts for the
8 // ideas for permutation and gradient selection.
9 //
10 // Copyright (c) 2011 Stefan Gustavson. All rights reserved.
11 // Distributed under the MIT license. See LICENSE file.
12 // https://github.com/ashima/webgl-noise
13 //
14
15 vec4 mod289(vec4 x)
16 {
17   return x - floor(x * (1.0 / 289.0)) * 289.0;
18 }
19
20 vec4 permute(vec4 x)
21 {
22   return mod289(((x*34.0)+1.0)*x);
23 }
24
25 vec4 taylorInvSqrt(vec4 r)
26 {
27   return 1.79284291400159 - 0.85373472095314 * r;
28 }
29
30 vec2 fade(vec2 t) {
31   return t*t*t*(t*(t*6.0-15.0)+10.0);
32 }
33
34 // Classic Perlin noise
35 float cnoise(vec2 P)
36 {
37   vec4 Pi = floor(P.xyxy) + vec4(0.0, 0.0, 1.0, 1.0);
38   vec4 Pf = fract(P.xyxy) - vec4(0.0, 0.0, 1.0, 1.0);
39   Pi = mod289(Pi); // To avoid truncation effects in permutation
40   vec4 ix = Pi.xzxz;
41   vec4 iy = Pi.yyww;
42   vec4 fx = Pf.xzxz;
43   vec4 fy = Pf.yyww;
44
45   vec4 i = permute(permute(ix) + iy);
46
47   vec4 gx = fract(i * (1.0 / 41.0)) * 2.0 - 1.0 ;
48   vec4 gy = abs(gx) - 0.5 ;
49   vec4 tx = floor(gx + 0.5);
50   gx = gx - tx;
51
52   vec2 g00 = vec2(gx.x,gy.x);
53   vec2 g10 = vec2(gx.y,gy.y);
54   vec2 g01 = vec2(gx.z,gy.z);
55   vec2 g11 = vec2(gx.w,gy.w);
56
57   vec4 norm = taylorInvSqrt(vec4(dot(g00, g00), dot(g01, g01), dot(g10, g10), dot(g11, g11)));
58   g00 *= norm.x;
59   g01 *= norm.y;
60   g10 *= norm.z;
61   g11 *= norm.w;
62
63   float n00 = dot(g00, vec2(fx.x, fy.x));
64   float n10 = dot(g10, vec2(fx.y, fy.y));
65   float n01 = dot(g01, vec2(fx.z, fy.z));
66   float n11 = dot(g11, vec2(fx.w, fy.w));
67
68   vec2 fade_xy = fade(Pf.xy);
69   vec2 n_x = mix(vec2(n00, n01), vec2(n10, n11), fade_xy.x);
70   float n_xy = mix(n_x.x, n_x.y, fade_xy.y);
71   return 2.3 * n_xy;
72 }
73
74 #pragma glslify: export(cnoise)