@ghostty-webgpu/shaders 0.0.0-stage → 0.0.4

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Shaul Lavo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,21 @@
1
- # Temporary Holding Version
1
+ # ghostty-webgpu-shaders
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Optional compiled shader effects for a `ghostty-webgpu` terminal.
4
+
5
+ ```sh
6
+ npm install ghostty-webgpu ghostty-webgpu-shaders
7
+ ```
8
+
9
+ ```ts
10
+ import { createShaderAddon } from '@ghostty-webgpu/shaders'
11
+ import compiled from './effect.js'
12
+
13
+ const effect = terminal.use(createShaderAddon(compiled))
14
+ await effect.api.ready
15
+ // Later:
16
+ effect.dispose()
17
+ ```
18
+
19
+ Supply compiled WGSL, GLSL ES 3.00, or both. The package has no compiler dependency.
20
+
21
+ [Usage and lifecycle](docs/usage.md) · [Shader bindings](docs/bindings.md)
@@ -0,0 +1,2 @@
1
+ import { type CompiledShader, type ShaderAddon, type ShaderAddonOptions } from './types.js';
2
+ export declare function createShaderAddon(shader: CompiledShader, options?: ShaderAddonOptions): ShaderAddon;
package/dist/addon.js ADDED
@@ -0,0 +1,397 @@
1
+ import { packShaderUniforms, SHADER_UNIFORM_BYTE_LENGTH } from '@ghostty-webgpu/shader-abi';
2
+ import { resolveStartupBackend, subscribeCanvasImage } from './canvas-image.js';
3
+ import { FrameSchedule } from './frame-schedule.js';
4
+ import { WebGlShaderPass, WebGpuShaderPass } from './pass.js';
5
+ import { frameUniforms, UniformState } from './terminal-uniforms.js';
6
+ import { ShaderAddonError, validateShader, } from './types.js';
7
+ function deferred() {
8
+ let resolve;
9
+ let reject;
10
+ const promise = new Promise((yes, no) => {
11
+ resolve = yes;
12
+ reject = no;
13
+ });
14
+ // Lifecycle promises can reject before a consumer starts awaiting them.
15
+ void promise.catch(() => { });
16
+ return { promise, resolve, reject };
17
+ }
18
+ async function acquireDevice(gpu) {
19
+ if (!gpu)
20
+ return undefined;
21
+ try {
22
+ const adapter = await gpu.requestAdapter();
23
+ return await adapter?.requestDevice();
24
+ }
25
+ catch {
26
+ return undefined;
27
+ }
28
+ }
29
+ function createGlPass(canvas) {
30
+ try {
31
+ return new WebGlShaderPass(canvas);
32
+ }
33
+ catch (cause) {
34
+ canvas.getContext('webgl2')?.getExtension('WEBGL_lose_context')?.loseContext();
35
+ throw cause;
36
+ }
37
+ }
38
+ async function createPass(canvas, shader, options, terminalBackend, onError) {
39
+ const preferGl = !shader.wgsl || (terminalBackend === 'webgl2' && Boolean(shader.glsl));
40
+ const backend = options.backend ?? (preferGl ? 'webgl2' : 'webgpu');
41
+ if (backend === 'webgl2') {
42
+ if (!shader.glsl)
43
+ throw new ShaderAddonError('backend', 'WebGL2 requires compiled GLSL output.');
44
+ return createGlPass(canvas);
45
+ }
46
+ if (!shader.wgsl)
47
+ throw new ShaderAddonError('backend', 'WebGPU requires compiled WGSL output.');
48
+ const device = await acquireDevice(canvas.ownerDocument.defaultView?.navigator.gpu);
49
+ if (!device && !options.backend && shader.glsl)
50
+ return createGlPass(canvas);
51
+ if (!device)
52
+ throw new ShaderAddonError('backend', 'A WebGPU adapter and device are unavailable. Supply GLSL to enable WebGL2 output.');
53
+ try {
54
+ const pass = new WebGpuShaderPass(device, canvas, onError);
55
+ void device.lost.then((info) => {
56
+ if (info.reason !== 'destroyed')
57
+ onError(info);
58
+ });
59
+ device.addEventListener('uncapturederror', (event) => onError(event.error));
60
+ return pass;
61
+ }
62
+ catch (cause) {
63
+ canvas.getContext('webgpu')?.unconfigure();
64
+ device.destroy();
65
+ throw cause;
66
+ }
67
+ }
68
+ class Controller {
69
+ scope;
70
+ shader;
71
+ options;
72
+ #installed = deferred();
73
+ #available = deferred();
74
+ ready = this.#installed.promise;
75
+ #frames = new FrameSchedule();
76
+ #uniforms = new ArrayBuffer(SHADER_UNIFORM_BYTE_LENGTH);
77
+ #state = new UniformState();
78
+ #terminal;
79
+ #pass;
80
+ #output;
81
+ #capture;
82
+ #source;
83
+ #view;
84
+ #observer;
85
+ #disposed = false;
86
+ #started = false;
87
+ #revision = 0;
88
+ #raf = 0;
89
+ #resizeRaf = 0;
90
+ #paused;
91
+ #captured = false;
92
+ #upload = false;
93
+ #shaderReady = false;
94
+ #compiles = Promise.resolve();
95
+ #cleanup = [];
96
+ constructor(scope, shader, options) {
97
+ this.scope = scope;
98
+ this.shader = shader;
99
+ this.options = options;
100
+ this.#terminal = scope.terminal;
101
+ this.#paused = options.paused ?? false;
102
+ scope.own(() => this.dispose());
103
+ this.#cleanup.push(this.#terminal.on('open', () => this.start()).dispose);
104
+ this.#cleanup.push(this.#terminal.on('frame', () => this.frame()).dispose);
105
+ this.#cleanup.push(this.#terminal.on('appearance', () => this.invalidate()).dispose);
106
+ if (this.#terminal.lifecycle === 'open')
107
+ this.start();
108
+ void this.setShader(shader).catch(() => { });
109
+ }
110
+ start() {
111
+ if (this.#disposed || this.#started)
112
+ return;
113
+ this.#started = true;
114
+ void this.initialize().catch((cause) => this.fail(cause));
115
+ }
116
+ async initialize() {
117
+ const terminal = this.#terminal;
118
+ const root = terminal.element;
119
+ const source = terminal.canvas;
120
+ if (!root || !source)
121
+ throw new ShaderAddonError('capture', 'Open the terminal with a canvas renderer.');
122
+ const snapshot = terminal.frameSnapshot();
123
+ if (snapshot && 'then' in snapshot) {
124
+ void snapshot.catch(() => { });
125
+ throw new ShaderAddonError('worker', 'Shader capture requires a main-thread terminal. Worker frames arrive after the source drawing buffer is presented.');
126
+ }
127
+ if (terminal.diagnostics.rendererBackend === 'dom')
128
+ throw new ShaderAddonError('backend', 'Shader capture requires a WebGPU, WebGL2, or Canvas2D terminal renderer.');
129
+ const automaticDualLanguage = !this.options.backend && Boolean(this.shader.wgsl) && Boolean(this.shader.glsl);
130
+ const terminalBackend = automaticDualLanguage
131
+ ? await resolveStartupBackend(terminal, terminal.diagnostics.rendererBackend)
132
+ : terminal.diagnostics.rendererBackend;
133
+ if (this.#disposed)
134
+ return;
135
+ const currentSource = terminal.canvas;
136
+ if (!currentSource)
137
+ throw new ShaderAddonError('capture', 'Open the terminal with a canvas renderer.');
138
+ if (terminalBackend === 'dom')
139
+ throw new ShaderAddonError('backend', 'Shader capture requires a WebGPU, WebGL2, or Canvas2D terminal renderer.');
140
+ this.#cleanup.push(subscribeCanvasImage(terminal, () => this.capture()));
141
+ const view = root.ownerDocument.defaultView;
142
+ if (!view)
143
+ throw new ShaderAddonError('capture', 'The terminal must belong to a window.');
144
+ this.#view = view;
145
+ const output = root.ownerDocument.createElement('canvas');
146
+ output.dataset['ghosttyShader'] = '';
147
+ output.setAttribute('aria-hidden', 'true');
148
+ output.style.cssText = 'position:absolute;pointer-events:none;display:none;';
149
+ this.#output = output;
150
+ this.#capture = root.ownerDocument.createElement('canvas');
151
+ this.#source = currentSource;
152
+ currentSource.after(output);
153
+ this.listen(root.ownerDocument, 'visibilitychange', this.synchronize);
154
+ this.listen(view, 'resize', this.resized);
155
+ this.listen(root, 'focusin', this.focused);
156
+ this.listen(root, 'focusout', this.focused);
157
+ this.listen(root, 'pointermove', this.pointer);
158
+ this.listen(root, 'pointerdown', this.pointer);
159
+ this.listen(view, 'pointerup', this.pointer);
160
+ this.listen(output, 'webglcontextlost', this.contextLost);
161
+ this.#observer = new ResizeObserver(this.resized);
162
+ this.#observer.observe(currentSource);
163
+ const pass = await createPass(output, this.shader, this.options, terminalBackend, (cause) => this.fail(cause));
164
+ if (this.#disposed) {
165
+ pass.dispose();
166
+ return;
167
+ }
168
+ this.#pass = pass;
169
+ output.dataset['backend'] = pass.backend;
170
+ this.#available.resolve(pass);
171
+ this.synchronize();
172
+ // A row refresh can submit no draw; rebuild once to capture an already-presented WebGL canvas.
173
+ terminal.clearTextureAtlas();
174
+ }
175
+ setShader(shader) {
176
+ if (this.#disposed)
177
+ return Promise.resolve(false);
178
+ const revision = ++this.#revision;
179
+ const operation = this.#compiles
180
+ .catch(() => { })
181
+ .then(async () => {
182
+ if (!this.current(revision))
183
+ return false;
184
+ validateShader(shader);
185
+ const pass = await this.#available.promise;
186
+ if (!this.current(revision))
187
+ return false;
188
+ if (pass.backend === 'webgpu' && !shader.wgsl)
189
+ throw new ShaderAddonError('backend', 'WebGPU requires compiled WGSL output.');
190
+ if (pass.backend === 'webgl2' && !shader.glsl)
191
+ throw new ShaderAddonError('backend', 'WebGL2 requires compiled GLSL output.');
192
+ await pass.setShader(shader, () => this.current(revision));
193
+ if (!this.current(revision))
194
+ return false;
195
+ this.#shaderReady = true;
196
+ this.#installed.resolve();
197
+ this.invalidate();
198
+ return true;
199
+ })
200
+ .catch((cause) => {
201
+ if (!this.current(revision))
202
+ return false;
203
+ if (!this.#shaderReady)
204
+ this.fail(cause);
205
+ throw cause;
206
+ });
207
+ this.#compiles = operation;
208
+ return operation;
209
+ }
210
+ current(revision) {
211
+ return !this.#disposed && revision === this.#revision;
212
+ }
213
+ setPaused(paused) {
214
+ this.#paused = paused;
215
+ this.synchronize();
216
+ }
217
+ synchronize = () => {
218
+ if (!this.#view || this.#disposed)
219
+ return;
220
+ this.#frames.setActive(!this.#paused && !this.#view.document.hidden, this.#view.performance.now());
221
+ this.#view.cancelAnimationFrame(this.#raf);
222
+ this.#raf = 0;
223
+ this.invalidate();
224
+ };
225
+ focused = () => {
226
+ this.#state.focusChanged(this.#frames.timeAt(this.#view?.performance.now() ?? 0));
227
+ this.invalidate();
228
+ };
229
+ pointer = (event) => {
230
+ if (!('clientX' in event) || typeof event.clientX !== 'number')
231
+ return;
232
+ if (!('clientY' in event) || typeof event.clientY !== 'number')
233
+ return;
234
+ const canvas = this.#output;
235
+ if (!canvas || !canvas.width || !canvas.height)
236
+ return;
237
+ const rect = canvas.getBoundingClientRect();
238
+ if (!rect.width || !rect.height)
239
+ return;
240
+ this.#state.pointer(event.type, ((event.clientX - rect.left) * canvas.width) / rect.width, ((rect.bottom - event.clientY) * canvas.height) / rect.height);
241
+ this.invalidate();
242
+ };
243
+ contextLost = (event) => {
244
+ event.preventDefault();
245
+ this.fail(new ShaderAddonError('gpu', 'The shader output WebGL2 context was lost.'));
246
+ };
247
+ resized = () => {
248
+ if (this.#disposed || !this.#view || this.#resizeRaf)
249
+ return;
250
+ this.#resizeRaf = this.#view.requestAnimationFrame(this.refresh);
251
+ };
252
+ refresh = () => {
253
+ this.#resizeRaf = 0;
254
+ if (this.#disposed)
255
+ return;
256
+ this.layout();
257
+ if (this.#terminal.lifecycle === 'open')
258
+ this.#terminal.refresh(0, this.#terminal.appearance.grid.rows - 1);
259
+ };
260
+ layout() {
261
+ const source = this.#terminal.canvas;
262
+ const output = this.#output;
263
+ if (!source || !output || !this.#view)
264
+ return;
265
+ if (this.#source !== source) {
266
+ this.#observer?.disconnect();
267
+ this.#observer?.observe(source);
268
+ this.#source = source;
269
+ source.after(output);
270
+ }
271
+ const css = this.#view.getComputedStyle(source);
272
+ const left = parseFloat(css.paddingLeft) || 0;
273
+ const top = parseFloat(css.paddingTop) || 0;
274
+ output.style.left = `${source.offsetLeft + source.clientLeft + left}px`;
275
+ output.style.top = `${source.offsetTop + source.clientTop + top}px`;
276
+ output.style.width = `${source.clientWidth - left - (parseFloat(css.paddingRight) || 0)}px`;
277
+ output.style.height = `${source.clientHeight - top - (parseFloat(css.paddingBottom) || 0)}px`;
278
+ this.#pass?.resize({ width: source.width, height: source.height });
279
+ }
280
+ frame() {
281
+ if (this.#disposed)
282
+ return;
283
+ if (this.#terminal.diagnostics.rendererBackend === 'dom') {
284
+ this.fail(new ShaderAddonError('backend', 'The terminal renderer no longer publishes canvas images.'));
285
+ return;
286
+ }
287
+ this.invalidate();
288
+ }
289
+ capture() {
290
+ if (this.#disposed || !this.#capture || !this.#pass)
291
+ return;
292
+ const source = this.#terminal.canvas;
293
+ if (!source || !source.width || !source.height)
294
+ return;
295
+ try {
296
+ this.layout();
297
+ const copy = this.#capture;
298
+ if (copy.width !== source.width)
299
+ copy.width = source.width;
300
+ if (copy.height !== source.height)
301
+ copy.height = source.height;
302
+ const context = copy.getContext('2d');
303
+ if (!context)
304
+ throw new ShaderAddonError('capture', 'A Canvas2D snapshot context is unavailable.');
305
+ // Replace transparent pixels while the newly drawn source buffer is still available.
306
+ context.globalCompositeOperation = 'copy';
307
+ context.drawImage(source, 0, 0);
308
+ this.#captured = true;
309
+ this.#upload = true;
310
+ this.invalidate();
311
+ }
312
+ catch (cause) {
313
+ this.fail(cause);
314
+ }
315
+ }
316
+ invalidate() {
317
+ this.#frames.invalidate();
318
+ this.schedule();
319
+ }
320
+ schedule() {
321
+ if (this.#disposed || !this.#view || this.#view.document.hidden || this.#raf)
322
+ return;
323
+ if (!this.#captured || !this.#shaderReady || !this.#frames.pending)
324
+ return;
325
+ this.#raf = this.#view.requestAnimationFrame(this.animate);
326
+ }
327
+ animate = (timestamp) => {
328
+ this.#raf = 0;
329
+ try {
330
+ this.#frames.draw(timestamp, this.draw);
331
+ }
332
+ catch (cause) {
333
+ this.fail(cause);
334
+ }
335
+ this.schedule();
336
+ };
337
+ draw = (frame) => {
338
+ const pass = this.#pass;
339
+ const copy = this.#capture;
340
+ if (this.#disposed || !pass || !copy || !pass.ready())
341
+ return false;
342
+ if (this.#upload) {
343
+ pass.capture(copy);
344
+ this.#upload = false;
345
+ }
346
+ const uniforms = frameUniforms(this.#terminal, this.#state, frame, copy);
347
+ const drawn = pass.draw(packShaderUniforms(uniforms, this.#uniforms));
348
+ if (drawn && this.#output)
349
+ this.#output.style.display = 'block';
350
+ return drawn;
351
+ };
352
+ listen(target, type, callback) {
353
+ target.addEventListener(type, callback);
354
+ this.#cleanup.push(() => target.removeEventListener(type, callback));
355
+ }
356
+ fail(cause) {
357
+ if (this.#disposed)
358
+ return;
359
+ const error = cause instanceof ShaderAddonError
360
+ ? cause
361
+ : new ShaderAddonError('gpu', 'The shader output could not render.', { cause });
362
+ this.#installed.reject(error);
363
+ this.#available.reject(error);
364
+ this.dispose();
365
+ this.options.onError?.(error);
366
+ }
367
+ dispose() {
368
+ if (this.#disposed)
369
+ return;
370
+ this.#disposed = true;
371
+ this.#revision += 1;
372
+ const error = new ShaderAddonError('disposed', 'The shader extension was disposed.');
373
+ this.#installed.reject(error);
374
+ this.#available.reject(error);
375
+ this.#view?.cancelAnimationFrame(this.#raf);
376
+ this.#view?.cancelAnimationFrame(this.#resizeRaf);
377
+ this.#raf = 0;
378
+ this.#resizeRaf = 0;
379
+ this.#observer?.disconnect();
380
+ for (const cleanup of this.#cleanup)
381
+ cleanup();
382
+ this.#cleanup = [];
383
+ this.#pass?.dispose();
384
+ this.#output?.remove();
385
+ if (this.#capture) {
386
+ this.#capture.width = 0;
387
+ this.#capture.height = 0;
388
+ }
389
+ }
390
+ }
391
+ export function createShaderAddon(shader, options = {}) {
392
+ validateShader(shader);
393
+ return {
394
+ name: '@ghostty-webgpu/shaders',
395
+ setup: (scope) => ({ api: new Controller(scope, shader, options) }),
396
+ };
397
+ }
@@ -0,0 +1,5 @@
1
+ import type { TerminalApi } from 'ghostty-webgpu';
2
+ type TerminalBackend = TerminalApi['diagnostics']['rendererBackend'];
3
+ export declare function resolveStartupBackend(terminal: object, fallback: TerminalBackend): Promise<TerminalBackend>;
4
+ export declare function subscribeCanvasImage(terminal: object, listener: () => void): () => void;
5
+ export {};
@@ -0,0 +1,42 @@
1
+ import { ShaderAddonError } from './types.js';
2
+ const observeCanvasImage = Symbol.for('ghostty-webgpu.observeCanvasImage');
3
+ const observeStartupBackend = Symbol.for('ghostty-webgpu.resolveStartupBackend');
4
+ function isTerminalBackend(value) {
5
+ return (value === undefined ||
6
+ value === 'canvas2d' ||
7
+ value === 'dom' ||
8
+ value === 'webgl2' ||
9
+ value === 'webgpu');
10
+ }
11
+ export async function resolveStartupBackend(terminal, fallback) {
12
+ const binding = Reflect.get(terminal, observeStartupBackend);
13
+ if (typeof binding !== 'function')
14
+ return fallback;
15
+ const result = await binding.call(terminal);
16
+ return isTerminalBackend(result) ? result : fallback;
17
+ }
18
+ export function subscribeCanvasImage(terminal, listener) {
19
+ try {
20
+ const binding = Reflect.get(terminal, observeCanvasImage);
21
+ if (typeof binding !== 'function')
22
+ throw new ShaderAddonError('capture', 'The terminal has no canvas-image subscription.');
23
+ const subscription = binding.call(terminal, listener);
24
+ if (typeof subscription !== 'object' || subscription === null || !('kind' in subscription))
25
+ throw new ShaderAddonError('capture', 'The canvas-image subscription is invalid.');
26
+ if (subscription.kind === 'unsupported')
27
+ throw new ShaderAddonError('backend', 'The terminal renderer does not publish canvas images.');
28
+ if (subscription.kind !== 'subscription' ||
29
+ !('dispose' in subscription) ||
30
+ typeof subscription.dispose !== 'function')
31
+ throw new ShaderAddonError('capture', 'The canvas-image subscription is invalid.');
32
+ const dispose = subscription.dispose;
33
+ return () => dispose.call(subscription);
34
+ }
35
+ catch (cause) {
36
+ if (cause instanceof ShaderAddonError)
37
+ throw cause;
38
+ throw new ShaderAddonError('capture', 'The terminal canvas-image subscription failed.', {
39
+ cause,
40
+ });
41
+ }
42
+ }
@@ -0,0 +1,13 @@
1
+ export interface ShaderFrame {
2
+ readonly time: number;
3
+ readonly delta: number;
4
+ readonly frame: number;
5
+ }
6
+ export declare class FrameSchedule {
7
+ #private;
8
+ get pending(): boolean;
9
+ setActive(active: boolean, timestamp: number): void;
10
+ invalidate(): void;
11
+ timeAt(timestamp: number): number;
12
+ draw(timestamp: number, submit: (frame: ShaderFrame) => boolean): void;
13
+ }
@@ -0,0 +1,36 @@
1
+ export class FrameSchedule {
2
+ #activeSince;
3
+ #elapsed = 0;
4
+ #lastDrawTime = 0;
5
+ #frame = 0;
6
+ #dirty = true;
7
+ get pending() {
8
+ return this.#dirty || this.#activeSince !== undefined;
9
+ }
10
+ setActive(active, timestamp) {
11
+ if (active === (this.#activeSince !== undefined))
12
+ return;
13
+ this.#elapsed = this.timeAt(timestamp);
14
+ this.#activeSince = active ? timestamp : undefined;
15
+ }
16
+ invalidate() {
17
+ this.#dirty = true;
18
+ }
19
+ timeAt(timestamp) {
20
+ if (this.#activeSince === undefined)
21
+ return this.#elapsed;
22
+ return this.#elapsed + Math.max(0, timestamp - this.#activeSince) / 1000;
23
+ }
24
+ draw(timestamp, submit) {
25
+ if (!this.pending)
26
+ return;
27
+ const time = this.timeAt(timestamp);
28
+ const delta = Math.max(0, time - this.#lastDrawTime);
29
+ this.#dirty = true;
30
+ if (!submit({ time, delta, frame: this.#frame }))
31
+ return;
32
+ this.#dirty = false;
33
+ this.#lastDrawTime = time;
34
+ this.#frame = (this.#frame + 1) % 2147483647;
35
+ }
36
+ }
@@ -0,0 +1,5 @@
1
+ export { FULLSCREEN_VERTEX_GLSL, FULLSCREEN_VERTEX_WGSL, packShaderUniforms, SHADER_SCHEMA_VERSION, SHADER_UNIFORM_BYTE_LENGTH, SHADER_UNIFORM_FIELDS, SHADER_UNIFORM_LAYOUT, } from '@ghostty-webgpu/shader-abi';
2
+ export type { CompiledGhosttyShader, ShaderUniformField, ShaderUniformValues, ShaderVector2, ShaderVector3, ShaderVector4, } from '@ghostty-webgpu/shader-abi';
3
+ export { createShaderAddon } from './addon.js';
4
+ export { ShaderAddonError } from './types.js';
5
+ export type { CompiledShader, ShaderAddon, ShaderAddonApi, ShaderAddonOptions } from './types.js';
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { FULLSCREEN_VERTEX_GLSL, FULLSCREEN_VERTEX_WGSL, packShaderUniforms, SHADER_SCHEMA_VERSION, SHADER_UNIFORM_BYTE_LENGTH, SHADER_UNIFORM_FIELDS, SHADER_UNIFORM_LAYOUT, } from '@ghostty-webgpu/shader-abi';
2
+ export { createShaderAddon } from './addon.js';
3
+ export { ShaderAddonError } from './types.js';
package/dist/pass.d.ts ADDED
@@ -0,0 +1,38 @@
1
+ import { type CompiledShader } from './types.js';
2
+ type ShaderPassErrorHandler = (cause: unknown) => void;
3
+ export interface ShaderPass {
4
+ readonly backend: 'webgpu' | 'webgl2';
5
+ resize(size: ShaderOutputSize): void;
6
+ capture(source: HTMLCanvasElement): void;
7
+ ready(): boolean;
8
+ draw(uniforms: ArrayBuffer): boolean;
9
+ setShader(shader: CompiledShader, current: () => boolean): Promise<void>;
10
+ dispose(): void;
11
+ }
12
+ export interface ShaderOutputSize {
13
+ readonly height: number;
14
+ readonly width: number;
15
+ }
16
+ export declare class WebGpuShaderPass implements ShaderPass {
17
+ #private;
18
+ readonly backend = "webgpu";
19
+ constructor(device: GPUDevice, canvas: HTMLCanvasElement, onError: ShaderPassErrorHandler);
20
+ setShader(shader: CompiledShader, current: () => boolean): Promise<void>;
21
+ resize(size: ShaderOutputSize): void;
22
+ capture(source: HTMLCanvasElement): void;
23
+ ready(): boolean;
24
+ draw(uniforms: ArrayBuffer): boolean;
25
+ dispose(): void;
26
+ }
27
+ export declare class WebGlShaderPass implements ShaderPass {
28
+ #private;
29
+ readonly backend = "webgl2";
30
+ constructor(canvas: HTMLCanvasElement);
31
+ setShader(shader: CompiledShader, current: () => boolean): Promise<void>;
32
+ resize(size: ShaderOutputSize): void;
33
+ capture(source: HTMLCanvasElement): void;
34
+ draw(uniforms: ArrayBuffer): boolean;
35
+ ready(): boolean;
36
+ dispose(): void;
37
+ }
38
+ export {};
package/dist/pass.js ADDED
@@ -0,0 +1,367 @@
1
+ import { FULLSCREEN_VERTEX_GLSL, FULLSCREEN_VERTEX_WGSL, SHADER_UNIFORM_BYTE_LENGTH, } from '@ghostty-webgpu/shader-abi';
2
+ import { ShaderAddonError } from './types.js';
3
+ function requireResource(value, name) {
4
+ if (value === null)
5
+ throw new ShaderAddonError('gpu', `Could not create ${name}`);
6
+ return value;
7
+ }
8
+ function shaderLayout(device) {
9
+ return device.createBindGroupLayout({
10
+ entries: [
11
+ {
12
+ binding: 0,
13
+ visibility: GPUShaderStage.FRAGMENT,
14
+ buffer: { type: 'uniform', minBindingSize: SHADER_UNIFORM_BYTE_LENGTH },
15
+ },
16
+ { binding: 1, visibility: GPUShaderStage.FRAGMENT, texture: {} },
17
+ { binding: 2, visibility: GPUShaderStage.FRAGMENT, sampler: {} },
18
+ ],
19
+ });
20
+ }
21
+ export class WebGpuShaderPass {
22
+ backend = 'webgpu';
23
+ #canvas;
24
+ #context;
25
+ #device;
26
+ #format;
27
+ #vertex;
28
+ #layout;
29
+ #uniforms;
30
+ #sampler;
31
+ #onError;
32
+ #shaderPipeline;
33
+ #textures;
34
+ #effectReady = true;
35
+ #disposed = false;
36
+ constructor(device, canvas, onError) {
37
+ this.#device = device;
38
+ this.#canvas = canvas;
39
+ this.#onError = onError;
40
+ this.#context = requireResource(canvas.getContext('webgpu'), 'WebGPU output context');
41
+ this.#format = navigator.gpu.getPreferredCanvasFormat();
42
+ this.#context.configure({ device, format: this.#format, alphaMode: 'opaque' });
43
+ this.#layout = shaderLayout(device);
44
+ this.#vertex = device.createShaderModule({ code: FULLSCREEN_VERTEX_WGSL });
45
+ this.#uniforms = device.createBuffer({
46
+ size: SHADER_UNIFORM_BYTE_LENGTH,
47
+ usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.UNIFORM,
48
+ });
49
+ this.#sampler = device.createSampler({ magFilter: 'linear', minFilter: 'linear' });
50
+ }
51
+ async setShader(shader, current) {
52
+ if (this.#disposed)
53
+ return;
54
+ const device = this.#device;
55
+ device.pushErrorScope('validation');
56
+ let pipeline;
57
+ let failure;
58
+ try {
59
+ const module = device.createShaderModule({ code: shader.wgsl ?? '' });
60
+ const info = await module.getCompilationInfo();
61
+ const messages = info.messages.filter((message) => message.type === 'error');
62
+ if (messages.length > 0) {
63
+ throw new ShaderAddonError('gpu', messages.map((message) => message.message).join('\n'));
64
+ }
65
+ if (!this.#disposed)
66
+ pipeline = await device.createRenderPipelineAsync({
67
+ layout: device.createPipelineLayout({ bindGroupLayouts: [this.#layout] }),
68
+ vertex: { module: this.#vertex, entryPoint: 'main' },
69
+ fragment: {
70
+ module,
71
+ entryPoint: shader.entryPoint ?? 'main',
72
+ targets: [{ format: this.#format }],
73
+ },
74
+ primitive: { topology: 'triangle-list' },
75
+ });
76
+ }
77
+ catch (cause) {
78
+ failure = cause;
79
+ }
80
+ const validation = await device.popErrorScope();
81
+ if (this.#disposed)
82
+ return;
83
+ if (failure !== undefined)
84
+ throw failure;
85
+ if (validation)
86
+ throw new ShaderAddonError('gpu', validation.message);
87
+ if (current())
88
+ this.#shaderPipeline = pipeline;
89
+ }
90
+ resize(size) {
91
+ if (this.#disposed)
92
+ return;
93
+ if (this.#canvas.width === size.width && this.#canvas.height === size.height)
94
+ return;
95
+ this.#canvas.width = size.width;
96
+ this.#canvas.height = size.height;
97
+ }
98
+ capture(source) {
99
+ if (this.#disposed ||
100
+ source.width === 0 ||
101
+ source.height === 0 ||
102
+ this.#canvas.width === 0 ||
103
+ this.#canvas.height === 0)
104
+ return;
105
+ const textures = this.#texturesFor(source.width, source.height);
106
+ this.#device.queue.copyExternalImageToTexture({ source, flipY: true }, { texture: textures.raw }, [source.width, source.height]);
107
+ }
108
+ ready() {
109
+ return !this.#disposed && this.#effectReady;
110
+ }
111
+ draw(uniforms) {
112
+ if (this.#disposed || !this.#textures || !this.#effectReady)
113
+ return false;
114
+ const pipeline = this.#shaderPipeline;
115
+ if (!pipeline)
116
+ return false;
117
+ this.#device.queue.writeBuffer(this.#uniforms, 0, uniforms);
118
+ const encoder = this.#device.createCommandEncoder();
119
+ this.#render(encoder, this.#context.getCurrentTexture().createView(), pipeline, this.#textures.shader);
120
+ this.#device.queue.submit([encoder.finish()]);
121
+ this.#trackEffectCompletion();
122
+ return true;
123
+ }
124
+ #trackEffectCompletion() {
125
+ this.#effectReady = false;
126
+ const completion = this.#device.queue.onSubmittedWorkDone();
127
+ void completion.then(this.#effectCompleted, this.#effectFailed);
128
+ }
129
+ #effectCompleted = () => {
130
+ if (this.#disposed)
131
+ return;
132
+ this.#effectReady = true;
133
+ };
134
+ #effectFailed = (cause) => {
135
+ if (this.#disposed)
136
+ return;
137
+ this.#onError(cause);
138
+ };
139
+ dispose() {
140
+ if (this.#disposed)
141
+ return;
142
+ this.#disposed = true;
143
+ this.#textures?.raw.destroy();
144
+ this.#uniforms.destroy();
145
+ this.#context.unconfigure();
146
+ this.#device.destroy();
147
+ }
148
+ #texturesFor(width, height) {
149
+ if (this.#textures?.width === width && this.#textures.height === height)
150
+ return this.#textures;
151
+ this.#textures?.raw.destroy();
152
+ const raw = this.#device.createTexture({
153
+ size: [width, height],
154
+ format: 'rgba8unorm',
155
+ usage: GPUTextureUsage.COPY_DST |
156
+ GPUTextureUsage.TEXTURE_BINDING |
157
+ GPUTextureUsage.RENDER_ATTACHMENT,
158
+ });
159
+ this.#textures = {
160
+ raw,
161
+ width,
162
+ height,
163
+ shader: this.#device.createBindGroup({
164
+ layout: this.#layout,
165
+ entries: [
166
+ { binding: 0, resource: { buffer: this.#uniforms } },
167
+ { binding: 1, resource: raw.createView() },
168
+ { binding: 2, resource: this.#sampler },
169
+ ],
170
+ }),
171
+ };
172
+ return this.#textures;
173
+ }
174
+ #render(encoder, view, pipeline, bindings) {
175
+ const pass = encoder.beginRenderPass({
176
+ colorAttachments: [{ view, loadOp: 'clear', storeOp: 'store', clearValue: [0, 0, 0, 1] }],
177
+ });
178
+ pass.setPipeline(pipeline);
179
+ pass.setBindGroup(0, bindings);
180
+ pass.draw(3);
181
+ pass.end();
182
+ }
183
+ }
184
+ function compileGlShader(gl, type, source) {
185
+ const shader = requireResource(gl.createShader(type), 'WebGL shader');
186
+ gl.shaderSource(shader, source);
187
+ gl.compileShader(shader);
188
+ if (gl.getShaderParameter(shader, gl.COMPILE_STATUS))
189
+ return shader;
190
+ const message = gl.getShaderInfoLog(shader);
191
+ gl.deleteShader(shader);
192
+ throw new ShaderAddonError('gpu', `WebGL shader compilation failed: ${message}`);
193
+ }
194
+ export class WebGlShaderPass {
195
+ backend = 'webgl2';
196
+ #canvas;
197
+ #gl;
198
+ #vertex;
199
+ #texture;
200
+ #uniforms;
201
+ #vao;
202
+ #shader;
203
+ #hasSource = false;
204
+ #effectFence;
205
+ #disposed = false;
206
+ constructor(canvas) {
207
+ this.#canvas = canvas;
208
+ this.#gl = requireResource(canvas.getContext('webgl2', {
209
+ alpha: false,
210
+ antialias: false,
211
+ premultipliedAlpha: false,
212
+ preserveDrawingBuffer: true,
213
+ }), 'WebGL2 output context');
214
+ const gl = this.#gl;
215
+ this.#vertex = compileGlShader(gl, gl.VERTEX_SHADER, FULLSCREEN_VERTEX_GLSL);
216
+ this.#texture = requireResource(gl.createTexture(), 'WebGL input texture');
217
+ this.#uniforms = requireResource(gl.createBuffer(), 'WebGL uniform buffer');
218
+ this.#vao = requireResource(gl.createVertexArray(), 'WebGL vertex array');
219
+ gl.bindTexture(gl.TEXTURE_2D, this.#texture);
220
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
221
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
222
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
223
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
224
+ gl.disable(gl.DITHER);
225
+ gl.disable(gl.BLEND);
226
+ gl.bindBuffer(gl.UNIFORM_BUFFER, this.#uniforms);
227
+ gl.bufferData(gl.UNIFORM_BUFFER, SHADER_UNIFORM_BYTE_LENGTH, gl.DYNAMIC_DRAW);
228
+ gl.bindBufferBase(gl.UNIFORM_BUFFER, 0, this.#uniforms);
229
+ gl.bindBuffer(gl.UNIFORM_BUFFER, null);
230
+ }
231
+ async setShader(shader, current) {
232
+ if (this.#disposed)
233
+ return;
234
+ const program = this.#program(shader.glsl ?? '');
235
+ try {
236
+ this.#configureSampler(program, shader.webgl?.channel0 ?? (shader.webgl ? null : 'iChannel0'));
237
+ const block = shader.webgl?.uniformBlock ?? (shader.webgl ? null : 'GhosttyUniforms');
238
+ if (block)
239
+ this.#configureUniformBlock(program, block);
240
+ if (!current())
241
+ return this.#gl.deleteProgram(program);
242
+ this.#gl.deleteProgram(this.#shader?.program ?? null);
243
+ this.#shader = { program, hasUniforms: block !== null };
244
+ }
245
+ catch (cause) {
246
+ this.#gl.deleteProgram(program);
247
+ throw cause;
248
+ }
249
+ }
250
+ resize(size) {
251
+ if (this.#disposed)
252
+ return;
253
+ if (this.#canvas.width === size.width && this.#canvas.height === size.height)
254
+ return;
255
+ this.#canvas.width = size.width;
256
+ this.#canvas.height = size.height;
257
+ }
258
+ capture(source) {
259
+ if (this.#disposed ||
260
+ source.width === 0 ||
261
+ source.height === 0 ||
262
+ this.#canvas.width === 0 ||
263
+ this.#canvas.height === 0)
264
+ return;
265
+ const gl = this.#gl;
266
+ gl.activeTexture(gl.TEXTURE0);
267
+ gl.bindTexture(gl.TEXTURE_2D, this.#texture);
268
+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
269
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source);
270
+ this.#hasSource = true;
271
+ }
272
+ draw(uniforms) {
273
+ if (this.#disposed || !this.#hasSource)
274
+ return false;
275
+ const gl = this.#gl;
276
+ const shader = this.#shader;
277
+ if (!shader)
278
+ return false;
279
+ if (!this.#effectReady())
280
+ return false;
281
+ const program = shader.program;
282
+ gl.useProgram(program);
283
+ gl.bindVertexArray(this.#vao);
284
+ gl.activeTexture(gl.TEXTURE0);
285
+ gl.bindTexture(gl.TEXTURE_2D, this.#texture);
286
+ if (shader?.hasUniforms)
287
+ this.#bindUniforms(uniforms);
288
+ gl.viewport(0, 0, this.#canvas.width, this.#canvas.height);
289
+ gl.drawArrays(gl.TRIANGLES, 0, 3);
290
+ this.#effectFence = requireResource(gl.fenceSync(gl.SYNC_GPU_COMMANDS_COMPLETE, 0), 'WebGL effect fence');
291
+ gl.flush();
292
+ return true;
293
+ }
294
+ ready() {
295
+ if (this.#disposed)
296
+ return false;
297
+ return this.#effectReady();
298
+ }
299
+ #effectReady() {
300
+ const fence = this.#effectFence;
301
+ if (!fence)
302
+ return true;
303
+ const status = this.#gl.clientWaitSync(fence, 0, 0);
304
+ if (status === this.#gl.WAIT_FAILED)
305
+ throw new ShaderAddonError('gpu', 'WebGL2 effect fence wait failed');
306
+ if (status === this.#gl.TIMEOUT_EXPIRED)
307
+ return false;
308
+ if (status !== this.#gl.ALREADY_SIGNALED && status !== this.#gl.CONDITION_SATISFIED)
309
+ throw new ShaderAddonError('gpu', `Unexpected WebGL2 effect fence status: ${status}`);
310
+ this.#gl.deleteSync(fence);
311
+ this.#effectFence = undefined;
312
+ return true;
313
+ }
314
+ dispose() {
315
+ if (this.#disposed)
316
+ return;
317
+ this.#disposed = true;
318
+ const gl = this.#gl;
319
+ if (this.#effectFence) {
320
+ gl.deleteSync(this.#effectFence);
321
+ this.#effectFence = undefined;
322
+ }
323
+ gl.deleteProgram(this.#shader?.program ?? null);
324
+ gl.deleteShader(this.#vertex);
325
+ gl.deleteTexture(this.#texture);
326
+ gl.deleteBuffer(this.#uniforms);
327
+ gl.deleteVertexArray(this.#vao);
328
+ gl.getExtension('WEBGL_lose_context')?.loseContext();
329
+ }
330
+ #bindUniforms(uniforms) {
331
+ const gl = this.#gl;
332
+ gl.bindBuffer(gl.UNIFORM_BUFFER, this.#uniforms);
333
+ gl.bufferSubData(gl.UNIFORM_BUFFER, 0, uniforms);
334
+ }
335
+ #configureSampler(program, name) {
336
+ if (name === null)
337
+ return;
338
+ const location = this.#gl.getUniformLocation(program, name);
339
+ this.#gl.useProgram(program);
340
+ this.#gl.uniform1i(location, 0);
341
+ }
342
+ #configureUniformBlock(program, name) {
343
+ const gl = this.#gl;
344
+ const block = gl.getUniformBlockIndex(program, name);
345
+ if (block === gl.INVALID_INDEX)
346
+ throw new ShaderAddonError('gpu', `WebGL uniform block ${name} was not linked`);
347
+ gl.uniformBlockBinding(program, block, 0);
348
+ }
349
+ #program(source) {
350
+ const gl = this.#gl;
351
+ const fragment = compileGlShader(gl, gl.FRAGMENT_SHADER, source);
352
+ const program = gl.createProgram();
353
+ if (!program) {
354
+ gl.deleteShader(fragment);
355
+ throw new ShaderAddonError('gpu', 'Could not create WebGL program');
356
+ }
357
+ gl.attachShader(program, this.#vertex);
358
+ gl.attachShader(program, fragment);
359
+ gl.linkProgram(program);
360
+ gl.deleteShader(fragment);
361
+ if (gl.getProgramParameter(program, gl.LINK_STATUS))
362
+ return program;
363
+ const message = gl.getProgramInfoLog(program);
364
+ gl.deleteProgram(program);
365
+ throw new ShaderAddonError('gpu', `WebGL program linking failed: ${message}`);
366
+ }
367
+ }
@@ -0,0 +1,21 @@
1
+ import type { ShaderUniformValues, ShaderVector4 } from '@ghostty-webgpu/shader-abi';
2
+ import type { TerminalApi } from 'ghostty-webgpu';
3
+ import type { ShaderFrame } from './frame-schedule.js';
4
+ export declare class UniformState {
5
+ current: ShaderVector4;
6
+ previous: ShaderVector4;
7
+ currentColor: ShaderVector4;
8
+ previousColor: ShaderVector4;
9
+ style: number;
10
+ previousStyle: number;
11
+ changedAt: number;
12
+ focusAt: number;
13
+ mouse: ShaderVector4;
14
+ focusChanged(time: number): void;
15
+ pointer(type: string, x: number, y: number): void;
16
+ update(cursor: ShaderVector4, color: ShaderVector4, style: number, time: number): void;
17
+ }
18
+ export declare function frameUniforms(terminal: TerminalApi, state: UniformState, frame: ShaderFrame, size: {
19
+ width: number;
20
+ height: number;
21
+ }): Partial<ShaderUniformValues>;
@@ -0,0 +1,106 @@
1
+ function rgb(color) {
2
+ return [color.r / 255, color.g / 255, color.b / 255];
3
+ }
4
+ function rgba(color) {
5
+ return [color.r / 255, color.g / 255, color.b / 255, 1];
6
+ }
7
+ export class UniformState {
8
+ current = [0, 0, 0, 0];
9
+ previous = [0, 0, 0, 0];
10
+ currentColor = [0, 0, 0, 0];
11
+ previousColor = [0, 0, 0, 0];
12
+ style = 0;
13
+ previousStyle = 0;
14
+ changedAt = 0;
15
+ focusAt = 0;
16
+ mouse = [0, 0, 0, 0];
17
+ focusChanged(time) {
18
+ this.focusAt = time;
19
+ }
20
+ pointer(type, x, y) {
21
+ if (!Number.isFinite(x) || !Number.isFinite(y))
22
+ return;
23
+ const previous = this.mouse;
24
+ if (type === 'pointerdown') {
25
+ this.mouse = [x, y, x, y];
26
+ return;
27
+ }
28
+ if (type === 'pointerup') {
29
+ this.mouse = [x, y, -Math.abs(previous[2]), -Math.abs(previous[3])];
30
+ return;
31
+ }
32
+ this.mouse = [x, y, previous[2], previous[3]];
33
+ }
34
+ update(cursor, color, style, time) {
35
+ if (cursor.every((value, index) => value === this.current[index]) &&
36
+ color.every((value, index) => value === this.currentColor[index]) &&
37
+ style === this.style)
38
+ return;
39
+ this.previous = this.current;
40
+ this.previousColor = this.currentColor;
41
+ this.previousStyle = this.style;
42
+ this.current = cursor;
43
+ this.currentColor = color;
44
+ this.style = style;
45
+ this.changedAt = time;
46
+ }
47
+ }
48
+ function cursorStyle(style) {
49
+ if (style === 'bar')
50
+ return 2;
51
+ if (style === 'underline')
52
+ return 3;
53
+ return 0;
54
+ }
55
+ export function frameUniforms(terminal, state, frame, size) {
56
+ const submitted = terminal.submittedFrame;
57
+ const theme = submitted?.theme ?? terminal.appearance.theme;
58
+ const cursor = submitted?.paintedCursor ?? submitted?.cursor.viewport;
59
+ const grid = submitted?.grid ?? terminal.appearance.grid;
60
+ const width = size.width / grid.columns;
61
+ const height = size.height / grid.rows;
62
+ const position = cursor
63
+ ? [cursor.x * width, size.height - cursor.y * height, width, height]
64
+ : [0, 0, 0, 0];
65
+ state.update(position, rgba(theme.cursor), cursorStyle(submitted?.paintedCursor?.style ??
66
+ submitted?.cursor.style ??
67
+ terminal.appearance.cursor.style), frame.time);
68
+ const date = new Date();
69
+ const seconds = date.getHours() * 3600 +
70
+ date.getMinutes() * 60 +
71
+ date.getSeconds() +
72
+ date.getMilliseconds() / 1000;
73
+ return {
74
+ iResolution: [size.width, size.height, 1],
75
+ iTime: frame.time,
76
+ iTimeDelta: frame.delta,
77
+ iFrameRate: frame.delta > 0 ? 1 / frame.delta : 0,
78
+ iFrame: frame.frame,
79
+ iChannelTime: [frame.time, 0, 0, 0],
80
+ iChannelResolution: [
81
+ [size.width, size.height, 1],
82
+ [0, 0, 0],
83
+ [0, 0, 0],
84
+ [0, 0, 0],
85
+ ],
86
+ iMouse: state.mouse,
87
+ iDate: [date.getFullYear(), date.getMonth(), date.getDate(), seconds],
88
+ iCurrentCursor: state.current,
89
+ iPreviousCursor: state.previous,
90
+ iCurrentCursorColor: state.currentColor,
91
+ iPreviousCursorColor: state.previousColor,
92
+ iCurrentCursorStyle: state.style,
93
+ iPreviousCursorStyle: state.previousStyle,
94
+ iCursorVisible: submitted?.paintedCursor?.visible ? 1 : 0,
95
+ iTimeCursorChange: state.changedAt,
96
+ iFocus: terminal.element?.contains(terminal.element.ownerDocument.activeElement) ? 1 : 0,
97
+ iTimeFocus: state.focusAt,
98
+ iPalette: terminal.appearance.theme.palette.map(rgb),
99
+ iBackgroundColor: rgb(theme.background),
100
+ iForegroundColor: rgb(theme.foreground),
101
+ iCursorColor: rgb(theme.cursor),
102
+ iCursorText: rgb(theme.cursorText ?? theme.background),
103
+ iSelectionForegroundColor: rgb(theme.selectionForeground),
104
+ iSelectionBackgroundColor: rgb(theme.selectionBackground),
105
+ };
106
+ }
@@ -0,0 +1,33 @@
1
+ import { type CompiledGhosttyShader } from '@ghostty-webgpu/shader-abi';
2
+ import type { Extension } from 'ghostty-webgpu';
3
+ type ShaderBindings = Partial<Pick<CompiledGhosttyShader, 'schemaVersion' | 'uniformLayout' | 'webgl'>> & {
4
+ readonly entryPoint?: string;
5
+ };
6
+ /** Accepts full compiler output and artifacts containing only one backend. */
7
+ export type CompiledShader = ShaderBindings & ({
8
+ readonly wgsl: string;
9
+ readonly glsl?: string;
10
+ } | {
11
+ readonly wgsl?: string;
12
+ readonly glsl: string;
13
+ });
14
+ export interface ShaderAddonOptions {
15
+ readonly backend?: 'webgpu' | 'webgl2';
16
+ readonly paused?: boolean;
17
+ readonly onError?: (error: ShaderAddonError) => void;
18
+ }
19
+ export interface ShaderAddonApi {
20
+ /** Resolves after installation, including when installed before terminal.open(). */
21
+ readonly ready: Promise<void>;
22
+ /** False means a newer replacement or disposal superseded this request. */
23
+ setShader(shader: CompiledShader): Promise<boolean>;
24
+ /** Freezes effect time; terminal updates still draw. */
25
+ setPaused(paused: boolean): void;
26
+ }
27
+ export type ShaderAddon = Extension<ShaderAddonApi>;
28
+ export declare class ShaderAddonError extends Error {
29
+ readonly code: 'artifact' | 'backend' | 'capture' | 'disposed' | 'gpu' | 'worker';
30
+ constructor(code: 'artifact' | 'backend' | 'capture' | 'disposed' | 'gpu' | 'worker', message: string, options?: ErrorOptions);
31
+ }
32
+ export declare function validateShader(shader: CompiledShader): void;
33
+ export {};
package/dist/types.js ADDED
@@ -0,0 +1,22 @@
1
+ import { SHADER_SCHEMA_VERSION, SHADER_UNIFORM_LAYOUT, } from '@ghostty-webgpu/shader-abi';
2
+ export class ShaderAddonError extends Error {
3
+ code;
4
+ constructor(code, message, options) {
5
+ super(message, options);
6
+ this.code = code;
7
+ this.name = 'ShaderAddonError';
8
+ }
9
+ }
10
+ export function validateShader(shader) {
11
+ if (!shader || typeof shader !== 'object')
12
+ throw new ShaderAddonError('artifact', 'Pass a compiled WGSL or GLSL shader object.');
13
+ if (shader.schemaVersion !== undefined && shader.schemaVersion !== SHADER_SCHEMA_VERSION)
14
+ throw new ShaderAddonError('artifact', `Use shader artifact schema version ${SHADER_SCHEMA_VERSION}.`);
15
+ if (shader.uniformLayout !== undefined && shader.uniformLayout !== SHADER_UNIFORM_LAYOUT)
16
+ throw new ShaderAddonError('artifact', `Use the ${SHADER_UNIFORM_LAYOUT} uniform layout.`);
17
+ if (typeof shader.wgsl === 'string' && shader.wgsl.trim())
18
+ return;
19
+ if (typeof shader.glsl === 'string' && shader.glsl.trim())
20
+ return;
21
+ throw new ShaderAddonError('artifact', 'The compiled shader must contain WGSL or GLSL output.');
22
+ }
@@ -0,0 +1,61 @@
1
+ # Shader bindings
2
+
3
+ The addon accepts compiled fragment programs through `CompiledShader`. It supplies a fullscreen triangle with no vertex buffers. Fragment entry defaults to `main`; WGSL can override it with `entryPoint`. The fragment input is `@location(0) vec2<f32>` in WGSL or `in vec2 _vs2fs_location0` in GLSL. UV `(0, 0)` is the bottom-left of the terminal content. Fragment output is a color at location zero. Output is opaque.
4
+
5
+ ## Source texture
6
+
7
+ WebGPU group zero bindings are:
8
+
9
+ | Binding | Resource |
10
+ | ------- | ---------------------------------------- |
11
+ | 0 | Uniform buffer, 4496 bytes |
12
+ | 1 | Terminal `texture_2d<f32>`, RGBA8 |
13
+ | 2 | Filtering sampler, linear, clamp-to-edge |
14
+
15
+ Texture row zero is the logical bottom row on both backends. Sampling at UV `(0, 0)` reads the bottom-left terminal pixel. Direct WGSL position builtins still use WebGPU's native top-origin coordinates. The vertex UV is the shared bottom-origin coordinate.
16
+
17
+ A hand-authored compiled WGSL pass can use only the resources it needs:
18
+
19
+ ```ts
20
+ const compiled = {
21
+ wgsl: `
22
+ @group(0) @binding(1) var terminalTexture: texture_2d<f32>;
23
+ @group(0) @binding(2) var terminalSampler: sampler;
24
+ @fragment fn main(@location(0) uv: vec2<f32>) -> @location(0) vec4<f32> {
25
+ return textureSample(terminalTexture, terminalSampler, uv);
26
+ }`,
27
+ }
28
+ ```
29
+
30
+ For GLSL ES 3.00, `webgl.uniformBlock` names the std140 block and `webgl.channel0` names its `sampler2D`. They default to `GhosttyUniforms` and `iChannel0`. Use `null` for a resource your program omits, for example `webgl: { uniformBlock: null, channel0: null }` for a constant-color fragment. Full compiler output carries its generated names. The sampler uses texture unit zero, and the uniform block uses buffer binding zero.
31
+
32
+ ## Uniform ABI
33
+
34
+ `SHADER_UNIFORM_FIELDS` exposes names, types, byte offsets, counts, and strides. `SHADER_UNIFORM_BYTE_LENGTH` is 4496. `packShaderUniforms(values, output?)` packs this little-endian std140 layout. Arrays use 16-byte strides, including scalar arrays. WGSL represents `iChannelTime` as four `vec4<f32>` values with each time in `.x`. Unused bytes and omitted values are zero, except `iResolution.z`, which defaults to one.
35
+
36
+ | Field | Type/count | Byte offset |
37
+ | --------------------------------------------------------- | -------------------- | ------------- |
38
+ | iResolution | vec3 | 0 |
39
+ | iTime, iTimeDelta, iFrameRate | float each | 12, 16, 20 |
40
+ | iFrame | int | 24 |
41
+ | iChannelTime | float[4], stride 16 | 32 |
42
+ | iChannelResolution | vec3[4], stride 16 | 96 |
43
+ | iMouse, iDate | vec4 each | 160, 176 |
44
+ | iSampleRate | float | 192 |
45
+ | iCurrentCursor, iPreviousCursor | vec4 each | 208, 224 |
46
+ | iCurrentCursorColor, iPreviousCursorColor | vec4 each | 240, 256 |
47
+ | iCurrentCursorStyle, iPreviousCursorStyle, iCursorVisible | int each | 272, 276, 280 |
48
+ | iTimeCursorChange, iTimeFocus | float each | 284, 288 |
49
+ | iFocus | int | 292 |
50
+ | iPalette | vec3[256], stride 16 | 304 |
51
+ | iBackgroundColor, iForegroundColor | vec3 each | 4400, 4416 |
52
+ | iCursorColor, iCursorText | vec3 each | 4432, 4448 |
53
+ | iSelectionForegroundColor, iSelectionBackgroundColor | vec3 each | 4464, 4480 |
54
+
55
+ Resolution uses backing pixels. Time is active elapsed seconds; delta is time since the last submitted effect frame. `iFrame` starts at zero and advances only on submission. Channel zero has the terminal dimensions/time; other channels and sample rate are zero. There are no additional channel textures.
56
+
57
+ Mouse `.xy` is the current bottom-origin backing-pixel position. `.zw` holds the press origin, positive while pressed and negative after release. Date is local year, zero-based month, day of month, and seconds since midnight.
58
+
59
+ Cursor rectangles are `(left, top, width, height)` in bottom-origin pixels. The previous rectangle/color/style changes when the current one changes. Styles are block `0`, bar `2`, underline `3`. Visibility reflects the last submitted terminal cursor paint. Focus is `1` when the terminal contains the active element. Cursor/focus timestamps use effect time. Theme colors and the 256-entry palette use normalized RGB; cursor colors include alpha one.
60
+
61
+ The uniform packing and bounded-frame scheduling are adapted from the MIT-licensed `ghostty-web-shaderc` runtime and showcase at revision `331a7ee`.
package/docs/usage.md ADDED
@@ -0,0 +1,46 @@
1
+ # Usage and lifecycle
2
+
3
+ Install the addon separately from `ghostty-webgpu`. Terminal core has no dependency on this package.
4
+
5
+ ```ts
6
+ import { createShaderAddon } from '@ghostty-webgpu/shaders'
7
+
8
+ const handle = terminal.use(
9
+ createShaderAddon(compiled, {
10
+ paused: false,
11
+ onError: (error) => console.error(error.code, error.message),
12
+ }),
13
+ )
14
+ await handle.api.ready
15
+ await handle.api.setShader(nextCompiled)
16
+ handle.api.setPaused(true)
17
+ handle.dispose()
18
+ ```
19
+
20
+ `compiled` is an object containing nonempty `wgsl`, `glsl`, or both. These are already compiled fragment programs. A full `CompiledGhosttyShader` object from `ghostty-web-shaderc` is structurally accepted. Partial output may omit `schemaVersion`, `uniformLayout`, `entryPoint`, and `webgl`. If supplied, the schema and layout must be `1` and `ghostty-v1`. See [bindings](bindings.md) for custom authoring.
21
+
22
+ Compile in your build or with a compiler you load yourself. This package neither resolves nor loads a compiler, parser, WASM, or Three.js. Its packed entry can be imported without a terminal runtime installed. The terminal peer supplies TypeScript types and the host extension lifecycle.
23
+
24
+ ## Backend selection
25
+
26
+ With both languages, the addon prefers WebGL2 when the terminal selected WebGL2, and WebGPU otherwise. If a WebGPU adapter/device is unavailable and GLSL is present, it uses WebGL2. WGSL-only output selects WebGPU; GLSL-only output selects WebGL2. Canvas2D source terminals work with either output backend.
27
+
28
+ `backend: 'webgpu' | 'webgl2'` makes selection strict. Missing language output or unavailable browser capability rejects `ready` with a `ShaderAddonError`. Backend selection happens once per installation. Replacements must supply that backend's language.
29
+
30
+ ## Installation and replacement
31
+
32
+ Installation works before or after `terminal.open()`. `ready` waits for opening, output device initialization, and a valid shader. It rejects if initialization fails or the addon is disposed first.
33
+
34
+ `setShader` resolves `true` when its program becomes current. A superseded request or disposal resolves `false`. Requests are serialized, and only the newest can become current. Invalid replacements reject while keeping the last valid program and pixels. An invalid initial program rejects `ready`, removes the addon canvas, and calls `onError`.
35
+
36
+ Main-thread WebGPU, WebGL2, and both Canvas2D modes are supported. A custom factory must forward the internal options to a built-in renderer. Independent renderers using only public options reject with code `backend`. DOM renderers reject with code `backend`; runtime fallback to DOM removes the overlay and reports the same error, including while paused. Worker terminals reject with code `worker`: their asynchronous snapshots arrive after the non-preserved source drawing buffer can clear. Use a main-thread terminal for this addon.
37
+
38
+ ## Capture and ownership
39
+
40
+ The addon inserts a `pointer-events: none`, `aria-hidden` overlay into `terminal.element`, before the terminal's input/composition elements. It follows the source content box, padding, backing dimensions, and DPR. Source canvas, focus, keyboard input, selection, and accessibility nodes stay owned by the terminal. Renderer recovery can replace the source canvas; the next submitted frame retargets capture and geometry.
41
+
42
+ A private synchronous image notification copies each genuine source draw into an owned transparent Canvas2D staging canvas. The replacing copy removes erased pixels, including transparent backgrounds and partial glyph alpha. Accepted publications that do not draw retain the previous snapshot, so WebGL2 buffers cleared after presentation do not blank the effect. The effect output remains opaque; staging is not flattened into the theme background. Installation calls the public `clearTextureAtlas()` once to guarantee a fresh draw even for an unchanged, already-presented terminal. The output then uploads that snapshot. This copy has a cost proportional to terminal pixel area; this package makes no hardware performance claim.
43
+
44
+ At most one output draw is submitted per animation frame and one unfinished effect frame is retained. WebGPU queue completion and WebGL2 fences gate uploads/draws. Busy output retains the latest snapshot and elapsed time. Pause and document visibility freeze effect time. Terminal changes can still redraw while paused; hidden documents resume with current terminal state.
45
+
46
+ `handle.dispose()` removes only the overlay and owned resources/listeners. It leaves the terminal usable. Terminal disposal also disposes the addon. Device/context loss rejects pending installation, removes the overlay, and calls `onError`; reinstall to create fresh output resources. Original terminal pixels remain underneath on disposal or failure.
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "@ghostty-webgpu/shaders",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.4",
4
+ "description": "Optional compiled shader effects for ghostty-webgpu terminals",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/ShaulLavo/ghostty-webgpu.git",
9
+ "directory": "packages/shaders"
10
+ },
11
+ "files": [
12
+ "dist",
13
+ "docs",
14
+ "README.md",
15
+ "LICENSE"
16
+ ],
17
+ "type": "module",
18
+ "sideEffects": false,
19
+ "exports": {
20
+ ".": {
21
+ "types": "./dist/index.d.ts",
22
+ "import": "./dist/index.js"
23
+ }
24
+ },
25
+ "publishConfig": {
26
+ "access": "public",
27
+ "provenance": true
28
+ },
29
+ "scripts": {
30
+ "build": "node --input-type=module -e \"import { rmSync } from 'node:fs'; rmSync('dist', { force: true, recursive: true })\" && tsc -p tsconfig.build.json",
31
+ "typecheck": "tsc --noEmit",
32
+ "lint": "oxlint src scripts",
33
+ "format": "oxfmt --write .",
34
+ "format:check": "oxfmt --check .",
35
+ "test": "vitest run",
36
+ "test:browser": "bun run --cwd ../.. test:browser packages/shaders/src/tests/",
37
+ "test:package": "node scripts/package-smoke.mjs",
38
+ "verify": "bun run build && bun run typecheck && bun run lint && bun run format:check && bun run test && bun run test:package"
39
+ },
40
+ "dependencies": {
41
+ "@ghostty-webgpu/shader-abi": "0.0.1"
42
+ },
43
+ "devDependencies": {
44
+ "@webgpu/types": "0.1.74",
45
+ "oxfmt": "0.70.0",
46
+ "oxlint": "1.85.0",
47
+ "typescript": "7.0.2",
48
+ "vitest": "5.0.2"
49
+ },
50
+ "peerDependencies": {
51
+ "ghostty-webgpu": "^0.3.32"
52
+ },
53
+ "engines": {
54
+ "node": ">=20"
55
+ },
56
+ "packageManager": "bun@1.4.4"
57
+ }