-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathCellular2D_Deriv.glsl
62 lines (56 loc) · 2.37 KB
/
Cellular2D_Deriv.glsl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
//
// Wombat
// An efficient texture-free GLSL procedural noise library
// Source: https://github.com/BrianSharpe/Wombat
// Derived from: https://github.com/BrianSharpe/GPU-Noise-Lib
//
// I'm not one for copyrights. Use the code however you wish.
// All I ask is that credit be given back to the blog or myself when appropriate.
// And also to let me know if you come up with any changes, improvements, thoughts or interesting uses for this stuff. :)
// Thanks!
//
// Brian Sharpe
// brisharpe CIRCLE_A yahoo DOT com
// http://briansharpe.wordpress.com
// https://github.com/BrianSharpe
//
//
// This represents a modified version of Stefan Gustavson's work at http://www.itn.liu.se/~stegu/GLSL-cellular
// The noise is optimized to use a 2x2 search window instead of 3x3
// Modifications are...
// - faster random number generation
// - analytical final normalization
// - random point offset is restricted to prevent artifacts
//
//
// Cellular Noise 2D Deriv
// Return value range of 0.0->1.0, with format vec3( value, xderiv, yderiv )
//
vec3 Cellular2D_Deriv( vec2 P )
{
// https://github.com/BrianSharpe/Wombat/blob/master/Cellular2D_Deriv.glsl
// establish our grid cell and unit position
vec2 Pi = floor(P);
vec2 Pf = P - Pi;
// calculate the hash
vec4 Pt = vec4( Pi.xy, Pi.xy + 1.0 );
Pt = Pt - floor(Pt * ( 1.0 / 71.0 )) * 71.0;
Pt += vec2( 26.0, 161.0 ).xyxy;
Pt *= Pt;
Pt = Pt.xzxz * Pt.yyww;
vec4 hash_x = fract( Pt * ( 1.0 / 951.135664 ) );
vec4 hash_y = fract( Pt * ( 1.0 / 642.949883 ) );
// generate the 4 points
hash_x = hash_x * 2.0 - 1.0;
hash_y = hash_y * 2.0 - 1.0;
const float JITTER_WINDOW = 0.25; // 0.25 will guarentee no artifacts
hash_x = ( ( hash_x * hash_x * hash_x ) - sign( hash_x ) ) * JITTER_WINDOW + vec4( 0.0, 1.0, 0.0, 1.0 );
hash_y = ( ( hash_y * hash_y * hash_y ) - sign( hash_y ) ) * JITTER_WINDOW + vec4( 0.0, 0.0, 1.0, 1.0 );
// return the closest squared distance + derivatives ( thanks to Jonathan Dupuy )
vec4 dx = Pf.xxxx - hash_x;
vec4 dy = Pf.yyyy - hash_y;
vec4 d = dx * dx + dy * dy;
vec3 t1 = d.x < d.y ? vec3( d.x, dx.x, dy.x ) : vec3( d.y, dx.y, dy.y );
vec3 t2 = d.z < d.w ? vec3( d.z, dx.z, dy.z ) : vec3( d.w, dx.w, dy.w );
return ( t1.x < t2.x ? t1 : t2 ) * vec3( 1.0, 2.0, 2.0 ) * ( 1.0 / 1.125 ); // return a value scaled to 0.0->1.0
}