@jsb188/gfx 1.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +522 -0
  2. package/elements/Shapes.helpers.ts +204 -0
  3. package/elements/Shapes.hooks.ts +171 -0
  4. package/elements/Shapes.tsx +505 -0
  5. package/elements/Shapes.types.ts +81 -0
  6. package/elements/Stack.helpers.ts +42 -0
  7. package/elements/Stack.tsx +143 -0
  8. package/elements/Text.helpers.ts +45 -0
  9. package/elements/Text.hooks.ts +197 -0
  10. package/elements/Text.tsx +98 -0
  11. package/libs/chain.ts +174 -0
  12. package/libs/dotGrid.helpers.ts +53 -0
  13. package/libs/dotGrid.ts +954 -0
  14. package/libs/effects/dotEffects.ts +136 -0
  15. package/libs/effects/effectQuad.ts +146 -0
  16. package/libs/effects/effectRegion.ts +299 -0
  17. package/libs/effects/imageEffects.ts +599 -0
  18. package/libs/effects/index.ts +8 -0
  19. package/libs/effects/ripple.ts +160 -0
  20. package/libs/glsl.ts +134 -0
  21. package/libs/passes.ts +374 -0
  22. package/libs/pointer.ts +151 -0
  23. package/libs/runtime.ts +329 -0
  24. package/libs/texture.ts +160 -0
  25. package/libs/types.ts +94 -0
  26. package/libs/uniforms.ts +32 -0
  27. package/main.ts +4 -0
  28. package/modules/Carousel.helpers.ts +316 -0
  29. package/modules/Carousel.hooks.ts +520 -0
  30. package/modules/Carousel.tsx +631 -0
  31. package/modules/Dots.tsx +269 -0
  32. package/modules/DotsBoard.helpers.ts +388 -0
  33. package/modules/DotsBoard.hooks.ts +144 -0
  34. package/modules/DotsBoard.strings.ts +649 -0
  35. package/modules/DotsBoard.types.ts +240 -0
  36. package/modules/DotsBoardCanvas.hooks.ts +49 -0
  37. package/modules/DotsBoardCanvas.tsx +190 -0
  38. package/modules/DotsBoardElements.tsx +330 -0
  39. package/modules/Gallery.helpers.ts +32 -0
  40. package/modules/Gallery.hooks.ts +149 -0
  41. package/modules/Gallery.tsx +194 -0
  42. package/modules/GfxCanvas.hooks.ts +12 -0
  43. package/modules/GfxCanvas.tsx +189 -0
  44. package/modules/Hero.tsx +90 -0
  45. package/modules/KineticHeader.helpers.ts +44 -0
  46. package/modules/KineticHeader.hooks.ts +206 -0
  47. package/modules/KineticHeader.tsx +305 -0
  48. package/modules/KineticHeader.types.ts +56 -0
  49. package/modules/ScrollSteps.hooks.ts +138 -0
  50. package/modules/ScrollSteps.tsx +98 -0
  51. package/package.json +52 -0
  52. package/scenes/Carousel.ts +277 -0
  53. package/scenes/DotsBoard.helpers.ts +12 -0
  54. package/scenes/DotsBoard.ts +245 -0
  55. package/scenes/Hero.ts +280 -0
  56. package/tsconfig.json +13 -0
  57. package/utils/align.ts +18 -0
  58. package/utils/color.ts +112 -0
  59. package/utils/dotEffectSpecs.ts +79 -0
  60. package/utils/dotGridSpecs.ts +469 -0
  61. package/utils/easing.ts +18 -0
  62. package/utils/imageEffectSpecs.ts +89 -0
  63. package/utils/motion.ts +88 -0
  64. package/utils/random.ts +22 -0
  65. package/utils/strings.ts +116 -0
@@ -0,0 +1,160 @@
1
+ import type { OGLRenderingContext, Program, Texture } from 'ogl';
2
+ import { PassChain, createPassProgram } from '../chain.ts';
3
+ import { fragmentShader } from '../glsl.ts';
4
+ import { setVec2 } from '../uniforms.ts';
5
+
6
+ export interface RippleSimulationOptions {
7
+ /** Simulation resolution relative to the canvas; ripples are smooth, so 0.35 is plenty. */
8
+ scale?: number;
9
+ /** Energy kept per step; closer to 1 rings longer. */
10
+ damping?: number;
11
+ /** Wave speed term; must stay below 0.5 for the explicit scheme to be stable. */
12
+ propagation?: number;
13
+ /** Steps per frame; more steps make faster waves at the same stability. */
14
+ substeps?: number;
15
+ /** Radius of each disturbance as a fraction of canvas height. */
16
+ dropRadius?: number;
17
+ /** Height of each disturbance; heights are clamped to ±0.5. */
18
+ dropStrength?: number;
19
+ /** Pointer travel (fraction of canvas height) between successive drops while moving. */
20
+ dropSpacing?: number;
21
+ /** Seconds after the last drop before the surface is flattened and stepping stops. */
22
+ settleSeconds?: number;
23
+ }
24
+
25
+ // Heights are stored offset by 0.5 so the same shader works in RGBA8 when half-float is missing.
26
+ const WAVE_FRAGMENT = fragmentShader(`
27
+ uniform vec2 uDrop;
28
+ uniform float uDropRadius;
29
+ uniform float uDropStrength;
30
+ uniform float uDamping;
31
+ uniform float uPropagation;
32
+ void main() {
33
+ vec2 texel = 1.0 / uResolution;
34
+ vec2 aspect = vec2(uResolution.x / uResolution.y, 1.0);
35
+ vec4 state = texture(tInput, vUv);
36
+ float current = state.r - 0.5;
37
+ float previous = state.g - 0.5;
38
+ float neighbors =
39
+ texture(tInput, vUv + vec2(texel.x, 0.0)).r +
40
+ texture(tInput, vUv - vec2(texel.x, 0.0)).r +
41
+ texture(tInput, vUv + vec2(0.0, texel.y)).r +
42
+ texture(tInput, vUv - vec2(0.0, texel.y)).r - 2.0;
43
+ float next = (2.0 * current - previous + uPropagation * (neighbors - 4.0 * current)) * uDamping;
44
+ float drop = smoothstep(uDropRadius, 0.0, length((vUv - uDrop) * aspect));
45
+ next = clamp(next - drop * uDropStrength, -0.5, 0.5);
46
+ fragColor = vec4(next + 0.5, current + 0.5, 0.0, 1.0);
47
+ }
48
+ `);
49
+
50
+ const CLEAR_FRAGMENT = fragmentShader(`
51
+ void main() {
52
+ fragColor = vec4(0.5, 0.5, 0.0, 1.0);
53
+ }
54
+ `);
55
+
56
+ /*
57
+ * Cursor-driven water surface: a 2D wave equation on a small ping-pong buffer whose height
58
+ * field other passes read as a displacement (`texture` getter). Feed it the pointer every
59
+ * frame; it drops a disturbance whenever the pointer has travelled far enough.
60
+ */
61
+ export class RippleSimulation {
62
+ private readonly chain: PassChain;
63
+ private readonly wave: Program;
64
+ private readonly clear: Program;
65
+ private readonly scale: number;
66
+ private readonly substeps: number;
67
+ private readonly dropSpacing: number;
68
+ private readonly settleSeconds: number;
69
+ private lastDrop: [number, number] | null = null;
70
+ private lastDropAt = Number.NEGATIVE_INFINITY;
71
+ private dirty = false;
72
+
73
+ constructor(gl: OGLRenderingContext, options: RippleSimulationOptions = {}) {
74
+ this.scale = options.scale ?? 0.35;
75
+ this.substeps = Math.max(1, Math.round(options.substeps ?? 3));
76
+ this.dropSpacing = options.dropSpacing ?? 0.015;
77
+ this.settleSeconds = options.settleSeconds ?? 4;
78
+ this.chain = new PassChain(gl, { halfFloat: true });
79
+ this.wave = createPassProgram(gl, WAVE_FRAGMENT, {
80
+ uDrop: { value: [-10, -10] },
81
+ uDropRadius: { value: options.dropRadius ?? 0.02 },
82
+ uDropStrength: { value: options.dropStrength ?? 0.5 },
83
+ uDamping: { value: options.damping ?? 0.985 },
84
+ uPropagation: { value: Math.min(0.49, options.propagation ?? 0.4) },
85
+ });
86
+ this.clear = createPassProgram(gl, CLEAR_FRAGMENT);
87
+ this.reset();
88
+ }
89
+
90
+ /** Current height field; r = height + 0.5, aligned to canvas UVs. */
91
+ get texture(): Texture {
92
+ return this.chain.output;
93
+ }
94
+
95
+ /** Simulation size in texels, for gradient sampling. */
96
+ get size(): [number, number] {
97
+ return [this.chain.width, this.chain.height];
98
+ }
99
+
100
+ /*
101
+ * Match the canvas aspect at the simulation scale; contents are discarded.
102
+ */
103
+ setSize(width: number, height: number) {
104
+ this.chain.setSize(width * this.scale, height * this.scale);
105
+ this.reset();
106
+ }
107
+
108
+ /*
109
+ * Flatten the surface.
110
+ */
111
+ reset() {
112
+ this.chain.render([this.clear]);
113
+ this.lastDrop = null;
114
+ this.dirty = false;
115
+ }
116
+
117
+ /*
118
+ * Advance the surface one frame. While `disturb` is true, the pointer leaves drops as it
119
+ * moves; afterwards the surface keeps settling for `settleSeconds`, then flattens and stops
120
+ * stepping so an idle hero costs nothing. Returns whether a step ran.
121
+ */
122
+ update(pointer: { x: number; y: number }, disturb: boolean, elapsed: number) {
123
+ let dropped = false;
124
+ if (disturb) {
125
+ const aspect = this.chain.width / this.chain.height;
126
+ const last = this.lastDrop;
127
+ const travelled = last ? Math.hypot((pointer.x - last[0]) * aspect, pointer.y - last[1]) : Number.POSITIVE_INFINITY;
128
+ if (travelled >= this.dropSpacing) {
129
+ this.lastDrop = [pointer.x, pointer.y];
130
+ this.lastDropAt = elapsed;
131
+ dropped = true;
132
+ this.dirty = true;
133
+ }
134
+ } else {
135
+ this.lastDrop = null;
136
+ }
137
+ if (!this.dirty) return false;
138
+ if (elapsed - this.lastDropAt > this.settleSeconds) {
139
+ this.reset();
140
+ return false;
141
+ }
142
+
143
+ for (let i = 0; i < this.substeps; i++) {
144
+ // Only the first substep receives the drop; later ones just propagate it.
145
+ const receivesDrop = dropped && i === 0;
146
+ setVec2(this.wave.uniforms.uDrop, receivesDrop ? pointer.x : -10, receivesDrop ? pointer.y : -10);
147
+ this.chain.render([this.wave]);
148
+ }
149
+ return true;
150
+ }
151
+
152
+ /*
153
+ * Free the buffers and programs.
154
+ */
155
+ dispose() {
156
+ this.chain.dispose();
157
+ this.wave.remove();
158
+ this.clear.remove();
159
+ }
160
+ }
package/libs/glsl.ts ADDED
@@ -0,0 +1,134 @@
1
+ /**
2
+ * GLSL ES 3.00 building blocks shared by every fullscreen pass.
3
+ *
4
+ * WebGL2 requires `#version` to be the very first characters of a shader, so
5
+ * every shader string in this package is assembled through `fragmentShader()`
6
+ * or starts with `GLSL_HEADER` directly.
7
+ */
8
+
9
+ export const GLSL_HEADER = '#version 300 es\nprecision highp float;\nprecision highp int;\n';
10
+
11
+ /** Numeric constants every shader may use; part of the pass prelude and available to custom vertex stages. */
12
+ export const GLSL_CONSTANTS = `
13
+ #define PI 3.14159265359
14
+ #define TWO_PI 6.28318530718
15
+ `;
16
+
17
+ /** Vertex stage for the single oversized triangle that covers the viewport. */
18
+ export const FULLSCREEN_VERTEX = `${GLSL_HEADER}
19
+ in vec2 position;
20
+ in vec2 uv;
21
+ out vec2 vUv;
22
+ void main() {
23
+ vUv = uv;
24
+ gl_Position = vec4(position, 0.0, 1.0);
25
+ }
26
+ `;
27
+
28
+ /** Constants, plus the inputs the pass chain supplies to every pass. */
29
+ export const GLSL_PASS_PRELUDE = `${GLSL_CONSTANTS}
30
+ in vec2 vUv;
31
+ out vec4 fragColor;
32
+ uniform sampler2D tInput;
33
+ uniform vec2 uResolution;
34
+ `;
35
+
36
+ /** Cheap 2D hash returning two pseudo-random values in 0..1. */
37
+ export const GLSL_HASH2 = `
38
+ vec2 hash2(vec2 p) {
39
+ return fract(sin(vec2(dot(p, vec2(127.1, 311.7)), dot(p, vec2(269.5, 183.3)))) * 43758.5453);
40
+ }
41
+ `;
42
+
43
+ /** 2D rotation matrix for an angle in radians. */
44
+ export const GLSL_ROTATE_2D = `
45
+ mat2 rotate2d(float a) {
46
+ float c = cos(a);
47
+ float s = sin(a);
48
+ return mat2(c, -s, s, c);
49
+ }
50
+ `;
51
+
52
+ /** Photoshop-style overlay blend. */
53
+ export const GLSL_BLEND_OVERLAY = `
54
+ vec3 blendOverlay(vec3 base, vec3 blend) {
55
+ return mix(2.0 * base * blend, 1.0 - 2.0 * (1.0 - base) * (1.0 - blend), step(0.5, base));
56
+ }
57
+ `;
58
+
59
+ /** Map canvas UVs onto an image the way CSS object-fit: cover does, centered. */
60
+ export const GLSL_COVER_UV = `
61
+ vec2 coverUv(vec2 uv, vec2 canvasSize, vec2 imageSize) {
62
+ float canvasAspect = canvasSize.x / canvasSize.y;
63
+ float imageAspect = imageSize.x / imageSize.y;
64
+ vec2 scale = canvasAspect > imageAspect
65
+ ? vec2(1.0, imageAspect / canvasAspect)
66
+ : vec2(canvasAspect / imageAspect, 1.0);
67
+ return (uv - 0.5) * scale + 0.5;
68
+ }
69
+ `;
70
+
71
+ /** Rec. 601 luma. */
72
+ export const GLSL_LUMA = `
73
+ float luma(vec3 color) {
74
+ return dot(color, vec3(0.299, 0.587, 0.114));
75
+ }
76
+ `;
77
+
78
+ /** Smooth value noise in 0..1 built on a float hash, plus a two-channel variant. */
79
+ export const GLSL_VALUE_NOISE = `
80
+ float hash1(vec2 p) {
81
+ return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453);
82
+ }
83
+ float valueNoise(vec2 p) {
84
+ vec2 i = floor(p);
85
+ vec2 f = fract(p);
86
+ f = f * f * (3.0 - 2.0 * f);
87
+ return mix(
88
+ mix(hash1(i), hash1(i + vec2(1.0, 0.0)), f.x),
89
+ mix(hash1(i + vec2(0.0, 1.0)), hash1(i + vec2(1.0, 1.0)), f.x),
90
+ f.y
91
+ );
92
+ }
93
+ vec2 valueNoise2(vec2 p) {
94
+ return vec2(valueNoise(p), valueNoise(p + vec2(37.2, 91.7)));
95
+ }
96
+ `;
97
+
98
+ /** Animated feature point of the Voronoi cell containing `st` (requires GLSL_HASH2). */
99
+ export const GLSL_VORONOI = `
100
+ vec2 voronoiPoint(vec2 st, float phase) {
101
+ vec2 cell = floor(st);
102
+ vec2 local = fract(st);
103
+ float nearestDistance = 15.0;
104
+ vec2 nearestPoint = vec2(0.0);
105
+ for (int j = -1; j <= 1; j++) {
106
+ for (int i = -1; i <= 1; i++) {
107
+ vec2 neighbor = vec2(float(i), float(j));
108
+ vec2 point = hash2(cell + neighbor);
109
+ point = 0.5 + 0.5 * sin(5.0 + phase + TWO_PI * point);
110
+ float d = length(neighbor + point - local);
111
+ if (d < nearestDistance) {
112
+ nearestDistance = d;
113
+ nearestPoint = point;
114
+ }
115
+ }
116
+ }
117
+ return nearestPoint;
118
+ }
119
+ `;
120
+
121
+ /** Jimenez interleaved gradient noise: a screen-space dither that needs no texture. */
122
+ export const GLSL_INTERLEAVED_GRADIENT_NOISE = `
123
+ float interleavedGradientNoise(vec2 pixel) {
124
+ return fract(52.9829189 * fract(dot(pixel, vec2(0.06711056, 0.00583715))));
125
+ }
126
+ `;
127
+
128
+ /*
129
+ * Assemble a complete fragment shader from the shared prelude, optional chunks, and a body.
130
+ * Duplicate chunks are included once, so callers can list a dependency more than once.
131
+ */
132
+ export function fragmentShader(body: string, chunks: string[] = []) {
133
+ return GLSL_HEADER + GLSL_PASS_PRELUDE + [...new Set(chunks)].join('\n') + body;
134
+ }
package/libs/passes.ts ADDED
@@ -0,0 +1,374 @@
1
+ import type { OGLRenderingContext, Program } from 'ogl';
2
+ import { createPassProgram } from './chain.ts';
3
+ import type { UniformValues } from './uniforms.ts';
4
+ import {
5
+ GLSL_BLEND_OVERLAY,
6
+ GLSL_COVER_UV,
7
+ GLSL_HASH2,
8
+ GLSL_INTERLEAVED_GRADIENT_NOISE,
9
+ GLSL_ROTATE_2D,
10
+ GLSL_VORONOI,
11
+ fragmentShader,
12
+ } from './glsl.ts';
13
+ import type { EffectRegionInstance } from './effects/effectRegion.ts';
14
+ import type { ImageEffectInstance } from './effects/imageEffects.ts';
15
+ import type { RGB } from './types.ts';
16
+
17
+ /**
18
+ * Reusable fullscreen passes. Each factory compiles a Program whose static look is fixed by its
19
+ * options; the uniforms named in each factory's comment are the ones a scene drives per frame.
20
+ * Chain passes write an RGBA "light field": rgb is a color and alpha is how strongly it applies.
21
+ */
22
+
23
+ export interface SpotlightPassOptions {
24
+ /** Diameter of the lit region as a fraction of canvas height before skew. */
25
+ radius: number;
26
+ /** 0 = hard edge, 1 = the whole radius is gradient. */
27
+ falloff: number;
28
+ /** 0.5 = circle; toward 1 stretches horizontally, toward 0 vertically. */
29
+ skew: number;
30
+ /** Rotation of the skew axis in turns (0..1). */
31
+ angle: number;
32
+ /** Color outside the spotlight. */
33
+ shadeColor: RGB;
34
+ /** Color inside the spotlight; written with alpha 0 so it reads as "no shade". */
35
+ clearColor: RGB;
36
+ }
37
+
38
+ /*
39
+ * Draw a soft, optionally skewed radial shade that is clear at `uPosition` (drive per frame).
40
+ */
41
+ export function createSpotlightPass(gl: OGLRenderingContext, options: SpotlightPassOptions): Program {
42
+ const fragment = fragmentShader(
43
+ `
44
+ uniform vec2 uPosition;
45
+ uniform float uRadius;
46
+ uniform float uFalloff;
47
+ uniform float uSkew;
48
+ uniform float uAngle;
49
+ uniform vec3 uShadeColor;
50
+ uniform vec3 uClearColor;
51
+ void main() {
52
+ vec2 aspect = vec2(uResolution.x / uResolution.y, 1.0);
53
+ vec2 skew = vec2(uSkew, 1.0 - uSkew);
54
+ mat2 rotation = rotate2d(uAngle * TWO_PI);
55
+ vec2 point = (vUv * aspect * rotation) * skew;
56
+ vec2 center = (uPosition * aspect * rotation) * skew;
57
+ float halfRadius = uRadius * 0.5;
58
+ float inner = halfRadius - uFalloff * halfRadius * 0.5;
59
+ float outer = halfRadius + uFalloff * halfRadius * 0.5;
60
+ float shade = smoothstep(inner, outer, distance(point, center));
61
+ fragColor = mix(vec4(uClearColor, 0.0), vec4(uShadeColor, 1.0), shade);
62
+ }
63
+ `,
64
+ [GLSL_ROTATE_2D],
65
+ );
66
+ return createPassProgram(gl, fragment, {
67
+ uPosition: { value: [0.5, 0.5] },
68
+ uRadius: { value: options.radius },
69
+ uFalloff: { value: options.falloff },
70
+ uSkew: { value: options.skew },
71
+ uAngle: { value: options.angle },
72
+ uShadeColor: { value: options.shadeColor },
73
+ uClearColor: { value: options.clearColor },
74
+ });
75
+ }
76
+
77
+ export interface SineWarpPassOptions {
78
+ /** Wave count across the canvas; multiplied by 20 internally. */
79
+ frequency: number;
80
+ /** Displacement strength; 1 shifts by about a tenth of the canvas. */
81
+ amplitude: number;
82
+ /** Phase advance in radians per second. */
83
+ speed: number;
84
+ /** 0 displaces horizontally by row, 1 vertically by column. */
85
+ axis: number;
86
+ }
87
+
88
+ /*
89
+ * Ripple the input with a slow travelling sine displacement (drive `uTime` per frame).
90
+ */
91
+ export function createSineWarpPass(gl: OGLRenderingContext, options: SineWarpPassOptions): Program {
92
+ const fragment = fragmentShader(`
93
+ uniform float uTime;
94
+ uniform float uFrequency;
95
+ uniform float uAmplitude;
96
+ uniform float uSpeed;
97
+ uniform float uAxis;
98
+ void main() {
99
+ vec2 wave = vUv * 2.0 - 1.0;
100
+ float frequency = 20.0 * uFrequency;
101
+ float amplitude = uAmplitude * 0.2;
102
+ float phase = uTime * uSpeed;
103
+ float waveX = sin(wave.y * frequency + phase) * amplitude;
104
+ float waveY = sin(wave.x * frequency + phase * 1.3) * amplitude;
105
+ wave += vec2(mix(waveX, 0.0, uAxis), mix(0.0, waveY, uAxis));
106
+ fragColor = texture(tInput, wave * 0.5 + 0.5);
107
+ }
108
+ `);
109
+ return createPassProgram(gl, fragment, {
110
+ uTime: { value: 0 },
111
+ uFrequency: { value: options.frequency },
112
+ uAmplitude: { value: options.amplitude },
113
+ uSpeed: { value: options.speed },
114
+ uAxis: { value: options.axis },
115
+ });
116
+ }
117
+
118
+ export interface VoronoiShatterPassOptions {
119
+ /** Cell density; 1 is roughly 50 cells across the canvas height. */
120
+ scale: number;
121
+ /** How far each cell displaces its sample, as a fraction of the canvas (0.2 × spread). */
122
+ spread: number;
123
+ /** Rotation of the cell grid in turns (0..1). */
124
+ angle: number;
125
+ /** 0 = square cells, toward 1 stretches cells into tall shards. */
126
+ skew: number;
127
+ /** Cell drift in radians per second. */
128
+ speed: number;
129
+ }
130
+
131
+ /*
132
+ * Break the input into drifting Voronoi shards, each sampling from its own offset (drive `uTime`).
133
+ */
134
+ export function createVoronoiShatterPass(gl: OGLRenderingContext, options: VoronoiShatterPassOptions): Program {
135
+ const fragment = fragmentShader(
136
+ `
137
+ uniform float uScale;
138
+ uniform float uSpread;
139
+ uniform float uAngle;
140
+ uniform float uSkew;
141
+ uniform float uSpeed;
142
+ uniform float uTime;
143
+ void main() {
144
+ vec2 aspect = vec2(uResolution.x / uResolution.y, 1.0);
145
+ vec2 st = (vUv - 0.5) * aspect * 50.0 * uScale;
146
+ st = st * rotate2d(uAngle * TWO_PI) * mix(vec2(1.0), vec2(1.0, 0.0), uSkew);
147
+ vec2 offset = (voronoiPoint(st, uTime * uSpeed) - 0.5) * 0.4 * uSpread;
148
+ fragColor = texture(tInput, vUv + offset);
149
+ }
150
+ `,
151
+ [GLSL_HASH2, GLSL_ROTATE_2D, GLSL_VORONOI],
152
+ );
153
+ return createPassProgram(gl, fragment, {
154
+ uScale: { value: options.scale },
155
+ uSpread: { value: options.spread },
156
+ uAngle: { value: options.angle },
157
+ uSkew: { value: options.skew },
158
+ uSpeed: { value: options.speed },
159
+ uTime: { value: 0 },
160
+ });
161
+ }
162
+
163
+ export interface BokehPassOptions {
164
+ /** Blur radius as a fraction of canvas height; the spiral reaches about 9× this value. */
165
+ radius: number;
166
+ /** Extra weight given to bright samples so highlights bloom into discs; 0 is a plain blur. */
167
+ highlight: number;
168
+ /** Sample count; 50 matches the reference look, lower is cheaper. */
169
+ samples?: number;
170
+ /** Per-pixel spiral rotation range in radians; small values break repetition, large ones add grain. */
171
+ jitter?: number;
172
+ }
173
+
174
+ /*
175
+ * Golden-angle spiral disc blur with per-pixel rotation dithering, preserving alpha coverage.
176
+ */
177
+ export function createBokehPass(gl: OGLRenderingContext, options: BokehPassOptions): Program {
178
+ const samples = Math.max(4, Math.round(options.samples ?? 50));
179
+ const fragment = fragmentShader(
180
+ `
181
+ #define SAMPLES ${samples.toFixed(1)}
182
+ #define GOLDEN_ANGLE 2.39996323
183
+ uniform float uRadius;
184
+ uniform float uHighlight;
185
+ uniform float uJitter;
186
+ vec2 spiralSample(float theta, inout float r) {
187
+ r += 1.0 / r;
188
+ return (r - 1.0) * vec2(cos(theta), sin(theta));
189
+ }
190
+ void main() {
191
+ vec2 pixelSize = vec2(uResolution.y / uResolution.x, 1.0) * uRadius;
192
+ // A slight per-pixel twist of the spiral hides its repetition without adding visible grain.
193
+ mat2 rotation = rotate2d((hash2(gl_FragCoord.xy).x - 0.5) * uJitter);
194
+ vec3 color = vec3(0.0);
195
+ vec3 weights = vec3(0.0);
196
+ float alpha = 0.0;
197
+ float r = 1.0;
198
+ for (float j = 0.0; j < GOLDEN_ANGLE * SAMPLES; j += GOLDEN_ANGLE) {
199
+ vec2 offset = rotation * (spiralSample(j, r) * pixelSize);
200
+ vec4 sampleColor = texture(tInput, vUv + offset);
201
+ vec3 weight = vec3(5.0) + pow(sampleColor.rgb, vec3(9.0)) * uHighlight;
202
+ color += sampleColor.rgb * weight;
203
+ weights += weight;
204
+ alpha += sampleColor.a;
205
+ }
206
+ fragColor = vec4(color / weights, alpha / SAMPLES);
207
+ }
208
+ `,
209
+ [GLSL_HASH2, GLSL_ROTATE_2D],
210
+ );
211
+ return createPassProgram(gl, fragment, {
212
+ uRadius: { value: options.radius },
213
+ uHighlight: { value: options.highlight },
214
+ uJitter: { value: options.jitter ?? 0.06 },
215
+ });
216
+ }
217
+
218
+ export interface ImageLightCompositeOptions {
219
+ /** Brand color: the pre-load fill and the overlay tint applied to the image. */
220
+ baseColor: RGB;
221
+ /** Color multiplied into lit (alpha 0) regions of the light field. */
222
+ lightColor: RGB;
223
+ /** 0..1 amount of `baseColor` overlay applied to the image. */
224
+ tint: number;
225
+ /** 0..1 how strongly the light field modulates the image. */
226
+ intensity: number;
227
+ }
228
+
229
+ /*
230
+ * Emit one effect group's snippets with `amount` bound to that group's per-pixel amount.
231
+ */
232
+ function effectGroupCode(effects: ImageEffectInstance[], amount: string, key: 'uvCode' | 'colorCode') {
233
+ const code = effects.map((effect) => effect[key] ?? '').join('\n');
234
+ return code.trim() ? `amount = ${amount};\n${code}` : '';
235
+ }
236
+
237
+ export interface ImageEffectShaderParts {
238
+ /** Uniform declarations (image, pointer, amounts, time, every effect's own) plus `sampleImage()`; include as a chunk. */
239
+ declarations: string;
240
+ /** Statements for the start of `main()`: declare `aspect`, `texel`, `uv`, ... and leave the effected color in `vec3 image`. */
241
+ body: string;
242
+ /** GLSL chunks the declarations and body depend on; pass to `fragmentShader`. */
243
+ chunks: string[];
244
+ /** Uniform values for the host program: `tImage`, `uImageSize`, `uPointer`, `uEffectAmount`, `uRegionEffectAmount`, `uTime`, and every effect's own by reference. */
245
+ uniforms: UniformValues;
246
+ }
247
+
248
+ /*
249
+ * Assemble the shader pieces that present a cover-fit `tImage` through image effects, for any
250
+ * host pass to splice into its own fragment shader. Two effect groups are supported:
251
+ * `regionEffects` are always on, scaled per pixel by `region` (a mask; omit it to cover the
252
+ * whole image), and `hoverEffects` are scaled by `uEffectAmount`. The host's `uResolution`
253
+ * is the size of the area being drawn, and `vUv` spans it.
254
+ */
255
+ export function imageEffectShaderParts({
256
+ hoverEffects = [],
257
+ regionEffects = [],
258
+ region,
259
+ }: {
260
+ hoverEffects?: ImageEffectInstance[];
261
+ regionEffects?: ImageEffectInstance[];
262
+ region?: EffectRegionInstance;
263
+ }): ImageEffectShaderParts {
264
+ const effects = [...regionEffects, ...hoverEffects];
265
+ // One sampling effect at most; the hover group's takes precedence so it stays visible.
266
+ const sampleEffect = hoverEffects.find((effect) => effect.sampleCode) ?? regionEffects.find((effect) => effect.sampleCode);
267
+ const sampleAmount = sampleEffect && hoverEffects.includes(sampleEffect) ? 'hoverAmount' : 'regionAmount';
268
+ const regionMask = region && regionEffects.length ? 'regionMask(vUv, pointer, aspect)' : '1.0';
269
+ const declarations = `
270
+ uniform sampler2D tImage;
271
+ uniform vec2 uImageSize;
272
+ uniform vec2 uPointer;
273
+ uniform float uEffectAmount;
274
+ uniform float uRegionEffectAmount;
275
+ uniform float uTime;
276
+ ${effects.map((effect) => effect.declarations).join('\n')}
277
+ ${region ? region.chunk : ''}
278
+ vec3 sampleImage(vec2 screenUv) {
279
+ return texture(tImage, coverUv(screenUv, uResolution, uImageSize)).rgb;
280
+ }
281
+ `;
282
+ const body = `
283
+ vec2 aspect = vec2(uResolution.x / uResolution.y, 1.0);
284
+ vec2 texel = 1.0 / uResolution;
285
+ vec2 pointer = uPointer;
286
+ float time = uTime;
287
+ float hoverAmount = uEffectAmount;
288
+ float regionAmount = ${regionEffects.length ? `uRegionEffectAmount * ${regionMask}` : '0.0'};
289
+ float amount = 0.0;
290
+ vec2 uv = vUv;
291
+ vec3 image;
292
+ ${
293
+ effects.length
294
+ ? `// Idle (no hover, no region effects) skips every effect so multi-tap effects cost nothing until used.
295
+ if (hoverAmount > 0.0 || ${regionEffects.length ? 'uRegionEffectAmount > 0.0' : 'false'}) {
296
+ ${effectGroupCode(regionEffects, 'regionAmount', 'uvCode')}
297
+ ${effectGroupCode(hoverEffects, 'hoverAmount', 'uvCode')}
298
+ amount = ${sampleAmount};
299
+ ${sampleEffect?.sampleCode ?? 'image = sampleImage(uv);'}
300
+ ${effectGroupCode(regionEffects, 'regionAmount', 'colorCode')}
301
+ ${effectGroupCode(hoverEffects, 'hoverAmount', 'colorCode')}
302
+ } else {
303
+ image = sampleImage(uv);
304
+ }`
305
+ : 'image = sampleImage(uv);'
306
+ }
307
+ `;
308
+ return {
309
+ declarations,
310
+ body,
311
+ chunks: [GLSL_COVER_UV, declarations, ...effects.flatMap((effect) => effect.chunks)],
312
+ uniforms: {
313
+ tImage: { value: null },
314
+ uImageSize: { value: [1, 1] },
315
+ uPointer: { value: [0.5, 0.5] },
316
+ uEffectAmount: { value: 0 },
317
+ uRegionEffectAmount: { value: 1 },
318
+ uTime: { value: 0 },
319
+ ...Object.assign({}, ...effects.map((effect) => effect.uniforms), region?.uniforms ?? {}),
320
+ },
321
+ };
322
+ }
323
+
324
+ /*
325
+ * Present a cover-fit image modulated by the chain's light field, optionally through image
326
+ * effects spliced into the same shader (see `imageEffectShaderParts` for the two effect
327
+ * groups). Set `tImage`, `uImageSize`, and `uImageLoaded` once the image texture is ready;
328
+ * drive `uPointer`, `uEffectAmount`, and `uTime` per frame. All effect and region uniforms
329
+ * are merged in by reference.
330
+ */
331
+ export function createImageLightCompositePass(
332
+ gl: OGLRenderingContext,
333
+ {
334
+ hoverEffects = [],
335
+ regionEffects = [],
336
+ region,
337
+ ...options
338
+ }: ImageLightCompositeOptions & {
339
+ hoverEffects?: ImageEffectInstance[];
340
+ regionEffects?: ImageEffectInstance[];
341
+ region?: EffectRegionInstance;
342
+ },
343
+ ): Program {
344
+ const parts = imageEffectShaderParts({ hoverEffects, regionEffects, region });
345
+ const fragment = fragmentShader(
346
+ `
347
+ uniform float uImageLoaded;
348
+ uniform vec3 uBaseColor;
349
+ uniform vec3 uLightColor;
350
+ uniform float uTint;
351
+ uniform float uIntensity;
352
+ void main() {
353
+ ${parts.body}
354
+ vec3 tinted = mix(image, blendOverlay(image, uBaseColor), uTint);
355
+ vec3 base = mix(uBaseColor, tinted, uImageLoaded);
356
+ vec4 light = texture(tInput, vUv);
357
+ vec3 blend = mix(uLightColor, light.rgb, light.a);
358
+ vec3 color = base * mix(vec3(1.0), blend, uIntensity);
359
+ // Break up 8-bit banding in the long soft gradients.
360
+ color += (interleavedGradientNoise(gl_FragCoord.xy) - 0.5) / 255.0;
361
+ fragColor = vec4(color, 1.0);
362
+ }
363
+ `,
364
+ [...parts.chunks, GLSL_BLEND_OVERLAY, GLSL_INTERLEAVED_GRADIENT_NOISE],
365
+ );
366
+ return createPassProgram(gl, fragment, {
367
+ ...parts.uniforms,
368
+ uImageLoaded: { value: 0 },
369
+ uBaseColor: { value: options.baseColor },
370
+ uLightColor: { value: options.lightColor },
371
+ uTint: { value: options.tint },
372
+ uIntensity: { value: options.intensity },
373
+ });
374
+ }