-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathGrainient.jsx
More file actions
284 lines (253 loc) · 8.92 KB
/
Grainient.jsx
File metadata and controls
284 lines (253 loc) · 8.92 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
import { useEffect, useRef } from 'react';
import { Renderer, Program, Mesh, Triangle } from 'ogl';
import './Grainient.css';
const hexToRgb = hex => {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
if (!result) return [1, 1, 1];
return [parseInt(result[1], 16) / 255, parseInt(result[2], 16) / 255, parseInt(result[3], 16) / 255];
};
const vertex = `#version 300 es
in vec2 position;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
}
`;
const fragment = `#version 300 es
precision highp float;
uniform vec2 iResolution;
uniform float iTime;
uniform float uTimeSpeed;
uniform float uColorBalance;
uniform float uWarpStrength;
uniform float uWarpFrequency;
uniform float uWarpSpeed;
uniform float uWarpAmplitude;
uniform float uBlendAngle;
uniform float uBlendSoftness;
uniform float uRotationAmount;
uniform float uNoiseScale;
uniform float uGrainAmount;
uniform float uGrainScale;
uniform float uGrainAnimated;
uniform float uContrast;
uniform float uGamma;
uniform float uSaturation;
uniform vec2 uCenterOffset;
uniform float uZoom;
uniform vec3 uColor1;
uniform vec3 uColor2;
uniform vec3 uColor3;
out vec4 fragColor;
#define S(a,b,t) smoothstep(a,b,t)
mat2 Rot(float a){float s=sin(a),c=cos(a);return mat2(c,-s,s,c);}
vec2 hash(vec2 p){p=vec2(dot(p,vec2(2127.1,81.17)),dot(p,vec2(1269.5,283.37)));return fract(sin(p)*43758.5453);}
float noise(vec2 p){vec2 i=floor(p),f=fract(p),u=f*f*(3.0-2.0*f);float n=mix(mix(dot(-1.0+2.0*hash(i+vec2(0.0,0.0)),f-vec2(0.0,0.0)),dot(-1.0+2.0*hash(i+vec2(1.0,0.0)),f-vec2(1.0,0.0)),u.x),mix(dot(-1.0+2.0*hash(i+vec2(0.0,1.0)),f-vec2(0.0,1.0)),dot(-1.0+2.0*hash(i+vec2(1.0,1.0)),f-vec2(1.0,1.0)),u.x),u.y);return 0.5+0.5*n;}
void mainImage(out vec4 o, vec2 C){
float t=iTime*uTimeSpeed;
vec2 uv=C/iResolution.xy;
float ratio=iResolution.x/iResolution.y;
vec2 tuv=uv-0.5+uCenterOffset;
tuv/=max(uZoom,0.001);
float degree=noise(vec2(t*0.1,tuv.x*tuv.y)*uNoiseScale);
tuv.y*=1.0/ratio;
tuv*=Rot(radians((degree-0.5)*uRotationAmount+180.0));
tuv.y*=ratio;
float frequency=uWarpFrequency;
float ws=max(uWarpStrength,0.001);
float amplitude=uWarpAmplitude/ws;
float warpTime=t*uWarpSpeed;
tuv.x+=sin(tuv.y*frequency+warpTime)/amplitude;
tuv.y+=sin(tuv.x*(frequency*1.5)+warpTime)/(amplitude*0.5);
vec3 colLav=uColor1;
vec3 colOrg=uColor2;
vec3 colDark=uColor3;
float b=uColorBalance;
float s=max(uBlendSoftness,0.0);
mat2 blendRot=Rot(radians(uBlendAngle));
float blendX=(tuv*blendRot).x;
float edge0=-0.3-b-s;
float edge1=0.2-b+s;
float v0=0.5-b+s;
float v1=-0.3-b-s;
vec3 layer1=mix(colDark,colOrg,S(edge0,edge1,blendX));
vec3 layer2=mix(colOrg,colLav,S(edge0,edge1,blendX));
vec3 col=mix(layer1,layer2,S(v0,v1,tuv.y));
vec2 grainUv=uv*max(uGrainScale,0.001);
if(uGrainAnimated>0.5){grainUv+=vec2(iTime*0.05);}
float grain=fract(sin(dot(grainUv,vec2(12.9898,78.233)))*43758.5453);
col+=(grain-0.5)*uGrainAmount;
col=(col-0.5)*uContrast+0.5;
float luma=dot(col,vec3(0.2126,0.7152,0.0722));
col=mix(vec3(luma),col,uSaturation);
col=pow(max(col,0.0),vec3(1.0/max(uGamma,0.001)));
col=clamp(col,0.0,1.0);
o=vec4(col,1.0);
}
void main(){
vec4 o=vec4(0.0);
mainImage(o,gl_FragCoord.xy);
fragColor=o;
}
`;
// Keep renderer/program alive across re-renders so Effect 2 can update
// uniforms without ever rebuilding the WebGL context.
const ctxMap = new WeakMap();
const Grainient = ({
timeSpeed = 0.25,
colorBalance = 0.0,
warpStrength = 1.0,
warpFrequency = 5.0,
warpSpeed = 2.0,
warpAmplitude = 50.0,
blendAngle = 0.0,
blendSoftness = 0.05,
rotationAmount = 500.0,
noiseScale = 2.0,
grainAmount = 0.1,
grainScale = 2.0,
grainAnimated = false,
contrast = 1.5,
gamma = 1.0,
saturation = 1.0,
centerX = 0.0,
centerY = 0.0,
zoom = 0.9,
color1 = '#FF9FFC',
color2 = '#5227FF',
color3 = '#B19EEF',
className = ''
}) => {
const containerRef = useRef(null);
// Effect 1: build WebGL context once, pause when offscreen / tab hidden
useEffect(() => {
const container = containerRef.current;
if (!container) return;
const renderer = new Renderer({
webgl: 2,
alpha: true,
antialias: false,
dpr: Math.min(window.devicePixelRatio || 1, 2)
});
const gl = renderer.gl;
const canvas = gl.canvas;
canvas.style.width = '100%';
canvas.style.height = '100%';
canvas.style.display = 'block';
container.appendChild(canvas);
const geometry = new Triangle(gl);
const program = new Program(gl, {
vertex,
fragment,
uniforms: {
iTime: { value: 0 },
iResolution: { value: new Float32Array([1, 1]) },
uTimeSpeed: { value: 0.25 },
uColorBalance: { value: 0.0 },
uWarpStrength: { value: 1.0 },
uWarpFrequency: { value: 5.0 },
uWarpSpeed: { value: 2.0 },
uWarpAmplitude: { value: 50.0 },
uBlendAngle: { value: 0.0 },
uBlendSoftness: { value: 0.05 },
uRotationAmount: { value: 500.0 },
uNoiseScale: { value: 2.0 },
uGrainAmount: { value: 0.1 },
uGrainScale: { value: 2.0 },
uGrainAnimated: { value: 0.0 },
uContrast: { value: 1.5 },
uGamma: { value: 1.0 },
uSaturation: { value: 1.0 },
uCenterOffset: { value: new Float32Array([0, 0]) },
uZoom: { value: 0.9 },
uColor1: { value: new Float32Array([1, 1, 1]) },
uColor2: { value: new Float32Array([1, 1, 1]) },
uColor3: { value: new Float32Array([1, 1, 1]) }
}
});
const mesh = new Mesh(gl, { geometry, program });
ctxMap.set(container, { renderer, program, mesh });
const setSize = () => {
const rect = container.getBoundingClientRect();
const w = Math.max(1, Math.floor(rect.width));
const h = Math.max(1, Math.floor(rect.height));
renderer.setSize(w, h);
const res = program.uniforms.iResolution.value;
res[0] = gl.drawingBufferWidth;
res[1] = gl.drawingBufferHeight;
};
const ro = new ResizeObserver(setSize);
ro.observe(container);
setSize();
let raf = 0;
let isVisible = true;
let isPageVisible = !document.hidden;
const t0 = performance.now();
const loop = t => {
program.uniforms.iTime.value = (t - t0) * 0.001;
renderer.render({ scene: mesh });
raf = requestAnimationFrame(loop);
};
const tryStart = () => {
if (isVisible && isPageVisible && raf === 0) raf = requestAnimationFrame(loop);
};
const tryStop = () => {
if (raf !== 0) { cancelAnimationFrame(raf); raf = 0; }
};
const io = new IntersectionObserver(
([entry]) => { isVisible = entry.isIntersecting; isVisible ? tryStart() : tryStop(); },
{ threshold: 0 }
);
io.observe(container);
const onVisibility = () => {
isPageVisible = !document.hidden;
isPageVisible ? tryStart() : tryStop();
};
document.addEventListener('visibilitychange', onVisibility);
tryStart();
return () => {
tryStop();
ro.disconnect();
io.disconnect();
document.removeEventListener('visibilitychange', onVisibility);
ctxMap.delete(container);
try { container.removeChild(canvas); } catch { /* ignore */ }
};
}, []); // renderer created once
// Effect 2: sync props to uniforms — zero GPU cost, no teardown
useEffect(() => {
const container = containerRef.current;
if (!container) return;
const ctx = ctxMap.get(container);
if (!ctx) return;
const { program } = ctx;
const u = program.uniforms;
u.uTimeSpeed.value = timeSpeed;
u.uColorBalance.value = colorBalance;
u.uWarpStrength.value = warpStrength;
u.uWarpFrequency.value = warpFrequency;
u.uWarpSpeed.value = warpSpeed;
u.uWarpAmplitude.value = warpAmplitude;
u.uBlendAngle.value = blendAngle;
u.uBlendSoftness.value = blendSoftness;
u.uRotationAmount.value = rotationAmount;
u.uNoiseScale.value = noiseScale;
u.uGrainAmount.value = grainAmount;
u.uGrainScale.value = grainScale;
u.uGrainAnimated.value = grainAnimated ? 1.0 : 0.0;
u.uContrast.value = contrast;
u.uGamma.value = gamma;
u.uSaturation.value = saturation;
u.uCenterOffset.value = new Float32Array([centerX, centerY]);
u.uZoom.value = zoom;
u.uColor1.value = new Float32Array(hexToRgb(color1));
u.uColor2.value = new Float32Array(hexToRgb(color2));
u.uColor3.value = new Float32Array(hexToRgb(color3));
}, [
timeSpeed, colorBalance, warpStrength, warpFrequency, warpSpeed,
warpAmplitude, blendAngle, blendSoftness, rotationAmount, noiseScale,
grainAmount, grainScale, grainAnimated, contrast, gamma, saturation,
centerX, centerY, zoom, color1, color2, color3
]);
return <div ref={containerRef} className={`grainient-container ${className}`.trim()} />;
};
export default Grainient;