@wolsok/loading-wave 0.0.1 → 0.0.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 (40) hide show
  1. package/README.md +113 -12
  2. package/esm2022/index.js +1 -0
  3. package/esm2022/index.js.map +1 -1
  4. package/esm2022/lib/canvas-wave-renderer.js +34 -12
  5. package/esm2022/lib/canvas-wave-renderer.js.map +1 -1
  6. package/esm2022/lib/choose-wave-renderer.js +8 -3
  7. package/esm2022/lib/choose-wave-renderer.js.map +1 -1
  8. package/esm2022/lib/loading-wave-options.js +16 -2
  9. package/esm2022/lib/loading-wave-options.js.map +1 -1
  10. package/esm2022/lib/loading-wave.js +11 -3
  11. package/esm2022/lib/loading-wave.js.map +1 -1
  12. package/esm2022/lib/renderer.js.map +1 -1
  13. package/esm2022/lib/wave-model.js +33 -9
  14. package/esm2022/lib/wave-model.js.map +1 -1
  15. package/esm2022/lib/webgl/echo.js +5 -0
  16. package/esm2022/lib/webgl/echo.js.map +1 -0
  17. package/esm2022/lib/webgl/loading-wave-shader.js +1 -0
  18. package/esm2022/lib/webgl/loading-wave-shader.js.map +1 -0
  19. package/esm2022/lib/webgl/shader-program.js +227 -0
  20. package/esm2022/lib/webgl/shader-program.js.map +1 -0
  21. package/esm2022/lib/webgl/shaders/ripple.shader.js +110 -0
  22. package/esm2022/lib/webgl/shaders/ripple.shader.js.map +1 -0
  23. package/esm2022/lib/webgl/webgl-wave-renderer.js +102 -92
  24. package/esm2022/lib/webgl/webgl-wave-renderer.js.map +1 -1
  25. package/index.d.ts +3 -1
  26. package/lib/canvas-wave-renderer.d.ts +2 -0
  27. package/lib/choose-wave-renderer.d.ts +3 -0
  28. package/lib/loading-wave-options.d.ts +24 -4
  29. package/lib/loading-wave.d.ts +3 -3
  30. package/lib/renderer.d.ts +5 -0
  31. package/lib/wave-model.d.ts +17 -6
  32. package/lib/webgl/echo.d.ts +4 -0
  33. package/lib/webgl/loading-wave-shader.d.ts +20 -0
  34. package/lib/webgl/shader-program.d.ts +33 -0
  35. package/lib/webgl/shaders/ripple.shader.d.ts +10 -0
  36. package/lib/webgl/webgl-wave-renderer.d.ts +18 -7
  37. package/package.json +1 -1
  38. package/esm2022/lib/webgl/wave-shaders.js +0 -114
  39. package/esm2022/lib/webgl/wave-shaders.js.map +0 -1
  40. package/lib/webgl/wave-shaders.d.ts +0 -14
@@ -1,42 +1,24 @@
1
- import { dotsOpacity, sizeCanvas, } from '../renderer';
2
- import { frontRadius, hasPreviousSweep } from '../wave-model';
3
- import { ECHO_LAG, WAVE_FRAGMENT_SHADER, WAVE_VERTEX_SHADER, } from './wave-shaders';
4
- const UNIFORMS = [
5
- 'u_size',
6
- 'u_bufferSize',
7
- 'u_spacing',
8
- 'u_dotSize',
9
- 'u_color',
10
- 'u_center',
11
- 'u_frontRadius',
12
- 'u_echoRadius',
13
- 'u_travel',
14
- 'u_previousSweep',
15
- 'u_falloff',
16
- 'u_rise',
17
- 'u_maxPush',
18
- 'u_wave',
19
- 'u_dots',
20
- ];
21
- /** the shaders did not compile or link on this GPU */
22
- export class WaveShaderError extends Error {
23
- constructor() {
24
- super(...arguments);
25
- this.name = 'WaveShaderError';
26
- }
27
- }
1
+ import { sizeCanvas, } from '../renderer';
2
+ import { frontRadius, hasPreviousSweep, sweepPhase, } from '../wave-model';
3
+ import { linkWaveProgram, STANDARD_UNIFORMS, WaveShaderError, } from './shader-program';
4
+ import { ECHO_LAG } from './echo';
5
+ export { WaveShaderError };
28
6
  /**
29
- * Draws the wave with a WebGL2 fragment shader: the 2D canvas's look plus a
30
- * glow around lit dots and an echo ripple trailing the front.
7
+ * Draws the wave with a WebGL2 fragment shader (`LoadingWaveShader`) over a
8
+ * full-canvas triangle, setting the contract's `ws_*` uniforms and the
9
+ * shader's own each frame.
31
10
  */
32
11
  export class WebGlWaveRenderer {
33
12
  /** @throws WaveShaderError when the shaders fail on this GPU */
34
- constructor(canvas, gl, look, hooks) {
13
+ constructor(canvas, gl, look, shader, hooks) {
35
14
  this.canvas = canvas;
36
15
  this.gl = gl;
37
16
  this.look = look;
38
17
  this.hooks = hooks;
39
18
  this.kind = 'webgl';
19
+ this.ownLocations = new Map();
20
+ /** uniforms `setShaderUniforms` left out, set to 0 on the next draw */
21
+ this.pendingResets = {};
40
22
  this.lost = false;
41
23
  this.disposed = false;
42
24
  this.handleContextLost = (event) => {
@@ -44,8 +26,12 @@ export class WebGlWaveRenderer {
44
26
  this.lost = true;
45
27
  this.hooks.onContextLost();
46
28
  };
47
- this.program = linkProgram(gl);
48
- this.uniforms = Object.fromEntries(UNIFORMS.map((name) => [name, gl.getUniformLocation(this.program, name)]));
29
+ this.program = linkWaveProgram(gl, shader);
30
+ this.uniforms = Object.fromEntries(STANDARD_UNIFORMS.map((name) => [
31
+ name,
32
+ gl.getUniformLocation(this.program, name),
33
+ ]));
34
+ this.ownUniforms = shader.uniforms ?? {};
49
35
  canvas.addEventListener('webglcontextlost', this.handleContextLost);
50
36
  }
51
37
  /**
@@ -77,7 +63,7 @@ export class WebGlWaveRenderer {
77
63
  }
78
64
  gl.clearColor(0, 0, 0, 0);
79
65
  gl.clear(gl.COLOR_BUFFER_BIT);
80
- if (dotsOpacity(frame, this.look.color) <= 0) {
66
+ if (frame.dots <= 0) {
81
67
  return;
82
68
  }
83
69
  gl.useProgram(this.program);
@@ -87,6 +73,19 @@ export class WebGlWaveRenderer {
87
73
  setLook(look) {
88
74
  this.look = look;
89
75
  }
76
+ /**
77
+ * a uniform the new values leave out goes back to 0, the value GLSL gives
78
+ * every uniform before it is set
79
+ */
80
+ setShaderUniforms(uniforms) {
81
+ const next = uniforms ?? {};
82
+ for (const [name, value] of Object.entries(this.ownUniforms)) {
83
+ if (!(name in next)) {
84
+ this.pendingResets[name] = unsetValue(value);
85
+ }
86
+ }
87
+ this.ownUniforms = next;
88
+ }
90
89
  dispose() {
91
90
  if (this.disposed) {
92
91
  return;
@@ -100,22 +99,76 @@ export class WebGlWaveRenderer {
100
99
  this.hooks.onDispose?.();
101
100
  }
102
101
  setUniforms(geometry, frame) {
103
- const { gl, uniforms, look } = this;
104
- gl.uniform2f(uniforms.u_size, geometry.width, geometry.height);
105
- gl.uniform2f(uniforms.u_bufferSize, gl.drawingBufferWidth, gl.drawingBufferHeight);
106
- gl.uniform1f(uniforms.u_spacing, geometry.dotSpacing);
107
- gl.uniform1f(uniforms.u_dotSize, look.dotSize);
108
- gl.uniform3f(uniforms.u_color, look.color.r / 255, look.color.g / 255, look.color.b / 255);
109
- gl.uniform2f(uniforms.u_center, geometry.centerX, geometry.centerY);
110
- gl.uniform1f(uniforms.u_frontRadius, frontRadius(geometry, frame.elapsedMs));
111
- gl.uniform1f(uniforms.u_echoRadius, echoRadius(geometry, frame.elapsedMs));
112
- gl.uniform1f(uniforms.u_travel, geometry.travel);
113
- gl.uniform1f(uniforms.u_previousSweep, hasPreviousSweep(geometry, frame.elapsedMs) ? 1 : 0);
114
- gl.uniform1f(uniforms.u_falloff, geometry.falloff);
115
- gl.uniform1f(uniforms.u_rise, geometry.rise);
116
- gl.uniform1f(uniforms.u_maxPush, geometry.maxPush);
117
- gl.uniform1f(uniforms.u_wave, frame.wave);
118
- gl.uniform1f(uniforms.u_dots, dotsOpacity(frame, look.color));
102
+ const { gl, uniforms: locations, look } = this;
103
+ const bufferWidth = gl.drawingBufferWidth;
104
+ const bufferHeight = gl.drawingBufferHeight;
105
+ gl.uniform2f(locations.ws_size, geometry.width, geometry.height);
106
+ gl.uniform2f(locations.ws_bufferSize, bufferWidth, bufferHeight);
107
+ gl.uniform1f(locations.ws_pixel, geometry.width / Math.max(1, bufferWidth));
108
+ gl.uniform1f(locations.ws_spacing, geometry.dotSpacing);
109
+ gl.uniform1f(locations.ws_dotSize, look.dotSize);
110
+ setColor(gl, locations.ws_color, look.color);
111
+ setColor(gl, locations.ws_accent, look.accent ?? look.color);
112
+ gl.uniform2f(locations.ws_center, geometry.centerX, geometry.centerY);
113
+ gl.uniform1f(locations.ws_frontRadius, frontRadius(geometry, frame.elapsedMs));
114
+ gl.uniform1f(locations.ws_echoRadius, echoRadius(geometry, frame.elapsedMs));
115
+ gl.uniform1f(locations.ws_travel, geometry.travel);
116
+ gl.uniform1f(locations.ws_falloff, geometry.falloff);
117
+ gl.uniform1f(locations.ws_rise, geometry.rise);
118
+ gl.uniform1f(locations.ws_tail, geometry.tail);
119
+ gl.uniform1f(locations.ws_maxPush, geometry.maxPush);
120
+ gl.uniform1f(locations.ws_phase, sweepPhase(geometry, frame.elapsedMs));
121
+ gl.uniform1f(locations.ws_time, frame.elapsedMs / 1000);
122
+ gl.uniform1f(locations.ws_previousSweep, hasPreviousSweep(geometry, frame.elapsedMs) ? 1 : 0);
123
+ gl.uniform1f(locations.ws_wave, frame.wave);
124
+ gl.uniform1f(locations.ws_dots, frame.dots);
125
+ // a dropped uniform is reset once, then left alone
126
+ const own = { ...this.pendingResets, ...this.ownUniforms };
127
+ this.pendingResets = {};
128
+ for (const [name, value] of Object.entries(own)) {
129
+ // the ws_ uniforms are the lib's: a shader's own never override them
130
+ if (!name.startsWith('ws_')) {
131
+ setOwnUniform(gl, this.ownLocation(name), value);
132
+ }
133
+ }
134
+ }
135
+ /** where the shader's own uniform lives, looked up once per name */
136
+ ownLocation(name) {
137
+ if (!this.ownLocations.has(name)) {
138
+ this.ownLocations.set(name, this.gl.getUniformLocation(this.program, name));
139
+ }
140
+ return this.ownLocations.get(name) ?? null;
141
+ }
142
+ }
143
+ /** zeros of the same size as `value` */
144
+ const ZEROS = {
145
+ 1: [0],
146
+ 2: [0, 0],
147
+ 3: [0, 0, 0],
148
+ 4: [0, 0, 0, 0],
149
+ };
150
+ function unsetValue(value) {
151
+ return typeof value === 'number' ? 0 : ZEROS[value.length];
152
+ }
153
+ /** a colour as a straight RGBA `vec4`, each 0 to 1 */
154
+ function setColor(gl, location, { r, g, b, alpha = 1 }) {
155
+ gl.uniform4f(location, r / 255, g / 255, b / 255, alpha);
156
+ }
157
+ /** sets a `float` to `vec4` uniform by how many components the value has */
158
+ function setOwnUniform(gl, location, value) {
159
+ const [x, y = 0, z = 0, w = 0] = typeof value === 'number' ? [value] : value;
160
+ const size = typeof value === 'number' ? 1 : value.length;
161
+ if (size === 1) {
162
+ gl.uniform1f(location, x);
163
+ }
164
+ else if (size === 2) {
165
+ gl.uniform2f(location, x, y);
166
+ }
167
+ else if (size === 3) {
168
+ gl.uniform3f(location, x, y, z);
169
+ }
170
+ else {
171
+ gl.uniform4f(location, x, y, z, w);
119
172
  }
120
173
  }
121
174
  /**
@@ -126,47 +179,4 @@ export function echoRadius(geometry, elapsedMs) {
126
179
  const echoElapsed = elapsedMs - ECHO_LAG * geometry.sweepMs;
127
180
  return echoElapsed < 0 ? -1 : frontRadius(geometry, echoElapsed);
128
181
  }
129
- function compileShader(gl, type, source) {
130
- const shader = gl.createShader(type);
131
- if (shader == null) {
132
- throw new WaveShaderError('could not create a shader');
133
- }
134
- gl.shaderSource(shader, source);
135
- gl.compileShader(shader);
136
- if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
137
- const log = gl.getShaderInfoLog(shader);
138
- gl.deleteShader(shader);
139
- throw new WaveShaderError(`shader did not compile: ${log}`);
140
- }
141
- return shader;
142
- }
143
- function linkProgram(gl) {
144
- const vertex = compileShader(gl, gl.VERTEX_SHADER, WAVE_VERTEX_SHADER);
145
- let fragment;
146
- try {
147
- fragment = compileShader(gl, gl.FRAGMENT_SHADER, WAVE_FRAGMENT_SHADER);
148
- }
149
- catch (error) {
150
- gl.deleteShader(vertex);
151
- throw error;
152
- }
153
- const program = gl.createProgram();
154
- if (program == null) {
155
- gl.deleteShader(vertex);
156
- gl.deleteShader(fragment);
157
- throw new WaveShaderError('could not create a program');
158
- }
159
- gl.attachShader(program, vertex);
160
- gl.attachShader(program, fragment);
161
- gl.linkProgram(program);
162
- // the program keeps what it needs
163
- gl.deleteShader(vertex);
164
- gl.deleteShader(fragment);
165
- if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
166
- const log = gl.getProgramInfoLog(program);
167
- gl.deleteProgram(program);
168
- throw new WaveShaderError(`shaders did not link: ${log}`);
169
- }
170
- return program;
171
- }
172
182
  //# sourceMappingURL=webgl-wave-renderer.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"webgl-wave-renderer.js","sourceRoot":"","sources":["../../../../../../../libs/public/ws-loading-wave/src/lib/webgl/webgl-wave-renderer.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,WAAW,EACX,UAAU,GAIX,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAgB,MAAM,eAAe,CAAC;AAC5E,OAAO,EACL,QAAQ,EACR,oBAAoB,EACpB,kBAAkB,GACnB,MAAM,gBAAgB,CAAC;AAExB,MAAM,QAAQ,GAAG;IACf,QAAQ;IACR,cAAc;IACd,WAAW;IACX,WAAW;IACX,SAAS;IACT,UAAU;IACV,eAAe;IACf,cAAc;IACd,UAAU;IACV,iBAAiB;IACjB,WAAW;IACX,QAAQ;IACR,WAAW;IACX,QAAQ;IACR,QAAQ;CACA,CAAC;AAIX,sDAAsD;AACtD,MAAM,OAAO,eAAgB,SAAQ,KAAK;IAA1C;;QAC2B,SAAI,GAAG,iBAAiB,CAAC;IACpD,CAAC;CAAA;AASD;;;GAGG;AACH,MAAM,OAAO,iBAAiB;IAc5B,gEAAgE;IAChE,YACkB,MAAyB,EACxB,EAA0B,EACnC,IAAc,EACL,KAA6B;QAH9B,WAAM,GAAN,MAAM,CAAmB;QACxB,OAAE,GAAF,EAAE,CAAwB;QACnC,SAAI,GAAJ,IAAI,CAAU;QACL,UAAK,GAAL,KAAK,CAAwB;QAlBhC,SAAI,GAAG,OAAO,CAAC;QAIvB,SAAI,GAAG,KAAK,CAAC;QACb,aAAQ,GAAG,KAAK,CAAC;QAER,sBAAiB,GAAG,CAAC,KAAY,EAAQ,EAAE;YAC1D,KAAK,CAAC,cAAc,EAAE,CAAC;YACvB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;Y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,CAAC,CAAC;QAC1C,EAAE,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC;QAC1B,MAAM,IAAI,eAAe,CAAC,yBAAyB,GAAG,EAAE,CAAC,CAAC;IAC5D,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import {\n dotsOpacity,\n sizeCanvas,\n WaveFrame,\n WaveLook,\n WaveRenderer,\n} from '../renderer';\nimport { frontRadius, hasPreviousSweep, WaveGeometry } from '../wave-model';\nimport {\n ECHO_LAG,\n WAVE_FRAGMENT_SHADER,\n WAVE_VERTEX_SHADER,\n} from './wave-shaders';\n\nconst UNIFORMS = [\n 'u_size',\n 'u_bufferSize',\n 'u_spacing',\n 'u_dotSize',\n 'u_color',\n 'u_center',\n 'u_frontRadius',\n 'u_echoRadius',\n 'u_travel',\n 'u_previousSweep',\n 'u_falloff',\n 'u_rise',\n 'u_maxPush',\n 'u_wave',\n 'u_dots',\n] as const;\n\ntype UniformName = (typeof UNIFORMS)[number];\n\n/** the shaders did not compile or link on this GPU */\nexport class WaveShaderError extends Error {\n public override readonly name = 'WaveShaderError';\n}\n\nexport interface WebGlWaveRendererHooks {\n /** the browser took the GPU context away; the renderer draws no more */\n readonly onContextLost: () => void;\n /** called once by dispose(), after the context was freed */\n readonly onDispose?: () => void;\n}\n\n/**\n * Draws the wave with a WebGL2 fragment shader: the 2D canvas's look plus a\n * glow around lit dots and an echo ripple trailing the front.\n */\nexport class WebGlWaveRenderer implements WaveRenderer {\n public readonly kind = 'webgl';\n private readonly program: WebGLProgram;\n private readonly uniforms: Record<UniformName, WebGLUniformLocation | null>;\n private geometry?: WaveGeometry;\n private lost = false;\n private disposed = false;\n\n private readonly handleContextLost = (event: Event): void => {\n event.preventDefault();\n this.lost = true;\n this.hooks.onContextLost();\n };\n\n /** @throws WaveShaderError when the shaders fail on this GPU */\n public constructor(\n public readonly canvas: HTMLCanvasElement,\n private readonly gl: WebGL2RenderingContext,\n private look: WaveLook,\n private readonly hooks: WebGlWaveRendererHooks\n ) {\n this.program = linkProgram(gl);\n this.uniforms = Object.fromEntries(\n UNIFORMS.map((name) => [name, gl.getUniformLocation(this.program, name)])\n ) as Record<UniformName, WebGLUniformLocation | null>;\n canvas.addEventListener('webglcontextlost', this.handleContextLost);\n }\n\n /**\n * A WebGL2 context, or `null` where the browser offers none. With\n * `hardwareOnly` also `null` where it would render on the CPU (no GPU, a\n * blocked driver, a software renderer).\n */\n public static createContext(\n canvas: HTMLCanvasElement,\n hardwareOnly = true\n ): WebGL2RenderingContext | null {\n return canvas.getContext('webgl2', {\n alpha: true,\n premultipliedAlpha: true,\n antialias: false,\n depth: false,\n stencil: false,\n powerPreference: 'low-power',\n failIfMajorPerformanceCaveat: hardwareOnly,\n });\n }\n\n public resize(geometry: WaveGeometry, pixelRatio: number): void {\n this.geometry = geometry;\n sizeCanvas(this.canvas, geometry, pixelRatio);\n // a GPU may give a smaller drawing buffer than the canvas asks for\n this.gl.viewport(\n 0,\n 0,\n this.gl.drawingBufferWidth,\n this.gl.drawingBufferHeight\n );\n }\n\n public draw(frame: WaveFrame): void {\n const { gl, geometry } = this;\n if (this.lost || this.disposed || geometry == null) {\n return;\n }\n gl.clearColor(0, 0, 0, 0);\n gl.clear(gl.COLOR_BUFFER_BIT);\n if (dotsOpacity(frame, this.look.color) <= 0) {\n return;\n }\n gl.useProgram(this.program);\n this.setUniforms(geometry, frame);\n gl.drawArrays(gl.TRIANGLES, 0, 3);\n }\n\n public setLook(look: WaveLook): void {\n this.look = look;\n }\n\n public dispose(): void {\n if (this.disposed) {\n return;\n }\n this.disposed = true;\n this.canvas.removeEventListener('webglcontextlost', this.handleContextLost);\n if (!this.gl.isContextLost()) {\n this.gl.deleteProgram(this.program);\n this.gl.getExtension('WEBGL_lose_context')?.loseContext();\n }\n this.hooks.onDispose?.();\n }\n\n private setUniforms(geometry: WaveGeometry, frame: WaveFrame): void {\n const { gl, uniforms, look } = this;\n gl.uniform2f(uniforms.u_size, geometry.width, geometry.height);\n gl.uniform2f(\n uniforms.u_bufferSize,\n gl.drawingBufferWidth,\n gl.drawingBufferHeight\n );\n gl.uniform1f(uniforms.u_spacing, geometry.dotSpacing);\n gl.uniform1f(uniforms.u_dotSize, look.dotSize);\n gl.uniform3f(\n uniforms.u_color,\n look.color.r / 255,\n look.color.g / 255,\n look.color.b / 255\n );\n gl.uniform2f(uniforms.u_center, geometry.centerX, geometry.centerY);\n gl.uniform1f(\n uniforms.u_frontRadius,\n frontRadius(geometry, frame.elapsedMs)\n );\n gl.uniform1f(uniforms.u_echoRadius, echoRadius(geometry, frame.elapsedMs));\n gl.uniform1f(uniforms.u_travel, geometry.travel);\n gl.uniform1f(\n uniforms.u_previousSweep,\n hasPreviousSweep(geometry, frame.elapsedMs) ? 1 : 0\n );\n gl.uniform1f(uniforms.u_falloff, geometry.falloff);\n gl.uniform1f(uniforms.u_rise, geometry.rise);\n gl.uniform1f(uniforms.u_maxPush, geometry.maxPush);\n gl.uniform1f(uniforms.u_wave, frame.wave);\n gl.uniform1f(uniforms.u_dots, dotsOpacity(frame, look.color));\n }\n}\n\n/**\n * The echo's radius, trailing the front by `ECHO_LAG` of a sweep; negative,\n * so no echo shows, until the front has run that far.\n */\nexport function echoRadius(geometry: WaveGeometry, elapsedMs: number): number {\n const echoElapsed = elapsedMs - ECHO_LAG * geometry.sweepMs;\n return echoElapsed < 0 ? -1 : frontRadius(geometry, echoElapsed);\n}\n\nfunction compileShader(\n gl: WebGL2RenderingContext,\n type: number,\n source: string\n): WebGLShader {\n const shader = gl.createShader(type);\n if (shader == null) {\n throw new WaveShaderError('could not create a shader');\n }\n gl.shaderSource(shader, source);\n gl.compileShader(shader);\n if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n const log = gl.getShaderInfoLog(shader);\n gl.deleteShader(shader);\n throw new WaveShaderError(`shader did not compile: ${log}`);\n }\n return shader;\n}\n\nfunction linkProgram(gl: WebGL2RenderingContext): WebGLProgram {\n const vertex = compileShader(gl, gl.VERTEX_SHADER, WAVE_VERTEX_SHADER);\n let fragment: WebGLShader;\n try {\n fragment = compileShader(gl, gl.FRAGMENT_SHADER, WAVE_FRAGMENT_SHADER);\n } catch (error) {\n gl.deleteShader(vertex);\n throw error;\n }\n const program = gl.createProgram();\n if (program == null) {\n gl.deleteShader(vertex);\n gl.deleteShader(fragment);\n throw new WaveShaderError('could not create a program');\n }\n gl.attachShader(program, vertex);\n gl.attachShader(program, fragment);\n gl.linkProgram(program);\n // the program keeps what it needs\n gl.deleteShader(vertex);\n gl.deleteShader(fragment);\n if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {\n const log = gl.getProgramInfoLog(program);\n gl.deleteProgram(program);\n throw new WaveShaderError(`shaders did not link: ${log}`);\n }\n return program;\n}\n"]}
1
+ {"version":3,"file":"webgl-wave-renderer.js","sourceRoot":"","sources":["../../../../../../../libs/public/ws-loading-wave/src/lib/webgl/webgl-wave-renderer.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,UAAU,GAKX,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,WAAW,EACX,gBAAgB,EAChB,UAAU,GAEX,MAAM,eAAe,CAAC;AAMvB,OAAO,EACL,eAAe,EACf,iBAAiB,EAEjB,eAAe,GAChB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAElC,OAAO,EAAE,eAAe,EAAE,CAAC;AAS3B;;;;GAIG;AACH,MAAM,OAAO,iBAAiB;IAwB5B,gEAAgE;IAChE,YACkB,MAAyB,EACxB,EAA0B,EACnC,IAAc,EACtB,MAAyB,EACR,KAA6B;QAJ9B,WAAM,GAAN,MAAM,CAAmB;QACxB,OAAE,GAAF,EAAE,CAAwB;QACnC,SAAI,GAAJ,IAAI,CAAU;QAEL,UAAK,GAAL,KAAK,CAAwB;QA7BhC,SAAI,GAAG,OAAO,CAAC;QAMd,iBAAY,GAAG,IAAI,GAAG,EAGpC,CAAC;QAEJ,uEAAuE;QAC/D,kBAAa,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QACtB,EAAE,CAAC,SAAS,CAAC,QAAQ,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC/B,CAAC;SAAM,IAAI,IAAI,KAAK,CAAC,EAAE,CAAC;QACtB,EAAE,CAAC,SAAS,CAAC,QAAQ,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAClC,CAAC;SAAM,CAAC;QACN,EAAE,CAAC,SAAS,CAAC,QAAQ,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IACrC,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,UAAU,CAAC,QAAsB,EAAE,SAAiB;IAClE,MAAM,WAAW,GAAG,SAAS,GAAG,QAAQ,GAAG,QAAQ,CAAC,OAAO,CAAC;IAC5D,OAAO,WAAW,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,QAAQ,EAAE,WAAW,CAAC,CAAC;AACnE,CAAC","sourcesContent":["import {\n sizeCanvas,\n WaveFrame,\n WaveLook,\n WaveRenderer,\n type Rgb,\n} from '../renderer';\nimport {\n frontRadius,\n hasPreviousSweep,\n sweepPhase,\n WaveGeometry,\n} from '../wave-model';\nimport type {\n LoadingWaveShader,\n ShaderUniforms,\n ShaderUniformValue,\n} from './loading-wave-shader';\nimport {\n linkWaveProgram,\n STANDARD_UNIFORMS,\n StandardUniform,\n WaveShaderError,\n} from './shader-program';\nimport { ECHO_LAG } from './echo';\n\nexport { WaveShaderError };\n\nexport interface WebGlWaveRendererHooks {\n /** the browser took the GPU context away; the renderer draws no more */\n readonly onContextLost: () => void;\n /** called once by dispose(), after the context was freed */\n readonly onDispose?: () => void;\n}\n\n/**\n * Draws the wave with a WebGL2 fragment shader (`LoadingWaveShader`) over a\n * full-canvas triangle, setting the contract's `ws_*` uniforms and the\n * shader's own each frame.\n */\nexport class WebGlWaveRenderer implements WaveRenderer {\n public readonly kind = 'webgl';\n private readonly program: WebGLProgram;\n private readonly uniforms: Record<\n StandardUniform,\n WebGLUniformLocation | null\n >;\n private readonly ownLocations = new Map<\n string,\n WebGLUniformLocation | null\n >();\n private ownUniforms: ShaderUniforms;\n /** uniforms `setShaderUniforms` left out, set to 0 on the next draw */\n private pendingResets: Record<string, ShaderUniformValue> = {};\n private geometry?: WaveGeometry;\n private lost = false;\n private disposed = false;\n\n private readonly handleContextLost = (event: Event): void => {\n event.preventDefault();\n this.lost = true;\n this.hooks.onContextLost();\n };\n\n /** @throws WaveShaderError when the shaders fail on this GPU */\n public constructor(\n public readonly canvas: HTMLCanvasElement,\n private readonly gl: WebGL2RenderingContext,\n private look: WaveLook,\n shader: LoadingWaveShader,\n private readonly hooks: WebGlWaveRendererHooks\n ) {\n this.program = linkWaveProgram(gl, shader);\n this.uniforms = Object.fromEntries(\n STANDARD_UNIFORMS.map((name) => [\n name,\n gl.getUniformLocation(this.program, name),\n ])\n ) as Record<StandardUniform, WebGLUniformLocation | null>;\n this.ownUniforms = shader.uniforms ?? {};\n canvas.addEventListener('webglcontextlost', this.handleContextLost);\n }\n\n /**\n * A WebGL2 context, or `null` where the browser offers none. With\n * `hardwareOnly` also `null` where it would render on the CPU (no GPU, a\n * blocked driver, a software renderer).\n */\n public static createContext(\n canvas: HTMLCanvasElement,\n hardwareOnly = true\n ): WebGL2RenderingContext | null {\n return canvas.getContext('webgl2', {\n alpha: true,\n premultipliedAlpha: true,\n antialias: false,\n depth: false,\n stencil: false,\n powerPreference: 'low-power',\n failIfMajorPerformanceCaveat: hardwareOnly,\n });\n }\n\n public resize(geometry: WaveGeometry, pixelRatio: number): void {\n this.geometry = geometry;\n sizeCanvas(this.canvas, geometry, pixelRatio);\n // a GPU may give a smaller drawing buffer than the canvas asks for\n this.gl.viewport(\n 0,\n 0,\n this.gl.drawingBufferWidth,\n this.gl.drawingBufferHeight\n );\n }\n\n public draw(frame: WaveFrame): void {\n const { gl, geometry } = this;\n if (this.lost || this.disposed || geometry == null) {\n return;\n }\n gl.clearColor(0, 0, 0, 0);\n gl.clear(gl.COLOR_BUFFER_BIT);\n if (frame.dots <= 0) {\n return;\n }\n gl.useProgram(this.program);\n this.setUniforms(geometry, frame);\n gl.drawArrays(gl.TRIANGLES, 0, 3);\n }\n\n public setLook(look: WaveLook): void {\n this.look = look;\n }\n\n /**\n * a uniform the new values leave out goes back to 0, the value GLSL gives\n * every uniform before it is set\n */\n public setShaderUniforms(uniforms: ShaderUniforms | undefined): void {\n const next = uniforms ?? {};\n for (const [name, value] of Object.entries(this.ownUniforms)) {\n if (!(name in next)) {\n this.pendingResets[name] = unsetValue(value);\n }\n }\n this.ownUniforms = next;\n }\n\n public dispose(): void {\n if (this.disposed) {\n return;\n }\n this.disposed = true;\n this.canvas.removeEventListener('webglcontextlost', this.handleContextLost);\n if (!this.gl.isContextLost()) {\n this.gl.deleteProgram(this.program);\n this.gl.getExtension('WEBGL_lose_context')?.loseContext();\n }\n this.hooks.onDispose?.();\n }\n\n private setUniforms(geometry: WaveGeometry, frame: WaveFrame): void {\n const { gl, uniforms: locations, look } = this;\n const bufferWidth = gl.drawingBufferWidth;\n const bufferHeight = gl.drawingBufferHeight;\n gl.uniform2f(locations.ws_size, geometry.width, geometry.height);\n gl.uniform2f(locations.ws_bufferSize, bufferWidth, bufferHeight);\n gl.uniform1f(locations.ws_pixel, geometry.width / Math.max(1, bufferWidth));\n gl.uniform1f(locations.ws_spacing, geometry.dotSpacing);\n gl.uniform1f(locations.ws_dotSize, look.dotSize);\n setColor(gl, locations.ws_color, look.color);\n setColor(gl, locations.ws_accent, look.accent ?? look.color);\n gl.uniform2f(locations.ws_center, geometry.centerX, geometry.centerY);\n gl.uniform1f(\n locations.ws_frontRadius,\n frontRadius(geometry, frame.elapsedMs)\n );\n gl.uniform1f(\n locations.ws_echoRadius,\n echoRadius(geometry, frame.elapsedMs)\n );\n gl.uniform1f(locations.ws_travel, geometry.travel);\n gl.uniform1f(locations.ws_falloff, geometry.falloff);\n gl.uniform1f(locations.ws_rise, geometry.rise);\n gl.uniform1f(locations.ws_tail, geometry.tail);\n gl.uniform1f(locations.ws_maxPush, geometry.maxPush);\n gl.uniform1f(locations.ws_phase, sweepPhase(geometry, frame.elapsedMs));\n gl.uniform1f(locations.ws_time, frame.elapsedMs / 1000);\n gl.uniform1f(\n locations.ws_previousSweep,\n hasPreviousSweep(geometry, frame.elapsedMs) ? 1 : 0\n );\n gl.uniform1f(locations.ws_wave, frame.wave);\n gl.uniform1f(locations.ws_dots, frame.dots);\n // a dropped uniform is reset once, then left alone\n const own = { ...this.pendingResets, ...this.ownUniforms };\n this.pendingResets = {};\n for (const [name, value] of Object.entries(own)) {\n // the ws_ uniforms are the lib's: a shader's own never override them\n if (!name.startsWith('ws_')) {\n setOwnUniform(gl, this.ownLocation(name), value);\n }\n }\n }\n\n /** where the shader's own uniform lives, looked up once per name */\n private ownLocation(name: string): WebGLUniformLocation | null {\n if (!this.ownLocations.has(name)) {\n this.ownLocations.set(\n name,\n this.gl.getUniformLocation(this.program, name)\n );\n }\n return this.ownLocations.get(name) ?? null;\n }\n}\n\n/** zeros of the same size as `value` */\nconst ZEROS: Record<1 | 2 | 3 | 4, ShaderUniformValue> = {\n 1: [0],\n 2: [0, 0],\n 3: [0, 0, 0],\n 4: [0, 0, 0, 0],\n};\n\nfunction unsetValue(value: ShaderUniformValue): ShaderUniformValue {\n return typeof value === 'number' ? 0 : ZEROS[value.length];\n}\n\n/** a colour as a straight RGBA `vec4`, each 0 to 1 */\nfunction setColor(\n gl: WebGL2RenderingContext,\n location: WebGLUniformLocation | null,\n { r, g, b, alpha = 1 }: Rgb\n): void {\n gl.uniform4f(location, r / 255, g / 255, b / 255, alpha);\n}\n\n/** sets a `float` to `vec4` uniform by how many components the value has */\nfunction setOwnUniform(\n gl: WebGL2RenderingContext,\n location: WebGLUniformLocation | null,\n value: ShaderUniformValue\n): void {\n const [x, y = 0, z = 0, w = 0] = typeof value === 'number' ? [value] : value;\n const size = typeof value === 'number' ? 1 : value.length;\n if (size === 1) {\n gl.uniform1f(location, x);\n } else if (size === 2) {\n gl.uniform2f(location, x, y);\n } else if (size === 3) {\n gl.uniform3f(location, x, y, z);\n } else {\n gl.uniform4f(location, x, y, z, w);\n }\n}\n\n/**\n * The echo's radius, trailing the front by `ECHO_LAG` of a sweep; negative,\n * so no echo shows, until the front has run that far.\n */\nexport function echoRadius(geometry: WaveGeometry, elapsedMs: number): number {\n const echoElapsed = elapsedMs - ECHO_LAG * geometry.sweepMs;\n return echoElapsed < 0 ? -1 : frontRadius(geometry, echoElapsed);\n}\n"]}
package/index.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  export { LoadingWaveDirective } from './lib/loading-wave.directive';
2
2
  export { DEFAULT_LOADING_WAVE_OPTIONS, LOADING_WAVE_OPTIONS, provideLoadingWave, } from './lib/loading-wave-options';
3
- export type { AfterLoading, LoadingWaveOptions, WaveRendererPreference, } from './lib/loading-wave-options';
3
+ export type { AfterLoading, LoadingWaveOptions, ResolvedLoadingWaveOptions, WaveRendererPreference, } from './lib/loading-wave-options';
4
4
  export type { WaveRendererKind } from './lib/renderer';
5
+ export type { LoadingWaveShader, ShaderUniforms, ShaderUniformValue, } from './lib/webgl/loading-wave-shader';
6
+ export { rippleShader } from './lib/webgl/shaders/ripple.shader';
@@ -19,6 +19,8 @@ export declare class CanvasWaveRenderer implements WaveRenderer {
19
19
  resize(geometry: WaveGeometry, pixelRatio: number): void;
20
20
  draw(frame: WaveFrame): void;
21
21
  setLook(look: WaveLook): void;
22
+ /** a 2D canvas runs no shader */
23
+ setShaderUniforms(): void;
22
24
  dispose(): void;
23
25
  /** draws every dot at rest in one path, returns the lit ones */
24
26
  private drawRestingDots;
@@ -1,5 +1,6 @@
1
1
  import type { WaveRendererPreference } from './loading-wave-options';
2
2
  import type { WaveLook, WaveRenderer } from './renderer';
3
+ import type { LoadingWaveShader } from './webgl/loading-wave-shader';
3
4
  /** counts the waves that hold a WebGL context */
4
5
  export declare class GpuContextBudget {
5
6
  private readonly max;
@@ -13,6 +14,8 @@ export declare const PAGE_GPU_BUDGET: GpuContextBudget;
13
14
  export interface ChooseWaveRendererParams {
14
15
  readonly preference: WaveRendererPreference;
15
16
  readonly look: WaveLook;
17
+ /** what the WebGL renderer draws with */
18
+ readonly shader: LoadingWaveShader;
16
19
  /** a new, detached canvas for each renderer tried */
17
20
  readonly createCanvas: () => HTMLCanvasElement;
18
21
  /** the WebGL renderer lost its context; swap it for a 2D one */
@@ -1,4 +1,5 @@
1
1
  import { InjectionToken, Provider } from '@angular/core';
2
+ import type { LoadingWaveShader } from './webgl/loading-wave-shader';
2
3
  /** what the dots do once loading ended */
3
4
  export type AfterLoading = 'hide' | 'keep';
4
5
  /** which renderer draws the wave */
@@ -15,6 +16,11 @@ export interface LoadingWaveOptions {
15
16
  readonly dotSize: number;
16
17
  /** any CSS colour; unset, the dots take the host's `currentColor` */
17
18
  readonly color?: string;
19
+ /**
20
+ * any CSS colour for the lit dots and the wave itself; unset, they take
21
+ * the dots' colour
22
+ */
23
+ readonly accentColor?: string;
18
24
  /** how long one sweep of the wave across the element takes, in ms */
19
25
  readonly sweepMs: number;
20
26
  /**
@@ -23,13 +29,27 @@ export interface LoadingWaveOptions {
23
29
  * that fails. `'canvas'` never uses WebGL.
24
30
  */
25
31
  readonly renderer: WaveRendererPreference;
32
+ /**
33
+ * 0 (a straight front) to 1 (a half circle): how far the wave front's ends
34
+ * lag its middle, as a share of `min(height / 2, width)`; 0.5 when unset
35
+ */
36
+ readonly frontRoundness?: number;
37
+ /**
38
+ * the fragment shader the WebGL renderer draws with: a built-in one
39
+ * (`rippleShader`) or one's own; unset, `rippleShader`. The 2D canvas
40
+ * always draws the dot wave.
41
+ */
42
+ readonly shader?: LoadingWaveShader;
26
43
  }
27
- export declare const DEFAULT_LOADING_WAVE_OPTIONS: LoadingWaveOptions;
44
+ /** options with every default filled in, as the wave runs with them */
45
+ export type ResolvedLoadingWaveOptions = LoadingWaveOptions & Required<Pick<LoadingWaveOptions, 'frontRoundness' | 'shader'>>;
46
+ export declare const DEFAULT_LOADING_WAVE_OPTIONS: ResolvedLoadingWaveOptions;
28
47
  export declare const LOADING_WAVE_OPTIONS: InjectionToken<LoadingWaveOptions>;
29
48
  /** sets app-wide defaults; the directive's own options still win */
30
49
  export declare function provideLoadingWave(options: Partial<LoadingWaveOptions>): Provider;
31
50
  /**
32
- * Merges `overrides` into `defaults`, ignoring `undefined` values and
33
- * replacing sizes and durations that are no positive finite number.
51
+ * Merges `overrides` into `defaults`, ignoring `undefined` values,
52
+ * replacing sizes and durations that are no positive finite number and
53
+ * clamping the front's roundness into 0 to 1.
34
54
  */
35
- export declare function resolveLoadingWaveOptions(defaults: LoadingWaveOptions, overrides?: Partial<LoadingWaveOptions>): LoadingWaveOptions;
55
+ export declare function resolveLoadingWaveOptions(defaults: LoadingWaveOptions, overrides?: Partial<LoadingWaveOptions>): ResolvedLoadingWaveOptions;
@@ -1,4 +1,4 @@
1
- import type { LoadingWaveOptions } from './loading-wave-options';
1
+ import type { ResolvedLoadingWaveOptions } from './loading-wave-options';
2
2
  import type { WaveRendererKind } from './renderer';
3
3
  import type { WaveEnvironment } from './wave-environment';
4
4
  /**
@@ -25,14 +25,14 @@ export declare class LoadingWave {
25
25
  private loading;
26
26
  private disconnects;
27
27
  private hostStyle?;
28
- constructor(host: HTMLElement, options: LoadingWaveOptions, env: WaveEnvironment, onRendererChange?: (kind: WaveRendererKind | null) => void);
28
+ constructor(host: HTMLElement, options: ResolvedLoadingWaveOptions, env: WaveEnvironment, onRendererChange?: (kind: WaveRendererKind | null) => void);
29
29
  setLoading(loading: boolean): void;
30
30
  /**
31
31
  * applies new options: look, spacing and speed in place; a new renderer or
32
32
  * `afterLoading` starts a running effect over, and resting dots stay where
33
33
  * the new options keep them
34
34
  */
35
- setOptions(options: LoadingWaveOptions): void;
35
+ setOptions(options: ResolvedLoadingWaveOptions): void;
36
36
  dispose(): void;
37
37
  private mount;
38
38
  private unmount;
package/lib/renderer.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { ShaderUniforms } from './webgl/loading-wave-shader';
1
2
  import type { WaveGeometry } from './wave-model';
2
3
  export type WaveRendererKind = 'webgl' | 'canvas';
3
4
  /** a colour channel by channel, each 0 to 255 */
@@ -15,6 +16,8 @@ export interface WaveLook {
15
16
  /** diameter of a dot at rest, in CSS pixels */
16
17
  readonly dotSize: number;
17
18
  readonly color: Rgb;
19
+ /** the colour lit dots and the wave take; the dots' colour when unset */
20
+ readonly accent?: Rgb;
18
21
  }
19
22
  /** what one frame shows */
20
23
  export interface WaveFrame {
@@ -42,6 +45,8 @@ export interface WaveRenderer {
42
45
  draw(frame: WaveFrame): void;
43
46
  /** changes the dots' look, say after the theme changed the host's colour */
44
47
  setLook(look: WaveLook): void;
48
+ /** changes the values of a shader's own uniforms; only WebGL has any */
49
+ setShaderUniforms(uniforms: ShaderUniforms | undefined): void;
45
50
  /** frees what the renderer holds; the canvas stays where it is */
46
51
  dispose(): void;
47
52
  }
@@ -1,13 +1,19 @@
1
1
  /**
2
2
  * The loading wave as pure math, shared by the 2D canvas renderer and
3
- * mirrored by the WebGL shader (`webgl/wave-shaders.ts`).
3
+ * mirrored by the WebGL shaders' header (`webgl/shader-program.ts`).
4
4
  *
5
- * The wave front is an arc of a circle whose centre lies far left of the
6
- * element, at mid-height: a ripple from off-screen. Its radius grows at an
7
- * even speed, so the front sweeps from the left edge until the lit tail
8
- * behind it has left the element at every row, then starts again.
5
+ * The wave front is an arc of a circle whose centre lies left of the
6
+ * element, at mid-height: a ripple from off-screen. How round it is
7
+ * (`frontRoundness`) sets the circle's radius. Its radius grows at an even
8
+ * speed, so the front sweeps from the left edge until the lit tail behind
9
+ * it has left the element at every row, then starts again.
9
10
  * Every length is in CSS pixels, every time in milliseconds.
10
11
  */
12
+ /**
13
+ * How round the front is by default: its ends lag its middle by half of
14
+ * `min(height / 2, width)`.
15
+ */
16
+ export declare const DEFAULT_FRONT_ROUNDNESS = 0.5;
11
17
  /** how lit a dot stays once the front passed it, as in the video */
12
18
  export declare const AFTERGLOW = 0.45;
13
19
  /** share of a sweep after which a passed dot's afterglow starts to fade */
@@ -42,6 +48,11 @@ export interface WaveGeometry {
42
48
  export interface WaveGeometryOptions {
43
49
  readonly dotSpacing: number;
44
50
  readonly sweepMs: number;
51
+ /**
52
+ * 0 (a straight front) to 1: how far the front's ends lag its middle, as a
53
+ * share of `min(height / 2, width)`; `DEFAULT_FRONT_ROUNDNESS` when unset
54
+ */
55
+ readonly frontRoundness?: number;
45
56
  }
46
57
  export interface Point {
47
58
  readonly x: number;
@@ -51,7 +62,7 @@ export interface Displacement {
51
62
  readonly dx: number;
52
63
  readonly dy: number;
53
64
  }
54
- export declare function waveGeometry(width: number, height: number, { dotSpacing: askedSpacing, sweepMs }: WaveGeometryOptions): WaveGeometry;
65
+ export declare function waveGeometry(width: number, height: number, { dotSpacing: askedSpacing, sweepMs, frontRoundness, }: WaveGeometryOptions): WaveGeometry;
55
66
  /** the share of the current sweep that has passed, 0 up to (not including) 1 */
56
67
  export declare function sweepPhase(geometry: WaveGeometry, elapsedMs: number): number;
57
68
  /** the front's radius at the time `elapsedMs` */
@@ -0,0 +1,4 @@
1
+ /** strength of the echo ripple trailing the front, times the main front's */
2
+ export declare const ECHO_STRENGTH = 0.4;
3
+ /** the echo trails the front by this share of a sweep */
4
+ export declare const ECHO_LAG: number;
@@ -0,0 +1,20 @@
1
+ /** a uniform's value: a `float`, or the components of a `vec2` to `vec4` */
2
+ export type ShaderUniformValue = number | readonly [number] | readonly [number, number] | readonly [number, number, number] | readonly [number, number, number, number];
3
+ /** values of the uniforms a fragment declares itself, by their GLSL name */
4
+ export type ShaderUniforms = Readonly<Record<string, ShaderUniformValue>>;
5
+ /**
6
+ * A fragment shader for the loading wave's WebGL renderer.
7
+ *
8
+ * `fragment` is GLSL ES 3.00 that defines `vec4 wsShade(vec2 point)`: the
9
+ * straight (not premultiplied) colour and opacity at `point`, in CSS pixels
10
+ * from the host's top left corner. The lib puts the `ws_*` uniforms and
11
+ * helpers before it and a `main` after it (see the README), so the fragment
12
+ * holds neither `#version` nor `main`. At `ws_wave == 0` it draws its resting
13
+ * state, without `ws_time`: that is what `afterLoading: 'keep'` leaves and
14
+ * what `prefers-reduced-motion` shows.
15
+ */
16
+ export interface LoadingWaveShader {
17
+ readonly fragment: string;
18
+ /** values of uniforms the fragment declares itself; never `ws_*` ones */
19
+ readonly uniforms?: ShaderUniforms;
20
+ }
@@ -0,0 +1,33 @@
1
+ import type { LoadingWaveShader } from './loading-wave-shader';
2
+ /** the shaders did not compile or link on this GPU */
3
+ export declare class WaveShaderError extends Error {
4
+ readonly name = "WaveShaderError";
5
+ }
6
+ /**
7
+ * The uniforms the lib sets for every shader. `ws_bufferSize` and `ws_dots`
8
+ * are for `main` only.
9
+ */
10
+ export declare const STANDARD_UNIFORMS: readonly ["ws_size", "ws_bufferSize", "ws_pixel", "ws_spacing", "ws_dotSize", "ws_color", "ws_accent", "ws_center", "ws_frontRadius", "ws_echoRadius", "ws_travel", "ws_falloff", "ws_rise", "ws_tail", "ws_maxPush", "ws_phase", "ws_time", "ws_previousSweep", "ws_wave", "ws_dots"];
11
+ export type StandardUniform = (typeof STANDARD_UNIFORMS)[number];
12
+ /** one triangle that covers the whole canvas, no vertex buffer needed */
13
+ export declare const WAVE_VERTEX_SHADER = "#version 300 es\nvoid main() {\n vec2 corner = vec2(float((gl_VertexID << 1) & 2), float(gl_VertexID & 2));\n gl_Position = vec4(corner * 2.0 - 1.0, 0.0, 1.0);\n}\n";
14
+ /**
15
+ * What every fragment shader starts with: the uniforms and helpers of the
16
+ * contract (`LoadingWaveShader`). The `WS_*` constants mirror the
17
+ * TypeScript ones (`renderer.ts`, `wave-model.ts`, `echo.ts`);
18
+ * `shader-constants.spec.ts` keeps them equal. Kept a plain literal, so a
19
+ * bundler can tell it has no side effects.
20
+ */
21
+ export declare const WAVE_SHADER_HEADER = "#version 300 es\nprecision highp float;\n\nuniform vec2 ws_size;\nuniform vec2 ws_bufferSize;\nuniform float ws_pixel;\nuniform float ws_spacing;\nuniform float ws_dotSize;\nuniform vec4 ws_color;\nuniform vec4 ws_accent;\nuniform vec2 ws_center;\nuniform float ws_frontRadius;\nuniform float ws_echoRadius;\nuniform float ws_travel;\nuniform float ws_falloff;\nuniform float ws_rise;\nuniform float ws_tail;\nuniform float ws_maxPush;\nuniform float ws_phase;\nuniform float ws_time;\nuniform float ws_previousSweep;\nuniform float ws_wave;\nuniform float ws_dots;\n\nconst float WS_REST_ALPHA = 0.22;\nconst float WS_LIT_ALPHA = 0.9;\nconst float WS_LIT_GROWTH = 0.8;\nconst float WS_FRONT_LINE_ALPHA = 0.14;\nconst float WS_AFTERGLOW = 0.45;\nconst float WS_AFTERGLOW_FADE_START = 0.45;\nconst float WS_ECHO_STRENGTH = 0.4;\n\n/** how far p lies behind the front: negative ahead of it */\nfloat ws_behindFront(vec2 p) {\n return ws_frontRadius - length(p - ws_center);\n}\n\n/** how far p lies behind the echo; far ahead of it while there is none */\nfloat ws_behindEcho(vec2 p) {\n return ws_echoRadius < 0.0 ? -1.0e6 : ws_echoRadius - length(p - ws_center);\n}\n\n/** the bright part right behind a front: 1 there, dimming behind, 0 ahead */\nfloat ws_frontGlow(float behind) {\n return smoothstep(-ws_rise, 0.0, behind) * exp(-max(behind, 0.0) / ws_falloff);\n}\n\n/** what stays lit once the front passed, fading until the next one comes */\nfloat ws_afterglow(float behind) {\n if (behind < 0.0 && ws_previousSweep < 0.5) {\n return 0.0;\n }\n float sincePassed = (behind >= 0.0 ? behind : behind + ws_travel) / ws_travel;\n return WS_AFTERGLOW * (1.0 - smoothstep(WS_AFTERGLOW_FADE_START, 1.0, sincePassed));\n}\n\n/** the wave's light at p, 0 to 1, already scaled by ws_wave */\nfloat ws_waveIntensity(vec2 p) {\n float behind = ws_behindFront(p);\n return ws_wave * max(ws_frontGlow(behind), ws_afterglow(behind));\n}\n\n/** the echo's front glow at p, scaled by its strength and ws_wave */\nfloat ws_echoGlow(vec2 p) {\n return ws_wave * WS_ECHO_STRENGTH * ws_frontGlow(ws_behindEcho(p));\n}\n\n/** a stable pseudo-random number in [0, 1) per p, say per grid cell */\nfloat ws_hash(vec2 p) {\n vec3 p3 = fract(vec3(p.xyx) * 0.1031);\n p3 += dot(p3, p3.yzx + 33.33);\n return fract((p3.x + p3.y) * p3.z);\n}\n\n/** two stable pseudo-random numbers in [0, 1) per p */\nvec2 ws_hash2(vec2 p) {\n vec3 p3 = fract(vec3(p.xyx) * vec3(0.1031, 0.1030, 0.0973));\n p3 += dot(p3, p3.yzx + 33.33);\n return fract((p3.xx + p3.yz) * p3.zy);\n}\n\n/** the grid cell p lies in */\nvec2 ws_cell(vec2 p) {\n return floor(p / ws_spacing);\n}\n\n/** the centre of a grid cell, where its dot sits */\nvec2 ws_cellCenter(vec2 cell) {\n return (cell + 0.5) * ws_spacing;\n}\n\n/** anti-aliased coverage of a disk at p, 0 to 1 */\nfloat ws_dotDisk(vec2 p, vec2 center, float radius) {\n float edge = 0.5 * ws_pixel;\n return 1.0 - smoothstep(radius - edge, radius + edge, length(p - center));\n}\n\n/** anti-aliased coverage of a line of the given width along a segment */\nfloat ws_segment(vec2 p, vec2 a, vec2 b, float width) {\n vec2 ab = b - a;\n float along = clamp(dot(p - a, ab) / max(dot(ab, ab), 1.0e-6), 0.0, 1.0);\n float away = length(p - a - ab * along);\n float edge = 0.5 * ws_pixel;\n return 1.0 - smoothstep(0.5 * width - edge, 0.5 * width + edge, away);\n}\n\n/** the dots' colour mixed towards the accent by lit, 0 to 1 */\nvec4 ws_ink(float lit) {\n return mix(ws_color, ws_accent, clamp(lit, 0.0, 1.0));\n}\n";
22
+ /**
23
+ * What every fragment shader ends with: maps the drawing buffer onto the
24
+ * host in CSS pixels (y down), calls `wsShade` and fades it by `ws_dots`.
25
+ */
26
+ export declare const WAVE_SHADER_MAIN = "\nout vec4 ws_outColor;\n\nvoid main() {\n // the drawing buffer may be smaller than asked for: map it onto the host\n vec2 cssPerPixel = ws_size / ws_bufferSize;\n vec2 point = vec2(gl_FragCoord.x, ws_bufferSize.y - gl_FragCoord.y) * cssPerPixel;\n vec4 shade = clamp(wsShade(point), 0.0, 1.0);\n float alpha = shade.a * ws_dots;\n ws_outColor = vec4(shade.rgb * alpha, alpha);\n}\n";
27
+ /** the whole fragment shader for a `LoadingWaveShader` */
28
+ export declare function assembleFragment(shader: LoadingWaveShader): string;
29
+ /**
30
+ * The program of the full-canvas triangle and the shader's fragment.
31
+ * @throws WaveShaderError when it does not compile or link on this GPU
32
+ */
33
+ export declare function linkWaveProgram(gl: WebGL2RenderingContext, shader: LoadingWaveShader): WebGLProgram;
@@ -0,0 +1,10 @@
1
+ import type { LoadingWaveShader } from '../loading-wave-shader';
2
+ /**
3
+ * The default look on the GPU: the wave as a ripple running through water
4
+ * over the dot grid. The crests (front and echo) are a height field; the
5
+ * dots are seen through its slope (refraction), shaded as small beads lit
6
+ * from the crest ahead of them, and bloom in the accent colour; the water
7
+ * itself shows as a faint body with a glossy sheen on the crests' slopes.
8
+ * Drawn over the host's background, so it reads in light and dark themes.
9
+ */
10
+ export declare const rippleShader: LoadingWaveShader;
@@ -1,9 +1,8 @@
1
1
  import { WaveFrame, WaveLook, WaveRenderer } from '../renderer';
2
2
  import { WaveGeometry } from '../wave-model';
3
- /** the shaders did not compile or link on this GPU */
4
- export declare class WaveShaderError extends Error {
5
- readonly name = "WaveShaderError";
6
- }
3
+ import type { LoadingWaveShader, ShaderUniforms } from './loading-wave-shader';
4
+ import { WaveShaderError } from './shader-program';
5
+ export { WaveShaderError };
7
6
  export interface WebGlWaveRendererHooks {
8
7
  /** the browser took the GPU context away; the renderer draws no more */
9
8
  readonly onContextLost: () => void;
@@ -11,8 +10,9 @@ export interface WebGlWaveRendererHooks {
11
10
  readonly onDispose?: () => void;
12
11
  }
13
12
  /**
14
- * Draws the wave with a WebGL2 fragment shader: the 2D canvas's look plus a
15
- * glow around lit dots and an echo ripple trailing the front.
13
+ * Draws the wave with a WebGL2 fragment shader (`LoadingWaveShader`) over a
14
+ * full-canvas triangle, setting the contract's `ws_*` uniforms and the
15
+ * shader's own each frame.
16
16
  */
17
17
  export declare class WebGlWaveRenderer implements WaveRenderer {
18
18
  readonly canvas: HTMLCanvasElement;
@@ -22,12 +22,16 @@ export declare class WebGlWaveRenderer implements WaveRenderer {
22
22
  readonly kind = "webgl";
23
23
  private readonly program;
24
24
  private readonly uniforms;
25
+ private readonly ownLocations;
26
+ private ownUniforms;
27
+ /** uniforms `setShaderUniforms` left out, set to 0 on the next draw */
28
+ private pendingResets;
25
29
  private geometry?;
26
30
  private lost;
27
31
  private disposed;
28
32
  private readonly handleContextLost;
29
33
  /** @throws WaveShaderError when the shaders fail on this GPU */
30
- constructor(canvas: HTMLCanvasElement, gl: WebGL2RenderingContext, look: WaveLook, hooks: WebGlWaveRendererHooks);
34
+ constructor(canvas: HTMLCanvasElement, gl: WebGL2RenderingContext, look: WaveLook, shader: LoadingWaveShader, hooks: WebGlWaveRendererHooks);
31
35
  /**
32
36
  * A WebGL2 context, or `null` where the browser offers none. With
33
37
  * `hardwareOnly` also `null` where it would render on the CPU (no GPU, a
@@ -37,8 +41,15 @@ export declare class WebGlWaveRenderer implements WaveRenderer {
37
41
  resize(geometry: WaveGeometry, pixelRatio: number): void;
38
42
  draw(frame: WaveFrame): void;
39
43
  setLook(look: WaveLook): void;
44
+ /**
45
+ * a uniform the new values leave out goes back to 0, the value GLSL gives
46
+ * every uniform before it is set
47
+ */
48
+ setShaderUniforms(uniforms: ShaderUniforms | undefined): void;
40
49
  dispose(): void;
41
50
  private setUniforms;
51
+ /** where the shader's own uniform lives, looked up once per name */
52
+ private ownLocation;
42
53
  }
43
54
  /**
44
55
  * The echo's radius, trailing the front by `ECHO_LAG` of a sweep; negative,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wolsok/loading-wave",
3
- "version": "0.0.1",
3
+ "version": "0.0.2",
4
4
  "description": "An Angular directive that lays a calm loading wave of lit dots behind any element, on the GPU with a 2D canvas fallback",
5
5
  "bugs": {
6
6
  "url": "https://github.com/WolfSoko/wol-sok-mono/issues"