@margoengine/shader 0.0.0-stage → 1.0.0

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 (92) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +1919 -2
  4. package/dist/attribute.d.ts +28 -0
  5. package/dist/black-hole.d.ts +246 -0
  6. package/dist/black-hole.js +445 -0
  7. package/dist/clock-BLGNexlt.js +52 -0
  8. package/dist/clock.d.ts +42 -0
  9. package/dist/compute-CXGG9qvI.js +360 -0
  10. package/dist/compute-texture.d.ts +100 -0
  11. package/dist/compute-texture.js +131 -0
  12. package/dist/compute-volume.d.ts +57 -0
  13. package/dist/compute-volume.js +130 -0
  14. package/dist/compute.d.ts +200 -0
  15. package/dist/control-CFjkGPBk.js +201 -0
  16. package/dist/control.d.ts +93 -0
  17. package/dist/deform.d.ts +111 -0
  18. package/dist/deform.js +89 -0
  19. package/dist/display-BrJM_Qkd.js +5 -0
  20. package/dist/editor-model.d.ts +192 -0
  21. package/dist/editor-pass.d.ts +71 -0
  22. package/dist/editor-pass.js +216 -0
  23. package/dist/editor.d.ts +150 -0
  24. package/dist/editor.js +1071 -0
  25. package/dist/effects.d.ts +150 -0
  26. package/dist/effects.js +87 -0
  27. package/dist/errors-CsQwshHA.js +7 -0
  28. package/dist/glsl/emit.d.ts +43 -0
  29. package/dist/glsl/host.d.ts +55 -0
  30. package/dist/glsl/material.d.ts +173 -0
  31. package/dist/glsl/parser.d.ts +76 -0
  32. package/dist/glsl/preprocess.d.ts +9 -0
  33. package/dist/glsl/presets.d.ts +33 -0
  34. package/dist/glsl/program.d.ts +210 -0
  35. package/dist/glsl/scene.d.ts +9 -0
  36. package/dist/glsl-material.d.ts +82 -0
  37. package/dist/glsl-material.js +288 -0
  38. package/dist/glsl-pass.d.ts +93 -0
  39. package/dist/glsl-pass.js +186 -0
  40. package/dist/glsl.d.ts +94 -0
  41. package/dist/glsl.js +170 -0
  42. package/dist/gpu-DQJk2xAv.js +55 -0
  43. package/dist/graph.d.ts +82 -0
  44. package/dist/graph.js +365 -0
  45. package/dist/index.d.ts +8 -0
  46. package/dist/index.js +103 -0
  47. package/dist/lighting-JU9yQPfM.js +77 -0
  48. package/dist/lighting.d.ts +62 -0
  49. package/dist/lighting.js +1 -0
  50. package/dist/material-C6bpqlnE.js +1184 -0
  51. package/dist/material-CZ8V1FeA.js +299 -0
  52. package/dist/material.d.ts +79 -0
  53. package/dist/node-B6yoIC9V.js +590 -0
  54. package/dist/node.d.ts +433 -0
  55. package/dist/noise.d.ts +38 -0
  56. package/dist/noise.js +107 -0
  57. package/dist/own-stack-D1XnXrrz.js +11 -0
  58. package/dist/own-stack.d.ts +12 -0
  59. package/dist/pass.d.ts +109 -0
  60. package/dist/pass.js +239 -0
  61. package/dist/post-DLpZ110L.js +113 -0
  62. package/dist/post.d.ts +69 -0
  63. package/dist/preprocess-CWGWlBWQ.js +1195 -0
  64. package/dist/raw-0AYej3Ak.js +1500 -0
  65. package/dist/raw.d.ts +744 -0
  66. package/dist/raw.js +1 -0
  67. package/dist/readback.d.ts +42 -0
  68. package/dist/readback.js +85 -0
  69. package/dist/scope.d.ts +21 -0
  70. package/dist/serialization.d.ts +11 -0
  71. package/dist/serialization.js +192 -0
  72. package/dist/shadertoy/sound.d.ts +48 -0
  73. package/dist/shadertoy.d.ts +249 -0
  74. package/dist/shadertoy.js +909 -0
  75. package/dist/shared/caster.d.ts +159 -0
  76. package/dist/shared/fog.d.ts +33 -0
  77. package/dist/shared/fractal.d.ts +9 -0
  78. package/dist/shared/msaa.d.ts +30 -0
  79. package/dist/shared/stack.d.ts +22 -0
  80. package/dist/sound-CF_dzP41.js +78 -0
  81. package/dist/storage-format-DWaiSxmq.js +25 -0
  82. package/dist/storage-format.d.ts +7 -0
  83. package/dist/subgroups.d.ts +97 -0
  84. package/dist/subgroups.js +95 -0
  85. package/dist/texture-BawKO_h9.js +62 -0
  86. package/dist/texture-array.d.ts +7 -0
  87. package/dist/texture-array.js +11 -0
  88. package/dist/texture.d.ts +16 -0
  89. package/dist/utils.d.ts +106 -0
  90. package/dist/utils.js +90 -0
  91. package/dist/view-rect-Bm1ac-TK.js +16 -0
  92. package/package.json +149 -4
package/README.md CHANGED
@@ -1,3 +1,1920 @@
1
- # Temporary Holding Version
1
+ # @margoengine/shader
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
+ Typed shader nodes that compile to readable WGSL: node materials, node post effects and node compute passes, with a visual node editor.
4
+
5
+ `ComputePass`, `ScenePass` and `RawShaders` also detach from their actual scene
6
+ on disposal, leaving same-name plugins in other scenes alone. Restoration keeps
7
+ the registration. For example:
8
+
9
+ ```ts
10
+ import {Engine} from 'margoengine/core';
11
+ import {ComputePass, storage} from 'margoengine/shader';
12
+ import {ScenePass} from 'margoengine/shader/pass';
13
+ import {RawShaders} from 'margoengine/shader/raw';
14
+ const engine = await Engine.create(document.querySelector('canvas')!, {backend:'webgpu'});
15
+ const product = engine.createScene('product');
16
+ const values = storage(1, 'u32');
17
+ const compute = new ComputePass(1, i => values.store(i, 1));
18
+ const outputs = new ScenePass({outputs:{color:'rgba16float'}});
19
+ const raw = new RawShaders();
20
+ product.use(compute);
21
+ product.use(outputs);
22
+ product.use(raw);
23
+ compute.dispose();
24
+ outputs.dispose();
25
+ raw.dispose();
26
+ values.dispose();
27
+ engine.dispose();
28
+ ```
29
+
30
+ `NodePass.dispose()` detaches the pass from its owning scene. A same-name pass in
31
+ another scene is preserved; device restoration keeps the registration. For a
32
+ secondary scene, attach the PostStack with `scene.use()`:
33
+
34
+ ```ts
35
+ import {Engine} from 'margoengine/core';
36
+ import {PostStack} from 'margoengine/post/stack';
37
+ import {NodePass, inputColor} from 'margoengine/shader';
38
+ const engine = await Engine.create(document.querySelector('canvas')!, {backend:'webgpu'});
39
+ const product = engine.createScene('product');
40
+ const pass = new NodePass(inputColor());
41
+ const stack = new PostStack([pass]);
42
+ product.use(stack);
43
+ pass.dispose();
44
+ stack.dispose();
45
+ engine.dispose();
46
+ ```
47
+
48
+ Import `margoengine/shader` from the `margoengine` package, or `@margoengine/shader` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
49
+
50
+ Typed shader nodes that compile to readable WGSL. One graph API drives three hosts: `NodeMaterial` (a `@margoengine/materials` Material whose colour, normal, roughness, metalness, emissive, opacity and vertex position come from nodes), `NodePass` (a full-screen effect inside `@margoengine/post`'s PostStack) and `ComputePass` (a compute shader over a storage buffer, dispatched by the frame graph). Two more entries skip the graph: `@margoengine/shader/raw` draws your own WGSL with your own vertex layout, and `@margoengine/shader/effects` has ready-made screen effects. Graphs run on native WebGPU and on the full WebGL2 compatibility layer (`@margoengine/webgl2-compat`), which translates their WGSL to GLSL ES 3.00; `@margoengine/shader/glsl` takes GLSL functions in and shows the GLSL a graph becomes.
51
+
52
+ ```ts
53
+ import {createMesh, loadTexture} from 'margoengine/materials';
54
+ import {sphereGeometry} from 'margoengine/geometry';
55
+ import {NodeMaterial, uniform, texture, mix, color, uv, sin, time, positionLocal, normalLocal} from 'margoengine/shader';
56
+ import {createStage} from 'margoengine';
57
+ const stage = await createStage('#viewport', {backend: 'webgpu'});
58
+ const tint = uniform('#ff8800', {name: 'tint'}); // live: tint.value = '#00ff00' never recompiles
59
+ const wave = sin(time.add(uv().y.mul(10))).mul(0.5).add(0.5);
60
+ const map = await loadTexture('/rock.jpg', {wrapS: 'repeat', wrapT: 'repeat'});
61
+ const material = new NodeMaterial({
62
+ roughness: 0.6, // every Material option still applies
63
+ colorNode: mix(color('#2040ff'), tint, uv().y).mul(texture(map).rgb),
64
+ emissiveNode: tint.mul(wave.mul(0.2)),
65
+ positionNode: positionLocal.add(normalLocal.mul(wave.mul(0.05))), // object-space vertex position
66
+ });
67
+ createMesh(stage.engine, sphereGeometry(1, 64, 32), material);
68
+ ```
69
+
70
+ ```ts
71
+ import {PostStack} from 'margoengine/post';
72
+ import {Tonemap} from 'margoengine/tonemap';
73
+ import {NodePass, inputColor, inputDepth, screenUV, smoothstep, mix, vec3, uniform} from 'margoengine/shader';
74
+ import {createStage} from 'margoengine';
75
+ const stage = await createStage('#viewport', {backend: 'webgpu'});
76
+ const strength = uniform(0.8);
77
+ const vignette = new NodePass(inputColor().rgb.mul(smoothstep(0.8, 0.2, screenUV.sub(0.5).length()).mul(strength)));
78
+ const fog = new NodePass(mix(inputColor().rgb, vec3(0.6, 0.7, 0.8), inputDepth().mul(-40).add(1).saturate()), {kind: 'hdr'});
79
+ PostStack.attach(stage.engine, [fog, new Tonemap(), vignette]); // hdr passes before the display effect, ldr after
80
+ ```
81
+
82
+ One pass needs no stack of yours: `await NodePass.attach(engine, node, options?)` loads `@margoengine/post` and adds
83
+ the pass to the scene's PostStack after the last effect of its kind, or runs it in a new PostStack when the scene has
84
+ none (`PostStack.join`), and returns it. `pass.dispose()` takes it out of that stack, and a stack made for it goes
85
+ with it. The options are the constructor's (`kind`, `name`) plus `signal`, which cancels the attach while the stack
86
+ loads.
87
+
88
+ ```ts
89
+ import {NodePass, inputColor, vec4} from 'margoengine/shader';
90
+ import {createStage} from 'margoengine';
91
+ const stage = await createStage('#viewport', {backend: 'webgpu'});
92
+ const invert = await NodePass.attach(stage.engine, vec4(inputColor().rgb.oneMinus(), 1));
93
+ invert.dispose(); // removes the pass and its PostStack
94
+ ```
95
+
96
+ ```ts
97
+ import {PostStack} from 'margoengine/post/stack';
98
+ import {Tonemap} from 'margoengine/tonemap';
99
+ import {NodePass, inputColor, vec4} from 'margoengine/shader';
100
+ import {createStage} from 'margoengine';
101
+ const stage = await createStage('#viewport', {backend: 'webgpu'});
102
+ const stack = PostStack.attach(stage.engine, [new Tonemap()]);
103
+ const invert = await NodePass.attach(stage.engine, vec4(inputColor().rgb.oneMinus(), 1));
104
+ console.log(stack.effects.length); // 2: the pass joined the scene's stack after Tonemap
105
+ invert.dispose(); // Tonemap keeps drawing
106
+ stack.dispose();
107
+ ```
108
+
109
+ ```ts
110
+ import {ComputePass, NodeMaterial, storage, vec4, deltaTime} from 'margoengine/shader';
111
+ import {createStage} from 'margoengine';
112
+ const stage = await createStage('#viewport', {backend: 'webgpu'});
113
+ const field = storage(new Float32Array(4 * 1024), 'vec4f'); // or storage(1024, 'vec4f') for zeros
114
+ ComputePass.attach(stage.engine, 1024, i => field.store(i, field.element(i).add(vec4(0, deltaTime, 0, 0))));
115
+ new NodeMaterial({colorNode: field.element(3).xyz}); // any node reads it; field.buffer(device) hands it to other passes
116
+ ```
117
+
118
+ Cut-outs and slicing with `discard(condition, value)`, GPU counters and compaction with atomics:
119
+
120
+ ```ts
121
+ import {NodeMaterial, ComputePass, storage, discard, texture, materialColor, positionWorld, uniform, select, uint} from 'margoengine/shader';
122
+ import {loadTexture} from 'margoengine/materials';
123
+ import {createStage} from 'margoengine';
124
+ const n = 1024;
125
+ const stage = await createStage('#viewport', {backend: 'webgpu'});
126
+ const slice = uniform(1.5), leaf = await loadTexture('/leaf.png'), radii = new Float32Array(n).fill(0.2);
127
+ new NodeMaterial({colorNode: discard(texture(leaf).a.lessThan(0.5), texture(leaf))}); // alpha cut-out
128
+ new NodeMaterial({colorNode: discard(positionWorld.y.greaterThan(slice), materialColor)}); // section the part at y = slice
129
+
130
+ const counter = storage(1, 'u32', {atomic: true}), visible = storage(n, 'u32'), radius = storage(radii, 'f32');
131
+ ComputePass.attach(stage.engine, n, i => {
132
+ const keep = radius.element(i).greaterThan(0.1);
133
+ const slot = counter.atomicAdd(0, select(keep, uint(1), uint(0))); // previous value: this item's slot
134
+ return visible.store(select(keep, slot, uint(n - 1)), i); // compacted list; counter.element(0) is the count
135
+ });
136
+ // counter.update() before a frame resets it to its CPU data (zeros).
137
+ ```
138
+
139
+ Statements: variables that change, branches that run one side only, loops that leave early:
140
+
141
+ ```ts
142
+ import {block, If, Loop, Break, Var, NodeMaterial, ComputePass, storage, texture, uv, vec3, uint} from 'margoengine/shader';
143
+ import {loadTexture} from 'margoengine/materials';
144
+ import {createStage} from 'margoengine';
145
+ const n = 1024;
146
+ const stage = await createStage('#viewport', {backend: 'webgpu'});
147
+ const fog = await loadTexture('/fog.png');
148
+ const march = block(() => {
149
+ const light = Var(vec3(0)), depth = Var(0); // Var(0, 'u32') for other types
150
+ Loop(64, () => {
151
+ const density = texture(fog, uv().add(depth), 0).r; // an explicit level: see Limits
152
+ If(density.greaterThan(0.95), () => Break()); // stops this pixel's loop here
153
+ light.addAssign(vec3(density).mul(0.02));
154
+ depth.addAssign(0.01);
155
+ });
156
+ return light;
157
+ });
158
+ new NodeMaterial({colorNode: march});
159
+
160
+ const hits = storage(1, 'u32', {atomic: true}), out = storage(n, 'u32');
161
+ ComputePass.attach(stage.engine, n, i => { // a ComputePass body is a statement body already
162
+ If(i.mod(2).equal(0), () => {
163
+ out.store(hits.atomicAdd(0, 1), i); // runs here, for the even invocations only
164
+ });
165
+ });
166
+ ```
167
+
168
+ ## Statements
169
+
170
+ `block(() => value)` is a node worked out by statements; NodeMaterial slots, NodePass nodes and Fn bodies all take one. A ComputePass body and every body below are statement bodies too, so they need no `block`.
171
+
172
+ - `Var(init, type?)` declares a variable; `.assign(v)`, `.addAssign`, `.subAssign`, `.mulAssign`, `.divAssign` and `.assignElement(i, v)` change it. It is a node, so `x.add(1)`, `x.xy` and `x.lessThan(0)` read it.
173
+ - `If(cond, body).ElseIf(cond, body).Else(body)` runs one body. Only that body's nodes run, which is the reason to use it over `select`; a condition after the first is worked out only when the ones before it failed. Conditions are single `bool`s.
174
+ - `Loop(count, i => ...)` or `Loop({from, to, step}, i => ...)` counts with an `i32` `i`; the bounds are read once, on entry. `While(cond, body)` tests `cond` before each pass and hangs the GPU if it never fails, so bound it. `Break()` and `Continue()` work in both; `loop()` stays the plain fold.
175
+ - `Switch(i32 or u32 node).Case(1, body).Case([2, 3], body).Default(body)` picks one body. There is no fall-through, `Default` is optional, and `Break()` inside a Case ends the Switch rather than a loop around it, as in C and WGSL.
176
+ - `Let(node)` keeps a value as it is now. A node that reads a `Var` is worked out where it is used: after `const next = x.add(1); x.assign(0);`, `next` is `1`, while `Let(x.add(1))` taken before the assignment keeps the old sum.
177
+ - Storage `store` and atomics inside these bodies happen right there, in order. At the top level of a ComputePass body atomics run where they are made and writes run after them, returned or not.
178
+
179
+ Mistakes fail when the material or pass is built, with a message that says what to do: a statement outside a body, `Break()` with nothing to leave (a `block` is a value, so a Break in it cannot reach a loop outside it), a `Var` or `Let` used outside the body it was made in, repeated cases. An atomic made in a branch and used outside it is refused too, because the only way to emit it would be to run it twice.
180
+
181
+ ## Nodes
182
+
183
+ - Types: `f32`, `i32`, `u32`, `bool`, `vec2/3/4` of each, `mat2x2f`, `mat3x3f`, `mat4x4f`. `Node<'vec3f'>` is checked by TypeScript, and every operation checks again at run time with a message such as `vec3f + vec2f: operand types do not combine`. Numbers lift to the other operand's type; scalars splat (`mix(a, b, 0.5)`, `clamp(v, 0, 1)` on vectors).
184
+ - Constructors: `float int uint bool vec2 vec3 vec4 ivec2-4 uvec2-4 mat3 mat4`, `color('#rrggbb' | 0xrrggbb | [r, g, b])` (linear), conversions `.toFloat() .toInt() .toUint()`.
185
+ - Arithmetic and logic: `add sub mul div mod negate` (matrix times vector works), `lessThan lessThanEqual greaterThan greaterThanEqual equal notEqual and or not`, swizzles `.x .xy .rgb .zyx` (and `.xxx` on a scalar), `.element(i)`.
186
+ - Built-ins, as functions and methods: `abs sign floor ceil round trunc fract sin cos tan asin acos atan atan2 tanh exp exp2 log log2 sqrt inverseSqrt saturate normalize radians degrees dpdx dpdy fwidth min max pow clamp step smoothstep mix reflect refract cross length distance dot oneMinus`.
187
+ - Inputs: `uv()`, `vertexColor()`, `positionLocal`, `positionWorld`, `normalLocal`, `normalWorld`, `viewDirection`, `cameraPosition`, `screenUV`, `screenCoordinate`, `varying(node)`; in a NodeMaterial also `positionView`, `normalView`, `tangentLocal`, `tangentWorld`, `bitangentWorld`, `linearDepth`, `cameraNear`, `cameraFar`, `modelMatrix`, `viewMatrix`, `projectionMatrix`, `vertexIndex`, `instanceIndex`, `instanceMatrix`, `instanceColor`, `instanceUV` (see [Input nodes](#input-nodes)); frame uniforms `time`, `deltaTime`, `resolution`; `uniform(value, {type, name})` with `.value` live; `texture(materialsTexture, uv?, level?)`, `textureCube(cube, direction, level?)`, `texture3D(volume, uvw, level?)`.
188
+ - Material inputs (fragment): `materialColor`, `materialNormal`, `materialRoughness`, `materialMetalness`, `materialEmissive` (what the Material computed before nodes ran), `frontFacing`. Post inputs: `inputColor(uv?)`, `inputDepth(uv?)`. Compute input: `instanceIndex`.
189
+ - Control: `select(cond, ifTrue, ifFalse)`, `loop(count, init, (i, acc) => next)` (a bounded fold), `Fn(body, name)` (one WGSL function per argument-type signature) and `wgslFn(code)` for hand-written WGSL. `discard(cond, value)` drops the fragment where `cond` holds and is `value` elsewhere (NodeMaterial fragment nodes and NodePass nodes; a vertex or compute use throws). Statement-level `If`, `Loop` and the rest are under [Statements](#statements).
190
+ - Atomics: `storage(data, 'u32' | 'i32', {atomic: true})` gives `atomicAdd(i, v)`, `atomicMax`, `atomicMin` (each returns the previous value), `atomicLoad(i)` and `atomicStore(i, v)` (a write like `store`), in ComputePass nodes only; TypeScript refuses them on other storage types. They run in the order they are made, before the body's writes, even when their result is unused (inside `loop` or `Fn` bodies only where the result is used); equal calls are never merged. `element(i)` on an atomic buffer is an `atomicLoad` in compute and a plain read in materials and post.
191
+
192
+ The compiler hash-conses the graph, so equal subexpressions built separately (three calls to `uv().y`) become one `let`; nodes not reachable from an output, unused uniforms and unused textures are never emitted. Output text depends only on the graph, so equal graphs give equal shaders and pipelines cache; uniform values live in a buffer, so changing them never recompiles. `material.fragmentCode`, `material.vertexCode`, `pass.code()` and `computePass.code` show the generated WGSL; `test/snapshots` holds examples.
193
+
194
+ Float uniforms (scalars, vectors and matrices) must stay finite as float32; otherwise construction or a `.value` assignment throws `TypeError` and keeps the previous value. Portable graphs (`@margoengine/shader/graph`) need complete three-number `fallback.color` and `fallback.emissive` arrays. A material from `createGraphMaterial` keeps its validated graph in `material.surfaceGraph`, so a baking host can evaluate the same pattern with `evaluateSurfaceGraph`.
195
+
196
+ ## Visual editor (`@margoengine/shader/editor`)
197
+
198
+ `NodeEditor` is a node-graph editor for the portable surface graph (`SurfaceGraph`, `@margoengine/shader/graph`): pick nodes
199
+ from a palette, wire outputs to inputs, type constants, and see at once whether the graph is valid. It is plain DOM in a shadow
200
+ root (light and dark), needs no framework and has no effect on import. `onGraph` hands you every new valid graph, so a
201
+ material can be rebuilt as the artist edits (hot reload).
202
+
203
+ ```ts
204
+ import {createStage} from 'margoengine';
205
+ import {createMesh} from 'margoengine/materials';
206
+ import {sphereGeometry} from 'margoengine/geometry';
207
+ import {createGraphMaterial, type SurfaceGraph} from 'margoengine/shader/graph';
208
+ import {NodeEditor} from 'margoengine/shader/editor';
209
+ const stage = await createStage('#app');
210
+ const geometry = sphereGeometry(1, 64, 32);
211
+ const saved = localStorage.getItem('surface'); // {graph, layout} saved below, if any
212
+ const editor = new NodeEditor(document.querySelector<HTMLElement>('#editor')!, saved ? JSON.parse(saved) : {});
213
+ const mesh = createMesh(stage.engine, geometry, createGraphMaterial(editor.model.toGraph()));
214
+ const stop = editor.onGraph((graph: SurfaceGraph) => { // called for each new VALID graph, not for moves
215
+ mesh.material = createGraphMaterial(graph); // swapped live from the next frame
216
+ localStorage.setItem('surface', JSON.stringify({graph, layout: editor.layout}));
217
+ });
218
+ editor.onChange(status => console.log(status.ok ? 'ok' : status.message)); // fix-it text, e.g. which input is empty
219
+ // later: stop(); editor.dispose(); (or pass {signal} and abort it; `using editor = new NodeEditor(...)` works too)
220
+ ```
221
+
222
+ - **Using it.** `Shift+A` or a double click on the canvas opens the palette (type to search; arrows and Enter; 28 operations).
223
+ Drag from a node's output socket to an input socket, or click an output and then an input. Drag from a wired input to move
224
+ or drop the wire; click a wired input to pick its wire up. Drag a title bar to move nodes; drag empty canvas to pan, wheel to
225
+ zoom at the cursor. `Delete` removes the selection (or the wire of a focused input), `Ctrl+Z` / `Ctrl+Y` undo and redo,
226
+ `Ctrl+D` duplicates, `Ctrl+A` selects all, arrows nudge (Shift: 32 px), `F` fits, `Esc` cancels. Sockets are buttons with
227
+ labels, so the keyboard and screen readers can wire a graph; the status line is a live region. Touch works through the same
228
+ pointer events.
229
+ - **Unconnected inputs.** Most second inputs have a default shown as a number field (`Multiply` B = 1, `Mix` Factor = 0.5,
230
+ `Clamp` 0 to 1, `Combine` 0, 0, 0); type there instead of adding a Number node. The editor adds them as hidden `float`
231
+ nodes when it exports. Inputs without a default (the first input of most nodes) must be wired; until then the status line
232
+ names the node and input and `graph` throws, and nothing is reported to `onGraph`.
233
+ - **Validation as you edit.** The editor runs the real validator: loops are refused when you wire them, type mistakes (a vec3
234
+ into a number slot), the 128 node, depth 32 and work limits show in the status line, and the node a message is about is
235
+ outlined (click the status line to select it). Each node shows its output type. The **WGSL** button shows the shader
236
+ `createGraphMaterial` generates for the current graph (debugging).
237
+ - **Saving.** `editor.graph` is the portable graph (`serializeSurfaceGraph` makes the JSON) and `editor.layout` the node
238
+ positions; pass both back as `{graph, layout}`. Layout is not part of the portable graph. Constants of a portable graph are
239
+ immutable by design, so editing a number rebuilds the material (the pipeline cache makes equal graphs free); use a
240
+ `uniform` in code for values that change every frame.
241
+ - **Without the DOM.** `GraphModel` is the editor's state: `addNode`, `connect`, `connectOutput`, `setValue`, `setInline`,
242
+ `removeNodes`, `duplicate`, `batch`, `undo` / `redo`, `status()`, `toGraph()`. Use it to script graph edits in tools and tests.
243
+ `readOnly: true` shows a graph without allowing edits.
244
+
245
+ `node packages/shader/test/editor-check.mjs` builds a graph with a real mouse and keyboard in a
246
+ browser (palette, typed constants, dragged wires), draws the material it makes and reads the pixels back: the colour, a
247
+ rebuild after a retyped number, no rebuild after a node move, undo and redo, and that an incomplete or ill-typed graph keeps
248
+ the last valid material on screen.
249
+
250
+ ## Noise (`@margoengine/shader/noise`, 5.3 kB min+gzip on its own)
251
+
252
+ ```ts
253
+ import {createStage} from 'margoengine';
254
+ import {createMesh} from 'margoengine/materials';
255
+ import {planeGeometry} from 'margoengine/geometry';
256
+ import {NodeMaterial, positionLocal, normalLocal, uniform} from 'margoengine/shader';
257
+ import {simplex2, simplex3, perlin3, fbm, ridged, domainWarp} from 'margoengine/shader/noise';
258
+ const stage = await createStage('#app');
259
+ const p = positionLocal.xy.mul(0.4);
260
+ const height = ridged(q => simplex2(q, 42), p, {octaves: 5}); // GPU terrain, seed 42
261
+ const clouds = domainWarp(q => fbm(r => simplex3(r, 7), q), positionLocal, {strength: 0.6});
262
+ const seed = uniform(3, {type: 'u32', name: 'seed'}); // perlin3 reseeds live
263
+ const material = new NodeMaterial({positionNode: positionLocal.add(normalLocal.mul(height)), emissiveNode: perlin3(positionLocal, seed).abs().xxx.mul(clouds)});
264
+ createMesh(stage.engine, planeGeometry(10, 10, 128, 128), material);
265
+ ```
266
+
267
+ WGSL twins of `@margoengine/procedural/noise`: `simplex2`/`simplex3` match `new Noise(seed).simplex2`/`.simplex`, `perlin3`
268
+ matches `.perlin`, and `fbm`, `ridged`, `domainWarp` match the CPU combinators, so CPU code (physics, placement) can sample
269
+ the same field the GPU displaces. Agreement is to float rounding, not bits (f32 on the GPU, f64 on the CPU), measured on a
270
+ real adapter by `node packages/shader/test/noise-check.mjs`; on an Intel Arc 140V (Edge, 4096 points per field) the largest absolute difference was 2e-5 for single simplex and Perlin samples and 1.1e-4 for warped fBm (values span about [-1, 1]). Simplex seeds are compile-time
271
+ (each seed's 256-byte permutation is a private array, declared once per shader); `perlin3` takes a u32 node, so a uniform
272
+ reseeds without recompiling. Fractal sums unroll at graph build time (`octaves` 1..16). Example: `examples/noise.html` (terrain with CPU-placed markers resting on the GPU surface).
273
+
274
+ Cellular noise and 4D simplex, for cracks, cells, caustics and animation that loops:
275
+
276
+ ```ts
277
+ import {createStage} from 'margoengine';
278
+ import {createMesh} from 'margoengine/materials';
279
+ import {planeGeometry} from 'margoengine/geometry';
280
+ import {NodeMaterial, cos, mix, sin, smoothstep, time, uv, vec3, vec4} from 'margoengine/shader';
281
+ import {simplex4, voronoi2, worley3} from 'margoengine/shader/noise';
282
+ const stage = await createStage('#app');
283
+ const cell = voronoi2(uv().mul(8), 5); // x nearest, y second, z cell id
284
+ const crack = smoothstep(0, 0.05, cell.y.sub(cell.x)); // 0 on every border
285
+ const turn = time.mul((Math.PI * 2) / 4); // one circle in 4 seconds
286
+ const loop = simplex4(vec4(uv().mul(3), cos(turn), sin(turn)), 7); // repeats exactly every 4 seconds
287
+ createMesh(stage.engine, planeGeometry(4, 4), new NodeMaterial({
288
+ colorNode: mix(vec3(0.1), vec3(cell.z, 0.5, loop.mul(0.5).add(0.5)), crack),
289
+ emissiveNode: worley3(vec3(uv().mul(6), time)).oneMinus().pow(8).xxx, // caustic-like light
290
+ }));
291
+ ```
292
+
293
+ | Node | Returns | CPU twin |
294
+ | --- | --- | --- |
295
+ | `simplex4(p, seed)` | `f32`, about -1 to 1 | `new Noise(seed).simplex4(x, y, z, w)` |
296
+ | `worley3(p, seed)` | `f32`, distance from 0 | `new Noise(seed).worley(x, y, z)` |
297
+ | `worley2(p, seed)` | `f32`, distance from 0 | none |
298
+ | `voronoi2(p, seed)`, `voronoi3(p, seed)` | `vec3f`: nearest distance, second nearest, cell id 0 to 1 | `.x` of `voronoi3` is `worley` |
299
+
300
+ `seed` of the cellular nodes may be a u32 node, as for `perlin3`; `simplex4` seeds are compile-time, like the other simplex nodes. `fbm`, `ridged` and `domainWarp` take `vec4f` fields too. The cellular search visits two cells each side, which is exact for both distances: 25 cells in 2D, 125 in 3D with three hashes each, so `voronoi3` and `worley3` are costly per pixel and suit a bake, a compute pass or a low-resolution texture better than a full-screen fragment.
301
+
302
+ ## Utility nodes (`@margoengine/shader/utils`)
303
+
304
+ Ready nodes for what graphs keep rewriting. Each is plain nodes, so what you leave out costs nothing.
305
+
306
+ ```ts
307
+ import {createStage} from 'margoengine';
308
+ import {createMesh, loadTexture} from 'margoengine/materials';
309
+ import {planeGeometry} from 'margoengine/geometry';
310
+ import {NodeMaterial, positionWorld, texture, vec3} from 'margoengine/shader';
311
+ import {blendOverlay, bumpNormal, hue, normalMap, oscSine, parallaxUV, remap, triplanar} from 'margoengine/shader/utils';
312
+ const stage = await createStage('#app');
313
+ const [albedo, normals, height] = await Promise.all([
314
+ loadTexture('/brick.jpg'),
315
+ loadTexture('/brick-normal.png', {colorSpace: 'linear'}),
316
+ loadTexture('/brick-height.png', {colorSpace: 'linear'}),
317
+ ]);
318
+ const carved = parallaxUV(height, {scale: 0.04}); // read every map with this UV
319
+ createMesh(stage.engine, planeGeometry(4, 4), new NodeMaterial({
320
+ colorNode: blendOverlay(texture(albedo, carved).rgb, vec3(0.6, 0.5, 0.4), 0.5),
321
+ normalNode: normalMap(texture(normals, carved).rgb),
322
+ }));
323
+ const rock = new NodeMaterial({
324
+ colorNode: hue(triplanar(albedo, {scale: 0.5}).rgb, remap(oscSine(), 0, 1, -0.2, 0.2)), // no UVs needed
325
+ normalNode: bumpNormal(positionWorld.y.mul(8).sin().mul(0.02)),
326
+ });
327
+ createMesh(stage.engine, planeGeometry(2, 2), rock);
328
+ ```
329
+
330
+ | Node | Gives | Notes |
331
+ | --- | --- | --- |
332
+ | `normalMap(rgb, {strength, frame, coord, flipY})` | a `normalNode` | `rgb` is the map's colour, so load it with `{colorSpace: 'linear'}`. `frame: 'derivatives'` (default) works on any mesh; `'tangents'` reads the mesh's. `flipY: false` is for glTF UVs, with their origin at the top left. |
333
+ | `bumpNormal(height, {strength, normal})` | a `normalNode` | `height` in world units, as a node. Tilts `normal`, by default the surface's. |
334
+ | `triplanar(map, {position, normal, scale, sharpness})` | `vec4f` | `map` is a `Texture` or a function of a UV. Three reads. World space by default; `positionLocal` and `normalLocal` stick it to the object. |
335
+ | `parallaxUV(height, {coord, scale, steps, frame})` | `vec2f` | `height` is a `Texture` (red, 1 at the surface) or a function of a UV. `scale` is the depth in UV units, default 0.05. `steps: 1` is a plain offset; the default 16 searches. |
336
+ | `rotateUV(coord, angle, center?)`, `rotateAxis(v, axis, angle)` | `vec2f`, `vec3f` | Radians. `center` defaults to 0.5; `axis` must be unit length. |
337
+ | `matcapUV(normal?, position?)` | `vec2f` | View space, and the same lookup as `MatcapMaterial`. |
338
+ | `equirectUV(direction, {flipY})` | `vec2f` | The panorama layout of `@margoengine/environment`: the image's middle faces -z. `flipY: false` is for images not stored flipped. |
339
+ | `luminance(rgb)`, `saturation(rgb, amount)`, `hue(rgb, angle)` | `f32`, `vec3f` | Linear colour, Rec. 709 weights. `saturation` 0 is grey. `hue` turns about the grey axis, in radians, so it keeps the sum of the channels and not the luminance. |
340
+ | `blendAdd`, `blendSubtract`, `blendMultiply`, `blendScreen`, `blendOverlay`, `blendHardLight`, `blendSoftLight`, `blendDodge`, `blendBurn`, `blendDarken`, `blendLighten`, `blendDifference`, `blendExclusion` | `vec3f` | `(base, top, opacity = 1)`, the W3C formulas, for colours from 0 to 1. Brighter light clips. |
341
+ | `remap(x, inLow, inHigh, outLow = 0, outHigh = 1)`, `remapClamp(...)` | as `x` | Scalars or vectors. `remap` runs past the ends, `remapClamp` stops at them. `inLow` and `inHigh` must differ. |
342
+ | `oscSine(t = time)`, `oscSquare`, `oscTriangle`, `oscSawtooth` | `f32` | 0 to 1, one period per unit of `t`, so one a second by default. `oscSine(time.mul(4))` runs four times as fast. |
343
+
344
+ `normalMap`, `bumpNormal` and `parallaxUV` read screen derivatives, or a texture in a search, so they belong in fragment nodes. Outside a uniform branch the derivative rule of [Limits](#limits) applies, and `parallaxUV`'s `height` function must sample with an explicit level (`texture(map, q, 0).r`). A `Texture` passed to it is read at level 0, so a distant surface can shimmer. The search sees no silhouette: the mesh's outline stays flat. Grazing views are held at about 84 degrees, so the shift stays bounded.
345
+
346
+ `node packages/shader/test/utils-check.mjs` runs the maths nodes and all 13 blend modes over 256 random inputs against JavaScript formulas, and reads the rest back from a wall: each normal map direction in both frames, a known slope through `bumpNormal`, both projections of `triplanar`, `parallaxUV` against the depth worked out by hand for a flat and a sloped field at 45 degrees, `matcapUV` against `MatcapMaterial` on a sphere, and a panorama's top and bottom rows.
347
+
348
+ ## Read back one dispatch (`@margoengine/shader/readback`, 8.8 kB min+gzip on its own)
349
+
350
+ `ComputePass` runs every frame while attached. For a one-off result on the CPU (an editor tool, a bake, a test),
351
+ `computeReadback` runs a body once and resolves with a copy of a storage buffer:
352
+
353
+ ```ts
354
+ import {storage, uint} from 'margoengine/shader';
355
+ import {computeReadback} from 'margoengine/shader/readback';
356
+ import {createStage} from 'margoengine';
357
+ const stage = await createStage('#viewport', {backend: 'webgpu'});
358
+ const cells = new Uint32Array(1024);
359
+ const source = storage(Uint32Array.from(cells), 'u32'), output = storage(cells.length, 'u32');
360
+ const controller = new AbortController();
361
+ const {data} = await computeReadback(stage.engine, cells.length, i => output.store(i, source.element(i).add(uint(1))), output, {
362
+ signal: controller.signal, // cancel button: rejects with signal.reason
363
+ timeout: 30_000, // default; Infinity waits
364
+ });
365
+ source.dispose(); output.dispose(); // storage stays yours; `data` is a Uint32Array you own
366
+ ```
367
+
368
+ `target` is a GPUDevice or an engine (its current device; no frame needs to render). The job records one dispatch and a
369
+ copy into its own command buffer, submits it, maps a private readback buffer and copies the bytes out, so `data` is
370
+ neither `output.data` nor GPU memory. It settles exactly once:
371
+
372
+ | Outcome | Settles with |
373
+ | --- | --- |
374
+ | GPU finished | `{data, type, count}`: Float32Array, Int32Array or Uint32Array by element type |
375
+ | `signal` aborted (before the call: the GPU is never touched) | rejects with `signal.reason` |
376
+ | engine disposed during the job, or already disposed | MargoError `'disposed'` |
377
+ | device lost during the job, or already lost | MargoError `'failed'` naming the loss reason |
378
+ | WGSL or a GPU call failed validation or memory (inside the job's error scopes; the device stays usable) | MargoError `'failed'` with the GPU message |
379
+ | `timeout` elapsed | MargoError `'failed'` |
380
+ | engine without WebGPU | MargoError `'unsupported'` |
381
+
382
+ Whatever the outcome, the job's readback and uniform buffers are destroyed and its abort listener, device-loss
383
+ observer and timer removed as it settles (a pending map is cancelled by the destroy); storage the body uses is never
384
+ disposed for you. Frame values read a 1 x 1 resolution and deltaTime 0. `test/readback.test.js` checks every row on a
385
+ scripted device; `node packages/shader/test/readback-check.mjs` on a real adapter: 4,194,304 u32
386
+ read back exactly (65 ms on an NVIDIA Ampere GPU in Edge), a job on an engine that never rendered, abort right after
387
+ submit and while mapping, engine disposal and `device.destroy()` at both points, and a pipeline over the storage-binding
388
+ limit; every job destroyed its buffers and no GPU error escaped.
389
+
390
+ ## Input nodes
391
+
392
+ What a vertex or fragment knows, as nodes in the shader root. Each one tree-shakes, and the shader only reads what the graph uses.
393
+
394
+ ```ts
395
+ import {createStage} from 'margoengine';
396
+ import {createMesh} from 'margoengine/materials';
397
+ import {boxGeometry} from 'margoengine/geometry';
398
+ import {NodeMaterial, cameraFar, cameraNear, linearDepth, normalView, saturate, vec3} from 'margoengine/shader';
399
+ const stage = await createStage('#app');
400
+ const rim = saturate(normalView.z.negate().add(1)), // bright where the surface turns away
401
+ fog = linearDepth.sub(cameraNear).div(cameraFar.sub(cameraNear)); // 0 at the near plane, 1 at the far one
402
+ createMesh(stage.engine, boxGeometry(1, 1, 1), new NodeMaterial({emissiveNode: vec3(rim, fog, 0)}));
403
+ ```
404
+
405
+ | Node | Value | Notes |
406
+ | --- | --- | --- |
407
+ | `positionView`, `normalView` | view space: x right, y up, the camera looks along -z | |
408
+ | `linearDepth` | distance from the camera plane in world units, positive in front | |
409
+ | `tangentLocal`, `tangentWorld`, `bitangentWorld` | the mesh's tangent frame, unit length, with its handedness | a mesh without tangents gets a fixed frame around its normal, not lined up with its UVs: `computeTangents` from `@margoengine/geometry` gives real ones |
410
+ | `cameraNear`, `cameraFar` | the camera's planes, read back from its projection | perspective and orthographic |
411
+ | `modelMatrix`, `viewMatrix`, `projectionMatrix` | `mat4x4f` | `modelMatrix` is the mesh's, without an instance's |
412
+ | `vertexIndex`, `instanceIndex` | `u32` | in a fragment, the first vertex of the triangle |
413
+ | `instanceMatrix`, `instanceColor`, `instanceUV` | this instance's matrix, tint and UV scale (xy) and offset (zw) | identity, white and (1, 1, 0, 0) without instances |
414
+ | `textureCube(cube, direction, level?)` | a `CubeTexture` sampled along a direction | refuses a texture of another dimension |
415
+ | `texture3D(volume, uvw, level?)` | a `Texture` made with `{dimension: '3d'}` | refuses a texture of another dimension |
416
+
417
+ `NodePass` and `ComputePass` have no mesh, so these are NodeMaterial nodes. A depth pass reads `vertexIndex`, `instanceIndex` and the main camera, and nothing tied to tangents: a `positionNode` that reads those casts the mesh unmoved, as [Node output in every pass](#node-output-in-every-pass) describes.
418
+
419
+ `node packages/shader/test/inputs-check.mjs` reads each input back as a pixel on a wall the camera faces, with and without tangents, and compiles the instance inputs plain, instanced and in uniform rows.
420
+
421
+ ## Custom vertex attributes
422
+
423
+ `attribute(name, type)` is a per-vertex value of the mesh being drawn, from its `geometry.attributes`. Types are one to
424
+ four of `f32`, `i32` or `u32` (`'f32'`, `'vec3f'`, `'vec2u'`, ...), and `data` holds one value of that type per vertex,
425
+ component after component. One material serves any number of meshes, each with its own data, and every pass that draws
426
+ the material reads it, shadows included. In `positionNode` it is the vertex's value; in the colour slots it is
427
+ interpolated across the triangle, and integer types take the triangle's first vertex.
428
+
429
+ ```ts
430
+ import {createStage} from 'margoengine';
431
+ import {createMesh} from 'margoengine/materials';
432
+ import {planeGeometry} from 'margoengine/geometry';
433
+ import {NodeMaterial, attribute, color, mix, positionLocal, vec3} from 'margoengine/shader';
434
+ const stage = await createStage('#app');
435
+ const geometry = planeGeometry(2, 2, 32, 32), vertices = geometry.positions.length / 3;
436
+ const heat = Float32Array.from({length: vertices}, (_, i) => (geometry.positions[i * 3]! + 1) / 2);
437
+ const material = new NodeMaterial({
438
+ colorNode: mix(color('#2040ff'), color('#ff4020'), attribute('heat', 'f32')),
439
+ positionNode: positionLocal.add(vec3(0, 0, attribute('heat', 'f32').mul(0.5))),
440
+ });
441
+ const mesh = createMesh(stage.engine, {...geometry, attributes: {heat: {data: heat, type: 'f32'}}}, material);
442
+ heat.fill(1, 0, 33); // the first row of vertices
443
+ mesh.setGeometry({...geometry, attributes: {heat: {data: heat, type: 'f32'}}}, {start: 0, count: 33}); // uploads 33
444
+ ```
445
+
446
+ `createMesh`, `createInstancedMesh`, `setGeometry` and a material swap throw when the geometry lacks an attribute the
447
+ material reads, gives it another type or the wrong number of values, or holds a value that does not fit (`NaN`, a
448
+ fraction for an integer type). The values are copied when the call is made: edit your array, then call `setGeometry`,
449
+ with a range to upload those vertices alone. A bare array in `attributes` is one `f32` per vertex, the form
450
+ `margoengine/loaders` gives its extra scalars (PCD `intensity`, VTK point scalars, COLLADA channels), so a loaded
451
+ geometry draws with `attribute('intensity', 'f32')` as it is. Meshes that come from elsewhere (a loaded glTF,
452
+ `BatchedMesh`) have no `geometry.attributes`, so a material that reads one cannot draw them. The values of a mesh's attributes are interleaved
453
+ into one read-only storage buffer read by vertex index (one of the vertex stage's storage buffers), so the 80-byte
454
+ vertex and its pipelines are unchanged. `node packages/shader/test/attribute-check.mjs` (and `--compat`) compares meshes
455
+ drawn from attributes with the same meshes built on the CPU, pixel for pixel. Sources: D. Rákos, "Programmable Vertex
456
+ Pulling", in P. Cozzi and C. Riccio (eds.), "OpenGL Insights", CRC Press, 2012
457
+ (<https://www.taylorfrancis.com/books/9781439893777/chapters/10.1201/b12288-29>); W3C, "WebGPU Shading Language",
458
+ built-in values (<https://www.w3.org/TR/WGSL/#built-in-values>).
459
+
460
+ ## Skinning and morph targets (`@margoengine/shader/deform`)
461
+
462
+ Deformation as nodes, so a graph can add its own effect on top and every pass draws the result. `skinning()` is linear blend skinning and `morphing()` is morph targets, both as glTF 2.0 defines them; they run in the vertex stage from `storage()` buffers you fill.
463
+
464
+ ```ts
465
+ import {createStage} from 'margoengine';
466
+ import {createMesh} from 'margoengine/materials';
467
+ import {planeGeometry} from 'margoengine/geometry';
468
+ import {NodeMaterial, sin, storage, time, vec3} from 'margoengine/shader';
469
+ import {morphing, skinning, worldNormal} from 'margoengine/shader/deform';
470
+ const stage = await createStage('#app');
471
+ const geometry = planeGeometry(2, 2, 16, 16), vertices = geometry.positions.length / 3;
472
+ const skin = skinning({
473
+ bones: storage(new Float32Array([1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1]), 'vec4f'), // one matrix, four columns
474
+ joints: storage(new Uint32Array(vertices * 4), 'vec4u'), // four bone numbers per vertex
475
+ weights: storage(new Float32Array(vertices * 4).map((_, i) => (i % 4 ? 0 : 1)), 'vec4f'),
476
+ });
477
+ const morph = morphing({
478
+ count: 1,
479
+ vertices,
480
+ positions: storage(new Float32Array(vertices * 4), 'vec4f'), // offsets, target after target
481
+ weights: storage(new Float32Array([0.5]), 'f32'),
482
+ });
483
+ createMesh(stage.engine, geometry, new NodeMaterial({
484
+ positionNormals: 'keep', // normalNode below replaces them
485
+ positionNode: skin.position(morph.position()).add(vec3(0, sin(time).mul(0.1), 0)), // morph, then bones, then an effect
486
+ normalNode: worldNormal(skin.normal(morph.normal())),
487
+ }));
488
+ ```
489
+
490
+ Update the pose by writing the buffer's `data` and calling `update()`, or write the buffer from a `ComputePass`.
491
+
492
+ | Function | Returns | Notes |
493
+ | --- | --- | --- |
494
+ | `skinningFromModel(model, primitive)` | `skinning()`'s result and `{geometry, bones, joints, weights, update()}` | `primitive` is an entry of `model.primitives` whose node has a skin. |
495
+ | `skinning({bones, joints, weights})` | `{position(p?), normal(n?)}` | `bones` holds the joint matrix times the inverse bind matrix, four `vec4f` columns per bone, in mesh space. `p` and `n` default to the mesh's own, so pass a morph's output to chain them. |
496
+ | `morphing({count, vertices, positions, normals?, weights})` | `{position(p?), normal(n?)}` | The buffers hold `count * vertices` offsets, target after target. Without `normals`, `normal()` is the base normal. |
497
+ | `worldNormal(n)` | a `normalNode` | A mesh-space normal in world space, per vertex and interpolated. Right on scaled and mirrored meshes. |
498
+
499
+ **Normals.** `normalNode: worldNormal(skin.normal())` costs one blend per vertex and is what glTF asks for. Left out, a `positionNode` makes normals by the rules of [Node output in every pass](#node-output-in-every-pass): three evaluations of the skin per vertex, and the true normal of the deformed surface.
500
+
501
+ **A loaded glTF character.** `skinningFromModel(model, primitive)` reads the skin for you: joints, weights, inverse bind matrices, the bind pose as `geometry`, and a joint palette that `update()` fills from the model's nodes, so `Animation`, a pose you set by hand or anything else that moves those nodes drives it.
502
+
503
+ ```ts
504
+ import {createStage} from 'margoengine';
505
+ import {createMesh} from 'margoengine/materials';
506
+ import {loadGLTF} from 'margoengine/gltf/pbr';
507
+ import {Animation} from 'margoengine/animation';
508
+ import {NodeMaterial, positionWorld, sin, time, vec3} from 'margoengine/shader';
509
+ import {skinningFromModel, worldNormal} from 'margoengine/shader/deform';
510
+ const stage = await createStage('#app', {autoStart: false});
511
+ const {engine} = stage;
512
+ const model = await loadGLTF(engine, '/fox.glb');
513
+ const animation = Animation.attach(model);
514
+ const fox = skinningFromModel(model, model.primitives[0]);
515
+ createMesh(engine, fox.geometry, new NodeMaterial({
516
+ positionNode: fox.position().add(vec3(0, sin(time).mul(5), 0)),
517
+ normalNode: worldNormal(fox.normal()),
518
+ colorNode: positionWorld.normalize(),
519
+ }));
520
+ model.root.visible = false; // show the node version alone
521
+ engine.onFrame(() => fox.update());
522
+ engine.start();
523
+ ```
524
+
525
+ Draw `fox.geometry` at the world origin: the palette holds world matrices, so the skin lands where the model stands. `update()` reads the matrices of the last transform update, so called from `onFrame` the skin runs a frame behind the joints. `JOINTS_1` (more than four influences) is refused, and a mesh drawn this way keeps its bind pose bounds, so a character that walks far from them needs `engine.render({culling: false})` or its own bounds.
526
+
527
+ **A character played by `@margoengine/animation`, on its own mesh.** Its compute deformer already replaced the vertices every pass fetches, so in a NodeMaterial on such a character `positionLocal` and `normalLocal` are the posed vertex: add an effect with `positionLocal.add(...)` and leave these nodes out.
528
+
529
+ `node packages/shader/test/deform-check.mjs` compares each of these with the same mesh deformed on the CPU: position, morph into skin, an effect on top, lit normals (also on a stretched, mirrored mesh, and from neighbours), a new pose, the shadow, and an effect on vertices a compute deformer moved.
530
+
531
+ ## Extra outputs and scene passes (`@margoengine/shader/pass`)
532
+
533
+ A `ScenePass` draws its models into textures of its own before the frame's colour pass, and a `PassMaterial` writes extra outputs into them. Anything drawn later in the frame samples those textures with `texture()`: selective bloom, refraction, custom post chains.
534
+
535
+ ```ts
536
+ import {createStage} from 'margoengine';
537
+ import {Material, createMesh} from 'margoengine/materials';
538
+ import {planeGeometry} from 'margoengine/geometry';
539
+ import {PostStack} from 'margoengine/post';
540
+ import {NodePass, inputColor, texture, uv, vec4} from 'margoengine/shader';
541
+ import {PassMaterial, ScenePass} from 'margoengine/shader/pass';
542
+ const stage = await createStage('#app');
543
+ const pass = ScenePass.attach(stage.engine, {outputs: {glow: 'rgba16float'}});
544
+ const lamp = createMesh(stage.engine, planeGeometry(1, 1), new PassMaterial({outputs: {glow: vec4(4, 2, 1, 1)}}));
545
+ const wall = createMesh(stage.engine, planeGeometry(4, 4), new Material({color: [0.5, 0.5, 0.5]}));
546
+ pass.add(lamp);
547
+ pass.add(wall); // a plain mesh hides the glow it covers
548
+ PostStack.attach(stage.engine, [new NodePass(inputColor().rgb.add(texture(pass.texture('glow'), uv()).rgb))]);
549
+ ```
550
+
551
+ | Name | What it does |
552
+ | --- | --- |
553
+ | `ScenePass.attach(engine, {outputs, order?})` | `outputs` maps names to filterable colour formats such as `rgba16float` or `rgba8unorm`. `order` defaults to 0.5, before the colour pass. |
554
+ | `pass.add(model)` | Draws a gltf/pbr model or a mesh in the pass, opaque and masked surfaces only. Returns a remover. |
555
+ | `pass.texture(name)` | The output for `texture()`, the size of the drawing buffer. Transparent black where nothing was drawn. |
556
+ | `pass.velocity(previous?)` | A `vec2f` node for an output: how far the surface moved on screen since the last frame, in UV units. It covers camera motion; a moving mesh passes where it was as a world position. |
557
+ | `new PassMaterial({outputs, ...})` | A `NodeMaterial` with a `vec4f` node per output name, worked out after the surface, so `materialEmissive` and `materialNormal` hold the final values: `{emissive: vec4(materialEmissive, 1)}` is the glow of a surface alone. It draws as usual in the frame. |
558
+
559
+ **The lit colour.** The output name `color` holds the shaded colour of each surface, in linear light before tone mapping, whatever the canvas encodes, so a surface left out of the pass can show what is behind it and the frame encodes that light once:
560
+
561
+ ```ts
562
+ import {createStage} from 'margoengine';
563
+ import {Material, createMesh} from 'margoengine/materials';
564
+ import {planeGeometry} from 'margoengine/geometry';
565
+ import {NodeMaterial, screenUV, sin, texture, time, vec2} from 'margoengine/shader';
566
+ import {ScenePass} from 'margoengine/shader/pass';
567
+ const stage = await createStage('#app');
568
+ const pass = ScenePass.attach(stage.engine, {outputs: {color: 'rgba16float'}});
569
+ pass.add(createMesh(stage.engine, planeGeometry(4, 4), new Material({color: [0.8, 0.3, 0.2]})));
570
+ const wobble = vec2(sin(screenUV.y.mul(40).add(time)).mul(0.01), 0);
571
+ const pane = createMesh(stage.engine, planeGeometry(1, 1), new NodeMaterial({emissiveNode: texture(pass.texture('color'), screenUV.add(wobble)).rgb}));
572
+ pane.root.setPosition([0, 0, 0.5]);
573
+ ```
574
+
575
+ The pass draws each model a second time, and shading runs again only for `color`, single-sampled. The sky, core meshes, blended surfaces and other plugins are not in it. A model can be in a `ScenePass`, `SSR` and `SSGI` at once: each draws it with its own capture.
576
+
577
+ **The frame itself.** `sceneColor(engine)` reads what the frame has drawn so far, so core meshes, the sky, water, fog and other plugins are all there, resolved from MSAA, with no second draw. It is the snapshot `@margoengine/materials` transmission takes after the opaque phase, so the surface reading it is `transparent: true`, which draws after the snapshot, and other blended surfaces are not in it:
578
+
579
+ ```ts
580
+ import {createStage} from 'margoengine';
581
+ import {createMesh} from 'margoengine/materials';
582
+ import {planeGeometry} from 'margoengine/geometry';
583
+ import {NodeMaterial, screenUV, sin, time, vec2} from 'margoengine/shader';
584
+ import {sceneColor} from 'margoengine/shader/pass';
585
+ const stage = await createStage('#app');
586
+ const behind = sceneColor(stage.engine);
587
+ stage.box({color: '#c04030'});
588
+ const wobble = vec2(sin(screenUV.y.mul(40).add(time)).mul(0.01), 0);
589
+ const pane = createMesh(stage.engine, planeGeometry(2, 2), new NodeMaterial({shading: 'basic', transparent: true, toneMapped: false, emissiveNode: behind.read(screenUV.add(wobble))}));
590
+ pane.root.setPosition([0, 0, 1]);
591
+ ```
592
+
593
+ `behind.read(uv)` gives linear light, whatever the target encodes: on a display-encoded canvas it undoes the sRGB curve, and `toneMapped: false` encodes it back to the same value. A lit or tone-mapped surface adds its own light on top. `behind.texture` is the raw snapshot, in the frame's format. The frame pays for the snapshot from the first `sceneColor` until the last `dispose()`, and `hdrTarget` is the node telling which kind of target is bound.
594
+
595
+ `node packages/shader/test/pass-check.mjs` reads these back as pixels: two outputs with a plain mesh hiding one part, an output from a graph, a live uniform and the final emissive, the lit colour against the picture (sunlit and tone mapped too), a mesh moved in the same frame, a pane showing the wall behind it, a NodePass adding an output, a camera step as velocity, and a canvas resize.
596
+
597
+ ## Node output in every pass
598
+
599
+ A graph is one description of a surface, so every pass draws it. Each pass gets its own variant, compiled from the same nodes when the material is made:
600
+
601
+ ```ts
602
+ import {createStage} from 'margoengine';
603
+ import {createMesh} from 'margoengine/materials';
604
+ import {planeGeometry} from 'margoengine/geometry';
605
+ import {Shadows} from 'margoengine/shadows';
606
+ import {NodeMaterial, discard, normalLocal, positionLocal, sin, time, uv, vec3} from 'margoengine/shader';
607
+ const stage = await createStage('#app');
608
+ const flag = new NodeMaterial({
609
+ doubleSided: true,
610
+ positionNode: positionLocal.add(normalLocal.mul(sin(positionLocal.x.mul(6).add(time)).mul(0.1))), // shading follows the wave
611
+ colorNode: discard(uv().y.lessThan(0.1), vec3(0.8, 0.1, 0.1)), // the shadow has the same hole
612
+ });
613
+ const mesh = createMesh(stage.engine, planeGeometry(2, 1, 64, 32), flag), shadows = Shadows.attach(stage.engine);
614
+ shadows.add(mesh);
615
+ ```
616
+
617
+ | Pass | `positionNode` | `normalNode` | `discard()` |
618
+ | --- | --- | --- | --- |
619
+ | Colour, SSAO's G-buffer and ambient passes | yes | yes | yes |
620
+ | `Shadows`, `VirtualShadows`, `LocalShadows`, `Clustered` integrated shadows | yes | not read | yes |
621
+ | Picking primitives and contact shadows | yes | not read | yes |
622
+ | TAA velocity | yes: the surface moves as the mesh and camera do, and as the graph's uniforms changed since last frame | not read | yes |
623
+
624
+ **Normals.** After a `positionNode`, normals follow the new shape. `positionNormals: 'neighbours'` evaluates the graph again 0.001 mesh units to two sides of each vertex: smooth, for shapes worked out from `positionLocal`, at three evaluations of the graph per vertex. `'faces'` takes each triangle's normal in the fragment, for graphs that read `uv()`, whose neighbours a vertex cannot know: it shows facets on a coarse mesh and keeps a normal map's detail on top. `'keep'` leaves the mesh's normals. The default is `'faces'` when the graph reads `uv()`, else `'neighbours'`; a `normalNode` wins over `'faces'`.
625
+
626
+ **What a depth pass reads.** `cameraPosition`, `viewDirection`, `viewMatrix`, `projectionMatrix`, `positionView`, `normalView`, `linearDepth`, `cameraNear` and `cameraFar` are the main camera's in every depth pass, not the light's, so a mesh that faces the camera casts the shape the camera sees; in a multi-view frame that is `engine.camera`. A shadow has no surface, so fragment nodes that read `materialColor`, `materialNormal`, `materialRoughness`, `materialMetalness` or `materialEmissive` cast without their `discard()`, and a `positionNode` reading `tangentLocal`, `tangentWorld` or `bitangentWorld` casts the mesh unmoved; the colour pass is not affected. A `positionNode` also replaces a `displacementMap` in depth passes. Such a caster counts as moving, so shadow caches redraw it each frame. In TAA velocity a `positionNode` that reads the graph's uniforms (a `uniform()` you change, `time`, the camera) runs a second time on last frame's values, which TAA keeps per view, so a shape that moves over time leaves no ghost trail; nothing to register. A move driven by a storage buffer or a texture that changes (skinning bones, morph weights, a height map) is not tracked that way: its surface moves as the mesh and camera do.
627
+
628
+ `node packages/shader/test/passes-check.mjs` checks these on pixels: a caster moved by a graph against a plain mesh placed there in all four shadow passes, a cut caster against a half-sized one, both normal modes against the analytic normal of a wave, and SSAO's G-buffer pass drawing such a surface.
629
+
630
+ ## Lighting written in the graph (`@margoengine/shader/lighting`)
631
+
632
+ `LightingMaterial` is a `NodeMaterial` that writes its own lighting: toon steps, hatching, a custom BRDF. Shadows, clustered lights and the environment keep working, because the graph reads what those effects worked out. Attach them as for any material.
633
+
634
+ ```ts
635
+ import {createStage} from 'margoengine';
636
+ import {createMesh} from 'margoengine/materials';
637
+ import {sphereGeometry} from 'margoengine/geometry';
638
+ import {Shadows} from 'margoengine/shadows';
639
+ import {Clustered} from 'margoengine/clustered';
640
+ import {floor, max, normalWorld, reflect, viewDirection} from 'margoengine/shader';
641
+ import {LightingMaterial, ambientLight, environment, localLight, sunColor, sunDirection, sunVisibility} from 'margoengine/shader/lighting';
642
+ const stage = await createStage('#app');
643
+ // A BRDF of your own, for the sun and every clustered light: three flat bands.
644
+ const toon = new LightingMaterial({
645
+ color: '#3366ff',
646
+ lightModel: ({normal, direction, color}) => color.mul(floor(max(normal.dot(direction), 0).mul(3).add(0.5)).div(3)),
647
+ });
648
+ // Or the whole pixel: the sun as a band through its shadow, the rest of the light as it is, a mirror's rim on top.
649
+ const inked = new LightingMaterial({
650
+ color: '#ff8000',
651
+ lightingNode: sunColor.mul(sunVisibility).mul(normalWorld.dot(sunDirection).step(0.3).mul(0.25))
652
+ .add(localLight).add(ambientLight)
653
+ .add(environment(reflect(viewDirection.negate(), normalWorld), 0.2).mul(0.1)),
654
+ });
655
+ const shadows = Shadows.attach(stage.engine), lights = Clustered.attach(stage.engine);
656
+ lights.setLights([{position: [0, 2, 1], range: 12, color: [1, 0.3, 0.1], intensity: 20}]);
657
+ for (const material of [toon, inked]) {
658
+ const mesh = createMesh(stage.engine, sphereGeometry(0.8, 32, 16), material);
659
+ shadows.add(mesh);
660
+ lights.add(mesh);
661
+ }
662
+ ```
663
+
664
+ - **`lightModel`** is a function of `{direction, view, normal, color, roughness, metalness}` that returns the light leaving towards the camera, the cosine term included. It replaces the physically based response to the sun and to each clustered point, spot and extra directional light; their colour, falloff and shadows apply around it. Rectangle and disc area lights, ambient and emissive light stay as they are. It compiles to one WGSL function, so stage inputs (`uv()`, `positionLocal`, material nodes) work in it. It runs inside the clustered light loop, where WGSL forbids implicit-derivative reads: sample a texture with an explicit level, or in `lightingNode`.
665
+ - **`lightingNode`** is the final linear colour of the pixel, before fog and tone mapping. It reads:
666
+
667
+ | Node | What it reads | Without the effect |
668
+ | --- | --- | --- |
669
+ | `sunDirection` | unit vector towards the sun | |
670
+ | `sunColor` | the sun's colour times intensity, before shadows | |
671
+ | `sunVisibility` | the shadow effect's result per channel, 0 to 1 | 1 |
672
+ | `localLight` | the sum of the clustered lights, with their shadows | zero |
673
+ | `ambientLight` | ambient light with the material's response: image-based light, probes, the sky | the built-in sky |
674
+ | `litColor` | the colour the material shows with its usual lighting | |
675
+ | `environment(direction, roughness = 0)` | the scene's ambient light on a mirror facing `direction`, also in `lightModel` | the built-in sky |
676
+
677
+ In `lightingNode`, `normalWorld` is the shading normal, after normal maps and `normalNode`. The nodes above other than `environment` are refused in other slots and in `lightModel`, where there is no one sun. Set either option or both; `lightModel` then shapes `litColor`, `localLight` and the sun's share of them. `shading` must stay `'standard'`. An SSAO replay and the G-buffer see `normalNode` and the ambient light as they do on any material.
678
+
679
+ `node packages/shader/test/lighting-check.mjs` checks these against what they read: `sunVisibility` under a real shadow map, Lambert written as a `lightModel` against `shading: 'lambert'` on the sun and a point light, and `litColor`, `localLight` and `ambientLight` against a plain `Material` with the same effects.
680
+
681
+ ## The compute model
682
+
683
+ `ComputePass` runs 1D, 2D or 3D grids, shares memory inside a workgroup, and can take its size from an earlier pass. None of it costs anything in a pass that does not use it. Here each 256-wide workgroup sums its items with a prefix scan:
684
+
685
+ ```ts
686
+ import {ComputePass, Loop, If, Var, globalId, localIndex, storage, uint, workgroup, workgroupBarrier} from 'margoengine/shader';
687
+ import {createStage} from 'margoengine';
688
+ const stage = await createStage('#viewport', {backend: 'webgpu'});
689
+ const values = new Uint32Array(1024).fill(1);
690
+ const input = storage(Uint32Array.from(values), 'u32'), sums = storage(values.length, 'u32');
691
+ const tile = workgroup(256, 'u32');
692
+ ComputePass.attach(stage.engine, values.length, i => { // values.length: a multiple of 256, as it has barriers
693
+ tile.store(localIndex, input.element(i));
694
+ workgroupBarrier();
695
+ const step = Var(uint(1));
696
+ Loop(8, () => {
697
+ const mine = Var(tile.element(localIndex));
698
+ If(localIndex.greaterThanEqual(step), () => mine.addAssign(tile.element(localIndex.sub(step))));
699
+ workgroupBarrier(); // everyone has read
700
+ tile.store(localIndex, mine);
701
+ workgroupBarrier(); // everyone has written
702
+ step.mulAssign(uint(2));
703
+ });
704
+ return sums.store(i, tile.element(localIndex));
705
+ }, {workgroupSize: 256});
706
+
707
+ const image = storage(640 * 480, 'vec4f');
708
+ ComputePass.attach(stage.engine, [640, 480], i => image.store(i, globalId.toFloat().xyzz)); // 2D: i runs row by row
709
+
710
+ const args = storage(new Uint32Array([0, 1, 1]), 'u32'); // workgroups x, y, z, written by an earlier pass
711
+ ComputePass.attach(stage.engine, 1, () => args.store(0, sums.element(0).div(64).add(1)));
712
+ ComputePass.attach(stage.engine, 1 << 20, i => image.store(i, globalId.toFloat().xyzz), {indirect: args, order: -99});
713
+ ```
714
+
715
+ - **Grids.** `count` is a number, `[x, y]` or `[x, y, z]`; invocations past it return at once. The body's `i` numbers them row by row. `workgroupSize` takes the same forms, at most 256 invocations and 64 along z; the default is 64, `[8, 8]` or `[4, 4, 4]`. `globalId` (vec3u) is the position in the grid.
716
+ - **Inside a workgroup.** `localId`, `localIndex`, `workgroupId` and `workgroupCount` are the WGSL built-ins. `workgroup(count, type, {atomic})` declares memory the group shares; `.element(i)`, `.store(i, v)` (here and now, unlike a storage `store` at the top of a body) and `.uniformLoad(i)` use it.
717
+ - **Barriers.** `workgroupBarrier()`, `storageBarrier()` and `textureBarrier()`. Every invocation must reach one, so a pass with a barrier has no early return and its `count` must be a multiple of `workgroupSize`, or it throws. A barrier under a branch that differs between invocations is a WGSL uniformity error when the pipeline compiles; `uniformLoad` gives a value the group agrees on. Storage writes made before a barrier at the top of a body happen before it.
718
+ - **Atomics.** On storage and workgroup memory: `atomicAdd`, `atomicSub`, `atomicMax`, `atomicMin`, `atomicAnd`, `atomicOr`, `atomicXor`, `atomicExchange` (each returns the previous value), `atomicLoad`, `atomicStore`, and `atomicCompareExchange(i, compare, value)`, which returns `{old, exchanged}`. It is WGSL's weak form: it may fail when the values are equal, so retry on `exchanged`.
719
+ - **Indirect.** `{indirect: buffer, indirectOffset}` reads three u32 workgroup counts from a storage buffer at dispatch. `count` stays the limit of the guard, and the 65,535 groups check does not apply to it.
720
+
721
+ `node packages/shader/test/compute-model-check.mjs` checks each of these against a CPU result: a 1,024-item scan, 13 x 7 and 5 x 3 x 6 grids with the cells past the count left alone, an indirect dispatch sized by the pass before it, 256 invocations through every atomic including a compare-and-swap maximum, and a workgroup histogram.
722
+
723
+ ## Subgroups and half floats (`@margoengine/shader/subgroups`)
724
+
725
+ WebGPU's two optional compute features as nodes. Each comes from a function of the engine, which writes the fast WGSL when
726
+ the device has the feature and portable WGSL when it does not, so one graph runs everywhere. Ask for the features when you
727
+ create the engine; an adapter that lacks one simply leaves it out.
728
+
729
+ ```ts
730
+ import {createStage} from 'margoengine';
731
+ import {ComputePass, If, Let, storage} from 'margoengine/shader';
732
+ import {halfFloats, subgroups} from 'margoengine/shader/subgroups';
733
+ const stage = await createStage('#app', {features: ['subgroups', 'shader-f16']});
734
+ const sg = subgroups(stage.engine), h = halfFloats(stage.engine);
735
+
736
+ const values = storage(new Uint32Array(1024).fill(3), 'u32'), total = storage(1, 'u32', {atomic: true});
737
+ ComputePass.attach(stage.engine, 1024, i => {
738
+ const sum = Let(sg.add(values.element(i))); // all lanes at once, kept before any branch
739
+ If(sg.elect(), () => { total.atomicAdd(0, sum); }); // one atomic per subgroup, not one per invocation
740
+ });
741
+
742
+ const input = storage(new Float32Array(1024).fill(0.5), 'f32'), output = storage(1024, 'f32');
743
+ ComputePass.attach(stage.engine, 1024, i => output.store(i, h.full(h.half(input.element(i)).mul(0.25).add(1))));
744
+ console.log(sg.supported, h.supported);
745
+ ```
746
+
747
+ | Node | What each lane gets | With no `subgroups` feature |
748
+ | --- | --- | --- |
749
+ | `sg.size`, `sg.id` | lanes in this subgroup, this lane's number | `1`, `0` |
750
+ | `sg.add`, `mul`, `min`, `max`, `and`, `or`, `xor` | the reduction over the lanes | `x` |
751
+ | `sg.inclusiveAdd`, `inclusiveMul` | the reduction up to and including this lane | `x` |
752
+ | `sg.exclusiveAdd`, `exclusiveMul` | the reduction over the lanes before this one | `0`, `1` |
753
+ | `sg.all(b)`, `sg.any(b)` | whether `b` holds on every lane, on any lane | `b` |
754
+ | `sg.ballot(b)` | a bit per lane where `b` holds | `b` as bit 0 |
755
+ | `sg.elect()` | true on one lane | `true` |
756
+ | `sg.broadcast(x, lane)`, `sg.broadcastFirst(x)` | `x` of that lane, a constant, or the first active lane | `x` |
757
+ | `sg.shuffle(x, lane)`, `shuffleUp`, `shuffleDown`, `shuffleXor` | `x` of another lane | `x` |
758
+
759
+ - **The fallback is a subgroup of one lane.** WebGPU never promises a subgroup size, so code written properly works for any
760
+ `size`, and one is a size: nothing to branch on, no shared memory, and the same answer at the end. Lanes of a `shuffle`
761
+ must stay below `size`.
762
+ - **Uniform control flow.** A subgroup call has to run on every lane together, so a ComputePass that uses one runs whole
763
+ workgroups as a barrier does: its count is a multiple of `workgroupSize`, and WGSL refuses a call under a branch. Keep a
764
+ result with `Let` before an `If`.
765
+ - **Half floats.** `h.half(x)` gives an f16 node (`'f16'`, `'vec2h'` to `'vec4h'`) and `h.full(x)` turns it back. Numbers join in
766
+ as `0.25h`, and an f32 node has to go through `half` first, which TypeScript checks. Without `shader-f16` the same graph
767
+ stays f32, so a value keeps more precision and goes past 65,504 without turning infinite.
768
+ - **Packed storage.** `packHalf2(vec2)` and `unpackHalf2(u32)` hold two floats rounded to f16 in one u32 on every device.
769
+ Storage buffers have no f16 element type.
770
+
771
+ ## Compute that writes textures (`@margoengine/shader/compute-texture`)
772
+
773
+ `storageTexture` is a texture a ComputePass writes; `pingPong` is a pair that a pass reads and writes in steps, for simulations, painting and repeated filters. Both work with `texture()`, so a material, NodePass or later pass reads them like any other texture.
774
+
775
+ ```ts
776
+ import {createStage} from 'margoengine';
777
+ import {createMesh} from 'margoengine/materials';
778
+ import {planeGeometry} from 'margoengine/geometry';
779
+ import {ComputePass, NodeMaterial, texture, vec2, vec4} from 'margoengine/shader';
780
+ import {pingPong} from 'margoengine/shader/compute-texture';
781
+ const stage = await createStage('#app');
782
+ const grid = pingPong(256, 256); // rgba16float, zeros
783
+ ComputePass.attach(stage.engine, grid.pixels, i => {
784
+ const at = grid.coord(i), p = grid.uv(at), step = vec2(1 / 256, 0);
785
+ const blur = texture(grid, p.sub(step), 0).add(texture(grid, p.add(step), 0)).mul(0.5); // filtered reads of last step
786
+ return grid.store(at, blur.mul(0.99).add(vec4(p.x.mul(0.01)))); // writes the next
787
+ });
788
+ createMesh(stage.engine, planeGeometry(2, 2), new NodeMaterial({shading: 'basic', colorNode: texture(grid).rgb}));
789
+ ```
790
+
791
+ - **Formats.** All 16 that every WebGPU device can write: `rgba8unorm`, `rgba8snorm`, `rgba8uint`, `rgba8sint`, `rgba16float` (default), `rgba16uint`, `rgba16sint`, and `r32`, `rg32`, `rgba32` in `float`, `uint` and `sint`. `load` and `store` use `vec4f`, `vec4u` or `vec4i` to match. `texture()` works on `rgba8unorm`, `rgba8snorm`, `rgba16float`, and on 32-bit floats where the device has `float32-filterable`; other formats throw a MargoError `'unsupported'` when bound, and `load` reads them.
792
+ - **The pair.** `load` and `texture()` read the front image; `store` writes the back one. A pass that stores swaps the pair after its dispatch, so two passes in a frame run as two steps, and a pass that only reads swaps nothing. `swap()` does it by hand. The back image holds the step before last, so write every texel you want kept.
793
+ - **One texture, one role per pass.** A pass reads or writes a `storageTexture`, because WebGPU refuses both in one dispatch; doing both throws when the pass is built. For r32 formats, `{readWrite: true}` allows it in place, each invocation on its own texels; it needs the browser's WGSL feature `readonly_and_readwrite_storage_textures` and throws a MargoError `'unsupported'` without it. Reads and writes of different invocations are not ordered: use `pingPong` for neighbours.
794
+ - **Helpers.** `t.pixels` is the count for one invocation per texel, `t.coord(i)` the texel of invocation `i`, and `t.uv(coord)` its centre as 0..1. `store` runs where it is made, also inside `If` and `Loop`. Options: `data` (first contents, and what a device loss restores), `filter`, `wrap`.
795
+ - **Baking.** `t.texture(device)` is the GPUTexture to copy from. To get texels on the CPU, read them through `computeReadback`: `computeReadback(engine, t.pixels, i => out.store(i, t.load(t.coord(i))), out)`.
796
+ - **Lifecycle.** `dispose()` (or `using`) destroys the GPU copies; the next use makes them again from `data`, as a device loss does. What compute wrote is not kept across either.
797
+
798
+ `node packages/shader/test/compute-texture-check.mjs` (real GPU): eight generations of Conway's life on a 32 x 32 pair equal a CPU run, a material follows the pair as it swaps, all 16 formats write and read back through a second pass, a blur sampling in compute gives exact thirds, and in-place r32float counts to 3.
799
+
800
+ ## GLSL functions (`@margoengine/shader/glsl`, 18.2 kB min+gzip on its own)
801
+
802
+ Bring GLSL you already have. `glslFn` turns a GLSL ES 3.00 or 1.00 function (with the helpers, structs and constants
803
+ it uses) into a node function, as `wgslFn` does for WGSL. It is translated to WGSL once, so the same source runs on
804
+ WebGPU and on the WebGL2 layer: there is no second copy to keep in step. `toGLSL` goes the other way: the GLSL ES 3.00
805
+ program the WebGL2 layer makes from a `NodePass`, a `NodeMaterial` that has drawn, or WGSL stages.
806
+
807
+ ```ts
808
+ import {createStage} from 'margoengine';
809
+ import {createMesh, Texture} from 'margoengine/materials';
810
+ import {planeGeometry} from 'margoengine/geometry';
811
+ import {NodeMaterial, NodePass, time, uv} from 'margoengine/shader';
812
+ import {glslFn, toGLSL} from 'margoengine/shader/glsl';
813
+ const stage = await createStage('#app');
814
+ const tint = glslFn<'vec3f'>(`vec3 tint(vec3 c, float t) { return mix(c, c.bgr, t); }`);
815
+ const checker = new Texture({data: new Uint8Array([255, 255, 255, 255, 40, 40, 40, 255, 40, 40, 40, 255, 255, 255, 255, 255]), width: 2, height: 2});
816
+ const tiles = glslFn<'vec4f'>(`#version 300 es
817
+ vec4 tiles(sampler2D map, vec2 uv, float count) {
818
+ vec2 cell = fract(uv * count);
819
+ return texture(map, uv * count) * (0.75 + 0.25 * step(0.5, cell.x));
820
+ }`);
821
+ const material = new NodeMaterial({colorNode: tint(tiles(checker, uv(), 4).rgb, time.sin().mul(0.5).add(0.5))});
822
+ createMesh(stage.engine, planeGeometry(2, 2), material);
823
+ const program = toGLSL(new NodePass(tiles(checker, uv(), 4)), await import('margoengine/webgl2-compat/glsl'));
824
+ console.log(program.fragment.source); // GLSL ES 3.00, with program.fragment.textures and .uniforms
825
+ ```
826
+
827
+ - Arguments: a node or a number per scalar or vector parameter (a boolean for `bool`), a node for a matrix, and a
828
+ `Texture` from `@margoengine/materials` of the matching dimension for a sampler. A texture that `texture()` also
829
+ reads binds once.
830
+ - Options: `name` picks the function to call (default: the last one defined), `defines` adds `#define` lines,
831
+ `flipY: true` flips y at every 2D lookup and `texelFetch` for code written for a bottom-left image origin, and
832
+ `strict: true` keeps WGSL's derivative uniformity rule. By default translated functions turn that rule off, so an
833
+ implicit `texture()` inside a branch on a per-pixel value compiles, as GLSL allows.
834
+ - Lookups in vertex or compute nodes read level 0, as `texture()` nodes do. A source without `#version` reads as
835
+ GLSL ES 3.00; `#version 100` and `#version 300 es` are accepted.
836
+ - Errors are MargoError `failed` with `line` and `column` (1-based, in your source) and a help link. A uniform or a
837
+ `gl_` built-in inside the function is refused with "pass it as an argument". Translation is cached per source,
838
+ options and stage (256 entries).
839
+ - `glslToWGSL(code, options)` returns the WGSL, the entry name, the parameters and the result type, for tools.
840
+ - `toGLSL(target, translator, options)` takes the layer's translator as its second argument, so this entry never loads
841
+ the 44 kB layer itself; `options` are the layer's (`clipControl`, `points`, `uniformBlockSize`,
842
+ `accurateInverseTrig`). A `NodeMaterial` that has not drawn yet throws MargoError `state`.
843
+
844
+ `node packages/shader/test/glsl-check.mjs` and `node packages/shader/test/glsl-check.mjs --compat` (real GPU) run every fixture of `test/glsl-fixtures.js` as written in the browser's own WebGL2 compiler and as `glslFn`
845
+ in a NodePass: within 1 level per channel on every pixel, natively and on the layer. NodeMaterials built from GLSL
846
+ match the same graphs written in WGSL and `texture()`, and every `toGLSL` program compiles and links in raw WebGL2.
847
+
848
+ ## Raw shaders (`@margoengine/shader/raw`, 15.2 kB min+gzip)
849
+
850
+ Your own WGSL vertex and fragment
851
+ entry points, any named attributes per vertex or per instance, live uniforms, textures and storage buffers, drawn into the
852
+ scene's colour and depth. Raw meshes also cast shadows, write SSAO's G-buffer, are culled and are picked like other meshes.
853
+
854
+ ```ts
855
+ import {RawShaders, RawShaderMaterial, RawMesh} from 'margoengine/shader/raw';
856
+ import {loadTexture} from 'margoengine/materials';
857
+ import {createStage} from 'margoengine';
858
+ const stage = await createStage('#viewport', {backend: 'webgpu'});
859
+ const raw = RawShaders.attach(stage.engine);
860
+ const texture = await loadTexture('/map.png');
861
+ const positions = new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]), colors = new Float32Array(9).fill(1), uvs = new Float32Array(6);
862
+ const indices = new Uint16Array([0, 1, 2]), offsets = new Float32Array(15 * 3);
863
+ const material = new RawShaderMaterial({
864
+ vertexShader: `
865
+ struct Out { @builtin(position) clip:vec4f, @location(0) color:vec3f, @location(1) uv:vec2f }
866
+ @vertex fn vertex(a:Attributes)->Out {
867
+ let lift = sin(camera.time + a.offset.x) * uniforms.wave;
868
+ return Out(camera.viewProjection * mesh.world * vec4f(a.position + a.offset + vec3f(0.0, lift, 0.0), 1.0), a.color, a.uv);
869
+ }
870
+ @fragment fn fragment(i:Out)->@location(0) vec4f {
871
+ return margoDisplay(vec4f(i.color * uniforms.tint * textureSample(map, mapSampler, i.uv).rgb, 1.0)); // lit like the scene
872
+ }`,
873
+ uniforms: {wave: {value: 0.2}, tint: {value: '#ff8800'}}, // f32 to vec4f, i32/u32 variants, mat3x3f, mat4x4f
874
+ textures: {map: texture}, // a materials Texture, GPUTexture or GPUTextureView, or (device) => texture;
875
+ // {texture, sampler, dimension, sampleType} as a plain object adds options
876
+ });
877
+ const mesh = raw.add(new RawMesh({
878
+ material,
879
+ attributes: {
880
+ position: {data: positions, type: 'vec3f'},
881
+ color: {data: colors, type: 'vec3f'},
882
+ uv: {data: uvs, type: 'vec2f'},
883
+ offset: {data: offsets, type: 'vec3f', step: 'instance'}, // one per instance; the instance count follows it
884
+ },
885
+ index: indices,
886
+ }));
887
+ material.uniforms.wave.value = 0.5; // live, never recompiles
888
+ mesh.setAttribute('offset', offsets, [10, 5]); // uploads instances 10..14 only
889
+ material.transparent = true; // render state is live too (a new pipeline compiles once)
890
+ ```
891
+
892
+ - **The prelude.** Each stage's module is a short prelude, then your code (`material.code('vertex', mesh)` shows it). It
893
+ declares `camera` (`view`, `projection`, `viewProjection`, `position`, `time`, `resolution`, the target size,
894
+ `deltaTime`, and `viewport`, the drawn view as x, y, width and height in target pixels), `mesh`
895
+ (`world`, and `normal`, the inverse transpose of its 3x3), `struct Attributes` with one `@location` per attribute in
896
+ the order given, `uniforms.<name>` (the WGSL layout is computed for you), each texture as `<name>` plus
897
+ `<name>Sampler`, each storage buffer as `<name>`, and two colour helpers. Fragment output is written exactly as returned (raw); `margoDisplay(c)`
898
+ applies the scene's display transform (PBR Neutral and sRGB on a display target, nothing inside an HDR PostStack
899
+ capture, which tonemaps later) and `margoEncode(c)` only the sRGB encoding, for unlit colour as lines and points write
900
+ it. With a separate `fragmentShader` each stage is its own module, so both may use `main`.
901
+ - **Arrays and structs.** `count` makes a uniform array, `struct` a uniform struct, and both together an array of structs.
902
+ An array's value is a list of elements or all their numbers in a row. Elements of a uniform array sit 16 bytes apart, so
903
+ the element is a vec3, a vec4, a matrix or a struct; a list of `f32` or `vec2f` belongs in a storage buffer, and the
904
+ material says so when it refuses one. A struct field is a plain uniform type, a nested struct (`{struct: {...}}`, read as
905
+ `uniforms.light.falloff.near`) or an array (`{type, count}` or `{count, struct}`), nested as deep as you like; each
906
+ sits at its WGSL uniform layout offset, every generated struct aligned to 16 bytes:
907
+ `{struct: {gain: 'f32', inner: {struct: {tint: 'vec3f'}}, rows: {type: 'vec4f', count: 2}}, value: {gain: 1, inner: {tint: [1, 0, 0]}, rows: [[0, 0, 0, 1], [0, 0, 0, 1]]}}`.
908
+ - **Storage buffers and bind groups.** `storage: {name: buffer}` declares `<name>:array<type>`. Pass a `storage()` node as
909
+ it is, so a compute pass fills what the mesh draws, or `{buffer, type, access}` with your own GPUBuffer (or a function of
910
+ the device, which also serves device restoration; a plain buffer is lost with its device, so the material binds a zeroed
911
+ stand-in and `engine.onError` hears of it once, see Device restore below). `type` may be a struct your code declares, in every stage that reads
912
+ the buffer. `'read_write'` binds to the fragment stage only, as WebGPU requires. `groups` adds up to two bind groups at
913
+ `@group(2)` and `@group(3)` for bindings your WGSL declares; each is a function of the device.
914
+ - **Device restore.** A texture or storage buffer you made belongs to the device that made it. Give `textures` a
915
+ `(device) => GPUTexture | GPUTextureView` and it is made once per device, so it is back after `engine.rebootDevice()`;
916
+ `ShaderMaterial` sampler uniforms take the same function. A plain GPUTexture, view or buffer is lost with its device: the
917
+ binding reads opaque white (a storage buffer reads a zeroed stand-in), `engine.onError` hears of it once (`'state'`,
918
+ [#borrowed-lost](https://margoengine.com/errors#borrowed-lost)), the frame keeps drawing, and assigning a new one to
919
+ `material.textures.<name>.texture` or `material.storage.<name>.buffer` brings it back.
920
+ - **Geometry.** Attribute types are `f32`, `vec2f` to `vec4f` and the `i32`/`u32` variants, up to 16 attributes;
921
+ per-vertex and per-instance attributes are each interleaved into one buffer. `setAttribute(name, data, [first,
922
+ count])` uploads only that element range; new lengths grow the buffer; `{data, type, step}` adds or retypes an
923
+ attribute (new layout, new pipeline). Optional index (`Uint16Array`, `Uint32Array` or numbers), `instanceCount`,
924
+ `vertexCount` (no attributes: vertex pulling), `topology`, `drawRange`. `matrix` is the model matrix; `mesh: coreMesh`
925
+ follows a core mesh (world = its world matrix x `matrix`) and hides with it.
926
+ - **Shared buffers.** Meshes whose packed vertex, instance or index bytes are equal hold one GPU buffer, counted per
927
+ device, so 10,000 boxes built from one geometry upload it once and a run of them binds it once. Nothing to set:
928
+ `new RawMesh({material, attributes, index})` with the same data is enough. A mesh leaves on its first write
929
+ (`setAttribute`, `setIndex`), and the others keep drawing the old bytes. Each shared buffer keeps a CPU copy of its
930
+ bytes to compare new meshes with, until its meshes have left it.
931
+ - **Render state.** `transparent` (drawn after the opaque scene, sorted back to front by distance), `blending`
932
+ (`'normal'` blends only when transparent; `'additive'`, `'multiply'`, `'premultiplied'`, `'none'` or a
933
+ `GPUBlendState`), `depthTest` (reversed-Z `greater-equal`), `depthWrite`, `cull` (`'back'`, `'front'`, `'none'`),
934
+ `colorWrite`; per mesh `renderOrder` and `visible`.
935
+ - **The pass.** Opaque raw meshes draw at frame-graph order 0.5 (after core meshes, before gltf/pbr and materials meshes
936
+ at 1), transparent ones at 7 (after water, sky and particles, before OIT at 8 and lines at 20);
937
+ `new RawShaders({opaqueOrder, transparentOrder})` moves them. Each draws into the pass's own colour and depth targets
938
+ with their format and MSAA sample count, so 1x/4x and a PostStack's HDR capture just work.
939
+ - **Compiling and errors.** Pipelines compile asynchronously and draw from the next frame on (`await raw.ready()` before a
940
+ one-off `engine.render()`). A WGSL error is a MargoError `'failed'` naming the stage and line in your code, set on
941
+ `material.error` and passed to `material.onError` (default `console.error`); only that draw is skipped. Assigning
942
+ `vertexShader` or `fragmentShader` recompiles.
943
+ - **Lifecycle.** `mesh.dispose()` frees its buffers and leaves the plugin; `material.dispose()` frees its uniforms and
944
+ pipelines (rebuilt if drawn again); `engine.removePlugin('shader:raw')` frees everything and keeps the meshes. Device
945
+ restoration rebuilds everything from the CPU copies; a materials Texture rebinds itself, a GPUTexture from the lost
946
+ device draws white with a warning until you assign a new one.
947
+
948
+ ### Shadows, SSAO, culling and picking
949
+
950
+ ```ts
951
+ import {createStage} from 'margoengine';
952
+ import {SSAO} from 'margoengine/post/ssao';
953
+ import {Picking} from 'margoengine/selection';
954
+ import {Shadows} from 'margoengine/shadows';
955
+ import {RawMesh, RawPicking, RawShaderMaterial, RawShaders} from 'margoengine/shader/raw';
956
+ const stage = await createStage('#app');
957
+ const engine = stage.engine, raw = RawShaders.attach(engine);
958
+ const material = new RawShaderMaterial({
959
+ vertexShader: `
960
+ struct Out {@builtin(position) clip:vec4f, @location(0) world:vec3f, @location(1) normal:vec3f}
961
+ @vertex fn vertex(a:Attributes)->Out {
962
+ let w = mesh.world * vec4f(a.position, 1);
963
+ return Out(camera.viewProjection * w, w.xyz, normalize(mesh.normal * a.normal));
964
+ }
965
+ @fragment fn gbuffer(i:Out)->MargoGBuffer {return margoGBuffer(i.normal, i.world, vec3f(0.3));}
966
+ @fragment fn fragment(i:Out)->@location(0) vec4f {return margoDisplay(vec4f(vec3f(0.3) + i.normal.y * 0.5, 1));}`,
967
+ gbufferEntry: 'gbuffer',
968
+ });
969
+ const mesh = raw.add(new RawMesh({
970
+ material,
971
+ attributes: {
972
+ position: {data: [-1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0], type: 'vec3f'},
973
+ normal: {data: [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1], type: 'vec3f'},
974
+ },
975
+ index: [0, 1, 2, 0, 2, 3],
976
+ }));
977
+ Shadows.attach(engine).add(mesh); // casts through your vertex shader
978
+ SSAO.attach(engine).add(raw); // meshes with gbufferEntry write their own normals
979
+ const picking = RawPicking.attach(Picking.attach(engine), raw); // engine.pick now answers raw meshes
980
+ await raw.ready();
981
+ const hit = await engine.pick(200, 150);
982
+ console.log(picking.rawOf(hit) === mesh);
983
+ ```
984
+
985
+ - **Shadows.** `shadows.add(mesh)` draws the mesh into every cascade of `Shadows` with your vertex stage, where
986
+ `camera.viewProjection` and `camera.projection * camera.view` are the cascade's light matrix. Both sides cast, whatever
987
+ the material's `cull`, as in the depth pass of every other caster. Your fragment stage runs
988
+ too when its code holds `discard`, so a cut-out shape casts a cut-out shadow. Transparent materials cast none.
989
+ `virtualShadows.add(mesh)` (`@margoengine/shadows/virtual`) and `localShadows.add(mesh)`
990
+ (`@margoengine/clustered/shadows`, point, spot, extra directional and area lights) cast the same way, and so does
991
+ Clustered's `addShadowCaster(mesh)` for its integrated `shadows` maps, which call the hook with forward depth
992
+ (`depthCompare: 'less-equal'`) and redraw every frame. `LocalShadows`
993
+ and `{static: true}` keep a raw caster's maps until `mesh.shadowVersion` changes: new attributes or indices, a newly
994
+ compiled pipeline, another material, new uniform values, or a moved mesh (its `matrix` or the core mesh it follows).
995
+ A vertex stage that moves points by `camera.time`, a texture or a storage buffer needs `mesh.invalidateShadow()` when
996
+ they change, or `localShadows.add(mesh, {dynamic: true})`. A raw shader receives no shadow unless it samples one
997
+ itself. `packages/shadows/test/cutout-casters-browser.mjs` checks a whole and a `discard`-cut raw quad in all four
998
+ passes and the cached maps following a move and a uniform, on WebGPU and the WebGL2 layer.
999
+ - **TAA.** A raw shader's motion is its own code, so TAA sees only a raw mesh's depth and the camera's motion, and a
1000
+ shape the shader moves ghosts. Give the material `velocityEntry`: a `@vertex fn` beside your vertex entry, with the same
1001
+ inputs, that returns `margoVelocity(position, positionBefore)`, where the vertex is now and where it was last frame, both
1002
+ before `mesh.world`. It may read `margoBefore.time` (last frame's `camera.time`) and `margoBefore.world`; keep last
1003
+ frame's value of any uniform your move reads beside it. The velocity pass draws with `depthCompare: 'equal'` against
1004
+ your vertex entry's depth, so compute the position there with the same expression `margoVelocity` uses
1005
+ (`camera.viewProjection * mesh.world * vec4f(p, 1)`) and declare it `@invariant`, as `MargoVelocity` does: WGSL lets
1006
+ two programs round the same expression differently otherwise (WGSL 12.10), and a pixel then gets no motion. The motion itself is taken from both positions relative to this frame's eye (TAA's `relative` matrices, in
1007
+ `margoBefore.relativeCurrent`, `relativePrevious` and `origin`), so a still mesh 1.6 km from the origin reads no motion
1008
+ from float32 rounding; `margoVelocity` fills `MargoVelocity`'s `current` for you. A GLSL material's velocity uses its
1009
+ own matrices for both positions, so it keeps that rounding far from the origin. Then `taa.add(raw)`: opaque meshes with the entry draw their
1010
+ motion into TAA's velocity pass, with last frame kept per TAA view. Without the entry nothing changes.
1011
+
1012
+ ```ts
1013
+ import {EngineKernel} from 'margoengine/core';
1014
+ import {TAA} from 'margoengine/taa';
1015
+ import {RawMesh, RawShaderMaterial, RawShaders} from 'margoengine/shader/raw';
1016
+ const engine = await EngineKernel.create(document.querySelector<HTMLCanvasElement>('#viewport')!, {backend: 'webgpu'});
1017
+ const raw = RawShaders.attach(engine), taa = TAA.attach(engine);
1018
+ const material = new RawShaderMaterial({
1019
+ vertexShader: `
1020
+ fn wave(p:vec3f, t:f32)->vec3f {return p + vec3f(0, sin(p.x * 3 + t) * 0.2, 0);}
1021
+ @vertex fn vertex(a:Attributes)->@builtin(position) @invariant vec4f {
1022
+ return camera.viewProjection * mesh.world * vec4f(wave(a.position, camera.time), 1);
1023
+ }
1024
+ @vertex fn velocity(a:Attributes)->MargoVelocity {
1025
+ return margoVelocity(wave(a.position, camera.time), wave(a.position, margoBefore.time));
1026
+ }
1027
+ @fragment fn fragment()->@location(0) vec4f {return margoDisplay(vec4f(0.2, 0.5, 0.9, 1));}`,
1028
+ velocityEntry: 'velocity',
1029
+ cull: 'none',
1030
+ });
1031
+ raw.add(new RawMesh({
1032
+ material,
1033
+ attributes: {position: {data: [-1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0], type: 'vec3f'}},
1034
+ index: [0, 1, 2, 0, 2, 3],
1035
+ }));
1036
+ taa.add(raw); // the waving quad writes its own motion
1037
+ ```
1038
+
1039
+ - **SSAO.** Opaque raw meshes occlude from their depth with nothing to set, like every mesh, and their pixels are not
1040
+ darkened. `ssao.add(raw)` with `gbufferEntry` on a material goes further: that `@fragment fn` returns
1041
+ `margoGBuffer(worldNormal, worldPosition, ambient)`, SSAO uses your normals, and `ambient` is the light it may take away.
1042
+ `GTAO` takes the same source (`gtao.add(raw)`), as it shares SSAO's G-buffer.
1043
+ - **SSR and SSGI.** Opaque raw meshes hide what is behind them in SSR's and SSGI's depth with nothing to set, and neither
1044
+ reflect nor take bounced light. `ssr.add(raw)`, `ssgi.add(raw)`, `targets.add(raw)` (`@margoengine/post/mrt`), `bounce.add(raw)` (`@margoengine/clustered`) and `pass.add(raw)` (a node `ScenePass`) with `captureEntry` on a material go further: that
1045
+ `@fragment fn` returns `margoCapture(MargoMaterial(worldPosition, worldNormal, toEye, baseColor, metallic, roughness,
1046
+ ambient))`, SSR reflects the screen in the surface by its normal, metallic and roughness, and SSGI adds the light bounced
1047
+ onto it by its normal and diffuse albedo (`ambient` is the ambient light your colour fragment added, which SSGI's bounce
1048
+ stands in for; `vec3f(0)` when it added none). In the capture pass meshes without the entry still write their depth, with
1049
+ their own `discard`s. `packages/shader/test/raw-check.mjs` (`ssrOwn`, `ssgiOwn`, `gtaoOwn`) checks each against the same
1050
+ mesh without the entry, on WebGPU and the WebGL2 layer.
1051
+ - **Node ScenePass.** In a `ScenePass` the capture entry's `color` output is the material's base colour. To write
1052
+ another output, declare `var<private> margoOut<name>:vec4f;` in your fragment code and assign it in the entry before it
1053
+ returns (`margoOutglow = vec4f(1, 0, 0, 1);` for an output `glow`); declare `var<private> margoBeauty:vec4f;` and
1054
+ assign it to give `color` your own lit colour. Outputs the entry leaves alone read as transparent black.
1055
+ `raw-check.mjs` (`passOwn`, `passDepth`) checks it on both backends.
1056
+
1057
+ ```ts
1058
+ import {createStage} from 'margoengine';
1059
+ import {SSR} from 'margoengine/post/ssr';
1060
+ import {RawMesh, RawShaderMaterial, RawShaders} from 'margoengine/shader/raw';
1061
+ const stage = await createStage('#app');
1062
+ const raw = RawShaders.attach(stage.engine);
1063
+ const floor = new RawShaderMaterial({
1064
+ vertexShader: `
1065
+ struct Out {@builtin(position) clip:vec4f, @location(0) world:vec3f, @location(1) normal:vec3f}
1066
+ @vertex fn vertex(a:Attributes)->Out {
1067
+ let w = mesh.world * vec4f(a.position, 1);
1068
+ return Out(camera.viewProjection * w, w.xyz, normalize(mesh.normal * a.normal));
1069
+ }
1070
+ @fragment fn capture(i:Out)->MargoCapture {
1071
+ return margoCapture(MargoMaterial(i.world, i.normal, camera.position - i.world, vec3f(0.9), 1.0, 0.05, vec3f(0)));
1072
+ }
1073
+ @fragment fn fragment(i:Out)->@location(0) vec4f {return vec4f(0.05, 0.05, 0.05, 1);}`,
1074
+ fragmentEntry: 'fragment',
1075
+ captureEntry: 'capture',
1076
+ });
1077
+ raw.add(new RawMesh({
1078
+ material: floor,
1079
+ attributes: {
1080
+ position: {data: [-3, 0, 3, 3, 0, 3, 3, 0, -3, -3, 0, -3], type: 'vec3f'},
1081
+ normal: {data: [0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0], type: 'vec3f'},
1082
+ },
1083
+ index: [0, 1, 2, 0, 2, 3],
1084
+ }));
1085
+ SSR.attach(stage.engine).add(raw); // the raw floor is a mirror of what the screen holds
1086
+ ```
1087
+
1088
+ - **Culling.** A mesh out of view is skipped in the colour, shadow, SSAO and pick passes, and counted in `raw.stats.culled`.
1089
+ The sphere comes from a per-vertex vec3f `position`. A mesh with no such attribute, or an instanced one, is never culled
1090
+ unless you give `bounds: {center, radius}`. A vertex shader that moves points outside that sphere needs `bounds` or
1091
+ `frustumCulled: false`.
1092
+ - **Picking.** `RawPicking.attach(picking, raw)` draws the meshes into the pick tile after the scene's meshes, in the same
1093
+ depth test, with your vertex stage, so a mesh is picked where it shows. `hit.mesh` is the core mesh it follows or an empty
1094
+ stand-in, and `picking.rawOf(hit)` gives the RawMesh back. One ID covers a mesh, so a hit names no instance, and a
1095
+ fragment's `discard` does not cut the pick.
1096
+
1097
+ Measured on an NVIDIA Ampere GPU (Edge, 4x and 1x MSAA) by `node scripts/shader-raw-gpu-check.js`:
1098
+ a quad with a per-vertex colour attribute and a per-instance offset and `u32` id matches its analytic colours within 0.55
1099
+ of 255 over 5,225 pixels, is hidden pixel for pixel behind a core box and drawn in front of it, live uniforms and a ranged
1100
+ `setAttribute` update it, device restoration redraws identical pixels, and an attached plugin with nothing visible or a
1101
+ removed one leaves every pixel unchanged.
1102
+
1103
+ ## GLSL programs as materials (`@margoengine/shader/glsl-material`, 35.6 kB min+gzip on its own, `RawMesh` included)
1104
+
1105
+ Paste a whole GLSL program, as a web engine's `RawShaderMaterial` takes one: a GLSL ES 3.00 or 1.00 vertex and fragment
1106
+ stage with `void main()`, your own `uniform`s, attributes and varyings. `ShaderMaterial` translates it to WGSL once per
1107
+ source and defines, with the same GLSL front end as `glslFn`, so one GLSL source draws on WebGPU and on the WebGL2
1108
+ layer. It is a `RawShaderMaterial`, so it draws with a `RawMesh` in the `RawShaders` plugin and keeps that render state.
1109
+
1110
+ ```ts
1111
+ import {createStage} from 'margoengine';
1112
+ import {RawShaders, RawMesh} from 'margoengine/shader/raw';
1113
+ import {ShaderMaterial, glslProgramToWGSL} from 'margoengine/shader/glsl-material';
1114
+ const stage = await createStage('#viewport', {controls: false});
1115
+ const raw = RawShaders.attach(stage.engine);
1116
+ const vertexShader = `#version 300 es
1117
+ in vec2 position;
1118
+ out vec2 vUv;
1119
+ void main() { vUv = position * 0.5 + 0.5; gl_Position = vec4(position, 0.0, 1.0); }`;
1120
+ const fragmentShader = `#version 300 es
1121
+ precision highp float;
1122
+ in vec2 vUv;
1123
+ uniform float time;
1124
+ uniform vec3 tint;
1125
+ uniform bool stripes;
1126
+ out vec4 color;
1127
+ void main() {
1128
+ float wave = 0.5 + 0.5 * sin(time + vUv.x * 12.0);
1129
+ color = vec4(tint * (stripes ? wave : 1.0), 1.0);
1130
+ }`;
1131
+ const material = new ShaderMaterial({
1132
+ vertexShader,
1133
+ fragmentShader,
1134
+ uniforms: {time: {value: 0}, tint: {value: '#ff8800'}, stripes: {value: true}},
1135
+ });
1136
+ raw.add(new RawMesh({material, attributes: {position: {data: new Float32Array([-1, -1, 3, -1, -1, 3]), type: 'vec2f'}}}));
1137
+ stage.engine.onFrame((_, delta) => (material.uniforms.time.value = (material.uniforms.time.value as number) + delta));
1138
+ console.log(glslProgramToWGSL({vertexShader, fragmentShader}).uniforms); // the GLSL names, types and WGSL members
1139
+ ```
1140
+
1141
+ - **Uniforms.** `material.uniforms.<name>.value` is live and never translates again. Values: a number
1142
+ or boolean, an array, typed array or `{x, y, z, w}` for a vector or a column-major matrix, `'#rrggbb'` for a `vec3`,
1143
+ and for a `sampler2D`, `samplerCube`, `sampler3D` or `sampler2DArray` a `Texture` of `@margoengine/materials`, a
1144
+ GPUTexture or a GPUTextureView. Types come from the GLSL: `float`, `int`, `uint`, `bool` and their vectors, `mat2`,
1145
+ `mat3`, `mat4`. A uniform the program declares and `uniforms` omits starts at zero (a sampler with no texture reads
1146
+ opaque white, as raw materials do; GL would read black). Both stages may declare the same uniform; its type must
1147
+ match.
1148
+ - **Attributes and varyings.** Attributes match a `RawMesh` attribute by name. One the mesh lacks reads GL's default
1149
+ (0, 0, 0, 1), and a narrower one is widened the same way, so `in vec4 position` takes a `vec2f` attribute. Varyings
1150
+ link by name and type; integer varyings must be `flat`. A flat varying takes its value from the first vertex of a
1151
+ triangle on WebGPU and from the last in GL, so keep flat values equal across a primitive.
1152
+ - **GL conventions.** By default the program sees GL's: `gl_Position` in GL clip space (z from -1 to 1, mapped onto
1153
+ Margo's reversed depth), `gl_FragCoord` with rows counted from the bottom and GL depth, `dFdy` along GL window y,
1154
+ `gl_FragDepth` in GL depth, and 2D lookups and `texelFetch` reading a Margo texture as GL reads one uploaded with
1155
+ `UNPACK_FLIP_Y_WEBGL` (`flipY: true`). `flipY: false` reads rows top down, and `clipSpace: 'webgpu'` takes clip z
1156
+ from 0 to 1 unchanged. Built-ins: `gl_Position`, `gl_PointSize`, `gl_VertexID`, `gl_InstanceID`, `gl_FragCoord`,
1157
+ `gl_FrontFacing`, `gl_PointCoord`, `gl_FragColor`, `gl_FragData[0]`, `gl_FragDepth`, `gl_DepthRange` and the
1158
+ `gl_Max*` constants at WebGL's minimums.
1159
+ - **Defines.** `defines: {NAME: value}` go before both stages (`true` as 1). Assigning `material.defines`, or editing
1160
+ it and setting `material.needsUpdate = true`, translates again; so does assigning `vertexShader` or `fragmentShader`.
1161
+ Translations are cached per source and defines (64 programs), so switching back costs nothing.
1162
+ - **Render state.** Everything a `RawShaderMaterial` takes (`transparent`, `blending`, `depthTest`, `depthWrite`,
1163
+ `cull`, `colorWrite`, `depthCompare`, `depthBias`, `alphaToCoverage`), plus the GL names a pasted program's
1164
+ material sets: `side` ('front', 'back' or 'double'; not together with `cull`), `depthFunc` in GL's sense (nearer is
1165
+ less, default 'less-equal'), `polygonOffset` with `polygonOffsetFactor` and `polygonOffsetUnits`, and
1166
+ `blending: 'custom'` with `blendSrc`, `blendDst`, `blendEquation` and their `Alpha` forms. All of them are live.
1167
+ - **Built-in names.** `builtins` picks the names under which the engine supplies its matrices and attributes; see
1168
+ [Engine values under familiar names](#engine-values-under-familiar-names).
1169
+ - **Errors.** Syntax and link errors throw MargoError `failed` from the constructor with `stage`, `line` and `column`
1170
+ in your GLSL as written and a help link: a varying whose type or interpolation differs between the stages, one read
1171
+ but never written, mixed versions, a uniform declared with two types, an unsupported uniform type, more than one
1172
+ colour output or `gl_FragData` above 0. `glslProgramToWGSL(source)` returns both stages' WGSL and the uniform,
1173
+ texture, attribute and varying tables for tools.
1174
+
1175
+ `node packages/shader/test/glsl-material-check.mjs` and the same command with `--compat`
1176
+ draw each program of `test/glsl-material-fixtures.js` with the browser's own WebGL compiler (WebGL 1 for GLSL ES 1.00,
1177
+ WebGL 2 for 3.00) and as a `ShaderMaterial`, then again after changing uniforms or defines: within 1 level per channel
1178
+ on every pixel, natively and on the layer.
1179
+
1180
+ ### Engine values under familiar names
1181
+
1182
+ A program pasted from another web engine reads that engine's names for the model, view and projection matrices and
1183
+ the vertex streams. `builtins` supplies Margo's values under one convention's names, each named after its signature
1184
+ uniform; [docs/porting-glsl.md](../../docs/porting-glsl.md) says which convention each engine uses.
1185
+
1186
+ | `builtins` | Uniforms the engine fills | Attributes `shaderMesh` fills |
1187
+ | --- | --- | --- |
1188
+ | `'modelViewMatrix'` | `modelMatrix`, `viewMatrix`, `modelViewMatrix`, `projectionMatrix`, `normalMatrix`, `cameraPosition`, `isOrthographic`; all may be used undeclared | `position`, `normal`, `uv`, `uv1`, `color`, `tangent`, `instanceMatrix`, `instanceColor`; all may be used undeclared |
1189
+ | `'worldViewProjection'` | `world`, `view`, `projection`, `worldView`, `worldViewProjection` | `position`, `normal`, `uv`, `uv2`, `color` (vec4) |
1190
+ | `'matrix_model'` | `matrix_model`, `matrix_normal`, `matrix_view`, `matrix_viewInverse`, `matrix_view3`, `matrix_projection`, `matrix_viewProjection`, `view_position`, `camera_params`, `screen_size`, `viewport_size`, `view_index` | `vertex_position`, `vertex_normal` |
1191
+ | `'auto'` (default) | the one convention the program's names show, or none; names of two conventions throw MargoError `failed` | as chosen |
1192
+ | `false` | none: the program declares every matrix it reads | none |
1193
+
1194
+ A name you list in `uniforms` is yours and the engine leaves it alone. Matrices follow GL: the projection takes view
1195
+ z onto clip z from -1 to 1, which the material maps onto Margo's reversed depth, so a program that writes
1196
+ `projectionMatrix * modelViewMatrix * vec4(position, 1.0)` draws in depth order with core meshes. `attributes:
1197
+ {myPos: 'position'}` maps your own attribute names onto streams; `defaultAttributeValues` sets what a stream the mesh
1198
+ lacks reads (the defaults: `uv` and `uv1` (0, 0), `color` and `instanceColor` white).
1199
+
1200
+ `shaderMesh(geometry, material, options)` builds the `RawMesh`: `geometry` is `{positions, normals, uvs, uvs1, colors,
1201
+ tangents, indices}` or a core `Geometry`; `options.attributes` and `options.instances` add data by GLSL name, and
1202
+ `instances: {instanceMatrix, instanceColor}` draws one copy per matrix. The mesh's `material` keeps its type, so its
1203
+ uniforms stay typed:
1204
+
1205
+ ```ts
1206
+ import {createStage} from 'margoengine';
1207
+ import {RawShaders} from 'margoengine/shader/raw';
1208
+ import {ShaderMaterial, shaderMesh, type ShaderUniformValue} from 'margoengine/shader/glsl-material';
1209
+ const stage = await createStage('#viewport');
1210
+ const raw = RawShaders.attach(stage.engine);
1211
+ const material = new ShaderMaterial({
1212
+ builtins: 'modelViewMatrix',
1213
+ vertexShader: `#version 300 es
1214
+ out vec3 vNormal;
1215
+ void main() {
1216
+ vNormal = normalize(normalMatrix * normal);
1217
+ gl_Position = projectionMatrix * modelViewMatrix * instanceMatrix * vec4(position, 1.0);
1218
+ }`,
1219
+ fragmentShader: `#version 300 es
1220
+ precision highp float;
1221
+ uniform float time;
1222
+ in vec3 vNormal;
1223
+ out vec4 color;
1224
+ void main() {
1225
+ color = vec4(vNormal * 0.5 + 0.5 + 0.1 * sin(time), 1.0);
1226
+ #include <tonemapping_fragment>
1227
+ #include <colorspace_fragment>
1228
+ }`,
1229
+ uniforms: {time: {value: 0}},
1230
+ });
1231
+ const s = 0.5;
1232
+ const positions = [-s, -s, 0, s, -s, 0, s, s, 0, -s, s, 0];
1233
+ const normals = [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1];
1234
+ const instanceMatrix = [-1, 0, 1].flatMap((x) => [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x * 1.5, 0, 0, 1]);
1235
+ const mesh = raw.add(shaderMesh({positions, normals, indices: [0, 1, 2, 0, 2, 3]}, material, {instances: {instanceMatrix}}));
1236
+ stage.engine.onFrame((_, delta) => {
1237
+ const time: ShaderUniformValue = mesh.material.uniforms.time.value; // typed through the mesh
1238
+ mesh.material.uniforms.time.value = (time as number) + delta;
1239
+ });
1240
+ ```
1241
+
1242
+ - **Includes.** `#include <name>` and `#include "name"` expand from `includes: {name: 'glsl'}` (8 deep), in both
1243
+ stages. Two chunks are built in for the fragment stage: `tonemapping_fragment` applies the display tone map to the
1244
+ colour the program wrote (PBR Neutral, only when Margo displays the frame) and `colorspace_fragment` encodes it to
1245
+ sRGB when the target expects that. An unknown include throws with its stage, line and column.
1246
+ - **Output colour.** A program's colour is taken as sRGB, as GL would show it on screen (`outputColorSpace: 'srgb'`,
1247
+ the default); `'linear'` takes it as linear light and lets Margo tone map and encode it like its own materials. A
1248
+ program that includes `colorspace_fragment` writes its colour as it is.
1249
+ - **Float textures the device cannot filter.** WebGPU filters `rgba32float` only with the optional `float32-filterable`
1250
+ feature. Name such a `sampler2D` in `unfilterable: {name: {filter: 'linear', wrap: 'clamp'}}` (`filter` `'nearest'`,
1251
+ `'linear'` or `'mipmap'`, `wrap` `'clamp'` or `'repeat'`): it binds as an unfilterable-float texture and its
1252
+ `texture()`, `textureLod`, `textureGrad` and `textureOffset` lookups read texels with `textureLoad` and filter them as
1253
+ GL does (OpenGL ES 3.0.6 section 3.8.10), so the result is the same with or without the feature. Shadertoy's buffer
1254
+ channels use it.
1255
+
1256
+ ### Raw depth state
1257
+
1258
+ `RawShaderMaterial` also takes `depthCompare` (default 'greater-equal', Margo's reversed depth), `depthBias` and
1259
+ `depthBiasSlopeScale` (triangles only), `alphaToCoverage` (multisampled targets) and `blending: 'subtractive'`, all
1260
+ live. A texture with `sampleType: 'depth'` is a `texture_depth_2d` (or cube, or 2d array) with a comparison sampler
1261
+ (default `compare: 'less-equal'`) for `textureSampleCompare`; with no texture it reads a far depth of 1.
1262
+
1263
+ ### Blocks, structs, arrays and samplers
1264
+
1265
+ Uniforms of any shape a GLSL ES program declares are live values under the names GL gives them:
1266
+
1267
+ - **Structs and arrays.** `uniform Light lights[2];`, `uniform vec2 offsets[4];`, nested structs and the non-square
1268
+ matrices (`mat2x3` and the rest) take a value shaped like the type: an object per struct, a list per array, and a flat
1269
+ run of numbers also works for an array of vectors. Each leaf is its own raw member, so changing one field reuploads
1270
+ without translating. `glslProgramToWGSL` lists each leaf (`lights[1].color`) with its `root` and `path`.
1271
+ - **Uniform blocks.** `uniform Rig { ... };` makes its fields plain uniforms; `uniform Rig { ... } rig;` makes one
1272
+ struct uniform `rig`. A block holds no samplers (GLSL ES 3.00 4.3.7).
1273
+ - **Sampler arrays.** `uniform sampler2D maps[2];` takes a list of textures. Indexing with a constant reads one
1274
+ binding; any other index (a loop counter, an ES 1.00 loop index) reads every element and keeps the one picked.
1275
+ - **Integer and shadow samplers.** `isampler2D`, `usampler2D` (and 3D, cube, 2D array) read textures of integers;
1276
+ `sampler2DShadow`, `samplerCubeShadow` and `sampler2DArrayShadow` compare against a depth texture. Pass a
1277
+ `GPUTexture` or `{texture, sampler}`, with the sampler's `compare` (default 'less-equal'), as the value.
1278
+
1279
+ ### Points, flat varyings, wireframes and saving
1280
+
1281
+ - **Sized points.** A vertex stage that writes `gl_PointSize`, drawn with `topology: 'point-list'`, gives squares of that
1282
+ many pixels of the view it is drawn in, centred on each point, with `gl_PointCoord` from the upper left (OpenGL ES
1283
+ 3.0.6 3.4): `shaderMesh`
1284
+ draws each point as an instance of six corners. A point whose centre leaves the view is dropped whole, as in GL.
1285
+ - **Flat varyings.** GL takes a flat value from a primitive's last vertex and WebGPU from its first, so for a program with
1286
+ a `flat` varying `shaderMesh` lists each triangle or line from its last vertex, winding kept; a strip becomes a list.
1287
+ - **Wireframe.** `wireframe: true` (live, on any `RawShaderMaterial`) draws each edge of the triangles once as a line.
1288
+ - **Saving.** `glslMaterialCodec(ShaderMaterial)` from `@margoengine/shader/serialization` keeps the GLSL, the uniform
1289
+ values and the state, and restoring translates the GLSL again. It takes the class, so the entry loads no GLSL front
1290
+ end; without it a ShaderMaterial has no codec and capturing one throws rather than saving its WGSL translation.
1291
+
1292
+ ```ts
1293
+ import {createStage} from 'margoengine';
1294
+ import {captureMaterialLibrary, restoreMaterialLibrary} from 'margoengine/materials/serialization';
1295
+ import {RawShaders} from 'margoengine/shader/raw';
1296
+ import {ShaderMaterial, shaderMesh} from 'margoengine/shader/glsl-material';
1297
+ import {glslMaterialCodec, shaderMaterialCodecs} from 'margoengine/shader/serialization';
1298
+ const stage = await createStage('#viewport');
1299
+ const raw = RawShaders.attach(stage.engine);
1300
+ const material = new ShaderMaterial({
1301
+ vertexShader: `#version 300 es
1302
+ in vec3 position;
1303
+ void main() { gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }`,
1304
+ fragmentShader: `#version 300 es
1305
+ precision highp float;
1306
+ struct Band { vec3 color; float width; };
1307
+ uniform Shade { Band bands[2]; float mixAmount; } shade;
1308
+ out vec4 color;
1309
+ void main() {
1310
+ float t = fract(gl_FragCoord.x / (shade.bands[0].width + shade.bands[1].width));
1311
+ color = vec4(mix(shade.bands[0].color, shade.bands[1].color, step(0.5, t) * shade.mixAmount), 1.0);
1312
+ }`,
1313
+ uniforms: {shade: {value: {bands: [{color: [1, 0.5, 0], width: 8}, {color: [0, 0.4, 1], width: 8}], mixAmount: 1}}},
1314
+ });
1315
+ raw.add(shaderMesh({positions: [-1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0], indices: [0, 1, 2, 0, 2, 3]}, material));
1316
+ material.wireframe = true;
1317
+ const codecs = [...shaderMaterialCodecs, glslMaterialCodec(ShaderMaterial)];
1318
+ const saved = await captureMaterialLibrary({material}, {codecs});
1319
+ const copy = (await restoreMaterialLibrary(saved, {codecs})).material as ShaderMaterial;
1320
+ console.log(copy.wireframe, copy.uniforms.shade.value);
1321
+ ```
1322
+
1323
+ - **Lights.** `lights: true` hands the program the scene's lights under Margo's names, as uniforms it declares (only
1324
+ those it declares are filled, each pass, with no new translation when they change): `vec3 sunDirection` (world space,
1325
+ unit, towards the sun), `vec3 sunColor` (`engine.lighting` radiance times intensity, linear), `vec3 ambientLight`
1326
+ (the ambient light core meshes get: `ambient` times radiance w), and the point and spot lights of
1327
+ `shaderScene(raw).setLights(clustered)` (a `Clustered` of `@margoengine/clustered`, or any `{list}` of its lights) as
1328
+ `pointLights[N]` and `spotLights[N]` with `int pointLightCount` and `spotLightCount`. Declare each list as an array
1329
+ of your own struct with any of the fields `vec3 position`, `vec3 color` (colour times intensity times
1330
+ `intensityScale`, linear), `float range` (0 is unlimited), `float decay` (default 2) and, for spots, `vec3 direction`,
1331
+ `float outerCos` and `float innerCos` (cosines of the cone's outer and inner half-angles). The lists fill in list
1332
+ order, as many as `N` holds. Clustered's own falloff is `clamp(1 - (d / range)^4, 0, 1)^2 / max(d^decay, 2^-12)`, and
1333
+ its cone `smoothstep(outerCos, innerCos, dot(-l, direction))`.
1334
+ - **Fog.** `fog: true` hands over `shaderScene(raw).setFog(fog)` (an `@margoengine/environment` `Fog`, or any object with its
1335
+ fields) as `vec3 fogColor`, `float fogNear`, `fogFar`, `fogDensity`, `fogHeight` and `fogHeightFalloff`. Margo's fog
1336
+ is linear from near to far at distance `d` from the camera, or `1 - exp(-(density d)^2)` when density is above 0,
1337
+ times `exp(-heightFalloff max(y - height, 0))`. `fogColor` comes as your program writes colour: display-ready
1338
+ (sRGB, as given) by default, linear with `outputColorSpace: 'linear'` or `#include <colorspace_fragment>`. Without a
1339
+ fog the values read as no fog (density 0, near and far at the float maximum). A name you give in `uniforms` is yours.
1340
+ - **Motion vectors.** `velocity: true` gives TAA (`taa.add(raw)`) the motion of every vertex the program moves: its
1341
+ vertex stage runs a second time with last frame's model matrix, view-projection and time, and TAA reads where each
1342
+ vertex was, as a WGSL `velocityEntry` writes it. A move driven by your own uniforms names, for each, the uniform that
1343
+ holds its value of last frame (`velocity: {wave: 'waveBefore'}`), which you set before you change the first; it needs
1344
+ no declaration. Without `velocity` TAA sees the camera's motion over the depth only, so a shape the shader moves
1345
+ leaves a trail.
1346
+ - **What each entry carries.** The scene options and `shaderScene` live in `shader/glsl-material` alone. `ShaderPass`
1347
+ and `Shadertoy` draw with the same program core without them, so their entries hold no light, fog or motion code;
1348
+ `toy.material()` refuses `lights`, `fog` and `velocity`. Their materials still pass `instanceof ShaderMaterial`.
1349
+
1350
+ ```ts
1351
+ import {createStage} from 'margoengine';
1352
+ import {sphereGeometry} from 'margoengine/geometry';
1353
+ import {TAA} from 'margoengine/taa';
1354
+ import {RawShaders} from 'margoengine/shader/raw';
1355
+ import {ShaderMaterial, shaderMesh, shaderScene} from 'margoengine/shader/glsl-material';
1356
+ const stage = await createStage('#viewport');
1357
+ const raw = RawShaders.attach(stage.engine);
1358
+ shaderScene(raw)
1359
+ .setFog({color: '#8899aa', near: 4, far: 30})
1360
+ .setLights({list: [{position: [2, 2, 3], range: 12, color: [1, 0.6, 0.3], intensity: 4}]});
1361
+ const material = new ShaderMaterial({
1362
+ lights: true,
1363
+ fog: true,
1364
+ velocity: {wave: 'waveBefore'},
1365
+ uniforms: {wave: {value: 0}, waveBefore: {value: 0}},
1366
+ vertexShader: `uniform float wave;
1367
+ varying vec3 vNormal;
1368
+ varying vec3 vWorld;
1369
+ void main() {
1370
+ vec3 p = position + normal * 0.1 * sin(wave + position.y * 4.0);
1371
+ vNormal = mat3(modelMatrix) * normal;
1372
+ vWorld = (modelMatrix * vec4(p, 1.0)).xyz;
1373
+ gl_Position = projectionMatrix * viewMatrix * vec4(vWorld, 1.0);
1374
+ }`,
1375
+ fragmentShader: `precision highp float;
1376
+ struct Point { vec3 position; vec3 color; float range; float decay; };
1377
+ uniform vec3 sunDirection;
1378
+ uniform vec3 sunColor;
1379
+ uniform vec3 ambientLight;
1380
+ uniform Point pointLights[4];
1381
+ uniform int pointLightCount;
1382
+ uniform vec3 fogColor;
1383
+ uniform float fogNear;
1384
+ uniform float fogFar;
1385
+ varying vec3 vNormal;
1386
+ varying vec3 vWorld;
1387
+ void main() {
1388
+ vec3 n = normalize(vNormal);
1389
+ vec3 c = ambientLight + sunColor * max(dot(n, sunDirection), 0.0);
1390
+ for (int i = 0; i < 4; i++) {
1391
+ if (i >= pointLightCount) break;
1392
+ vec3 l = pointLights[i].position - vWorld;
1393
+ float d = length(l);
1394
+ float x = d / pointLights[i].range;
1395
+ float w = clamp(1.0 - x * x * x * x, 0.0, 1.0);
1396
+ c += pointLights[i].color * max(dot(n, l / d), 0.0) * w * w / max(pow(d, pointLights[i].decay), 1.0 / 4096.0);
1397
+ }
1398
+ float f = clamp((distance(vWorld, cameraPosition) - fogNear) / (fogFar - fogNear), 0.0, 1.0);
1399
+ gl_FragColor = vec4(mix(c * 0.4, fogColor, f), 1.0);
1400
+ }`,
1401
+ });
1402
+ raw.add(shaderMesh(sphereGeometry(1, 48, 24), material));
1403
+ TAA.attach(stage.engine).add(raw);
1404
+ stage.engine.onFrame((_, delta) => {
1405
+ material.uniforms.waveBefore.value = material.uniforms.wave.value;
1406
+ material.uniforms.wave.value = (material.uniforms.wave.value as number) + delta * 3;
1407
+ });
1408
+ ```
1409
+
1410
+ ## GLSL post passes (`@margoengine/shader/glsl-pass`, 40.4 kB min+gzip on its own)
1411
+
1412
+ `ShaderPass` runs a full-screen GLSL ES 1.00 or 3.00 program as a stage of `@margoengine/post`'s PostStack, in the
1413
+ `{uniforms, vertexShader, fragmentShader}` form web engines use for post passes. The stack's colour reaches the program
1414
+ through the first of `tDiffuse`, `textureSampler` and `uColorBuffer` it declares (or the sampler named by `input`).
1415
+ Without a vertex stage the pass supplies one triangle over the target that writes `vUv`, `vUV` or `vUv0`, whichever the
1416
+ fragment reads, with uv (0, 0) at the lower left; a vertex stage of your own gets `position` (xyz) and `uv`, and
1417
+ `projectionMatrix` and `modelViewMatrix` are the identity, as for a full-screen quad.
1418
+
1419
+ ```ts
1420
+ import {createStage} from 'margoengine';
1421
+ import {PostStack} from 'margoengine/post';
1422
+ import {ShaderPass} from 'margoengine/shader/glsl-pass';
1423
+
1424
+ const stage = await createStage(document.querySelector('canvas')!);
1425
+ const pass = new ShaderPass({
1426
+ uniforms: {amount: {value: 0.5}},
1427
+ fragmentShader: `precision highp float;
1428
+ uniform sampler2D tDiffuse;
1429
+ uniform float amount;
1430
+ varying vec2 vUv;
1431
+ void main() {
1432
+ vec4 c = texture2D(tDiffuse, vUv);
1433
+ gl_FragColor = vec4(mix(c.rgb, vec3(dot(c.rgb, vec3(0.299, 0.587, 0.114))), amount), 1.0);
1434
+ }`,
1435
+ });
1436
+ PostStack.attach(stage.engine, [pass]);
1437
+ pass.uniforms.amount.value = 1; // live, no translation
1438
+ ```
1439
+
1440
+ `await ShaderPass.attach(engine, shader, options?)` does the same in one call: it loads `@margoengine/post`, adds the
1441
+ pass to the scene's PostStack after the last effect of its kind (or a new PostStack when there is none) and returns
1442
+ it, and `pass.dispose()` takes it out again, with the stack when attach made it. The options are the constructor's
1443
+ plus `signal`.
1444
+
1445
+ ```ts
1446
+ import {createStage} from 'margoengine';
1447
+ import {ShaderPass} from 'margoengine/shader/glsl-pass';
1448
+
1449
+ const stage = await createStage(document.querySelector('canvas')!);
1450
+ const invert = await ShaderPass.attach(stage.engine, {
1451
+ fragmentShader: `uniform sampler2D tDiffuse;
1452
+ varying vec2 vUv;
1453
+ void main() { gl_FragColor = vec4(1.0 - texture2D(tDiffuse, vUv).rgb, 1.0); }`,
1454
+ });
1455
+ invert.dispose(); // removes the pass and its PostStack
1456
+ ```
1457
+
1458
+ - **Options.** `kind`: `'ldr'` (default) runs on display colour after tonemapping and writes display colour;
1459
+ `'hdr'` runs on linear light before it and, when last, goes through the display transform (its `outputColorSpace`
1460
+ defaults to `'linear'`). `input` (default the first convention name declared; `null` for a pass that reads nothing),
1461
+ `name`, and the program options of `ShaderMaterial`: `glslVersion`, `flipY`, `strict`, `builtins`, `attributes`
1462
+ (`{aPosition: 'position'}`), `includes`, `outputColorSpace`, `blending` (default `'none'`: the pass replaces its
1463
+ output). `pass.material` is the ShaderMaterial (`pass.material.code('fragment')` shows the WGSL).
1464
+ - **What a pass reads.** `gl_FragCoord` counts pixels of the target from the lower left, as GL's; the input sampler
1465
+ reads the stack's colour with v up, as a GL render target reads. In a view of a multi-view frame the pass draws
1466
+ inside the view, and `vUv` names the input pixels under it (it runs over the view's part of the target). The pipeline compiles at once, so the first frame
1467
+ draws. `await pass.ready()` resolves when it has.
1468
+ - **Not here.** Scene depth as a sampler (NodePass has `inputDepth()`). Shadertoy programs run through
1469
+ `@margoengine/shader/shadertoy`, below.
1470
+
1471
+ ## Shadertoy programs (`@margoengine/shader/shadertoy`, 49.9 kB min+gzip on its own)
1472
+
1473
+ `Shadertoy` runs the Image tab of a Shadertoy program, `void mainImage(out vec4 fragColor, in vec2 fragCoord)` as
1474
+ written in Shadertoy's editor, with its documented inputs: `iResolution`, `iTime`, `iTimeDelta`, `iFrameRate`,
1475
+ `iFrame`, `iChannelTime[4]`, `iChannelResolution[4]`, `iMouse`, `iDate`, `iSampleRate`, `iChannel0` to `iChannel3`
1476
+ and the older `iGlobalTime`, with the Common tab, Buffer A to D, keyboard, video and audio channels. One toy draws
1477
+ three ways: as a PostStack pass, into a texture once a frame, or on a mesh.
1478
+
1479
+ ```ts
1480
+ import {createStage} from 'margoengine';
1481
+ import {PostStack} from 'margoengine/post';
1482
+ import {RawShaders} from 'margoengine/shader/raw';
1483
+ import {shaderMesh} from 'margoengine/shader/glsl-material';
1484
+ import {Shadertoy} from 'margoengine/shader/shadertoy';
1485
+
1486
+ const stage = await createStage(document.querySelector('canvas')!);
1487
+ const toy = new Shadertoy(`void mainImage(out vec4 fragColor, in vec2 fragCoord) {
1488
+ vec2 uv = fragCoord / iResolution.xy;
1489
+ fragColor = vec4(0.5 + 0.5 * cos(iTime + uv.xyx + vec3(0.0, 2.0, 4.0)), 1.0);
1490
+ }`);
1491
+ PostStack.attach(stage.engine, [toy.pass()]); // over the whole screen
1492
+
1493
+ // Or on a mesh, with fragCoord = uv * resolution; the attached toy runs the clock and draws toy.texture.
1494
+ stage.engine.use(toy); // Shadertoy.attach(stage.engine, source) makes and attaches a toy in one call
1495
+ RawShaders.attach(stage.engine).add(shaderMesh({positions: [-1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0], uvs: [0, 0, 1, 0, 1, 1, 0, 1], indices: [0, 1, 2, 0, 2, 3]}, toy.material()));
1496
+ ```
1497
+
1498
+ - **Channels.** `new Shadertoy({image: {source, iChannel0, ...}, resolution})`: a channel is a
1499
+ `@margoengine/materials` Texture, a GPUTexture or view, `(device) => GPUTexture | GPUTextureView` (made once per
1500
+ device; see Device restore below), `'input'` (in a pass, the colour of the stage before), a
1501
+ buffer `'A'` to `'D'`, `'keyboard'`, a video or image, an AnalyserNode, or null (opaque black, as GL reads an
1502
+ unbound unit), or `{texture, type, filter, wrap, resolution}` with `type` `'2d'` (default; `'3d'` for a 3D
1503
+ GPUTexture), `'cube'` or `'3d'`, `filter` `'linear'` (default), `'nearest'` or `'mipmap'` (a texture brings its own
1504
+ levels), `wrap` `'clamp'` (default) or `'repeat'`. A function's texture is a sampler2D unless `type` says `'3d'` or
1505
+ `'cube'`. 2D channels read Margo's images upright (v up, as Shadertoy's flipped uploads read); `iChannelResolution`
1506
+ is the GPUTexture's size (a function's: the texture it made), a Texture's `width` and `height`, the target for
1507
+ `'input'`, or `resolution`.
1508
+ - **Changing a channel.** `toy.setChannel(index, texture, tab)` (tab default `'image'`, else `'bufferA'` to
1509
+ `'bufferD'`, `'cubeA'` or `'sound'`) gives a texture channel a new GPUTexture or view of its sampler type, a
1510
+ Texture, a function or null, a video or image channel another, and an audio channel another AnalyserNode. The toy's
1511
+ own channels (`'input'`, a buffer, `'cubeA'`, `'keyboard'`) are set when it is made and throw a TypeError here, as
1512
+ does a texture of another sampler type.
1513
+ - **Device restore.** A GPUTexture or view you made belongs to the device that made it. A function channel is made
1514
+ again on the new device after `engine.rebootDevice()`. A plain one is lost: the channel reads opaque black (as an
1515
+ unbound one), `engine.onError` hears of it once (`'state'`,
1516
+ [#borrowed-lost](https://margoengine.com/errors#borrowed-lost)) under the channel's name, the frame keeps drawing,
1517
+ and `toy.setChannel` brings it back. The toy's buffers, Cube A and its keyboard, video and audio textures are its
1518
+ own and are made again by themselves.
1519
+
1520
+ ```ts
1521
+ import {createStage} from 'margoengine';
1522
+ import {PostStack} from 'margoengine/post';
1523
+ import {Shadertoy} from 'margoengine/shader/shadertoy';
1524
+
1525
+ const stage = await createStage(document.querySelector('canvas')!);
1526
+ // Made once per device, so the channel is back by itself after a device restore.
1527
+ const noise = (device: GPUDevice) => {
1528
+ const texture = device.createTexture({size: [64, 64], format: 'rgba8unorm', usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST});
1529
+ device.queue.writeTexture({texture}, crypto.getRandomValues(new Uint8Array(64 * 64 * 4)), {bytesPerRow: 64 * 4}, [64, 64]);
1530
+ return texture;
1531
+ };
1532
+ const toy = new Shadertoy({
1533
+ image: {
1534
+ source: `void mainImage(out vec4 fragColor, in vec2 fragCoord) {
1535
+ fragColor = vec4(texture(iChannel0, fragCoord / iChannelResolution[0].xy).rgb, 1.0);
1536
+ }`,
1537
+ iChannel0: {texture: noise, wrap: 'repeat'},
1538
+ },
1539
+ });
1540
+ PostStack.attach(stage.engine, [toy.pass()]);
1541
+ // A plain texture works too, but is lost with its device: set a new one after a restore.
1542
+ toy.setChannel(0, noise(stage.engine.gpu!));
1543
+ ```
1544
+ - **Inputs.** `toy.time`, `toy.frame`, `toy.timeDelta`, `toy.frameRate`, `toy.mouse` (`[x, y, clickX, clickY]` in
1545
+ pixels) and `toy.date` (year, month from 0 as JavaScript's Date, day, seconds since midnight; `undefined` follows
1546
+ the clock) are settable; `iSampleRate` is `sampleRate` (default 44100). The clock starts at frame 0, time 0 and adds
1547
+ each frame's delta; `pause()`, `play()` and `reset()` control it. A pass runs it by itself; for a material or the
1548
+ texture attach the toy (`engine.use(toy)`, or `Shadertoy.attach(engine, options)`). The assigned `{value}`s are read only: set the toy. Paused, the buffers
1549
+ and the keyboard, video and audio channels hold until `toy.frame` is set, which runs them once.
1550
+ - **Targets.** `toy.pass(options)` is a ShaderPass (`kind`, `name`, `flipY`, `blending` as there): `iResolution` is the
1551
+ target's size and fragCoord its pixel, from the lower left. `toy.texture` is an rgba8unorm image of `resolution`
1552
+ (default 512 x 512) drawn before the scene each frame while the toy is attached, for raw, node and GLSL materials.
1553
+ `toy.material(options)` is a ShaderMaterial (render state options as there) with fragCoord = uv * `resolution`.
1554
+ `toy.fragmentShader`, `toy.meshShaders` and `toy.buffers` show the GLSL around each source; an error names its tab
1555
+ (`error.tab`: `'common'`, `'image'`, `'bufferA'` to `'bufferD'`, `'cubeA'`, `'sound'`) and that tab's own line.
1556
+
1557
+ ### Multipass: Common, Buffer A to D, keyboard, video and audio
1558
+
1559
+ ```ts
1560
+ import {createStage} from 'margoengine';
1561
+ import {PostStack} from 'margoengine/post';
1562
+ import {Shadertoy} from 'margoengine/shader/shadertoy';
1563
+
1564
+ const stage = await createStage(document.querySelector('canvas')!);
1565
+ const toy = new Shadertoy({
1566
+ common: 'vec3 palette(float t) { return 0.5 + 0.5 * cos(6.2832 * (t + vec3(0.0, 0.33, 0.67))); }',
1567
+ // Buffer A reads its own last frame: a trail that fades.
1568
+ bufferA: {
1569
+ source: `void mainImage(out vec4 fragColor, in vec2 fragCoord) {
1570
+ vec2 uv = fragCoord / iResolution.xy, dot_ = 0.5 + 0.3 * vec2(cos(iTime), sin(iTime * 1.3));
1571
+ float d = length(uv - dot_);
1572
+ fragColor = max(texture(iChannel0, uv) * 0.97, vec4(palette(iTime * 0.1) * smoothstep(0.05, 0.0, d), 1.0));
1573
+ }`,
1574
+ iChannel0: 'A',
1575
+ },
1576
+ image: {
1577
+ source: `void mainImage(out vec4 fragColor, in vec2 fragCoord) {
1578
+ vec3 trail = texture(iChannel0, fragCoord / iResolution.xy).rgb;
1579
+ float space = texelFetch(iChannel1, ivec2(32, 0), 0).x; // the space bar is down
1580
+ fragColor = vec4(mix(trail, 1.0 - trail, space), 1.0);
1581
+ }`,
1582
+ iChannel0: {texture: 'A', filter: 'mipmap'},
1583
+ iChannel1: 'keyboard',
1584
+ },
1585
+ });
1586
+ PostStack.attach(stage.engine, [toy.pass()]);
1587
+ ```
1588
+
1589
+ - **Common and buffers.** `common` is placed before every tab's source. `bufferA` to `bufferD` take a source and
1590
+ channels as `image` does; each frame they draw in the order A, B, C, D, then the image, into rgba32float targets of
1591
+ the image's size that start at zero. A channel given `'A'` to `'D'` reads that buffer's latest image: its own last
1592
+ frame, this frame's for a buffer drawn before it. A buffer keeps all four components as written (negative and above
1593
+ 1 too); the image writes opaque colour.
1594
+ - **Filtering a buffer.** A buffer channel's `filter` is `'nearest'`, `'linear'` or `'mipmap'` (trilinear; the buffer's
1595
+ mip levels are made each frame by a 2 x 2 box) and `wrap` `'clamp'` or `'repeat'`. rgba32float can be filtered by
1596
+ the device only with `float32-filterable`, which is optional in WebGPU, so a linear or mipmap buffer channel reads
1597
+ its texels with `textureLoad` and filters them as GL does (four loads a level, OpenGL ES 3.0.6 section 3.8.10). It
1598
+ reads the same on every device, with or without the feature, and needs no `features` option. A function that takes
1599
+ `sampler2D` filters as the channel passed to it says.
1600
+ - **Keyboard.** `'keyboard'` is a 256 x 3 channel as Shadertoy's: `texelFetch(iChannel0, ivec2(keyCode, row), 0).x`
1601
+ is 1 when the key is down (row 0), went down this frame (row 1) or has been toggled by its presses (row 2). It
1602
+ listens on `keyboard` (default the window) and stops on `dispose()`.
1603
+ - **Video and images.** A `<video>`, canvas, OffscreenCanvas, ImageBitmap or `<img>` is copied into its channel each
1604
+ frame (a video once it has a frame; an image or ImageBitmap once), upright as Shadertoy's flipped uploads.
1605
+ `iChannelTime` is the video's `currentTime` and `iChannelResolution` its size. `filter: 'mipmap'` makes its levels.
1606
+ - **Audio.** An `AnalyserNode` (or any object with `getByteFrequencyData` and `getByteTimeDomainData`) is a 512 x 2
1607
+ channel: `texture(iChannel0, vec2(x, 0.25)).x` is the spectrum, `vec2(x, 0.75)` the waveform, as Shadertoy's sound
1608
+ input. `iChannelTime` is its context's `currentTime`.
1609
+ - **Base level.** A channel whose `filter` is `'nearest'` or `'linear'` reads only the base level of a texture that
1610
+ has mip levels, as GL does without a mipmap min filter (OpenGL ES 3.0.6 section 3.8.10).
1611
+
1612
+ ### Cube A, VR and sound
1613
+
1614
+ ```ts
1615
+ import {createStage} from 'margoengine';
1616
+ import {PostStack} from 'margoengine/post';
1617
+ import {Shadertoy} from 'margoengine/shader/shadertoy';
1618
+
1619
+ const stage = await createStage(document.querySelector('canvas')!);
1620
+ const toy = new Shadertoy({
1621
+ // Cube A: drawn into the six faces of a cube each frame; rayDir is the unit direction of the texel.
1622
+ cubeA: {
1623
+ source: `void mainCubemap(out vec4 fragColor, in vec2 fragCoord, in vec3 rayOri, in vec3 rayDir) {
1624
+ vec3 sky = mix(vec3(0.9, 0.6, 0.4), vec3(0.2, 0.4, 0.9), 0.5 + 0.5 * rayDir.y);
1625
+ fragColor = vec4(sky + 0.3 * pow(max(dot(rayDir, normalize(vec3(cos(iTime), 0.4, sin(iTime)))), 0.0), 64.0), 1.0);
1626
+ }`,
1627
+ size: 256,
1628
+ },
1629
+ image: {
1630
+ source: `void mainImage(out vec4 fragColor, in vec2 fragCoord) {
1631
+ vec2 p = (2.0 * fragCoord - iResolution.xy) / iResolution.y;
1632
+ fragColor = vec4(texture(iChannel0, normalize(vec3(p, -1.5))).rgb, 1.0);
1633
+ }
1634
+ // With vr: true a pass and a mesh call mainVR with each pixel's ray from the camera drawing it (each eye in XR).
1635
+ void mainVR(out vec4 fragColor, in vec2 fragCoord, in vec3 fragRayOri, in vec3 fragRayDir) {
1636
+ fragColor = vec4(texture(iChannel0, fragRayDir).rgb, 1.0);
1637
+ }`,
1638
+ iChannel0: 'cubeA',
1639
+ },
1640
+ // The Sound tab: one stereo sample per call, from -1 to 1.
1641
+ sound: {
1642
+ source: `vec2 mainSound(int samp, float time) {
1643
+ float note = sin(6.2831853 * fract(440.0 * time)) * exp(-3.0 * fract(time));
1644
+ return vec2(note, note * 0.8);
1645
+ }`,
1646
+ },
1647
+ vr: true,
1648
+ });
1649
+ PostStack.attach(stage.engine, [toy.pass()]);
1650
+
1651
+ // The samples, rendered over the next frames while the toy is attached.
1652
+ stage.engine.use(toy);
1653
+ const sound = await toy.sound({seconds: 4});
1654
+ const audio = new AudioContext(),
1655
+ player = audio.createBufferSource();
1656
+ player.buffer = sound.audioBuffer(audio);
1657
+ player.connect(audio.destination);
1658
+ player.start();
1659
+ ```
1660
+
1661
+ - **Cube A.** `cubeA: {source, size, iChannel0, ...}` takes `void mainCubemap(out vec4 fragColor, in vec2 fragCoord,
1662
+ in vec3 rayOri, in vec3 rayDir)`. Each frame, after the buffers and before the image, it is drawn into the six faces
1663
+ of an rgba16float cube of `size` pixels a face (a power of two from 1 to 2048, default 1024): `rayDir` is the unit
1664
+ direction through the texel's centre, faces as OpenGL ES 3.0.6 Table 3.21 numbers them, `rayOri` is zero and
1665
+ `fragCoord` is the texel's place in its face from the face's first row, so the faces hold what GL's would. Any tab
1666
+ reads it as `'cubeA'`, a `samplerCube` channel (`'nearest'`, `'linear'` or `'mipmap'`; the cube's levels are made
1667
+ each frame when a channel asks for them); Cube A reads its own last frame. It is one draw into a 3 x 2 atlas of the
1668
+ faces and six copies into the cube a frame, one more draw per mip level and six copies per level.
1669
+ - **mainVR.** With `vr: true` the Image source needs `void mainVR(out vec4 fragColor, in vec2 fragCoord, in vec3
1670
+ fragRayOri, in vec3 fragRayDir)`. `toy.pass()` calls it with the ray of each pixel from the camera that draws it:
1671
+ the camera's position and the direction to the pixel's point on the near plane (the inverse of its view-projection),
1672
+ so in an XR frame each eye's view gets its own rays. `toy.material()` calls it with the ray from the camera to the
1673
+ surface. `toy.texture` keeps calling mainImage. `toy.vrShader` shows the pass's program.
1674
+ - **mainSound.** `sound: {source, iChannel0, ...}` takes `vec2 mainSound(int samp, float time)`, or the older `vec2
1675
+ mainSound(float time)`; its channels read textures only. `toy.sound({seconds = 180, signal})` renders it while the
1676
+ toy is attached, 262,144 samples (one 512 x 512 rgba32float block) a frame, mapped back on the next frame, and
1677
+ resolves to `{sampleRate, channels: [left, right], audioBuffer(context)}`: one Float32Array a channel with values
1678
+ clamped to -1 to 1, `time` is `samp / sampleRate`, and `audioBuffer` makes a Web Audio buffer for any audio context.
1679
+ The signal rejects the promise with its reason; a new device starts the render again. `toy.soundShader` shows
1680
+ the program.
1681
+
1682
+ ## Screen effects (`@margoengine/shader/effects`, 8.6 kB min+gzip on its own)
1683
+
1684
+ Ready-made `NodePass` effects for a PostStack, each with live `uniforms` (`effect.uniforms.darkness.value = 0.5`). LDR by
1685
+ default (after tonemapping, on display colour); `{kind: 'hdr'}` runs one on linear light before the display effect.
1686
+
1687
+ ```ts
1688
+ import {PostStack} from 'margoengine/post';
1689
+ import {Tonemap} from 'margoengine/tonemap';
1690
+ import {vignette, rgbShift} from 'margoengine/shader/effects';
1691
+ import {createStage} from 'margoengine';
1692
+ const stage = await createStage('#viewport', {backend: 'webgpu'});
1693
+ const look = vignette({darkness: 0.6}), shift = rgbShift({amount: 0.004});
1694
+ PostStack.attach(stage.engine, [new Tonemap(), shift, look]);
1695
+ look.uniforms.darkness.value = 0.9; // live
1696
+ ```
1697
+
1698
+ | Preset | Parameters (default) |
1699
+ | --- | --- |
1700
+ | `vignette` | `darkness` 0.8, `radius` 0.4 (0 centre, 1 corner), `softness` 0.6 |
1701
+ | `rgbShift` | `amount` 0.002 (UV units, about 4 px at 1920 wide), `angle` 0 (radians; red moves right, blue left) |
1702
+ | `chromaticAberration` | `strength` 0.01 (red and blue scaled about the centre by 1 -/+ strength) |
1703
+ | `pixelate` | `size` 8 pixels; each block is the input pixel at its centre |
1704
+ | `halftone` | `size` 8 pixels, `angle` 0.26; `greyscale` (construction only) |
1705
+ | `dotScreen` | `size` 6 pixels, `angle` 0.785; black dots on white |
1706
+ | `sobel` | `strength` 1, `overlay` 0 (1 draws black edges over the image) |
1707
+ | `sepia` | `amount` 1 (W3C Filter Effects matrix) |
1708
+ | `posterize` | `levels` 4 |
1709
+
1710
+ The same GPU check feeds known images through them: Sobel gives exactly 4 x the luma step beside a step and 0 elsewhere,
1711
+ Each effect is one `NodePass`: one render pass that reads the previous image and writes its own at the output's precision, reusing one pass descriptor every frame. pixelate copies each block's centre pixel exactly, and posterize, sepia, vignette, RGB shift and chromatic aberration
1712
+ match their formulas within 0.6 of 255; halftone (8 px cells) and dot screen (12 px cells) keep flat 0.2 and 0.6 tones
1713
+ within 5 of 255 on average, since each dot covers its value's share of the cell. Their 1 px edge ramp adds about
1714
+ pi / 12 px^2 per dot and loses its outer half where a dot meets its cell's side, so small cells drift by a few levels
1715
+ (about 5 of 255 for dot screen's default 6 px at 80% ink).
1716
+
1717
+ ## Black hole (`@margoengine/shader/black-hole`)
1718
+
1719
+ A spinning (Kerr) black hole drawn by one full-screen raw shader: a thin accretion disk with the Page-Thorne flux,
1720
+ gravitational and Doppler redshift and beaming, a relativistic jet, and a lensed star field and Milky Way. Every ray is
1721
+ traced back from the camera through Kerr spacetime (fourth-order Runge-Kutta in Boyer-Lindquist coordinates), so the
1722
+ shadow, the photon ring and the disk's secondary images come out of the maths, not from a texture. The scene unit is the
1723
+ Schwarzschild radius r_s = 2M; the hole sits at the origin with its spin along +y.
1724
+
1725
+ ```ts
1726
+ import {BlackHole, traceGeodesic} from 'margoengine/shader/black-hole';
1727
+ import {ShaderClock} from 'margoengine/shader';
1728
+ import {createStage} from 'margoengine';
1729
+ const stage = await createStage('#viewport', {
1730
+ backend: 'webgpu',
1731
+ camera: {position: [-0.55, 0.95, 11.8], target: [0, -0.05, 0], fov: 38, near: 0.05, far: 1000},
1732
+ });
1733
+ const hole = BlackHole.attach(stage.engine, {spin: 0.9, accretion: 1, jet: 0.5});
1734
+ hole.view = 'redshift'; // 'beauty' (default), 'redshift', 'beaming', 'temperature', 'orders'
1735
+ hole.flare(ShaderClock.attach(stage.engine).time); // a hot spot that spirals in over 8 s on the engine clock
1736
+ const fan = [-3, -2, -1, 1, 2, 3].map((y) => traceGeodesic([0, y, 40], [0, 0, -1], {spin: hole.spin}));
1737
+ hole.showGeodesics(fan); // the rays drawn as lines; each knows its fate and disk crossings
1738
+ ```
1739
+
1740
+ | Option | Default | What it does |
1741
+ | --- | --- | --- |
1742
+ | `spin` | 0.9 | a = J / M^2, 0 to 0.998 (Thorne's limit). The horizon and ISCO follow it (`hole.horizon`, `hole.isco`). |
1743
+ | `accretion` | 1 | Disk brightness, a multiple of the default accretion rate; 0 hides the disk. |
1744
+ | `peakTemperature` | 4500 | Disk temperature at its flux peak in kelvin, before redshift; the colour is the Planckian locus at g T. |
1745
+ | `diskOuter` | 6 | Outer disk radius in r_s. |
1746
+ | `turbulence` | 0.6 | Disk turbulence, 0 (a smooth Page-Thorne disk) to 1. |
1747
+ | `jet`, `jetLorentz` | 0.5, 5 | Jet brightness (0 to 1) and its bulk Lorentz factor (1 to 20). |
1748
+ | `stars`, `galaxy` | 1, 1 | Star field and Milky Way brightness; 0 hides them. |
1749
+ | `timeScale` | 6 | Units of M of orbital time per second of the shader clock (`camera.time`). |
1750
+ | `diskTime` | null | External texture clock in seconds for replay. Null follows the engine shader clock. |
1751
+ | `diskInflow` | 0.002 | Prescribed inward drift in M per unit of orbital time, with zero giving circular advection. |
1752
+ | `exposure` | 1 | Linear exposure of the output. |
1753
+ | `view` | `'beauty'` | The picture, or a map that explains it: redshift g, beaming g^4, observed temperature, image order. |
1754
+ | `prefilter` | true | Band-limit the disk and draw stars as points through the lens (off shows a plain point-sampled march). |
1755
+ | `steps` | 260 | Integration steps per ray. |
1756
+
1757
+ The material backtraces each disk emitter through Kerr circular angular velocity and a steady radial drift
1758
+ before sampling its texture. The beaming map keeps the approaching side's Doppler factor and weights it by
1759
+ the moving emission. `hole.diskTime` can receive elapsed seconds from `PhysicsWorld`, and `kerrDiskAdvection`
1760
+ gives the corresponding radius and angular phase on the CPU.
1761
+
1762
+ The output is linear HDR: the disk's flux peak is about 0.8 before `exposure`, its Doppler-boosted side several times
1763
+ that. For a glowing picture, raise `exposure` and end with threshold-free bloom and a filmic curve, as
1764
+ `examples/event-horizon` does: `exposure: 4.9` on the hole, `new Bloom({strength: 0.05, threshold: 0, radius: 0.6})`
1765
+ and `new Tonemap({curve: 'acescg', contrast: 1.15})`.
1766
+
1767
+ How it works (sources, read as papers only):
1768
+
1769
+ - Kerr null geodesics in Boyer-Lindquist coordinates and the camera's ray in the zero-angular-momentum frame: O. James,
1770
+ E. von Tunzelmann, P. Franklin and K. S. Thorne, "Gravitational lensing by spinning black holes in astrophysics, and
1771
+ in the movie Interstellar", Classical and Quantum Gravity 32, 065001 (2015), eqs. A.9 to A.15,
1772
+ https://arxiv.org/abs/1502.03808. Stars are points carried through the inverse pixel-footprint jacobian with their
1773
+ magnification, as that paper's ray bundles do, so lensing never stretches them into dashes.
1774
+ - Horizon, ISCO, photon orbit and circular-orbit angular velocity: J. M. Bardeen, W. H. Press and S. A. Teukolsky,
1775
+ "Rotating black holes: locally nonrotating frames, energy extraction, and scalar synchrotron radiation", ApJ 178, 347
1776
+ (1972), https://ui.adsabs.harvard.edu/abs/1972ApJ...178..347B. Redshift g = 1 / (u^t (1 - Omega b)).
1777
+ - Disk flux: D. N. Page and K. S. Thorne, "Disk-accretion onto a black hole. Time-averaged structure of accretion
1778
+ disk", ApJ 191, 499 (1974), eq. 15n, https://ui.adsabs.harvard.edu/abs/1974ApJ...191..499P. Observed intensity g^4 F:
1779
+ J.-P. Luminet, "Image of a spherical black hole with thin accretion disk", A&A 75, 228 (1979),
1780
+ https://ui.adsabs.harvard.edu/abs/1979A&A....75..228L.
1781
+ - Jet: a parabolic funnel near the hole (K. Asada and M. Nakamura, "The structure of the M87 jet: a transition from
1782
+ parabolic to conical streamlines", ApJL 745, L28 (2012), https://ui.adsabs.harvard.edu/abs/2012ApJ...745L..28A),
1783
+ brightness D^(2 + alpha) (M. L. Lind and R. D. Blandford, "Semidynamical models of radio jets: relativistic beaming
1784
+ and source counts", ApJ 295, 358 (1985), https://ui.adsabs.harvard.edu/abs/1985ApJ...295..358L): side on it beams
1785
+ away and is nearly invisible; down the axis it is bright. Its light also climbs out of the hole's potential: the
1786
+ frequency ratio is the zero-angular-momentum frame's lapse times D (`kerrLapse`, Bardeen, Press and Teukolsky 1972),
1787
+ and the emitters switch on from 1.2 to 3 r_s, since the funnel next to the hole is starved of mass (R. D. Blandford
1788
+ and R. L. Znajek, "Electromagnetic extraction of energy from Kerr black holes", MNRAS 179, 433 (1977),
1789
+ https://doi.org/10.1093/mnras/179.3.433; J. C. McKinney, "General relativistic magnetohydrodynamic simulations of the
1790
+ jet formation and large-scale propagation from black hole accretion systems", MNRAS 368, 1561 (2006),
1791
+ https://arxiv.org/abs/astro-ph/0603045). Without both, the jet's base shone as a dot over the shadow seen from
1792
+ near the pole.
1793
+ - Disk detail without banding: the pixel footprint from ray differentials (H. Igehy, "Tracing ray differentials",
1794
+ SIGGRAPH 1999, https://graphics.stanford.edu/papers/trd/), octaves faded above the footprint's Nyquist limit (A.
1795
+ Norton, A. P. Rockwood and P. T. Skolmoski, "Clamping: a method of antialiasing textured surfaces by bandwidth
1796
+ limiting in object space", SIGGRAPH 1982, https://doi.org/10.1145/965145.801274), and two advected noise phases
1797
+ crossfaded every 24 s so Keplerian shear never winds the pattern without bound (F. Neyret, "Advected textures",
1798
+ SCA 2003, https://hal.inria.fr/inria-00537472). The turbulent brightness is log-normal, exp(5 turbulence n), as the
1799
+ surface density of magnetised disk turbulence is (S. A. Balbus and J. F. Hawley, "A powerful local shear instability
1800
+ in weakly magnetized disks. I. Linear analysis", ApJ 376, 214 (1991),
1801
+ https://ui.adsabs.harvard.edu/abs/1991ApJ...376..214B), so bright knots and dark lanes read at video resolution.
1802
+ - Sky: stars on a latitude-band grid in two layers (140 and 300 bands), a steep luminosity function and colours
1803
+ on the Planckian locus from 3,000 to 15,000 K. They crowd towards the galactic plane (5% of cells at the poles, about
1804
+ 20% in the plane), and the Milky Way is a thin and a thick disk and a bulge cut by dust lanes, so the lens visibly
1805
+ bends the band and its crowded star field into the Einstein ring.
1806
+ - The spin axis: Boyer-Lindquist coordinates are singular there. A ray of axial angular momentum b turns at
1807
+ sin(theta_min) = |b| / sqrt(q + a^2); near the axis each step covers at most a quarter of the way left to that turn
1808
+ (`kerrAxisStep`), and a ray that would turn within a third of `POLE_BAND` (0.001) is taken over the axis instead
1809
+ (`kerrAxial`): inside the band it goes straight, and the reflection at theta = 0 turns its phi by the swing a
1810
+ straight line makes there, 2 acos(theta_min / POLE_BAND) (`kerrAxisTurn`). Before, rays a hundredth of a pixel apart
1811
+ near the axis left in unrelated directions, a dashed seam through the sky and over the far disk. The disk-plane
1812
+ crossing test is half open (`crossesEquator`): a product test lost the crossing when a step ended exactly on theta =
1813
+ pi / 2 in f32, a dark speck on the disk.
1814
+ - Colour: the Planckian locus as cubic fits (B. Kang, O. Moon, C. Hong, H. Lee, B. Cho and Y. Kim, "Design of advanced color temperature control system for HDTV applications", Journal of the
1815
+ Korean Physical Society 41, 865 (2002)).
1816
+
1817
+ The CPU twin (`traceGeodesic`, `kerrRhs`, `kerrAxisStep`, `kerrAxial`, `kerrAxisTurn`, `crossesEquator`, `kerrLapse`,
1818
+ `novikovThorneFlux`, `diskRedshift`, `jetDoppler`, `blackbodyColor` and the radius functions) runs the same integrator
1819
+ step for step, for overlays and tests. Limits: a ray gets at most `steps` steps, so rays that graze the photon orbit
1820
+ end dark; the null condition holds under 1e-5 on escaping rays and drifts more on retrograde captured rays inside 4 M.
1821
+ The camera frame is built without atan2: one GPU compiler drops the sign of a negated component of a constant-scaled
1822
+ vector in a division (docs/known-bugs.md). GPU checks: `node packages/shader/test/black-hole-check.mjs` (camera frame,
1823
+ round stars, the jet side on, disk detail over time) and `node packages/shader/test/negated-division-check.mjs`
1824
+ (Margo's formulations, and whether the fault is present).
1825
+
1826
+ ## Saving shader materials (`@margoengine/shader/serialization`)
1827
+
1828
+ `shaderMaterialCodecs` lets `captureMaterialLibrary` and `restoreMaterialLibrary` from
1829
+ `@margoengine/materials/serialization` save `NodeMaterial`, `LightingMaterial` and `RawShaderMaterial` with the rest of
1830
+ a scene's materials, as plain JSON. A node material is saved compiled: its WGSL, its program's uniform block,
1831
+ declarations and bindings, and every base material option. Restoring rebuilds the material from that, without the
1832
+ node graph and without compiling anything again.
1833
+
1834
+ ```ts
1835
+ import { captureMaterialLibrary, restoreMaterialLibrary } from 'margoengine/materials/serialization';
1836
+ import { NodeMaterial, uniform, color, mix, uv } from 'margoengine/shader';
1837
+ import { shaderMaterialCodecs } from 'margoengine/shader/serialization';
1838
+
1839
+ const tint = uniform('#ff8800', { name: 'tint' }); // one live uniform, read by both materials
1840
+ const wall = new NodeMaterial({ colorNode: mix(color('#2040ff'), tint, uv().y) });
1841
+ const glow = new NodeMaterial({ emissiveNode: tint.mul(0.5), roughness: 0.3 });
1842
+
1843
+ const text = JSON.stringify(await captureMaterialLibrary({ wall, glow }, { codecs: shaderMaterialCodecs }));
1844
+ const copy = await restoreMaterialLibrary(JSON.parse(text), { codecs: shaderMaterialCodecs });
1845
+ const restored = copy.wall as NodeMaterial, other = copy.glow as NodeMaterial;
1846
+ console.log(restored.fragmentCode === wall.fragmentCode, other.roughness); // true 0.3
1847
+ const shared = restored.program.members[0].node!;
1848
+ console.log(shared === other.program.members[0].node, shared !== tint); // true true: one new uniform for both
1849
+ shared.value = [0, 1, 0]; // live, as before the save: both restored materials turn green
1850
+ ```
1851
+
1852
+ - **What each codec keeps.** Node and lighting materials: the compiled WGSL of every stage and pass, the uniform block
1853
+ and its members, storage and texture bindings, and the base `Material` parameters (`materialParameters`). Uniform
1854
+ nodes: type, name and current value. Storage inputs (`storage(array, type)`): a copy of the data, its element type
1855
+ and whether it is atomic. Sampled textures (`texture`, `textureCube`, `texture3D`, `textureArray`): the texture,
1856
+ stored by the materials library like any other. Raw materials: the WGSL, entry point names, extra bind groups,
1857
+ uniforms, textures, storage and the full render state (blending, depth, bias, cull, colour writes, wireframe,
1858
+ alpha to coverage).
1859
+ - **Shared values stay shared.** A uniform, buffer or texture used by several materials is stored once and restored
1860
+ as one new object used by all of them, so a value written after the restore drives every copy, as it did before.
1861
+ The originals are never touched.
1862
+ - **Fixed graphs.** A restored node material draws what was saved; to change its nodes, build a new material (nodes
1863
+ are fixed at construction anyway, see Limits). A library from a different shader format throws a `TypeError` that
1864
+ says so.
1865
+ - **GLSL materials** need `glslMaterialCodec(ShaderMaterial)` as well (see [saving GLSL
1866
+ materials](#points-flat-varyings-wireframes-and-saving)), which keeps the GLSL and translates it again.
1867
+ - **Functions.** An `onError` callback on a raw material is code, not data: capture throws a MargoError `state`
1868
+ unless `externalKey` names it and `resolveExternal` hands it back on restore, as for any other app value.
1869
+ - **Lazy loading.** Pass `loadCodecs: async () => (await import('margoengine/shader/serialization')).shaderMaterialCodecs`
1870
+ instead of `codecs`, and a library with no shader materials in it never downloads this entry.
1871
+
1872
+ ## Core compatibility at engine boundaries
1873
+
1874
+ Each engine-bound entry (`.`, `/graph`, `/readback`, `/raw`, `/black-hole`, `/effects`, `/editor`, `/compute-texture`, `/lighting`, `/deform`, `/pass`, `/subgroups`, `/serialization`, `/compute-volume`, `/editor-pass`, `/glsl-material`, `/glsl-pass`, `/shadertoy`) carries the core version its build was made for, stamped into its plugins, `attach` methods and `engineRuntime` calls, and checks the engine's core when it attaches or its plugin is set up, before it reads or changes the engine. A mismatched core version, or a second core module in the page (two installs, or one bundled twice), throws MargoError `'version'` naming both cores and the package, with the help link https://margoengine.com/errors#version. The cure is one core: dedupe or rebuild the packages against the same core build (`npm ls @margoengine/core` lists the copies); do not catch the error and go on. The check keeps no global state, and importing an entry registers nothing and attaches nothing. Details: [One core per engine](../core/README.md#one-core-per-engine-version-checks-extension) in the core README. The other entries (`/noise`, `/utils`, `/texture-array`, `/glsl`) carry no check of their own: the build found no plugin, `attach` or `engineRuntime` call in them, and anything they hand to an engine is checked by the entry that attaches it.
1875
+
1876
+ ## Limits
1877
+
1878
+ - Nodes are fixed when a NodeMaterial, NodePass or ComputePass is constructed; build a new one to change the graph. Only uniform values, textures' pixels and storage contents change live.
1879
+ - NodeMaterial patches gltf/pbr's shader (standard and KHR physical variants); [Node output in every pass](#node-output-in-every-pass) lists what the other passes see. At most 8 varyings. Its bindings start at group 2, binding 48, and node textures count against WebGPU's 16 sampled textures per stage: a `NodeMaterial` on a materials mesh fits 6 texture nodes alone, 5 with directional shadows and 3 with shadows, IBL and LocalShadows; past that, gltf/pbr throws a `RangeError` naming the combination.
1880
+ - `uv()` is the raw first UV set (no texture transform). `select` evaluates both branches; `If` runs one. A NodePass's discarded pixels stay the cleared transparent black. Fn bodies cannot read stage inputs such as `uv()`; pass them as arguments. No automatic derivative-safe sampling: `texture(map, uv)`, `dpdx`, `dpdy` and `fwidth` inside an `If`, `Switch` or `While` on a per-pixel value, or a loop with a non-uniform bound or a `Break` on one, are a WGSL uniformity error, reported when the pipeline compiles; pass `texture` an explicit level there or sample before the branch.
1881
+ - SSR, SSGI, scene targets (`@margoengine/post/mrt`), the clustered `LightBounce` and the node `ScenePass` see a raw mesh's own surface only through `captureEntry`, SSAO and GTAO through `gbufferEntry`; without them they see only the depth it writes. In scene targets a raw mesh's `t.light` is zero and `t.shadow` 1. A raw mesh with `captureEntry` added to an effect whose capture takes no `MargoMaterial` throws an `unsupported` MargoError. TAA velocity sees a mesh's own motion only through `velocityEntry`. A raw pick names the mesh, not the instance, and ignores `discard`. Uniform arrays hold 16-byte elements, struct fields are not arrays or structs, and a material has one colour target, 32-bit attribute formats only and at most two extra bind groups.
1882
+ - NodePass and ShaderPass run only inside a PostStack: a stack of one is fine, and `NodePass.attach` and `ShaderPass.attach` make one. Neither attach joins a PostStack the scene already has (a PostStack's effects are fixed when it is made); add the pass to that stack's array instead. An `hdr` pass that ends the chain tonemaps with ACES.
1883
+ - Subgroup operations and half floats run in ComputePass nodes only: `enable` has to open a module, and a material's shader is assembled from others. There are no `quad*` operations, and no f16 uniforms, storage or textures.
1884
+ - Storage textures are 2D, one mip level, one sample; `@margoengine/shader/compute-texture` has no 3D or array form.
1885
+ - ComputePass dispatches at most 65,535 workgroups per axis (an indirect dispatch is checked by the GPU only) and runs every frame while attached (`computeReadback` runs once; an atomic counter keeps counting unless `update()` resets it). Workgroup memory has no struct elements, and all of a pass's must fit the device's 16,384 bytes. Storage elements are 4- or 8- or 16-byte types (no vec3). A device loss re-uploads the CPU `data`, not what the GPU computed.
1886
+ - `glslFn` takes functions, not whole GLSL programs: no `main`, uniforms, `in`/`out` variables or `gl_` built-ins inside (pass them as arguments). Its parameters are scalars, vectors, square matrices and `sampler2D`, `samplerCube`, `sampler3D` or `sampler2DArray`; the called function takes inputs only (helpers may have `out` and `inout`). Sources are at most 65,536 code units and 32,768 tokens, with at most 128 levels of nesting. Line and column are exact for syntax errors and refusals; a backslash line continuation joins lines, so later lines count one less. `toGLSL` gives the layer's translation with its default options unless you pass them.
1887
+
1888
+ Size (min + gzip, as `examples/package-benchmarks/entry-sizes.mjs` measures it and `examples/package-benchmarks/results/entry-sizes.json` records it: each entry bundled on its own, peers external, so the figures overlap): root entry 18.7 kB; `NodeMaterial` with colour nodes only, 8.6 kB (post, compute, texture and statement code tree-shake away).
1889
+
1890
+ Apache-2.0. Optional, tree-shakable package; peers `@margoengine/core`, `@margoengine/materials` and `@margoengine/gltf/pbr` (^0.1.0 || ^1.0.0).
1891
+
1892
+ Build and unit tests: `npm test --workspace @margoengine/shader`. Browser check on a real WebGPU adapter: `node packages/shader/test/browser-check.mjs`.
1893
+
1894
+ ## Preview tier contract
1895
+
1896
+ GPU-only attachments refuse the small WebGL2 preview during setup with `MargoError` code `unsupported` and a help link. Native WebGPU and the full WebGL2 compatibility layer expose the WebGPU-shaped device these passes need. Use [automatic escalation](../webgl2-compat/README.md#automatic-escalation) with awaited setup to load the full layer when required. Existing real preview routes remain available.
1897
+
1898
+ ## Film time
1899
+
1900
+ A `Shadertoy` (and a Shadertoy pass) moves iTime and iFrame with `advanceTime(delta)` in the frame update, so `seek` from `@margoengine/cutscene/seek` starts a film scene on the frame a continuous run shows. iDate follows the wall clock unless you set `date`.
1901
+
1902
+ Shader `time` and `deltaTime` (node materials, `NodePass`, `ComputePass` and the raw camera block, `margoBefore.time` included) read the engine's frame clock, `ShaderClock`: seconds of frame deltas since it started, never the wall clock, so the same frame draws the same picture and a seek replays it with every other clock. `RawShaders`, `ComputePass` and `NodePass` attach it with themselves (the plugin `shader:clock`) and remove it with the last of them. A node material on an engine without one attaches it after the first frame that draws it, so attach it yourself before a seek when only node materials read `time`:
1903
+
1904
+ ```ts
1905
+ import {createMesh} from 'margoengine/materials';
1906
+ import {sphereGeometry} from 'margoengine/geometry';
1907
+ import {NodeMaterial, ShaderClock, color, sin, time} from 'margoengine/shader';
1908
+ import {seek} from 'margoengine/cutscene/seek';
1909
+ import {createStage} from 'margoengine';
1910
+ const stage = await createStage('#viewport', {backend: 'webgpu'});
1911
+ const clock = ShaderClock.attach(stage.engine); // one per engine; 0 until the first frame update
1912
+ const glow = sin(time).mul(0.5).add(0.5);
1913
+ createMesh(stage.engine, sphereGeometry(1, 64, 32), new NodeMaterial({colorNode: color('#ff4020').mul(glow)}));
1914
+ // This scene starts 12 s into the film: the pulse is where a run from 0 had it.
1915
+ await seek(stage.engine, 12, {fps: 30});
1916
+ stage.engine.render({delta: 1 / 30});
1917
+ console.log(clock.time); // 360 steps of 1 / 30 s, then the frame's own
1918
+ ```
1919
+
1920
+ Before this, shader `time` was `performance.now()` in seconds, the time since the page opened; it now starts at 0 with the clock.