@margoengine/shader 0.0.0-stage → 0.1.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.
- package/LICENSE +201 -0
- package/NOTICE +4 -0
- package/README.md +1771 -3
- package/dist/black-hole.d.ts +246 -0
- package/dist/black-hole.js +445 -0
- package/dist/clock-BLGNexlt.js +52 -0
- package/dist/clock.d.ts +42 -0
- package/dist/compute-D-BghbXj.js +354 -0
- package/dist/compute-texture.d.ts +100 -0
- package/dist/compute-texture.js +131 -0
- package/dist/compute-volume.d.ts +57 -0
- package/dist/compute-volume.js +130 -0
- package/dist/compute.d.ts +194 -0
- package/dist/control-DvjfV7R0.js +201 -0
- package/dist/control.d.ts +93 -0
- package/dist/deform.d.ts +111 -0
- package/dist/deform.js +89 -0
- package/dist/display-BrJM_Qkd.js +5 -0
- package/dist/editor-model.d.ts +192 -0
- package/dist/editor-pass.d.ts +71 -0
- package/dist/editor-pass.js +216 -0
- package/dist/editor.d.ts +150 -0
- package/dist/editor.js +1071 -0
- package/dist/effects.d.ts +150 -0
- package/dist/effects.js +87 -0
- package/dist/errors-CsQwshHA.js +7 -0
- package/dist/glsl/emit.d.ts +43 -0
- package/dist/glsl/host.d.ts +55 -0
- package/dist/glsl/material.d.ts +173 -0
- package/dist/glsl/parser.d.ts +76 -0
- package/dist/glsl/preprocess.d.ts +9 -0
- package/dist/glsl/presets.d.ts +33 -0
- package/dist/glsl/program.d.ts +210 -0
- package/dist/glsl/scene.d.ts +9 -0
- package/dist/glsl-material.d.ts +82 -0
- package/dist/glsl-material.js +288 -0
- package/dist/glsl-pass.d.ts +93 -0
- package/dist/glsl-pass.js +186 -0
- package/dist/glsl.d.ts +94 -0
- package/dist/glsl.js +170 -0
- package/dist/gpu-DQ5Jmggz.js +31 -0
- package/dist/graph.d.ts +82 -0
- package/dist/graph.js +365 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +8 -0
- package/dist/lighting-Dx8_RsBz.js +77 -0
- package/dist/lighting.d.ts +62 -0
- package/dist/lighting.js +1 -0
- package/dist/material-CU7p-Q8u.js +1184 -0
- package/dist/material-REzUrXtu.js +275 -0
- package/dist/material.d.ts +74 -0
- package/dist/node-DzKv9CF2.js +590 -0
- package/dist/node.d.ts +427 -0
- package/dist/noise.d.ts +38 -0
- package/dist/noise.js +107 -0
- package/dist/own-stack-D1XnXrrz.js +11 -0
- package/dist/own-stack.d.ts +12 -0
- package/dist/pass.d.ts +108 -0
- package/dist/pass.js +236 -0
- package/dist/post-DC62ZleD.js +113 -0
- package/dist/post.d.ts +69 -0
- package/dist/preprocess-CWGWlBWQ.js +1195 -0
- package/dist/raw-D0W8U3Qa.js +1351 -0
- package/dist/raw.d.ts +634 -0
- package/dist/raw.js +1 -0
- package/dist/readback.d.ts +42 -0
- package/dist/readback.js +84 -0
- package/dist/scope.d.ts +21 -0
- package/dist/serialization.d.ts +11 -0
- package/dist/serialization.js +192 -0
- package/dist/shadertoy/sound.d.ts +48 -0
- package/dist/shadertoy.d.ts +249 -0
- package/dist/shadertoy.js +909 -0
- package/dist/shared/caster.d.ts +152 -0
- package/dist/shared/fog.d.ts +33 -0
- package/dist/shared/fractal.d.ts +9 -0
- package/dist/shared/msaa.d.ts +25 -0
- package/dist/shared/stack.d.ts +22 -0
- package/dist/sound-CF_dzP41.js +78 -0
- package/dist/storage-format-DWaiSxmq.js +25 -0
- package/dist/storage-format.d.ts +7 -0
- package/dist/subgroups.d.ts +97 -0
- package/dist/subgroups.js +95 -0
- package/dist/texture-D6vy0bam.js +62 -0
- package/dist/texture-array.d.ts +7 -0
- package/dist/texture-array.js +11 -0
- package/dist/texture.d.ts +16 -0
- package/dist/utils.d.ts +106 -0
- package/dist/utils.js +90 -0
- package/dist/view-rect-Bm1ac-TK.js +16 -0
- package/package.json +151 -6
package/README.md
CHANGED
|
@@ -1,3 +1,1771 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# @margoengine/shader
|
|
2
|
+
|
|
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
|
+
## Skinning and morph targets (`@margoengine/shader/deform`)
|
|
422
|
+
|
|
423
|
+
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.
|
|
424
|
+
|
|
425
|
+
```ts
|
|
426
|
+
import {createStage} from 'margoengine';
|
|
427
|
+
import {createMesh} from 'margoengine/materials';
|
|
428
|
+
import {planeGeometry} from 'margoengine/geometry';
|
|
429
|
+
import {NodeMaterial, sin, storage, time, vec3} from 'margoengine/shader';
|
|
430
|
+
import {morphing, skinning, worldNormal} from 'margoengine/shader/deform';
|
|
431
|
+
const stage = await createStage('#app');
|
|
432
|
+
const geometry = planeGeometry(2, 2, 16, 16), vertices = geometry.positions.length / 3;
|
|
433
|
+
const skin = skinning({
|
|
434
|
+
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
|
|
435
|
+
joints: storage(new Uint32Array(vertices * 4), 'vec4u'), // four bone numbers per vertex
|
|
436
|
+
weights: storage(new Float32Array(vertices * 4).map((_, i) => (i % 4 ? 0 : 1)), 'vec4f'),
|
|
437
|
+
});
|
|
438
|
+
const morph = morphing({
|
|
439
|
+
count: 1,
|
|
440
|
+
vertices,
|
|
441
|
+
positions: storage(new Float32Array(vertices * 4), 'vec4f'), // offsets, target after target
|
|
442
|
+
weights: storage(new Float32Array([0.5]), 'f32'),
|
|
443
|
+
});
|
|
444
|
+
createMesh(stage.engine, geometry, new NodeMaterial({
|
|
445
|
+
positionNormals: 'keep', // normalNode below replaces them
|
|
446
|
+
positionNode: skin.position(morph.position()).add(vec3(0, sin(time).mul(0.1), 0)), // morph, then bones, then an effect
|
|
447
|
+
normalNode: worldNormal(skin.normal(morph.normal())),
|
|
448
|
+
}));
|
|
449
|
+
```
|
|
450
|
+
|
|
451
|
+
Update the pose by writing the buffer's `data` and calling `update()`, or write the buffer from a `ComputePass`.
|
|
452
|
+
|
|
453
|
+
| Function | Returns | Notes |
|
|
454
|
+
| --- | --- | --- |
|
|
455
|
+
| `skinningFromModel(model, primitive)` | `skinning()`'s result and `{geometry, bones, joints, weights, update()}` | `primitive` is an entry of `model.primitives` whose node has a skin. |
|
|
456
|
+
| `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. |
|
|
457
|
+
| `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. |
|
|
458
|
+
| `worldNormal(n)` | a `normalNode` | A mesh-space normal in world space, per vertex and interpolated. Right on scaled and mirrored meshes. |
|
|
459
|
+
|
|
460
|
+
**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.
|
|
461
|
+
|
|
462
|
+
**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.
|
|
463
|
+
|
|
464
|
+
```ts
|
|
465
|
+
import {createStage} from 'margoengine';
|
|
466
|
+
import {createMesh} from 'margoengine/materials';
|
|
467
|
+
import {loadGLTF} from 'margoengine/gltf/pbr';
|
|
468
|
+
import {Animation} from 'margoengine/animation';
|
|
469
|
+
import {NodeMaterial, positionWorld, sin, time, vec3} from 'margoengine/shader';
|
|
470
|
+
import {skinningFromModel, worldNormal} from 'margoengine/shader/deform';
|
|
471
|
+
const stage = await createStage('#app', {autoStart: false});
|
|
472
|
+
const {engine} = stage;
|
|
473
|
+
const model = await loadGLTF(engine, '/fox.glb');
|
|
474
|
+
const animation = Animation.attach(model);
|
|
475
|
+
const fox = skinningFromModel(model, model.primitives[0]);
|
|
476
|
+
createMesh(engine, fox.geometry, new NodeMaterial({
|
|
477
|
+
positionNode: fox.position().add(vec3(0, sin(time).mul(5), 0)),
|
|
478
|
+
normalNode: worldNormal(fox.normal()),
|
|
479
|
+
colorNode: positionWorld.normalize(),
|
|
480
|
+
}));
|
|
481
|
+
model.root.visible = false; // show the node version alone
|
|
482
|
+
engine.onFrame(() => fox.update());
|
|
483
|
+
engine.start();
|
|
484
|
+
```
|
|
485
|
+
|
|
486
|
+
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.
|
|
487
|
+
|
|
488
|
+
**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.
|
|
489
|
+
|
|
490
|
+
`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.
|
|
491
|
+
|
|
492
|
+
## Extra outputs and scene passes (`@margoengine/shader/pass`)
|
|
493
|
+
|
|
494
|
+
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.
|
|
495
|
+
|
|
496
|
+
```ts
|
|
497
|
+
import {createStage} from 'margoengine';
|
|
498
|
+
import {Material, createMesh} from 'margoengine/materials';
|
|
499
|
+
import {planeGeometry} from 'margoengine/geometry';
|
|
500
|
+
import {PostStack} from 'margoengine/post';
|
|
501
|
+
import {NodePass, inputColor, texture, uv, vec4} from 'margoengine/shader';
|
|
502
|
+
import {PassMaterial, ScenePass} from 'margoengine/shader/pass';
|
|
503
|
+
const stage = await createStage('#app');
|
|
504
|
+
const pass = ScenePass.attach(stage.engine, {outputs: {glow: 'rgba16float'}});
|
|
505
|
+
const lamp = createMesh(stage.engine, planeGeometry(1, 1), new PassMaterial({outputs: {glow: vec4(4, 2, 1, 1)}}));
|
|
506
|
+
const wall = createMesh(stage.engine, planeGeometry(4, 4), new Material({color: [0.5, 0.5, 0.5]}));
|
|
507
|
+
pass.add(lamp);
|
|
508
|
+
pass.add(wall); // a plain mesh hides the glow it covers
|
|
509
|
+
PostStack.attach(stage.engine, [new NodePass(inputColor().rgb.add(texture(pass.texture('glow'), uv()).rgb))]);
|
|
510
|
+
```
|
|
511
|
+
|
|
512
|
+
| Name | What it does |
|
|
513
|
+
| --- | --- |
|
|
514
|
+
| `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. |
|
|
515
|
+
| `pass.add(model)` | Draws a gltf/pbr model or a mesh in the pass, opaque and masked surfaces only. Returns a remover. |
|
|
516
|
+
| `pass.texture(name)` | The output for `texture()`, the size of the drawing buffer. Transparent black where nothing was drawn. |
|
|
517
|
+
| `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. |
|
|
518
|
+
| `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. |
|
|
519
|
+
|
|
520
|
+
**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:
|
|
521
|
+
|
|
522
|
+
```ts
|
|
523
|
+
import {createStage} from 'margoengine';
|
|
524
|
+
import {Material, createMesh} from 'margoengine/materials';
|
|
525
|
+
import {planeGeometry} from 'margoengine/geometry';
|
|
526
|
+
import {NodeMaterial, screenUV, sin, texture, time, vec2} from 'margoengine/shader';
|
|
527
|
+
import {ScenePass} from 'margoengine/shader/pass';
|
|
528
|
+
const stage = await createStage('#app');
|
|
529
|
+
const pass = ScenePass.attach(stage.engine, {outputs: {color: 'rgba16float'}});
|
|
530
|
+
pass.add(createMesh(stage.engine, planeGeometry(4, 4), new Material({color: [0.8, 0.3, 0.2]})));
|
|
531
|
+
const wobble = vec2(sin(screenUV.y.mul(40).add(time)).mul(0.01), 0);
|
|
532
|
+
const pane = createMesh(stage.engine, planeGeometry(1, 1), new NodeMaterial({emissiveNode: texture(pass.texture('color'), screenUV.add(wobble)).rgb}));
|
|
533
|
+
pane.root.setPosition([0, 0, 0.5]);
|
|
534
|
+
```
|
|
535
|
+
|
|
536
|
+
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.
|
|
537
|
+
|
|
538
|
+
**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:
|
|
539
|
+
|
|
540
|
+
```ts
|
|
541
|
+
import {createStage} from 'margoengine';
|
|
542
|
+
import {createMesh} from 'margoengine/materials';
|
|
543
|
+
import {planeGeometry} from 'margoengine/geometry';
|
|
544
|
+
import {NodeMaterial, screenUV, sin, time, vec2} from 'margoengine/shader';
|
|
545
|
+
import {sceneColor} from 'margoengine/shader/pass';
|
|
546
|
+
const stage = await createStage('#app');
|
|
547
|
+
const behind = sceneColor(stage.engine);
|
|
548
|
+
stage.box({color: '#c04030'});
|
|
549
|
+
const wobble = vec2(sin(screenUV.y.mul(40).add(time)).mul(0.01), 0);
|
|
550
|
+
const pane = createMesh(stage.engine, planeGeometry(2, 2), new NodeMaterial({shading: 'basic', transparent: true, toneMapped: false, emissiveNode: behind.read(screenUV.add(wobble))}));
|
|
551
|
+
pane.root.setPosition([0, 0, 1]);
|
|
552
|
+
```
|
|
553
|
+
|
|
554
|
+
`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.
|
|
555
|
+
|
|
556
|
+
`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.
|
|
557
|
+
|
|
558
|
+
## Node output in every pass
|
|
559
|
+
|
|
560
|
+
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:
|
|
561
|
+
|
|
562
|
+
```ts
|
|
563
|
+
import {createStage} from 'margoengine';
|
|
564
|
+
import {createMesh} from 'margoengine/materials';
|
|
565
|
+
import {planeGeometry} from 'margoengine/geometry';
|
|
566
|
+
import {Shadows} from 'margoengine/shadows';
|
|
567
|
+
import {NodeMaterial, discard, normalLocal, positionLocal, sin, time, uv, vec3} from 'margoengine/shader';
|
|
568
|
+
const stage = await createStage('#app');
|
|
569
|
+
const flag = new NodeMaterial({
|
|
570
|
+
doubleSided: true,
|
|
571
|
+
positionNode: positionLocal.add(normalLocal.mul(sin(positionLocal.x.mul(6).add(time)).mul(0.1))), // shading follows the wave
|
|
572
|
+
colorNode: discard(uv().y.lessThan(0.1), vec3(0.8, 0.1, 0.1)), // the shadow has the same hole
|
|
573
|
+
});
|
|
574
|
+
const mesh = createMesh(stage.engine, planeGeometry(2, 1, 64, 32), flag), shadows = Shadows.attach(stage.engine);
|
|
575
|
+
shadows.add(mesh);
|
|
576
|
+
```
|
|
577
|
+
|
|
578
|
+
| Pass | `positionNode` | `normalNode` | `discard()` |
|
|
579
|
+
| --- | --- | --- | --- |
|
|
580
|
+
| Colour, SSAO's G-buffer and ambient passes | yes | yes | yes |
|
|
581
|
+
| `Shadows`, `VirtualShadows`, `LocalShadows`, `Clustered` integrated shadows | yes | not read | yes |
|
|
582
|
+
| Picking primitives and contact shadows | yes | not read | yes |
|
|
583
|
+
| 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 |
|
|
584
|
+
|
|
585
|
+
**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'`.
|
|
586
|
+
|
|
587
|
+
**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.
|
|
588
|
+
|
|
589
|
+
`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.
|
|
590
|
+
|
|
591
|
+
## Lighting written in the graph (`@margoengine/shader/lighting`)
|
|
592
|
+
|
|
593
|
+
`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.
|
|
594
|
+
|
|
595
|
+
```ts
|
|
596
|
+
import {createStage} from 'margoengine';
|
|
597
|
+
import {createMesh} from 'margoengine/materials';
|
|
598
|
+
import {sphereGeometry} from 'margoengine/geometry';
|
|
599
|
+
import {Shadows} from 'margoengine/shadows';
|
|
600
|
+
import {Clustered} from 'margoengine/clustered';
|
|
601
|
+
import {floor, max, normalWorld, reflect, viewDirection} from 'margoengine/shader';
|
|
602
|
+
import {LightingMaterial, ambientLight, environment, localLight, sunColor, sunDirection, sunVisibility} from 'margoengine/shader/lighting';
|
|
603
|
+
const stage = await createStage('#app');
|
|
604
|
+
// A BRDF of your own, for the sun and every clustered light: three flat bands.
|
|
605
|
+
const toon = new LightingMaterial({
|
|
606
|
+
color: '#3366ff',
|
|
607
|
+
lightModel: ({normal, direction, color}) => color.mul(floor(max(normal.dot(direction), 0).mul(3).add(0.5)).div(3)),
|
|
608
|
+
});
|
|
609
|
+
// 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.
|
|
610
|
+
const inked = new LightingMaterial({
|
|
611
|
+
color: '#ff8000',
|
|
612
|
+
lightingNode: sunColor.mul(sunVisibility).mul(normalWorld.dot(sunDirection).step(0.3).mul(0.25))
|
|
613
|
+
.add(localLight).add(ambientLight)
|
|
614
|
+
.add(environment(reflect(viewDirection.negate(), normalWorld), 0.2).mul(0.1)),
|
|
615
|
+
});
|
|
616
|
+
const shadows = Shadows.attach(stage.engine), lights = Clustered.attach(stage.engine);
|
|
617
|
+
lights.setLights([{position: [0, 2, 1], range: 12, color: [1, 0.3, 0.1], intensity: 20}]);
|
|
618
|
+
for (const material of [toon, inked]) {
|
|
619
|
+
const mesh = createMesh(stage.engine, sphereGeometry(0.8, 32, 16), material);
|
|
620
|
+
shadows.add(mesh);
|
|
621
|
+
lights.add(mesh);
|
|
622
|
+
}
|
|
623
|
+
```
|
|
624
|
+
|
|
625
|
+
- **`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`.
|
|
626
|
+
- **`lightingNode`** is the final linear colour of the pixel, before fog and tone mapping. It reads:
|
|
627
|
+
|
|
628
|
+
| Node | What it reads | Without the effect |
|
|
629
|
+
| --- | --- | --- |
|
|
630
|
+
| `sunDirection` | unit vector towards the sun | |
|
|
631
|
+
| `sunColor` | the sun's colour times intensity, before shadows | |
|
|
632
|
+
| `sunVisibility` | the shadow effect's result per channel, 0 to 1 | 1 |
|
|
633
|
+
| `localLight` | the sum of the clustered lights, with their shadows | zero |
|
|
634
|
+
| `ambientLight` | ambient light with the material's response: image-based light, probes, the sky | the built-in sky |
|
|
635
|
+
| `litColor` | the colour the material shows with its usual lighting | |
|
|
636
|
+
| `environment(direction, roughness = 0)` | the scene's ambient light on a mirror facing `direction`, also in `lightModel` | the built-in sky |
|
|
637
|
+
|
|
638
|
+
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.
|
|
639
|
+
|
|
640
|
+
`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.
|
|
641
|
+
|
|
642
|
+
## The compute model
|
|
643
|
+
|
|
644
|
+
`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:
|
|
645
|
+
|
|
646
|
+
```ts
|
|
647
|
+
import {ComputePass, Loop, If, Var, globalId, localIndex, storage, uint, workgroup, workgroupBarrier} from 'margoengine/shader';
|
|
648
|
+
import {createStage} from 'margoengine';
|
|
649
|
+
const stage = await createStage('#viewport', {backend: 'webgpu'});
|
|
650
|
+
const values = new Uint32Array(1024).fill(1);
|
|
651
|
+
const input = storage(Uint32Array.from(values), 'u32'), sums = storage(values.length, 'u32');
|
|
652
|
+
const tile = workgroup(256, 'u32');
|
|
653
|
+
ComputePass.attach(stage.engine, values.length, i => { // values.length: a multiple of 256, as it has barriers
|
|
654
|
+
tile.store(localIndex, input.element(i));
|
|
655
|
+
workgroupBarrier();
|
|
656
|
+
const step = Var(uint(1));
|
|
657
|
+
Loop(8, () => {
|
|
658
|
+
const mine = Var(tile.element(localIndex));
|
|
659
|
+
If(localIndex.greaterThanEqual(step), () => mine.addAssign(tile.element(localIndex.sub(step))));
|
|
660
|
+
workgroupBarrier(); // everyone has read
|
|
661
|
+
tile.store(localIndex, mine);
|
|
662
|
+
workgroupBarrier(); // everyone has written
|
|
663
|
+
step.mulAssign(uint(2));
|
|
664
|
+
});
|
|
665
|
+
return sums.store(i, tile.element(localIndex));
|
|
666
|
+
}, {workgroupSize: 256});
|
|
667
|
+
|
|
668
|
+
const image = storage(640 * 480, 'vec4f');
|
|
669
|
+
ComputePass.attach(stage.engine, [640, 480], i => image.store(i, globalId.toFloat().xyzz)); // 2D: i runs row by row
|
|
670
|
+
|
|
671
|
+
const args = storage(new Uint32Array([0, 1, 1]), 'u32'); // workgroups x, y, z, written by an earlier pass
|
|
672
|
+
ComputePass.attach(stage.engine, 1, () => args.store(0, sums.element(0).div(64).add(1)));
|
|
673
|
+
ComputePass.attach(stage.engine, 1 << 20, i => image.store(i, globalId.toFloat().xyzz), {indirect: args, order: -99});
|
|
674
|
+
```
|
|
675
|
+
|
|
676
|
+
- **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.
|
|
677
|
+
- **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.
|
|
678
|
+
- **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.
|
|
679
|
+
- **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`.
|
|
680
|
+
- **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.
|
|
681
|
+
|
|
682
|
+
`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.
|
|
683
|
+
|
|
684
|
+
## Subgroups and half floats (`@margoengine/shader/subgroups`)
|
|
685
|
+
|
|
686
|
+
WebGPU's two optional compute features as nodes. Each comes from a function of the engine, which writes the fast WGSL when
|
|
687
|
+
the device has the feature and portable WGSL when it does not, so one graph runs everywhere. Ask for the features when you
|
|
688
|
+
create the engine; an adapter that lacks one simply leaves it out.
|
|
689
|
+
|
|
690
|
+
```ts
|
|
691
|
+
import {createStage} from 'margoengine';
|
|
692
|
+
import {ComputePass, If, Let, storage} from 'margoengine/shader';
|
|
693
|
+
import {halfFloats, subgroups} from 'margoengine/shader/subgroups';
|
|
694
|
+
const stage = await createStage('#app', {features: ['subgroups', 'shader-f16']});
|
|
695
|
+
const sg = subgroups(stage.engine), h = halfFloats(stage.engine);
|
|
696
|
+
|
|
697
|
+
const values = storage(new Uint32Array(1024).fill(3), 'u32'), total = storage(1, 'u32', {atomic: true});
|
|
698
|
+
ComputePass.attach(stage.engine, 1024, i => {
|
|
699
|
+
const sum = Let(sg.add(values.element(i))); // all lanes at once, kept before any branch
|
|
700
|
+
If(sg.elect(), () => { total.atomicAdd(0, sum); }); // one atomic per subgroup, not one per invocation
|
|
701
|
+
});
|
|
702
|
+
|
|
703
|
+
const input = storage(new Float32Array(1024).fill(0.5), 'f32'), output = storage(1024, 'f32');
|
|
704
|
+
ComputePass.attach(stage.engine, 1024, i => output.store(i, h.full(h.half(input.element(i)).mul(0.25).add(1))));
|
|
705
|
+
console.log(sg.supported, h.supported);
|
|
706
|
+
```
|
|
707
|
+
|
|
708
|
+
| Node | What each lane gets | With no `subgroups` feature |
|
|
709
|
+
| --- | --- | --- |
|
|
710
|
+
| `sg.size`, `sg.id` | lanes in this subgroup, this lane's number | `1`, `0` |
|
|
711
|
+
| `sg.add`, `mul`, `min`, `max`, `and`, `or`, `xor` | the reduction over the lanes | `x` |
|
|
712
|
+
| `sg.inclusiveAdd`, `inclusiveMul` | the reduction up to and including this lane | `x` |
|
|
713
|
+
| `sg.exclusiveAdd`, `exclusiveMul` | the reduction over the lanes before this one | `0`, `1` |
|
|
714
|
+
| `sg.all(b)`, `sg.any(b)` | whether `b` holds on every lane, on any lane | `b` |
|
|
715
|
+
| `sg.ballot(b)` | a bit per lane where `b` holds | `b` as bit 0 |
|
|
716
|
+
| `sg.elect()` | true on one lane | `true` |
|
|
717
|
+
| `sg.broadcast(x, lane)`, `sg.broadcastFirst(x)` | `x` of that lane, a constant, or the first active lane | `x` |
|
|
718
|
+
| `sg.shuffle(x, lane)`, `shuffleUp`, `shuffleDown`, `shuffleXor` | `x` of another lane | `x` |
|
|
719
|
+
|
|
720
|
+
- **The fallback is a subgroup of one lane.** WebGPU never promises a subgroup size, so code written properly works for any
|
|
721
|
+
`size`, and one is a size: nothing to branch on, no shared memory, and the same answer at the end. Lanes of a `shuffle`
|
|
722
|
+
must stay below `size`.
|
|
723
|
+
- **Uniform control flow.** A subgroup call has to run on every lane together, so a ComputePass that uses one runs whole
|
|
724
|
+
workgroups as a barrier does: its count is a multiple of `workgroupSize`, and WGSL refuses a call under a branch. Keep a
|
|
725
|
+
result with `Let` before an `If`.
|
|
726
|
+
- **Half floats.** `h.half(x)` gives an f16 node (`'f16'`, `'vec2h'` to `'vec4h'`) and `h.full(x)` turns it back. Numbers join in
|
|
727
|
+
as `0.25h`, and an f32 node has to go through `half` first, which TypeScript checks. Without `shader-f16` the same graph
|
|
728
|
+
stays f32, so a value keeps more precision and goes past 65,504 without turning infinite.
|
|
729
|
+
- **Packed storage.** `packHalf2(vec2)` and `unpackHalf2(u32)` hold two floats rounded to f16 in one u32 on every device.
|
|
730
|
+
Storage buffers have no f16 element type.
|
|
731
|
+
|
|
732
|
+
## Compute that writes textures (`@margoengine/shader/compute-texture`)
|
|
733
|
+
|
|
734
|
+
`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.
|
|
735
|
+
|
|
736
|
+
```ts
|
|
737
|
+
import {createStage} from 'margoengine';
|
|
738
|
+
import {createMesh} from 'margoengine/materials';
|
|
739
|
+
import {planeGeometry} from 'margoengine/geometry';
|
|
740
|
+
import {ComputePass, NodeMaterial, texture, vec2, vec4} from 'margoengine/shader';
|
|
741
|
+
import {pingPong} from 'margoengine/shader/compute-texture';
|
|
742
|
+
const stage = await createStage('#app');
|
|
743
|
+
const grid = pingPong(256, 256); // rgba16float, zeros
|
|
744
|
+
ComputePass.attach(stage.engine, grid.pixels, i => {
|
|
745
|
+
const at = grid.coord(i), p = grid.uv(at), step = vec2(1 / 256, 0);
|
|
746
|
+
const blur = texture(grid, p.sub(step), 0).add(texture(grid, p.add(step), 0)).mul(0.5); // filtered reads of last step
|
|
747
|
+
return grid.store(at, blur.mul(0.99).add(vec4(p.x.mul(0.01)))); // writes the next
|
|
748
|
+
});
|
|
749
|
+
createMesh(stage.engine, planeGeometry(2, 2), new NodeMaterial({shading: 'basic', colorNode: texture(grid).rgb}));
|
|
750
|
+
```
|
|
751
|
+
|
|
752
|
+
- **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.
|
|
753
|
+
- **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.
|
|
754
|
+
- **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.
|
|
755
|
+
- **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`.
|
|
756
|
+
- **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)`.
|
|
757
|
+
- **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.
|
|
758
|
+
|
|
759
|
+
`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.
|
|
760
|
+
|
|
761
|
+
## GLSL functions (`@margoengine/shader/glsl`, 18.2 kB min+gzip on its own)
|
|
762
|
+
|
|
763
|
+
Bring GLSL you already have. `glslFn` turns a GLSL ES 3.00 or 1.00 function (with the helpers, structs and constants
|
|
764
|
+
it uses) into a node function, as `wgslFn` does for WGSL. It is translated to WGSL once, so the same source runs on
|
|
765
|
+
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
|
|
766
|
+
program the WebGL2 layer makes from a `NodePass`, a `NodeMaterial` that has drawn, or WGSL stages.
|
|
767
|
+
|
|
768
|
+
```ts
|
|
769
|
+
import {createStage} from 'margoengine';
|
|
770
|
+
import {createMesh, Texture} from 'margoengine/materials';
|
|
771
|
+
import {planeGeometry} from 'margoengine/geometry';
|
|
772
|
+
import {NodeMaterial, NodePass, time, uv} from 'margoengine/shader';
|
|
773
|
+
import {glslFn, toGLSL} from 'margoengine/shader/glsl';
|
|
774
|
+
const stage = await createStage('#app');
|
|
775
|
+
const tint = glslFn<'vec3f'>(`vec3 tint(vec3 c, float t) { return mix(c, c.bgr, t); }`);
|
|
776
|
+
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});
|
|
777
|
+
const tiles = glslFn<'vec4f'>(`#version 300 es
|
|
778
|
+
vec4 tiles(sampler2D map, vec2 uv, float count) {
|
|
779
|
+
vec2 cell = fract(uv * count);
|
|
780
|
+
return texture(map, uv * count) * (0.75 + 0.25 * step(0.5, cell.x));
|
|
781
|
+
}`);
|
|
782
|
+
const material = new NodeMaterial({colorNode: tint(tiles(checker, uv(), 4).rgb, time.sin().mul(0.5).add(0.5))});
|
|
783
|
+
createMesh(stage.engine, planeGeometry(2, 2), material);
|
|
784
|
+
const program = toGLSL(new NodePass(tiles(checker, uv(), 4)), await import('margoengine/webgl2-compat/glsl'));
|
|
785
|
+
console.log(program.fragment.source); // GLSL ES 3.00, with program.fragment.textures and .uniforms
|
|
786
|
+
```
|
|
787
|
+
|
|
788
|
+
- Arguments: a node or a number per scalar or vector parameter (a boolean for `bool`), a node for a matrix, and a
|
|
789
|
+
`Texture` from `@margoengine/materials` of the matching dimension for a sampler. A texture that `texture()` also
|
|
790
|
+
reads binds once.
|
|
791
|
+
- Options: `name` picks the function to call (default: the last one defined), `defines` adds `#define` lines,
|
|
792
|
+
`flipY: true` flips y at every 2D lookup and `texelFetch` for code written for a bottom-left image origin, and
|
|
793
|
+
`strict: true` keeps WGSL's derivative uniformity rule. By default translated functions turn that rule off, so an
|
|
794
|
+
implicit `texture()` inside a branch on a per-pixel value compiles, as GLSL allows.
|
|
795
|
+
- Lookups in vertex or compute nodes read level 0, as `texture()` nodes do. A source without `#version` reads as
|
|
796
|
+
GLSL ES 3.00; `#version 100` and `#version 300 es` are accepted.
|
|
797
|
+
- Errors are MargoError `failed` with `line` and `column` (1-based, in your source) and a help link. A uniform or a
|
|
798
|
+
`gl_` built-in inside the function is refused with "pass it as an argument". Translation is cached per source,
|
|
799
|
+
options and stage (256 entries).
|
|
800
|
+
- `glslToWGSL(code, options)` returns the WGSL, the entry name, the parameters and the result type, for tools.
|
|
801
|
+
- `toGLSL(target, translator, options)` takes the layer's translator as its second argument, so this entry never loads
|
|
802
|
+
the 44 kB layer itself; `options` are the layer's (`clipControl`, `points`, `uniformBlockSize`,
|
|
803
|
+
`accurateInverseTrig`). A `NodeMaterial` that has not drawn yet throws MargoError `state`.
|
|
804
|
+
|
|
805
|
+
`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`
|
|
806
|
+
in a NodePass: within 1 level per channel on every pixel, natively and on the layer. NodeMaterials built from GLSL
|
|
807
|
+
match the same graphs written in WGSL and `texture()`, and every `toGLSL` program compiles and links in raw WebGL2.
|
|
808
|
+
|
|
809
|
+
## Raw shaders (`@margoengine/shader/raw`, 15.2 kB min+gzip)
|
|
810
|
+
|
|
811
|
+
Your own WGSL vertex and fragment
|
|
812
|
+
entry points, any named attributes per vertex or per instance, live uniforms, textures and storage buffers, drawn into the
|
|
813
|
+
scene's colour and depth. Raw meshes also cast shadows, write SSAO's G-buffer, are culled and are picked like other meshes.
|
|
814
|
+
|
|
815
|
+
```ts
|
|
816
|
+
import {RawShaders, RawShaderMaterial, RawMesh} from 'margoengine/shader/raw';
|
|
817
|
+
import {loadTexture} from 'margoengine/materials';
|
|
818
|
+
import {createStage} from 'margoengine';
|
|
819
|
+
const stage = await createStage('#viewport', {backend: 'webgpu'});
|
|
820
|
+
const raw = RawShaders.attach(stage.engine);
|
|
821
|
+
const texture = await loadTexture('/map.png');
|
|
822
|
+
const positions = new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]), colors = new Float32Array(9).fill(1), uvs = new Float32Array(6);
|
|
823
|
+
const indices = new Uint16Array([0, 1, 2]), offsets = new Float32Array(15 * 3);
|
|
824
|
+
const material = new RawShaderMaterial({
|
|
825
|
+
vertexShader: `
|
|
826
|
+
struct Out { @builtin(position) clip:vec4f, @location(0) color:vec3f, @location(1) uv:vec2f }
|
|
827
|
+
@vertex fn vertex(a:Attributes)->Out {
|
|
828
|
+
let lift = sin(camera.time + a.offset.x) * uniforms.wave;
|
|
829
|
+
return Out(camera.viewProjection * mesh.world * vec4f(a.position + a.offset + vec3f(0.0, lift, 0.0), 1.0), a.color, a.uv);
|
|
830
|
+
}
|
|
831
|
+
@fragment fn fragment(i:Out)->@location(0) vec4f {
|
|
832
|
+
return margoDisplay(vec4f(i.color * uniforms.tint * textureSample(map, mapSampler, i.uv).rgb, 1.0)); // lit like the scene
|
|
833
|
+
}`,
|
|
834
|
+
uniforms: {wave: {value: 0.2}, tint: {value: '#ff8800'}}, // f32 to vec4f, i32/u32 variants, mat3x3f, mat4x4f
|
|
835
|
+
textures: {map: texture}, // a materials Texture, GPUTexture or GPUTextureView, or (device) => texture;
|
|
836
|
+
// {texture, sampler, dimension, sampleType} as a plain object adds options
|
|
837
|
+
});
|
|
838
|
+
const mesh = raw.add(new RawMesh({
|
|
839
|
+
material,
|
|
840
|
+
attributes: {
|
|
841
|
+
position: {data: positions, type: 'vec3f'},
|
|
842
|
+
color: {data: colors, type: 'vec3f'},
|
|
843
|
+
uv: {data: uvs, type: 'vec2f'},
|
|
844
|
+
offset: {data: offsets, type: 'vec3f', step: 'instance'}, // one per instance; the instance count follows it
|
|
845
|
+
},
|
|
846
|
+
index: indices,
|
|
847
|
+
}));
|
|
848
|
+
material.uniforms.wave.value = 0.5; // live, never recompiles
|
|
849
|
+
mesh.setAttribute('offset', offsets, [10, 5]); // uploads instances 10..14 only
|
|
850
|
+
material.transparent = true; // render state is live too (a new pipeline compiles once)
|
|
851
|
+
```
|
|
852
|
+
|
|
853
|
+
- **The prelude.** Each stage's module is a short prelude, then your code (`material.code('vertex', mesh)` shows it). It
|
|
854
|
+
declares `camera` (`view`, `projection`, `viewProjection`, `position`, `time`, `resolution`, the target size,
|
|
855
|
+
`deltaTime`, and `viewport`, the drawn view as x, y, width and height in target pixels), `mesh`
|
|
856
|
+
(`world`, and `normal`, the inverse transpose of its 3x3), `struct Attributes` with one `@location` per attribute in
|
|
857
|
+
the order given, `uniforms.<name>` (the WGSL layout is computed for you), each texture as `<name>` plus
|
|
858
|
+
`<name>Sampler`, each storage buffer as `<name>`, and two colour helpers. Fragment output is written exactly as returned (raw); `margoDisplay(c)`
|
|
859
|
+
applies the scene's display transform (PBR Neutral and sRGB on a display target, nothing inside an HDR PostStack
|
|
860
|
+
capture, which tonemaps later) and `margoEncode(c)` only the sRGB encoding, for unlit colour as lines and points write
|
|
861
|
+
it. With a separate `fragmentShader` each stage is its own module, so both may use `main`.
|
|
862
|
+
- **Arrays and structs.** `count` makes a uniform array, `struct` a uniform struct, and both together an array of structs.
|
|
863
|
+
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
|
|
864
|
+
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
|
|
865
|
+
material says so when it refuses one. A struct field is a plain uniform type, not an array or another struct.
|
|
866
|
+
- **Storage buffers and bind groups.** `storage: {name: buffer}` declares `<name>:array<type>`. Pass a `storage()` node as
|
|
867
|
+
it is, so a compute pass fills what the mesh draws, or `{buffer, type, access}` with your own GPUBuffer (or a function of
|
|
868
|
+
the device, which also serves device restoration; a plain buffer is lost with its device, so the material binds a zeroed
|
|
869
|
+
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
|
|
870
|
+
the buffer. `'read_write'` binds to the fragment stage only, as WebGPU requires. `groups` adds up to two bind groups at
|
|
871
|
+
`@group(2)` and `@group(3)` for bindings your WGSL declares; each is a function of the device.
|
|
872
|
+
- **Device restore.** A texture or storage buffer you made belongs to the device that made it. Give `textures` a
|
|
873
|
+
`(device) => GPUTexture | GPUTextureView` and it is made once per device, so it is back after `engine.rebootDevice()`;
|
|
874
|
+
`ShaderMaterial` sampler uniforms take the same function. A plain GPUTexture, view or buffer is lost with its device: the
|
|
875
|
+
binding reads opaque white (a storage buffer reads a zeroed stand-in), `engine.onError` hears of it once (`'state'`,
|
|
876
|
+
[#borrowed-lost](https://margoengine.com/errors#borrowed-lost)), the frame keeps drawing, and assigning a new one to
|
|
877
|
+
`material.textures.<name>.texture` or `material.storage.<name>.buffer` brings it back.
|
|
878
|
+
- **Geometry.** Attribute types are `f32`, `vec2f` to `vec4f` and the `i32`/`u32` variants, up to 16 attributes;
|
|
879
|
+
per-vertex and per-instance attributes are each interleaved into one buffer. `setAttribute(name, data, [first,
|
|
880
|
+
count])` uploads only that element range; new lengths grow the buffer; `{data, type, step}` adds or retypes an
|
|
881
|
+
attribute (new layout, new pipeline). Optional index (`Uint16Array`, `Uint32Array` or numbers), `instanceCount`,
|
|
882
|
+
`vertexCount` (no attributes: vertex pulling), `topology`, `drawRange`. `matrix` is the model matrix; `mesh: coreMesh`
|
|
883
|
+
follows a core mesh (world = its world matrix x `matrix`) and hides with it.
|
|
884
|
+
- **Shared buffers.** Meshes whose packed vertex, instance or index bytes are equal hold one GPU buffer, counted per
|
|
885
|
+
device, so 10,000 boxes built from one geometry upload it once and a run of them binds it once. Nothing to set:
|
|
886
|
+
`new RawMesh({material, attributes, index})` with the same data is enough. A mesh leaves on its first write
|
|
887
|
+
(`setAttribute`, `setIndex`), and the others keep drawing the old bytes. Each shared buffer keeps a CPU copy of its
|
|
888
|
+
bytes to compare new meshes with, until its meshes have left it.
|
|
889
|
+
- **Render state.** `transparent` (drawn after the opaque scene, sorted back to front by distance), `blending`
|
|
890
|
+
(`'normal'` blends only when transparent; `'additive'`, `'multiply'`, `'premultiplied'`, `'none'` or a
|
|
891
|
+
`GPUBlendState`), `depthTest` (reversed-Z `greater-equal`), `depthWrite`, `cull` (`'back'`, `'front'`, `'none'`),
|
|
892
|
+
`colorWrite`; per mesh `renderOrder` and `visible`.
|
|
893
|
+
- **The pass.** Opaque raw meshes draw at frame-graph order 0.5 (after core meshes, before gltf/pbr and materials meshes
|
|
894
|
+
at 1), transparent ones at 7 (after water, sky and particles, before OIT at 8 and lines at 20);
|
|
895
|
+
`new RawShaders({opaqueOrder, transparentOrder})` moves them. Each draws into the pass's own colour and depth targets
|
|
896
|
+
with their format and MSAA sample count, so 1x/4x and a PostStack's HDR capture just work.
|
|
897
|
+
- **Compiling and errors.** Pipelines compile asynchronously and draw from the next frame on (`await raw.ready()` before a
|
|
898
|
+
one-off `engine.render()`). A WGSL error is a MargoError `'failed'` naming the stage and line in your code, set on
|
|
899
|
+
`material.error` and passed to `material.onError` (default `console.error`); only that draw is skipped. Assigning
|
|
900
|
+
`vertexShader` or `fragmentShader` recompiles.
|
|
901
|
+
- **Lifecycle.** `mesh.dispose()` frees its buffers and leaves the plugin; `material.dispose()` frees its uniforms and
|
|
902
|
+
pipelines (rebuilt if drawn again); `engine.removePlugin('shader:raw')` frees everything and keeps the meshes. Device
|
|
903
|
+
restoration rebuilds everything from the CPU copies; a materials Texture rebinds itself, a GPUTexture from the lost
|
|
904
|
+
device draws white with a warning until you assign a new one.
|
|
905
|
+
|
|
906
|
+
### Shadows, SSAO, culling and picking
|
|
907
|
+
|
|
908
|
+
```ts
|
|
909
|
+
import {createStage} from 'margoengine';
|
|
910
|
+
import {SSAO} from 'margoengine/post/ssao';
|
|
911
|
+
import {Picking} from 'margoengine/selection';
|
|
912
|
+
import {Shadows} from 'margoengine/shadows';
|
|
913
|
+
import {RawMesh, RawPicking, RawShaderMaterial, RawShaders} from 'margoengine/shader/raw';
|
|
914
|
+
const stage = await createStage('#app');
|
|
915
|
+
const engine = stage.engine, raw = RawShaders.attach(engine);
|
|
916
|
+
const material = new RawShaderMaterial({
|
|
917
|
+
vertexShader: `
|
|
918
|
+
struct Out {@builtin(position) clip:vec4f, @location(0) world:vec3f, @location(1) normal:vec3f}
|
|
919
|
+
@vertex fn vertex(a:Attributes)->Out {
|
|
920
|
+
let w = mesh.world * vec4f(a.position, 1);
|
|
921
|
+
return Out(camera.viewProjection * w, w.xyz, normalize(mesh.normal * a.normal));
|
|
922
|
+
}
|
|
923
|
+
@fragment fn gbuffer(i:Out)->MargoGBuffer {return margoGBuffer(i.normal, i.world, vec3f(0.3));}
|
|
924
|
+
@fragment fn fragment(i:Out)->@location(0) vec4f {return margoDisplay(vec4f(vec3f(0.3) + i.normal.y * 0.5, 1));}`,
|
|
925
|
+
gbufferEntry: 'gbuffer',
|
|
926
|
+
});
|
|
927
|
+
const mesh = raw.add(new RawMesh({
|
|
928
|
+
material,
|
|
929
|
+
attributes: {
|
|
930
|
+
position: {data: [-1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0], type: 'vec3f'},
|
|
931
|
+
normal: {data: [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1], type: 'vec3f'},
|
|
932
|
+
},
|
|
933
|
+
index: [0, 1, 2, 0, 2, 3],
|
|
934
|
+
}));
|
|
935
|
+
Shadows.attach(engine).add(mesh); // casts through your vertex shader
|
|
936
|
+
SSAO.attach(engine).add(raw); // meshes with gbufferEntry write their own normals
|
|
937
|
+
const picking = RawPicking.attach(Picking.attach(engine), raw); // engine.pick now answers raw meshes
|
|
938
|
+
await raw.ready();
|
|
939
|
+
const hit = await engine.pick(200, 150);
|
|
940
|
+
console.log(picking.rawOf(hit) === mesh);
|
|
941
|
+
```
|
|
942
|
+
|
|
943
|
+
- **Shadows.** `shadows.add(mesh)` draws the mesh into every cascade of `Shadows` with your vertex stage, where
|
|
944
|
+
`camera.viewProjection` and `camera.projection * camera.view` are the cascade's light matrix. Both sides cast, whatever
|
|
945
|
+
the material's `cull`, as in the depth pass of every other caster. Your fragment stage runs
|
|
946
|
+
too when its code holds `discard`, so a cut-out shape casts a cut-out shadow. Transparent materials cast none. For
|
|
947
|
+
`{static: true}`, call `mesh.invalidateShadow()` after moving the mesh; attribute changes and a newly compiled pipeline
|
|
948
|
+
redraw the map by themselves. A raw shader receives no shadow unless it samples one itself.
|
|
949
|
+
- **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
|
|
950
|
+
shape the shader moves ghosts. Give the material `velocityEntry`: a `@vertex fn` beside your vertex entry, with the same
|
|
951
|
+
inputs, that returns `margoVelocity(position, positionBefore)`, where the vertex is now and where it was last frame, both
|
|
952
|
+
before `mesh.world`. It may read `margoBefore.time` (last frame's `camera.time`) and `margoBefore.world`; keep last
|
|
953
|
+
frame's value of any uniform your move reads beside it. The velocity pass draws with `depthCompare: 'equal'` against
|
|
954
|
+
your vertex entry's depth, so compute the position there with the same expression `margoVelocity` uses
|
|
955
|
+
(`camera.viewProjection * mesh.world * vec4f(p, 1)`) and declare it `@invariant`, as `MargoVelocity` does: WGSL lets
|
|
956
|
+
two programs round the same expression differently otherwise (WGSL 12.10), and a pixel then gets no motion. Then `taa.add(raw)`: opaque meshes with the entry draw their
|
|
957
|
+
motion into TAA's velocity pass, with last frame kept per TAA view. Without the entry nothing changes.
|
|
958
|
+
|
|
959
|
+
```ts
|
|
960
|
+
import {EngineKernel} from 'margoengine/core';
|
|
961
|
+
import {TAA} from 'margoengine/taa';
|
|
962
|
+
import {RawMesh, RawShaderMaterial, RawShaders} from 'margoengine/shader/raw';
|
|
963
|
+
const engine = await EngineKernel.create(document.querySelector<HTMLCanvasElement>('#viewport')!, {backend: 'webgpu'});
|
|
964
|
+
const raw = RawShaders.attach(engine), taa = TAA.attach(engine);
|
|
965
|
+
const material = new RawShaderMaterial({
|
|
966
|
+
vertexShader: `
|
|
967
|
+
fn wave(p:vec3f, t:f32)->vec3f {return p + vec3f(0, sin(p.x * 3 + t) * 0.2, 0);}
|
|
968
|
+
@vertex fn vertex(a:Attributes)->@builtin(position) @invariant vec4f {
|
|
969
|
+
return camera.viewProjection * mesh.world * vec4f(wave(a.position, camera.time), 1);
|
|
970
|
+
}
|
|
971
|
+
@vertex fn velocity(a:Attributes)->MargoVelocity {
|
|
972
|
+
return margoVelocity(wave(a.position, camera.time), wave(a.position, margoBefore.time));
|
|
973
|
+
}
|
|
974
|
+
@fragment fn fragment()->@location(0) vec4f {return margoDisplay(vec4f(0.2, 0.5, 0.9, 1));}`,
|
|
975
|
+
velocityEntry: 'velocity',
|
|
976
|
+
cull: 'none',
|
|
977
|
+
});
|
|
978
|
+
raw.add(new RawMesh({
|
|
979
|
+
material,
|
|
980
|
+
attributes: {position: {data: [-1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0], type: 'vec3f'}},
|
|
981
|
+
index: [0, 1, 2, 0, 2, 3],
|
|
982
|
+
}));
|
|
983
|
+
taa.add(raw); // the waving quad writes its own motion
|
|
984
|
+
```
|
|
985
|
+
|
|
986
|
+
- **SSAO.** Opaque raw meshes occlude from their depth with nothing to set, like every mesh, and their pixels are not
|
|
987
|
+
darkened. `ssao.add(raw)` with `gbufferEntry` on a material goes further: that `@fragment fn` returns
|
|
988
|
+
`margoGBuffer(worldNormal, worldPosition, ambient)`, SSAO uses your normals, and `ambient` is the light it may take away.
|
|
989
|
+
- **Culling.** A mesh out of view is skipped in the colour, shadow, SSAO and pick passes, and counted in `raw.stats.culled`.
|
|
990
|
+
The sphere comes from a per-vertex vec3f `position`. A mesh with no such attribute, or an instanced one, is never culled
|
|
991
|
+
unless you give `bounds: {center, radius}`. A vertex shader that moves points outside that sphere needs `bounds` or
|
|
992
|
+
`frustumCulled: false`.
|
|
993
|
+
- **Picking.** `RawPicking.attach(picking, raw)` draws the meshes into the pick tile after the scene's meshes, in the same
|
|
994
|
+
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
|
|
995
|
+
stand-in, and `picking.rawOf(hit)` gives the RawMesh back. One ID covers a mesh, so a hit names no instance, and a
|
|
996
|
+
fragment's `discard` does not cut the pick.
|
|
997
|
+
|
|
998
|
+
Measured on an NVIDIA Ampere GPU (Edge, 4x and 1x MSAA) by `node scripts/shader-raw-gpu-check.js`:
|
|
999
|
+
a quad with a per-vertex colour attribute and a per-instance offset and `u32` id matches its analytic colours within 0.55
|
|
1000
|
+
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
|
|
1001
|
+
`setAttribute` update it, device restoration redraws identical pixels, and an attached plugin with nothing visible or a
|
|
1002
|
+
removed one leaves every pixel unchanged.
|
|
1003
|
+
|
|
1004
|
+
## GLSL programs as materials (`@margoengine/shader/glsl-material`, 35.6 kB min+gzip on its own, `RawMesh` included)
|
|
1005
|
+
|
|
1006
|
+
Paste a whole GLSL program, as a web engine's `RawShaderMaterial` takes one: a GLSL ES 3.00 or 1.00 vertex and fragment
|
|
1007
|
+
stage with `void main()`, your own `uniform`s, attributes and varyings. `ShaderMaterial` translates it to WGSL once per
|
|
1008
|
+
source and defines, with the same GLSL front end as `glslFn`, so one GLSL source draws on WebGPU and on the WebGL2
|
|
1009
|
+
layer. It is a `RawShaderMaterial`, so it draws with a `RawMesh` in the `RawShaders` plugin and keeps that render state.
|
|
1010
|
+
|
|
1011
|
+
```ts
|
|
1012
|
+
import {createStage} from 'margoengine';
|
|
1013
|
+
import {RawShaders, RawMesh} from 'margoengine/shader/raw';
|
|
1014
|
+
import {ShaderMaterial, glslProgramToWGSL} from 'margoengine/shader/glsl-material';
|
|
1015
|
+
const stage = await createStage('#viewport', {controls: false});
|
|
1016
|
+
const raw = RawShaders.attach(stage.engine);
|
|
1017
|
+
const vertexShader = `#version 300 es
|
|
1018
|
+
in vec2 position;
|
|
1019
|
+
out vec2 vUv;
|
|
1020
|
+
void main() { vUv = position * 0.5 + 0.5; gl_Position = vec4(position, 0.0, 1.0); }`;
|
|
1021
|
+
const fragmentShader = `#version 300 es
|
|
1022
|
+
precision highp float;
|
|
1023
|
+
in vec2 vUv;
|
|
1024
|
+
uniform float time;
|
|
1025
|
+
uniform vec3 tint;
|
|
1026
|
+
uniform bool stripes;
|
|
1027
|
+
out vec4 color;
|
|
1028
|
+
void main() {
|
|
1029
|
+
float wave = 0.5 + 0.5 * sin(time + vUv.x * 12.0);
|
|
1030
|
+
color = vec4(tint * (stripes ? wave : 1.0), 1.0);
|
|
1031
|
+
}`;
|
|
1032
|
+
const material = new ShaderMaterial({
|
|
1033
|
+
vertexShader,
|
|
1034
|
+
fragmentShader,
|
|
1035
|
+
uniforms: {time: {value: 0}, tint: {value: '#ff8800'}, stripes: {value: true}},
|
|
1036
|
+
});
|
|
1037
|
+
raw.add(new RawMesh({material, attributes: {position: {data: new Float32Array([-1, -1, 3, -1, -1, 3]), type: 'vec2f'}}}));
|
|
1038
|
+
stage.engine.onFrame((_, delta) => (material.uniforms.time.value = (material.uniforms.time.value as number) + delta));
|
|
1039
|
+
console.log(glslProgramToWGSL({vertexShader, fragmentShader}).uniforms); // the GLSL names, types and WGSL members
|
|
1040
|
+
```
|
|
1041
|
+
|
|
1042
|
+
- **Uniforms.** `material.uniforms.<name>.value` is live and never translates again. Values: a number
|
|
1043
|
+
or boolean, an array, typed array or `{x, y, z, w}` for a vector or a column-major matrix, `'#rrggbb'` for a `vec3`,
|
|
1044
|
+
and for a `sampler2D`, `samplerCube`, `sampler3D` or `sampler2DArray` a `Texture` of `@margoengine/materials`, a
|
|
1045
|
+
GPUTexture or a GPUTextureView. Types come from the GLSL: `float`, `int`, `uint`, `bool` and their vectors, `mat2`,
|
|
1046
|
+
`mat3`, `mat4`. A uniform the program declares and `uniforms` omits starts at zero (a sampler with no texture reads
|
|
1047
|
+
opaque white, as raw materials do; GL would read black). Both stages may declare the same uniform; its type must
|
|
1048
|
+
match.
|
|
1049
|
+
- **Attributes and varyings.** Attributes match a `RawMesh` attribute by name. One the mesh lacks reads GL's default
|
|
1050
|
+
(0, 0, 0, 1), and a narrower one is widened the same way, so `in vec4 position` takes a `vec2f` attribute. Varyings
|
|
1051
|
+
link by name and type; integer varyings must be `flat`. A flat varying takes its value from the first vertex of a
|
|
1052
|
+
triangle on WebGPU and from the last in GL, so keep flat values equal across a primitive.
|
|
1053
|
+
- **GL conventions.** By default the program sees GL's: `gl_Position` in GL clip space (z from -1 to 1, mapped onto
|
|
1054
|
+
Margo's reversed depth), `gl_FragCoord` with rows counted from the bottom and GL depth, `dFdy` along GL window y,
|
|
1055
|
+
`gl_FragDepth` in GL depth, and 2D lookups and `texelFetch` reading a Margo texture as GL reads one uploaded with
|
|
1056
|
+
`UNPACK_FLIP_Y_WEBGL` (`flipY: true`). `flipY: false` reads rows top down, and `clipSpace: 'webgpu'` takes clip z
|
|
1057
|
+
from 0 to 1 unchanged. Built-ins: `gl_Position`, `gl_PointSize`, `gl_VertexID`, `gl_InstanceID`, `gl_FragCoord`,
|
|
1058
|
+
`gl_FrontFacing`, `gl_PointCoord`, `gl_FragColor`, `gl_FragData[0]`, `gl_FragDepth`, `gl_DepthRange` and the
|
|
1059
|
+
`gl_Max*` constants at WebGL's minimums.
|
|
1060
|
+
- **Defines.** `defines: {NAME: value}` go before both stages (`true` as 1). Assigning `material.defines`, or editing
|
|
1061
|
+
it and setting `material.needsUpdate = true`, translates again; so does assigning `vertexShader` or `fragmentShader`.
|
|
1062
|
+
Translations are cached per source and defines (64 programs), so switching back costs nothing.
|
|
1063
|
+
- **Render state.** Everything a `RawShaderMaterial` takes (`transparent`, `blending`, `depthTest`, `depthWrite`,
|
|
1064
|
+
`cull`, `colorWrite`, `depthCompare`, `depthBias`, `alphaToCoverage`), plus the GL names a pasted program's
|
|
1065
|
+
material sets: `side` ('front', 'back' or 'double'; not together with `cull`), `depthFunc` in GL's sense (nearer is
|
|
1066
|
+
less, default 'less-equal'), `polygonOffset` with `polygonOffsetFactor` and `polygonOffsetUnits`, and
|
|
1067
|
+
`blending: 'custom'` with `blendSrc`, `blendDst`, `blendEquation` and their `Alpha` forms. All of them are live.
|
|
1068
|
+
- **Built-in names.** `builtins` picks the names under which the engine supplies its matrices and attributes; see
|
|
1069
|
+
[Engine values under familiar names](#engine-values-under-familiar-names).
|
|
1070
|
+
- **Errors.** Syntax and link errors throw MargoError `failed` from the constructor with `stage`, `line` and `column`
|
|
1071
|
+
in your GLSL as written and a help link: a varying whose type or interpolation differs between the stages, one read
|
|
1072
|
+
but never written, mixed versions, a uniform declared with two types, an unsupported uniform type, more than one
|
|
1073
|
+
colour output or `gl_FragData` above 0. `glslProgramToWGSL(source)` returns both stages' WGSL and the uniform,
|
|
1074
|
+
texture, attribute and varying tables for tools.
|
|
1075
|
+
|
|
1076
|
+
`node packages/shader/test/glsl-material-check.mjs` and the same command with `--compat`
|
|
1077
|
+
draw each program of `test/glsl-material-fixtures.js` with the browser's own WebGL compiler (WebGL 1 for GLSL ES 1.00,
|
|
1078
|
+
WebGL 2 for 3.00) and as a `ShaderMaterial`, then again after changing uniforms or defines: within 1 level per channel
|
|
1079
|
+
on every pixel, natively and on the layer.
|
|
1080
|
+
|
|
1081
|
+
### Engine values under familiar names
|
|
1082
|
+
|
|
1083
|
+
A program pasted from another web engine reads that engine's names for the model, view and projection matrices and
|
|
1084
|
+
the vertex streams. `builtins` supplies Margo's values under one convention's names, each named after its signature
|
|
1085
|
+
uniform; [docs/porting-glsl.md](../../docs/porting-glsl.md) says which convention each engine uses.
|
|
1086
|
+
|
|
1087
|
+
| `builtins` | Uniforms the engine fills | Attributes `shaderMesh` fills |
|
|
1088
|
+
| --- | --- | --- |
|
|
1089
|
+
| `'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 |
|
|
1090
|
+
| `'worldViewProjection'` | `world`, `view`, `projection`, `worldView`, `worldViewProjection` | `position`, `normal`, `uv`, `uv2`, `color` (vec4) |
|
|
1091
|
+
| `'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` |
|
|
1092
|
+
| `'auto'` (default) | the one convention the program's names show, or none; names of two conventions throw MargoError `failed` | as chosen |
|
|
1093
|
+
| `false` | none: the program declares every matrix it reads | none |
|
|
1094
|
+
|
|
1095
|
+
A name you list in `uniforms` is yours and the engine leaves it alone. Matrices follow GL: the projection takes view
|
|
1096
|
+
z onto clip z from -1 to 1, which the material maps onto Margo's reversed depth, so a program that writes
|
|
1097
|
+
`projectionMatrix * modelViewMatrix * vec4(position, 1.0)` draws in depth order with core meshes. `attributes:
|
|
1098
|
+
{myPos: 'position'}` maps your own attribute names onto streams; `defaultAttributeValues` sets what a stream the mesh
|
|
1099
|
+
lacks reads (the defaults: `uv` and `uv1` (0, 0), `color` and `instanceColor` white).
|
|
1100
|
+
|
|
1101
|
+
`shaderMesh(geometry, material, options)` builds the `RawMesh`: `geometry` is `{positions, normals, uvs, uvs1, colors,
|
|
1102
|
+
tangents, indices}` or a core `Geometry`; `options.attributes` and `options.instances` add data by GLSL name, and
|
|
1103
|
+
`instances: {instanceMatrix, instanceColor}` draws one copy per matrix. The mesh's `material` keeps its type, so its
|
|
1104
|
+
uniforms stay typed:
|
|
1105
|
+
|
|
1106
|
+
```ts
|
|
1107
|
+
import {createStage} from 'margoengine';
|
|
1108
|
+
import {RawShaders} from 'margoengine/shader/raw';
|
|
1109
|
+
import {ShaderMaterial, shaderMesh, type ShaderUniformValue} from 'margoengine/shader/glsl-material';
|
|
1110
|
+
const stage = await createStage('#viewport');
|
|
1111
|
+
const raw = RawShaders.attach(stage.engine);
|
|
1112
|
+
const material = new ShaderMaterial({
|
|
1113
|
+
builtins: 'modelViewMatrix',
|
|
1114
|
+
vertexShader: `#version 300 es
|
|
1115
|
+
out vec3 vNormal;
|
|
1116
|
+
void main() {
|
|
1117
|
+
vNormal = normalize(normalMatrix * normal);
|
|
1118
|
+
gl_Position = projectionMatrix * modelViewMatrix * instanceMatrix * vec4(position, 1.0);
|
|
1119
|
+
}`,
|
|
1120
|
+
fragmentShader: `#version 300 es
|
|
1121
|
+
precision highp float;
|
|
1122
|
+
uniform float time;
|
|
1123
|
+
in vec3 vNormal;
|
|
1124
|
+
out vec4 color;
|
|
1125
|
+
void main() {
|
|
1126
|
+
color = vec4(vNormal * 0.5 + 0.5 + 0.1 * sin(time), 1.0);
|
|
1127
|
+
#include <tonemapping_fragment>
|
|
1128
|
+
#include <colorspace_fragment>
|
|
1129
|
+
}`,
|
|
1130
|
+
uniforms: {time: {value: 0}},
|
|
1131
|
+
});
|
|
1132
|
+
const s = 0.5;
|
|
1133
|
+
const positions = [-s, -s, 0, s, -s, 0, s, s, 0, -s, s, 0];
|
|
1134
|
+
const normals = [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1];
|
|
1135
|
+
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]);
|
|
1136
|
+
const mesh = raw.add(shaderMesh({positions, normals, indices: [0, 1, 2, 0, 2, 3]}, material, {instances: {instanceMatrix}}));
|
|
1137
|
+
stage.engine.onFrame((_, delta) => {
|
|
1138
|
+
const time: ShaderUniformValue = mesh.material.uniforms.time.value; // typed through the mesh
|
|
1139
|
+
mesh.material.uniforms.time.value = (time as number) + delta;
|
|
1140
|
+
});
|
|
1141
|
+
```
|
|
1142
|
+
|
|
1143
|
+
- **Includes.** `#include <name>` and `#include "name"` expand from `includes: {name: 'glsl'}` (8 deep), in both
|
|
1144
|
+
stages. Two chunks are built in for the fragment stage: `tonemapping_fragment` applies the display tone map to the
|
|
1145
|
+
colour the program wrote (PBR Neutral, only when Margo displays the frame) and `colorspace_fragment` encodes it to
|
|
1146
|
+
sRGB when the target expects that. An unknown include throws with its stage, line and column.
|
|
1147
|
+
- **Output colour.** A program's colour is taken as sRGB, as GL would show it on screen (`outputColorSpace: 'srgb'`,
|
|
1148
|
+
the default); `'linear'` takes it as linear light and lets Margo tone map and encode it like its own materials. A
|
|
1149
|
+
program that includes `colorspace_fragment` writes its colour as it is.
|
|
1150
|
+
- **Float textures the device cannot filter.** WebGPU filters `rgba32float` only with the optional `float32-filterable`
|
|
1151
|
+
feature. Name such a `sampler2D` in `unfilterable: {name: {filter: 'linear', wrap: 'clamp'}}` (`filter` `'nearest'`,
|
|
1152
|
+
`'linear'` or `'mipmap'`, `wrap` `'clamp'` or `'repeat'`): it binds as an unfilterable-float texture and its
|
|
1153
|
+
`texture()`, `textureLod`, `textureGrad` and `textureOffset` lookups read texels with `textureLoad` and filter them as
|
|
1154
|
+
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
|
|
1155
|
+
channels use it.
|
|
1156
|
+
|
|
1157
|
+
### Raw depth state
|
|
1158
|
+
|
|
1159
|
+
`RawShaderMaterial` also takes `depthCompare` (default 'greater-equal', Margo's reversed depth), `depthBias` and
|
|
1160
|
+
`depthBiasSlopeScale` (triangles only), `alphaToCoverage` (multisampled targets) and `blending: 'subtractive'`, all
|
|
1161
|
+
live. A texture with `sampleType: 'depth'` is a `texture_depth_2d` (or cube, or 2d array) with a comparison sampler
|
|
1162
|
+
(default `compare: 'less-equal'`) for `textureSampleCompare`; with no texture it reads a far depth of 1.
|
|
1163
|
+
|
|
1164
|
+
### Blocks, structs, arrays and samplers
|
|
1165
|
+
|
|
1166
|
+
Uniforms of any shape a GLSL ES program declares are live values under the names GL gives them:
|
|
1167
|
+
|
|
1168
|
+
- **Structs and arrays.** `uniform Light lights[2];`, `uniform vec2 offsets[4];`, nested structs and the non-square
|
|
1169
|
+
matrices (`mat2x3` and the rest) take a value shaped like the type: an object per struct, a list per array, and a flat
|
|
1170
|
+
run of numbers also works for an array of vectors. Each leaf is its own raw member, so changing one field reuploads
|
|
1171
|
+
without translating. `glslProgramToWGSL` lists each leaf (`lights[1].color`) with its `root` and `path`.
|
|
1172
|
+
- **Uniform blocks.** `uniform Rig { ... };` makes its fields plain uniforms; `uniform Rig { ... } rig;` makes one
|
|
1173
|
+
struct uniform `rig`. A block holds no samplers (GLSL ES 3.00 4.3.7).
|
|
1174
|
+
- **Sampler arrays.** `uniform sampler2D maps[2];` takes a list of textures. Indexing with a constant reads one
|
|
1175
|
+
binding; any other index (a loop counter, an ES 1.00 loop index) reads every element and keeps the one picked.
|
|
1176
|
+
- **Integer and shadow samplers.** `isampler2D`, `usampler2D` (and 3D, cube, 2D array) read textures of integers;
|
|
1177
|
+
`sampler2DShadow`, `samplerCubeShadow` and `sampler2DArrayShadow` compare against a depth texture. Pass a
|
|
1178
|
+
`GPUTexture` or `{texture, sampler}`, with the sampler's `compare` (default 'less-equal'), as the value.
|
|
1179
|
+
|
|
1180
|
+
### Points, flat varyings, wireframes and saving
|
|
1181
|
+
|
|
1182
|
+
- **Sized points.** A vertex stage that writes `gl_PointSize`, drawn with `topology: 'point-list'`, gives squares of that
|
|
1183
|
+
many pixels of the view it is drawn in, centred on each point, with `gl_PointCoord` from the upper left (OpenGL ES
|
|
1184
|
+
3.0.6 3.4): `shaderMesh`
|
|
1185
|
+
draws each point as an instance of six corners. A point whose centre leaves the view is dropped whole, as in GL.
|
|
1186
|
+
- **Flat varyings.** GL takes a flat value from a primitive's last vertex and WebGPU from its first, so for a program with
|
|
1187
|
+
a `flat` varying `shaderMesh` lists each triangle or line from its last vertex, winding kept; a strip becomes a list.
|
|
1188
|
+
- **Wireframe.** `wireframe: true` (live, on any `RawShaderMaterial`) draws each edge of the triangles once as a line.
|
|
1189
|
+
- **Saving.** `glslMaterialCodec(ShaderMaterial)` from `@margoengine/shader/serialization` keeps the GLSL, the uniform
|
|
1190
|
+
values and the state, and restoring translates the GLSL again. It takes the class, so the entry loads no GLSL front
|
|
1191
|
+
end; without it a ShaderMaterial has no codec and capturing one throws rather than saving its WGSL translation.
|
|
1192
|
+
|
|
1193
|
+
```ts
|
|
1194
|
+
import {createStage} from 'margoengine';
|
|
1195
|
+
import {captureMaterialLibrary, restoreMaterialLibrary} from 'margoengine/materials/serialization';
|
|
1196
|
+
import {RawShaders} from 'margoengine/shader/raw';
|
|
1197
|
+
import {ShaderMaterial, shaderMesh} from 'margoengine/shader/glsl-material';
|
|
1198
|
+
import {glslMaterialCodec, shaderMaterialCodecs} from 'margoengine/shader/serialization';
|
|
1199
|
+
const stage = await createStage('#viewport');
|
|
1200
|
+
const raw = RawShaders.attach(stage.engine);
|
|
1201
|
+
const material = new ShaderMaterial({
|
|
1202
|
+
vertexShader: `#version 300 es
|
|
1203
|
+
in vec3 position;
|
|
1204
|
+
void main() { gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }`,
|
|
1205
|
+
fragmentShader: `#version 300 es
|
|
1206
|
+
precision highp float;
|
|
1207
|
+
struct Band { vec3 color; float width; };
|
|
1208
|
+
uniform Shade { Band bands[2]; float mixAmount; } shade;
|
|
1209
|
+
out vec4 color;
|
|
1210
|
+
void main() {
|
|
1211
|
+
float t = fract(gl_FragCoord.x / (shade.bands[0].width + shade.bands[1].width));
|
|
1212
|
+
color = vec4(mix(shade.bands[0].color, shade.bands[1].color, step(0.5, t) * shade.mixAmount), 1.0);
|
|
1213
|
+
}`,
|
|
1214
|
+
uniforms: {shade: {value: {bands: [{color: [1, 0.5, 0], width: 8}, {color: [0, 0.4, 1], width: 8}], mixAmount: 1}}},
|
|
1215
|
+
});
|
|
1216
|
+
raw.add(shaderMesh({positions: [-1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0], indices: [0, 1, 2, 0, 2, 3]}, material));
|
|
1217
|
+
material.wireframe = true;
|
|
1218
|
+
const codecs = [...shaderMaterialCodecs, glslMaterialCodec(ShaderMaterial)];
|
|
1219
|
+
const saved = await captureMaterialLibrary({material}, {codecs});
|
|
1220
|
+
const copy = (await restoreMaterialLibrary(saved, {codecs})).material as ShaderMaterial;
|
|
1221
|
+
console.log(copy.wireframe, copy.uniforms.shade.value);
|
|
1222
|
+
```
|
|
1223
|
+
|
|
1224
|
+
- **Lights.** `lights: true` hands the program the scene's lights under Margo's names, as uniforms it declares (only
|
|
1225
|
+
those it declares are filled, each pass, with no new translation when they change): `vec3 sunDirection` (world space,
|
|
1226
|
+
unit, towards the sun), `vec3 sunColor` (`engine.lighting` radiance times intensity, linear), `vec3 ambientLight`
|
|
1227
|
+
(the ambient light core meshes get: `ambient` times radiance w), and the point and spot lights of
|
|
1228
|
+
`shaderScene(raw).setLights(clustered)` (a `Clustered` of `@margoengine/clustered`, or any `{list}` of its lights) as
|
|
1229
|
+
`pointLights[N]` and `spotLights[N]` with `int pointLightCount` and `spotLightCount`. Declare each list as an array
|
|
1230
|
+
of your own struct with any of the fields `vec3 position`, `vec3 color` (colour times intensity times
|
|
1231
|
+
`intensityScale`, linear), `float range` (0 is unlimited), `float decay` (default 2) and, for spots, `vec3 direction`,
|
|
1232
|
+
`float outerCos` and `float innerCos` (cosines of the cone's outer and inner half-angles). The lists fill in list
|
|
1233
|
+
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
|
|
1234
|
+
its cone `smoothstep(outerCos, innerCos, dot(-l, direction))`.
|
|
1235
|
+
- **Fog.** `fog: true` hands over `shaderScene(raw).setFog(fog)` (an `@margoengine/environment` `Fog`, or any object with its
|
|
1236
|
+
fields) as `vec3 fogColor`, `float fogNear`, `fogFar`, `fogDensity`, `fogHeight` and `fogHeightFalloff`. Margo's fog
|
|
1237
|
+
is linear from near to far at distance `d` from the camera, or `1 - exp(-(density d)^2)` when density is above 0,
|
|
1238
|
+
times `exp(-heightFalloff max(y - height, 0))`. `fogColor` comes as your program writes colour: display-ready
|
|
1239
|
+
(sRGB, as given) by default, linear with `outputColorSpace: 'linear'` or `#include <colorspace_fragment>`. Without a
|
|
1240
|
+
fog the values read as no fog (density 0, near and far at the float maximum). A name you give in `uniforms` is yours.
|
|
1241
|
+
- **Motion vectors.** `velocity: true` gives TAA (`taa.add(raw)`) the motion of every vertex the program moves: its
|
|
1242
|
+
vertex stage runs a second time with last frame's model matrix, view-projection and time, and TAA reads where each
|
|
1243
|
+
vertex was, as a WGSL `velocityEntry` writes it. A move driven by your own uniforms names, for each, the uniform that
|
|
1244
|
+
holds its value of last frame (`velocity: {wave: 'waveBefore'}`), which you set before you change the first; it needs
|
|
1245
|
+
no declaration. Without `velocity` TAA sees the camera's motion over the depth only, so a shape the shader moves
|
|
1246
|
+
leaves a trail.
|
|
1247
|
+
- **What each entry carries.** The scene options and `shaderScene` live in `shader/glsl-material` alone. `ShaderPass`
|
|
1248
|
+
and `Shadertoy` draw with the same program core without them, so their entries hold no light, fog or motion code;
|
|
1249
|
+
`toy.material()` refuses `lights`, `fog` and `velocity`. Their materials still pass `instanceof ShaderMaterial`.
|
|
1250
|
+
|
|
1251
|
+
```ts
|
|
1252
|
+
import {createStage} from 'margoengine';
|
|
1253
|
+
import {sphereGeometry} from 'margoengine/geometry';
|
|
1254
|
+
import {TAA} from 'margoengine/taa';
|
|
1255
|
+
import {RawShaders} from 'margoengine/shader/raw';
|
|
1256
|
+
import {ShaderMaterial, shaderMesh, shaderScene} from 'margoengine/shader/glsl-material';
|
|
1257
|
+
const stage = await createStage('#viewport');
|
|
1258
|
+
const raw = RawShaders.attach(stage.engine);
|
|
1259
|
+
shaderScene(raw)
|
|
1260
|
+
.setFog({color: '#8899aa', near: 4, far: 30})
|
|
1261
|
+
.setLights({list: [{position: [2, 2, 3], range: 12, color: [1, 0.6, 0.3], intensity: 4}]});
|
|
1262
|
+
const material = new ShaderMaterial({
|
|
1263
|
+
lights: true,
|
|
1264
|
+
fog: true,
|
|
1265
|
+
velocity: {wave: 'waveBefore'},
|
|
1266
|
+
uniforms: {wave: {value: 0}, waveBefore: {value: 0}},
|
|
1267
|
+
vertexShader: `uniform float wave;
|
|
1268
|
+
varying vec3 vNormal;
|
|
1269
|
+
varying vec3 vWorld;
|
|
1270
|
+
void main() {
|
|
1271
|
+
vec3 p = position + normal * 0.1 * sin(wave + position.y * 4.0);
|
|
1272
|
+
vNormal = mat3(modelMatrix) * normal;
|
|
1273
|
+
vWorld = (modelMatrix * vec4(p, 1.0)).xyz;
|
|
1274
|
+
gl_Position = projectionMatrix * viewMatrix * vec4(vWorld, 1.0);
|
|
1275
|
+
}`,
|
|
1276
|
+
fragmentShader: `precision highp float;
|
|
1277
|
+
struct Point { vec3 position; vec3 color; float range; float decay; };
|
|
1278
|
+
uniform vec3 sunDirection;
|
|
1279
|
+
uniform vec3 sunColor;
|
|
1280
|
+
uniform vec3 ambientLight;
|
|
1281
|
+
uniform Point pointLights[4];
|
|
1282
|
+
uniform int pointLightCount;
|
|
1283
|
+
uniform vec3 fogColor;
|
|
1284
|
+
uniform float fogNear;
|
|
1285
|
+
uniform float fogFar;
|
|
1286
|
+
varying vec3 vNormal;
|
|
1287
|
+
varying vec3 vWorld;
|
|
1288
|
+
void main() {
|
|
1289
|
+
vec3 n = normalize(vNormal);
|
|
1290
|
+
vec3 c = ambientLight + sunColor * max(dot(n, sunDirection), 0.0);
|
|
1291
|
+
for (int i = 0; i < 4; i++) {
|
|
1292
|
+
if (i >= pointLightCount) break;
|
|
1293
|
+
vec3 l = pointLights[i].position - vWorld;
|
|
1294
|
+
float d = length(l);
|
|
1295
|
+
float x = d / pointLights[i].range;
|
|
1296
|
+
float w = clamp(1.0 - x * x * x * x, 0.0, 1.0);
|
|
1297
|
+
c += pointLights[i].color * max(dot(n, l / d), 0.0) * w * w / max(pow(d, pointLights[i].decay), 1.0 / 4096.0);
|
|
1298
|
+
}
|
|
1299
|
+
float f = clamp((distance(vWorld, cameraPosition) - fogNear) / (fogFar - fogNear), 0.0, 1.0);
|
|
1300
|
+
gl_FragColor = vec4(mix(c * 0.4, fogColor, f), 1.0);
|
|
1301
|
+
}`,
|
|
1302
|
+
});
|
|
1303
|
+
raw.add(shaderMesh(sphereGeometry(1, 48, 24), material));
|
|
1304
|
+
TAA.attach(stage.engine).add(raw);
|
|
1305
|
+
stage.engine.onFrame((_, delta) => {
|
|
1306
|
+
material.uniforms.waveBefore.value = material.uniforms.wave.value;
|
|
1307
|
+
material.uniforms.wave.value = (material.uniforms.wave.value as number) + delta * 3;
|
|
1308
|
+
});
|
|
1309
|
+
```
|
|
1310
|
+
|
|
1311
|
+
## GLSL post passes (`@margoengine/shader/glsl-pass`, 40.4 kB min+gzip on its own)
|
|
1312
|
+
|
|
1313
|
+
`ShaderPass` runs a full-screen GLSL ES 1.00 or 3.00 program as a stage of `@margoengine/post`'s PostStack, in the
|
|
1314
|
+
`{uniforms, vertexShader, fragmentShader}` form web engines use for post passes. The stack's colour reaches the program
|
|
1315
|
+
through the first of `tDiffuse`, `textureSampler` and `uColorBuffer` it declares (or the sampler named by `input`).
|
|
1316
|
+
Without a vertex stage the pass supplies one triangle over the target that writes `vUv`, `vUV` or `vUv0`, whichever the
|
|
1317
|
+
fragment reads, with uv (0, 0) at the lower left; a vertex stage of your own gets `position` (xyz) and `uv`, and
|
|
1318
|
+
`projectionMatrix` and `modelViewMatrix` are the identity, as for a full-screen quad.
|
|
1319
|
+
|
|
1320
|
+
```ts
|
|
1321
|
+
import {createStage} from 'margoengine';
|
|
1322
|
+
import {PostStack} from 'margoengine/post';
|
|
1323
|
+
import {ShaderPass} from 'margoengine/shader/glsl-pass';
|
|
1324
|
+
|
|
1325
|
+
const stage = await createStage(document.querySelector('canvas')!);
|
|
1326
|
+
const pass = new ShaderPass({
|
|
1327
|
+
uniforms: {amount: {value: 0.5}},
|
|
1328
|
+
fragmentShader: `precision highp float;
|
|
1329
|
+
uniform sampler2D tDiffuse;
|
|
1330
|
+
uniform float amount;
|
|
1331
|
+
varying vec2 vUv;
|
|
1332
|
+
void main() {
|
|
1333
|
+
vec4 c = texture2D(tDiffuse, vUv);
|
|
1334
|
+
gl_FragColor = vec4(mix(c.rgb, vec3(dot(c.rgb, vec3(0.299, 0.587, 0.114))), amount), 1.0);
|
|
1335
|
+
}`,
|
|
1336
|
+
});
|
|
1337
|
+
PostStack.attach(stage.engine, [pass]);
|
|
1338
|
+
pass.uniforms.amount.value = 1; // live, no translation
|
|
1339
|
+
```
|
|
1340
|
+
|
|
1341
|
+
`await ShaderPass.attach(engine, shader, options?)` does the same in one call: it loads `@margoengine/post`, adds the
|
|
1342
|
+
pass to the scene's PostStack after the last effect of its kind (or a new PostStack when there is none) and returns
|
|
1343
|
+
it, and `pass.dispose()` takes it out again, with the stack when attach made it. The options are the constructor's
|
|
1344
|
+
plus `signal`.
|
|
1345
|
+
|
|
1346
|
+
```ts
|
|
1347
|
+
import {createStage} from 'margoengine';
|
|
1348
|
+
import {ShaderPass} from 'margoengine/shader/glsl-pass';
|
|
1349
|
+
|
|
1350
|
+
const stage = await createStage(document.querySelector('canvas')!);
|
|
1351
|
+
const invert = await ShaderPass.attach(stage.engine, {
|
|
1352
|
+
fragmentShader: `uniform sampler2D tDiffuse;
|
|
1353
|
+
varying vec2 vUv;
|
|
1354
|
+
void main() { gl_FragColor = vec4(1.0 - texture2D(tDiffuse, vUv).rgb, 1.0); }`,
|
|
1355
|
+
});
|
|
1356
|
+
invert.dispose(); // removes the pass and its PostStack
|
|
1357
|
+
```
|
|
1358
|
+
|
|
1359
|
+
- **Options.** `kind`: `'ldr'` (default) runs on display colour after tonemapping and writes display colour;
|
|
1360
|
+
`'hdr'` runs on linear light before it and, when last, goes through the display transform (its `outputColorSpace`
|
|
1361
|
+
defaults to `'linear'`). `input` (default the first convention name declared; `null` for a pass that reads nothing),
|
|
1362
|
+
`name`, and the program options of `ShaderMaterial`: `glslVersion`, `flipY`, `strict`, `builtins`, `attributes`
|
|
1363
|
+
(`{aPosition: 'position'}`), `includes`, `outputColorSpace`, `blending` (default `'none'`: the pass replaces its
|
|
1364
|
+
output). `pass.material` is the ShaderMaterial (`pass.material.code('fragment')` shows the WGSL).
|
|
1365
|
+
- **What a pass reads.** `gl_FragCoord` counts pixels of the target from the lower left, as GL's; the input sampler
|
|
1366
|
+
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
|
|
1367
|
+
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
|
|
1368
|
+
draws. `await pass.ready()` resolves when it has.
|
|
1369
|
+
- **Not here.** Scene depth as a sampler (NodePass has `inputDepth()`). Shadertoy programs run through
|
|
1370
|
+
`@margoengine/shader/shadertoy`, below.
|
|
1371
|
+
|
|
1372
|
+
## Shadertoy programs (`@margoengine/shader/shadertoy`, 49.9 kB min+gzip on its own)
|
|
1373
|
+
|
|
1374
|
+
`Shadertoy` runs the Image tab of a Shadertoy program, `void mainImage(out vec4 fragColor, in vec2 fragCoord)` as
|
|
1375
|
+
written in Shadertoy's editor, with its documented inputs: `iResolution`, `iTime`, `iTimeDelta`, `iFrameRate`,
|
|
1376
|
+
`iFrame`, `iChannelTime[4]`, `iChannelResolution[4]`, `iMouse`, `iDate`, `iSampleRate`, `iChannel0` to `iChannel3`
|
|
1377
|
+
and the older `iGlobalTime`, with the Common tab, Buffer A to D, keyboard, video and audio channels. One toy draws
|
|
1378
|
+
three ways: as a PostStack pass, into a texture once a frame, or on a mesh.
|
|
1379
|
+
|
|
1380
|
+
```ts
|
|
1381
|
+
import {createStage} from 'margoengine';
|
|
1382
|
+
import {PostStack} from 'margoengine/post';
|
|
1383
|
+
import {RawShaders} from 'margoengine/shader/raw';
|
|
1384
|
+
import {shaderMesh} from 'margoengine/shader/glsl-material';
|
|
1385
|
+
import {Shadertoy} from 'margoengine/shader/shadertoy';
|
|
1386
|
+
|
|
1387
|
+
const stage = await createStage(document.querySelector('canvas')!);
|
|
1388
|
+
const toy = new Shadertoy(`void mainImage(out vec4 fragColor, in vec2 fragCoord) {
|
|
1389
|
+
vec2 uv = fragCoord / iResolution.xy;
|
|
1390
|
+
fragColor = vec4(0.5 + 0.5 * cos(iTime + uv.xyx + vec3(0.0, 2.0, 4.0)), 1.0);
|
|
1391
|
+
}`);
|
|
1392
|
+
PostStack.attach(stage.engine, [toy.pass()]); // over the whole screen
|
|
1393
|
+
|
|
1394
|
+
// Or on a mesh, with fragCoord = uv * resolution; the attached toy runs the clock and draws toy.texture.
|
|
1395
|
+
stage.engine.use(toy); // Shadertoy.attach(stage.engine, source) makes and attaches a toy in one call
|
|
1396
|
+
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()));
|
|
1397
|
+
```
|
|
1398
|
+
|
|
1399
|
+
- **Channels.** `new Shadertoy({image: {source, iChannel0, ...}, resolution})`: a channel is a
|
|
1400
|
+
`@margoengine/materials` Texture, a GPUTexture or view, `(device) => GPUTexture | GPUTextureView` (made once per
|
|
1401
|
+
device; see Device restore below), `'input'` (in a pass, the colour of the stage before), a
|
|
1402
|
+
buffer `'A'` to `'D'`, `'keyboard'`, a video or image, an AnalyserNode, or null (opaque black, as GL reads an
|
|
1403
|
+
unbound unit), or `{texture, type, filter, wrap, resolution}` with `type` `'2d'` (default; `'3d'` for a 3D
|
|
1404
|
+
GPUTexture), `'cube'` or `'3d'`, `filter` `'linear'` (default), `'nearest'` or `'mipmap'` (a texture brings its own
|
|
1405
|
+
levels), `wrap` `'clamp'` (default) or `'repeat'`. A function's texture is a sampler2D unless `type` says `'3d'` or
|
|
1406
|
+
`'cube'`. 2D channels read Margo's images upright (v up, as Shadertoy's flipped uploads read); `iChannelResolution`
|
|
1407
|
+
is the GPUTexture's size (a function's: the texture it made), a Texture's `width` and `height`, the target for
|
|
1408
|
+
`'input'`, or `resolution`.
|
|
1409
|
+
- **Changing a channel.** `toy.setChannel(index, texture, tab)` (tab default `'image'`, else `'bufferA'` to
|
|
1410
|
+
`'bufferD'`, `'cubeA'` or `'sound'`) gives a texture channel a new GPUTexture or view of its sampler type, a
|
|
1411
|
+
Texture, a function or null, a video or image channel another, and an audio channel another AnalyserNode. The toy's
|
|
1412
|
+
own channels (`'input'`, a buffer, `'cubeA'`, `'keyboard'`) are set when it is made and throw a TypeError here, as
|
|
1413
|
+
does a texture of another sampler type.
|
|
1414
|
+
- **Device restore.** A GPUTexture or view you made belongs to the device that made it. A function channel is made
|
|
1415
|
+
again on the new device after `engine.rebootDevice()`. A plain one is lost: the channel reads opaque black (as an
|
|
1416
|
+
unbound one), `engine.onError` hears of it once (`'state'`,
|
|
1417
|
+
[#borrowed-lost](https://margoengine.com/errors#borrowed-lost)) under the channel's name, the frame keeps drawing,
|
|
1418
|
+
and `toy.setChannel` brings it back. The toy's buffers, Cube A and its keyboard, video and audio textures are its
|
|
1419
|
+
own and are made again by themselves.
|
|
1420
|
+
|
|
1421
|
+
```ts
|
|
1422
|
+
import {createStage} from 'margoengine';
|
|
1423
|
+
import {PostStack} from 'margoengine/post';
|
|
1424
|
+
import {Shadertoy} from 'margoengine/shader/shadertoy';
|
|
1425
|
+
|
|
1426
|
+
const stage = await createStage(document.querySelector('canvas')!);
|
|
1427
|
+
// Made once per device, so the channel is back by itself after a device restore.
|
|
1428
|
+
const noise = (device: GPUDevice) => {
|
|
1429
|
+
const texture = device.createTexture({size: [64, 64], format: 'rgba8unorm', usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST});
|
|
1430
|
+
device.queue.writeTexture({texture}, crypto.getRandomValues(new Uint8Array(64 * 64 * 4)), {bytesPerRow: 64 * 4}, [64, 64]);
|
|
1431
|
+
return texture;
|
|
1432
|
+
};
|
|
1433
|
+
const toy = new Shadertoy({
|
|
1434
|
+
image: {
|
|
1435
|
+
source: `void mainImage(out vec4 fragColor, in vec2 fragCoord) {
|
|
1436
|
+
fragColor = vec4(texture(iChannel0, fragCoord / iChannelResolution[0].xy).rgb, 1.0);
|
|
1437
|
+
}`,
|
|
1438
|
+
iChannel0: {texture: noise, wrap: 'repeat'},
|
|
1439
|
+
},
|
|
1440
|
+
});
|
|
1441
|
+
PostStack.attach(stage.engine, [toy.pass()]);
|
|
1442
|
+
// A plain texture works too, but is lost with its device: set a new one after a restore.
|
|
1443
|
+
toy.setChannel(0, noise(stage.engine.gpu!));
|
|
1444
|
+
```
|
|
1445
|
+
- **Inputs.** `toy.time`, `toy.frame`, `toy.timeDelta`, `toy.frameRate`, `toy.mouse` (`[x, y, clickX, clickY]` in
|
|
1446
|
+
pixels) and `toy.date` (year, month from 0 as JavaScript's Date, day, seconds since midnight; `undefined` follows
|
|
1447
|
+
the clock) are settable; `iSampleRate` is `sampleRate` (default 44100). The clock starts at frame 0, time 0 and adds
|
|
1448
|
+
each frame's delta; `pause()`, `play()` and `reset()` control it. A pass runs it by itself; for a material or the
|
|
1449
|
+
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
|
|
1450
|
+
and the keyboard, video and audio channels hold until `toy.frame` is set, which runs them once.
|
|
1451
|
+
- **Targets.** `toy.pass(options)` is a ShaderPass (`kind`, `name`, `flipY`, `blending` as there): `iResolution` is the
|
|
1452
|
+
target's size and fragCoord its pixel, from the lower left. `toy.texture` is an rgba8unorm image of `resolution`
|
|
1453
|
+
(default 512 x 512) drawn before the scene each frame while the toy is attached, for raw, node and GLSL materials.
|
|
1454
|
+
`toy.material(options)` is a ShaderMaterial (render state options as there) with fragCoord = uv * `resolution`.
|
|
1455
|
+
`toy.fragmentShader`, `toy.meshShaders` and `toy.buffers` show the GLSL around each source; an error names its tab
|
|
1456
|
+
(`error.tab`: `'common'`, `'image'`, `'bufferA'` to `'bufferD'`, `'cubeA'`, `'sound'`) and that tab's own line.
|
|
1457
|
+
|
|
1458
|
+
### Multipass: Common, Buffer A to D, keyboard, video and audio
|
|
1459
|
+
|
|
1460
|
+
```ts
|
|
1461
|
+
import {createStage} from 'margoengine';
|
|
1462
|
+
import {PostStack} from 'margoengine/post';
|
|
1463
|
+
import {Shadertoy} from 'margoengine/shader/shadertoy';
|
|
1464
|
+
|
|
1465
|
+
const stage = await createStage(document.querySelector('canvas')!);
|
|
1466
|
+
const toy = new Shadertoy({
|
|
1467
|
+
common: 'vec3 palette(float t) { return 0.5 + 0.5 * cos(6.2832 * (t + vec3(0.0, 0.33, 0.67))); }',
|
|
1468
|
+
// Buffer A reads its own last frame: a trail that fades.
|
|
1469
|
+
bufferA: {
|
|
1470
|
+
source: `void mainImage(out vec4 fragColor, in vec2 fragCoord) {
|
|
1471
|
+
vec2 uv = fragCoord / iResolution.xy, dot_ = 0.5 + 0.3 * vec2(cos(iTime), sin(iTime * 1.3));
|
|
1472
|
+
float d = length(uv - dot_);
|
|
1473
|
+
fragColor = max(texture(iChannel0, uv) * 0.97, vec4(palette(iTime * 0.1) * smoothstep(0.05, 0.0, d), 1.0));
|
|
1474
|
+
}`,
|
|
1475
|
+
iChannel0: 'A',
|
|
1476
|
+
},
|
|
1477
|
+
image: {
|
|
1478
|
+
source: `void mainImage(out vec4 fragColor, in vec2 fragCoord) {
|
|
1479
|
+
vec3 trail = texture(iChannel0, fragCoord / iResolution.xy).rgb;
|
|
1480
|
+
float space = texelFetch(iChannel1, ivec2(32, 0), 0).x; // the space bar is down
|
|
1481
|
+
fragColor = vec4(mix(trail, 1.0 - trail, space), 1.0);
|
|
1482
|
+
}`,
|
|
1483
|
+
iChannel0: {texture: 'A', filter: 'mipmap'},
|
|
1484
|
+
iChannel1: 'keyboard',
|
|
1485
|
+
},
|
|
1486
|
+
});
|
|
1487
|
+
PostStack.attach(stage.engine, [toy.pass()]);
|
|
1488
|
+
```
|
|
1489
|
+
|
|
1490
|
+
- **Common and buffers.** `common` is placed before every tab's source. `bufferA` to `bufferD` take a source and
|
|
1491
|
+
channels as `image` does; each frame they draw in the order A, B, C, D, then the image, into rgba32float targets of
|
|
1492
|
+
the image's size that start at zero. A channel given `'A'` to `'D'` reads that buffer's latest image: its own last
|
|
1493
|
+
frame, this frame's for a buffer drawn before it. A buffer keeps all four components as written (negative and above
|
|
1494
|
+
1 too); the image writes opaque colour.
|
|
1495
|
+
- **Filtering a buffer.** A buffer channel's `filter` is `'nearest'`, `'linear'` or `'mipmap'` (trilinear; the buffer's
|
|
1496
|
+
mip levels are made each frame by a 2 x 2 box) and `wrap` `'clamp'` or `'repeat'`. rgba32float can be filtered by
|
|
1497
|
+
the device only with `float32-filterable`, which is optional in WebGPU, so a linear or mipmap buffer channel reads
|
|
1498
|
+
its texels with `textureLoad` and filters them as GL does (four loads a level, OpenGL ES 3.0.6 section 3.8.10). It
|
|
1499
|
+
reads the same on every device, with or without the feature, and needs no `features` option. A function that takes
|
|
1500
|
+
`sampler2D` filters as the channel passed to it says.
|
|
1501
|
+
- **Keyboard.** `'keyboard'` is a 256 x 3 channel as Shadertoy's: `texelFetch(iChannel0, ivec2(keyCode, row), 0).x`
|
|
1502
|
+
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
|
|
1503
|
+
listens on `keyboard` (default the window) and stops on `dispose()`.
|
|
1504
|
+
- **Video and images.** A `<video>`, canvas, OffscreenCanvas, ImageBitmap or `<img>` is copied into its channel each
|
|
1505
|
+
frame (a video once it has a frame; an image or ImageBitmap once), upright as Shadertoy's flipped uploads.
|
|
1506
|
+
`iChannelTime` is the video's `currentTime` and `iChannelResolution` its size. `filter: 'mipmap'` makes its levels.
|
|
1507
|
+
- **Audio.** An `AnalyserNode` (or any object with `getByteFrequencyData` and `getByteTimeDomainData`) is a 512 x 2
|
|
1508
|
+
channel: `texture(iChannel0, vec2(x, 0.25)).x` is the spectrum, `vec2(x, 0.75)` the waveform, as Shadertoy's sound
|
|
1509
|
+
input. `iChannelTime` is its context's `currentTime`.
|
|
1510
|
+
- **Base level.** A channel whose `filter` is `'nearest'` or `'linear'` reads only the base level of a texture that
|
|
1511
|
+
has mip levels, as GL does without a mipmap min filter (OpenGL ES 3.0.6 section 3.8.10).
|
|
1512
|
+
|
|
1513
|
+
### Cube A, VR and sound
|
|
1514
|
+
|
|
1515
|
+
```ts
|
|
1516
|
+
import {createStage} from 'margoengine';
|
|
1517
|
+
import {PostStack} from 'margoengine/post';
|
|
1518
|
+
import {Shadertoy} from 'margoengine/shader/shadertoy';
|
|
1519
|
+
|
|
1520
|
+
const stage = await createStage(document.querySelector('canvas')!);
|
|
1521
|
+
const toy = new Shadertoy({
|
|
1522
|
+
// Cube A: drawn into the six faces of a cube each frame; rayDir is the unit direction of the texel.
|
|
1523
|
+
cubeA: {
|
|
1524
|
+
source: `void mainCubemap(out vec4 fragColor, in vec2 fragCoord, in vec3 rayOri, in vec3 rayDir) {
|
|
1525
|
+
vec3 sky = mix(vec3(0.9, 0.6, 0.4), vec3(0.2, 0.4, 0.9), 0.5 + 0.5 * rayDir.y);
|
|
1526
|
+
fragColor = vec4(sky + 0.3 * pow(max(dot(rayDir, normalize(vec3(cos(iTime), 0.4, sin(iTime)))), 0.0), 64.0), 1.0);
|
|
1527
|
+
}`,
|
|
1528
|
+
size: 256,
|
|
1529
|
+
},
|
|
1530
|
+
image: {
|
|
1531
|
+
source: `void mainImage(out vec4 fragColor, in vec2 fragCoord) {
|
|
1532
|
+
vec2 p = (2.0 * fragCoord - iResolution.xy) / iResolution.y;
|
|
1533
|
+
fragColor = vec4(texture(iChannel0, normalize(vec3(p, -1.5))).rgb, 1.0);
|
|
1534
|
+
}
|
|
1535
|
+
// With vr: true a pass and a mesh call mainVR with each pixel's ray from the camera drawing it (each eye in XR).
|
|
1536
|
+
void mainVR(out vec4 fragColor, in vec2 fragCoord, in vec3 fragRayOri, in vec3 fragRayDir) {
|
|
1537
|
+
fragColor = vec4(texture(iChannel0, fragRayDir).rgb, 1.0);
|
|
1538
|
+
}`,
|
|
1539
|
+
iChannel0: 'cubeA',
|
|
1540
|
+
},
|
|
1541
|
+
// The Sound tab: one stereo sample per call, from -1 to 1.
|
|
1542
|
+
sound: {
|
|
1543
|
+
source: `vec2 mainSound(int samp, float time) {
|
|
1544
|
+
float note = sin(6.2831853 * fract(440.0 * time)) * exp(-3.0 * fract(time));
|
|
1545
|
+
return vec2(note, note * 0.8);
|
|
1546
|
+
}`,
|
|
1547
|
+
},
|
|
1548
|
+
vr: true,
|
|
1549
|
+
});
|
|
1550
|
+
PostStack.attach(stage.engine, [toy.pass()]);
|
|
1551
|
+
|
|
1552
|
+
// The samples, rendered over the next frames while the toy is attached.
|
|
1553
|
+
stage.engine.use(toy);
|
|
1554
|
+
const sound = await toy.sound({seconds: 4});
|
|
1555
|
+
const audio = new AudioContext(),
|
|
1556
|
+
player = audio.createBufferSource();
|
|
1557
|
+
player.buffer = sound.audioBuffer(audio);
|
|
1558
|
+
player.connect(audio.destination);
|
|
1559
|
+
player.start();
|
|
1560
|
+
```
|
|
1561
|
+
|
|
1562
|
+
- **Cube A.** `cubeA: {source, size, iChannel0, ...}` takes `void mainCubemap(out vec4 fragColor, in vec2 fragCoord,
|
|
1563
|
+
in vec3 rayOri, in vec3 rayDir)`. Each frame, after the buffers and before the image, it is drawn into the six faces
|
|
1564
|
+
of an rgba16float cube of `size` pixels a face (a power of two from 1 to 2048, default 1024): `rayDir` is the unit
|
|
1565
|
+
direction through the texel's centre, faces as OpenGL ES 3.0.6 Table 3.21 numbers them, `rayOri` is zero and
|
|
1566
|
+
`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
|
|
1567
|
+
reads it as `'cubeA'`, a `samplerCube` channel (`'nearest'`, `'linear'` or `'mipmap'`; the cube's levels are made
|
|
1568
|
+
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
|
|
1569
|
+
faces and six copies into the cube a frame, one more draw per mip level and six copies per level.
|
|
1570
|
+
- **mainVR.** With `vr: true` the Image source needs `void mainVR(out vec4 fragColor, in vec2 fragCoord, in vec3
|
|
1571
|
+
fragRayOri, in vec3 fragRayDir)`. `toy.pass()` calls it with the ray of each pixel from the camera that draws it:
|
|
1572
|
+
the camera's position and the direction to the pixel's point on the near plane (the inverse of its view-projection),
|
|
1573
|
+
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
|
|
1574
|
+
surface. `toy.texture` keeps calling mainImage. `toy.vrShader` shows the pass's program.
|
|
1575
|
+
- **mainSound.** `sound: {source, iChannel0, ...}` takes `vec2 mainSound(int samp, float time)`, or the older `vec2
|
|
1576
|
+
mainSound(float time)`; its channels read textures only. `toy.sound({seconds = 180, signal})` renders it while the
|
|
1577
|
+
toy is attached, 262,144 samples (one 512 x 512 rgba32float block) a frame, mapped back on the next frame, and
|
|
1578
|
+
resolves to `{sampleRate, channels: [left, right], audioBuffer(context)}`: one Float32Array a channel with values
|
|
1579
|
+
clamped to -1 to 1, `time` is `samp / sampleRate`, and `audioBuffer` makes a Web Audio buffer for any audio context.
|
|
1580
|
+
The signal rejects the promise with its reason; a new device starts the render again. `toy.soundShader` shows
|
|
1581
|
+
the program.
|
|
1582
|
+
|
|
1583
|
+
## Screen effects (`@margoengine/shader/effects`, 8.6 kB min+gzip on its own)
|
|
1584
|
+
|
|
1585
|
+
Ready-made `NodePass` effects for a PostStack, each with live `uniforms` (`effect.uniforms.darkness.value = 0.5`). LDR by
|
|
1586
|
+
default (after tonemapping, on display colour); `{kind: 'hdr'}` runs one on linear light before the display effect.
|
|
1587
|
+
|
|
1588
|
+
```ts
|
|
1589
|
+
import {PostStack} from 'margoengine/post';
|
|
1590
|
+
import {Tonemap} from 'margoengine/tonemap';
|
|
1591
|
+
import {vignette, rgbShift} from 'margoengine/shader/effects';
|
|
1592
|
+
import {createStage} from 'margoengine';
|
|
1593
|
+
const stage = await createStage('#viewport', {backend: 'webgpu'});
|
|
1594
|
+
const look = vignette({darkness: 0.6}), shift = rgbShift({amount: 0.004});
|
|
1595
|
+
PostStack.attach(stage.engine, [new Tonemap(), shift, look]);
|
|
1596
|
+
look.uniforms.darkness.value = 0.9; // live
|
|
1597
|
+
```
|
|
1598
|
+
|
|
1599
|
+
| Preset | Parameters (default) |
|
|
1600
|
+
| --- | --- |
|
|
1601
|
+
| `vignette` | `darkness` 0.8, `radius` 0.4 (0 centre, 1 corner), `softness` 0.6 |
|
|
1602
|
+
| `rgbShift` | `amount` 0.002 (UV units, about 4 px at 1920 wide), `angle` 0 (radians; red moves right, blue left) |
|
|
1603
|
+
| `chromaticAberration` | `strength` 0.01 (red and blue scaled about the centre by 1 -/+ strength) |
|
|
1604
|
+
| `pixelate` | `size` 8 pixels; each block is the input pixel at its centre |
|
|
1605
|
+
| `halftone` | `size` 8 pixels, `angle` 0.26; `greyscale` (construction only) |
|
|
1606
|
+
| `dotScreen` | `size` 6 pixels, `angle` 0.785; black dots on white |
|
|
1607
|
+
| `sobel` | `strength` 1, `overlay` 0 (1 draws black edges over the image) |
|
|
1608
|
+
| `sepia` | `amount` 1 (W3C Filter Effects matrix) |
|
|
1609
|
+
| `posterize` | `levels` 4 |
|
|
1610
|
+
|
|
1611
|
+
The same GPU check feeds known images through them: Sobel gives exactly 4 x the luma step beside a step and 0 elsewhere,
|
|
1612
|
+
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
|
|
1613
|
+
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
|
|
1614
|
+
within 5 of 255 on average, since each dot covers its value's share of the cell. Their 1 px edge ramp adds about
|
|
1615
|
+
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
|
|
1616
|
+
(about 5 of 255 for dot screen's default 6 px at 80% ink).
|
|
1617
|
+
|
|
1618
|
+
## Black hole (`@margoengine/shader/black-hole`)
|
|
1619
|
+
|
|
1620
|
+
A spinning (Kerr) black hole drawn by one full-screen raw shader: a thin accretion disk with the Page-Thorne flux,
|
|
1621
|
+
gravitational and Doppler redshift and beaming, a relativistic jet, and a lensed star field and Milky Way. Every ray is
|
|
1622
|
+
traced back from the camera through Kerr spacetime (fourth-order Runge-Kutta in Boyer-Lindquist coordinates), so the
|
|
1623
|
+
shadow, the photon ring and the disk's secondary images come out of the maths, not from a texture. The scene unit is the
|
|
1624
|
+
Schwarzschild radius r_s = 2M; the hole sits at the origin with its spin along +y.
|
|
1625
|
+
|
|
1626
|
+
```ts
|
|
1627
|
+
import {BlackHole, traceGeodesic} from 'margoengine/shader/black-hole';
|
|
1628
|
+
import {ShaderClock} from 'margoengine/shader';
|
|
1629
|
+
import {createStage} from 'margoengine';
|
|
1630
|
+
const stage = await createStage('#viewport', {
|
|
1631
|
+
backend: 'webgpu',
|
|
1632
|
+
camera: {position: [-0.55, 0.95, 11.8], target: [0, -0.05, 0], fov: 38, near: 0.05, far: 1000},
|
|
1633
|
+
});
|
|
1634
|
+
const hole = BlackHole.attach(stage.engine, {spin: 0.9, accretion: 1, jet: 0.5});
|
|
1635
|
+
hole.view = 'redshift'; // 'beauty' (default), 'redshift', 'beaming', 'temperature', 'orders'
|
|
1636
|
+
hole.flare(ShaderClock.attach(stage.engine).time); // a hot spot that spirals in over 8 s on the engine clock
|
|
1637
|
+
const fan = [-3, -2, -1, 1, 2, 3].map((y) => traceGeodesic([0, y, 40], [0, 0, -1], {spin: hole.spin}));
|
|
1638
|
+
hole.showGeodesics(fan); // the rays drawn as lines; each knows its fate and disk crossings
|
|
1639
|
+
```
|
|
1640
|
+
|
|
1641
|
+
| Option | Default | What it does |
|
|
1642
|
+
| --- | --- | --- |
|
|
1643
|
+
| `spin` | 0.9 | a = J / M^2, 0 to 0.998 (Thorne's limit). The horizon and ISCO follow it (`hole.horizon`, `hole.isco`). |
|
|
1644
|
+
| `accretion` | 1 | Disk brightness, a multiple of the default accretion rate; 0 hides the disk. |
|
|
1645
|
+
| `peakTemperature` | 4500 | Disk temperature at its flux peak in kelvin, before redshift; the colour is the Planckian locus at g T. |
|
|
1646
|
+
| `diskOuter` | 6 | Outer disk radius in r_s. |
|
|
1647
|
+
| `turbulence` | 0.6 | Disk turbulence, 0 (a smooth Page-Thorne disk) to 1. |
|
|
1648
|
+
| `jet`, `jetLorentz` | 0.5, 5 | Jet brightness (0 to 1) and its bulk Lorentz factor (1 to 20). |
|
|
1649
|
+
| `stars`, `galaxy` | 1, 1 | Star field and Milky Way brightness; 0 hides them. |
|
|
1650
|
+
| `timeScale` | 6 | Units of M of orbital time per second of the shader clock (`camera.time`). |
|
|
1651
|
+
| `diskTime` | null | External texture clock in seconds for replay. Null follows the engine shader clock. |
|
|
1652
|
+
| `diskInflow` | 0.002 | Prescribed inward drift in M per unit of orbital time, with zero giving circular advection. |
|
|
1653
|
+
| `exposure` | 1 | Linear exposure of the output. |
|
|
1654
|
+
| `view` | `'beauty'` | The picture, or a map that explains it: redshift g, beaming g^4, observed temperature, image order. |
|
|
1655
|
+
| `prefilter` | true | Band-limit the disk and draw stars as points through the lens (off shows a plain point-sampled march). |
|
|
1656
|
+
| `steps` | 260 | Integration steps per ray. |
|
|
1657
|
+
|
|
1658
|
+
The material backtraces each disk emitter through Kerr circular angular velocity and a steady radial drift
|
|
1659
|
+
before sampling its texture. The beaming map keeps the approaching side's Doppler factor and weights it by
|
|
1660
|
+
the moving emission. `hole.diskTime` can receive elapsed seconds from `PhysicsWorld`, and `kerrDiskAdvection`
|
|
1661
|
+
gives the corresponding radius and angular phase on the CPU.
|
|
1662
|
+
|
|
1663
|
+
The output is linear HDR: the disk's flux peak is about 0.8 before `exposure`, its Doppler-boosted side several times
|
|
1664
|
+
that. For a glowing picture, raise `exposure` and end with threshold-free bloom and a filmic curve, as
|
|
1665
|
+
`examples/event-horizon` does: `exposure: 4.9` on the hole, `new Bloom({strength: 0.05, threshold: 0, radius: 0.6})`
|
|
1666
|
+
and `new Tonemap({curve: 'acescg', contrast: 1.15})`.
|
|
1667
|
+
|
|
1668
|
+
How it works (sources, read as papers only):
|
|
1669
|
+
|
|
1670
|
+
- Kerr null geodesics in Boyer-Lindquist coordinates and the camera's ray in the zero-angular-momentum frame: O. James,
|
|
1671
|
+
E. von Tunzelmann, P. Franklin and K. S. Thorne, "Gravitational lensing by spinning black holes in astrophysics, and
|
|
1672
|
+
in the movie Interstellar", Classical and Quantum Gravity 32, 065001 (2015), eqs. A.9 to A.15,
|
|
1673
|
+
https://arxiv.org/abs/1502.03808. Stars are points carried through the inverse pixel-footprint jacobian with their
|
|
1674
|
+
magnification, as that paper's ray bundles do, so lensing never stretches them into dashes.
|
|
1675
|
+
- Horizon, ISCO, photon orbit and circular-orbit angular velocity: J. M. Bardeen, W. H. Press and S. A. Teukolsky,
|
|
1676
|
+
"Rotating black holes: locally nonrotating frames, energy extraction, and scalar synchrotron radiation", ApJ 178, 347
|
|
1677
|
+
(1972), https://ui.adsabs.harvard.edu/abs/1972ApJ...178..347B. Redshift g = 1 / (u^t (1 - Omega b)).
|
|
1678
|
+
- Disk flux: D. N. Page and K. S. Thorne, "Disk-accretion onto a black hole. Time-averaged structure of accretion
|
|
1679
|
+
disk", ApJ 191, 499 (1974), eq. 15n, https://ui.adsabs.harvard.edu/abs/1974ApJ...191..499P. Observed intensity g^4 F:
|
|
1680
|
+
J.-P. Luminet, "Image of a spherical black hole with thin accretion disk", A&A 75, 228 (1979),
|
|
1681
|
+
https://ui.adsabs.harvard.edu/abs/1979A&A....75..228L.
|
|
1682
|
+
- Jet: a parabolic funnel near the hole (K. Asada and M. Nakamura, "The structure of the M87 jet: a transition from
|
|
1683
|
+
parabolic to conical streamlines", ApJL 745, L28 (2012), https://ui.adsabs.harvard.edu/abs/2012ApJ...745L..28A),
|
|
1684
|
+
brightness D^(2 + alpha) (M. L. Lind and R. D. Blandford, "Semidynamical models of radio jets: relativistic beaming
|
|
1685
|
+
and source counts", ApJ 295, 358 (1985), https://ui.adsabs.harvard.edu/abs/1985ApJ...295..358L): side on it beams
|
|
1686
|
+
away and is nearly invisible; down the axis it is bright. Its light also climbs out of the hole's potential: the
|
|
1687
|
+
frequency ratio is the zero-angular-momentum frame's lapse times D (`kerrLapse`, Bardeen, Press and Teukolsky 1972),
|
|
1688
|
+
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
|
|
1689
|
+
and R. L. Znajek, "Electromagnetic extraction of energy from Kerr black holes", MNRAS 179, 433 (1977),
|
|
1690
|
+
https://doi.org/10.1093/mnras/179.3.433; J. C. McKinney, "General relativistic magnetohydrodynamic simulations of the
|
|
1691
|
+
jet formation and large-scale propagation from black hole accretion systems", MNRAS 368, 1561 (2006),
|
|
1692
|
+
https://arxiv.org/abs/astro-ph/0603045). Without both, the jet's base shone as a dot over the shadow seen from
|
|
1693
|
+
near the pole.
|
|
1694
|
+
- Disk detail without banding: the pixel footprint from ray differentials (H. Igehy, "Tracing ray differentials",
|
|
1695
|
+
SIGGRAPH 1999, https://graphics.stanford.edu/papers/trd/), octaves faded above the footprint's Nyquist limit (A.
|
|
1696
|
+
Norton, A. P. Rockwood and P. T. Skolmoski, "Clamping: a method of antialiasing textured surfaces by bandwidth
|
|
1697
|
+
limiting in object space", SIGGRAPH 1982, https://doi.org/10.1145/965145.801274), and two advected noise phases
|
|
1698
|
+
crossfaded every 24 s so Keplerian shear never winds the pattern without bound (F. Neyret, "Advected textures",
|
|
1699
|
+
SCA 2003, https://hal.inria.fr/inria-00537472). The turbulent brightness is log-normal, exp(5 turbulence n), as the
|
|
1700
|
+
surface density of magnetised disk turbulence is (S. A. Balbus and J. F. Hawley, "A powerful local shear instability
|
|
1701
|
+
in weakly magnetized disks. I. Linear analysis", ApJ 376, 214 (1991),
|
|
1702
|
+
https://ui.adsabs.harvard.edu/abs/1991ApJ...376..214B), so bright knots and dark lanes read at video resolution.
|
|
1703
|
+
- Sky: stars on a latitude-band grid in two layers (140 and 300 bands), a steep luminosity function and colours
|
|
1704
|
+
on the Planckian locus from 3,000 to 15,000 K. They crowd towards the galactic plane (5% of cells at the poles, about
|
|
1705
|
+
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
|
|
1706
|
+
bends the band and its crowded star field into the Einstein ring.
|
|
1707
|
+
- The spin axis: Boyer-Lindquist coordinates are singular there. A ray of axial angular momentum b turns at
|
|
1708
|
+
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
|
|
1709
|
+
(`kerrAxisStep`), and a ray that would turn within a third of `POLE_BAND` (0.001) is taken over the axis instead
|
|
1710
|
+
(`kerrAxial`): inside the band it goes straight, and the reflection at theta = 0 turns its phi by the swing a
|
|
1711
|
+
straight line makes there, 2 acos(theta_min / POLE_BAND) (`kerrAxisTurn`). Before, rays a hundredth of a pixel apart
|
|
1712
|
+
near the axis left in unrelated directions, a dashed seam through the sky and over the far disk. The disk-plane
|
|
1713
|
+
crossing test is half open (`crossesEquator`): a product test lost the crossing when a step ended exactly on theta =
|
|
1714
|
+
pi / 2 in f32, a dark speck on the disk.
|
|
1715
|
+
- 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
|
|
1716
|
+
Korean Physical Society 41, 865 (2002)).
|
|
1717
|
+
|
|
1718
|
+
The CPU twin (`traceGeodesic`, `kerrRhs`, `kerrAxisStep`, `kerrAxial`, `kerrAxisTurn`, `crossesEquator`, `kerrLapse`,
|
|
1719
|
+
`novikovThorneFlux`, `diskRedshift`, `jetDoppler`, `blackbodyColor` and the radius functions) runs the same integrator
|
|
1720
|
+
step for step, for overlays and tests. Limits: a ray gets at most `steps` steps, so rays that graze the photon orbit
|
|
1721
|
+
end dark; the null condition holds under 1e-5 on escaping rays and drifts more on retrograde captured rays inside 4 M.
|
|
1722
|
+
The camera frame is built without atan2: one GPU compiler drops the sign of a negated component of a constant-scaled
|
|
1723
|
+
vector in a division (docs/known-bugs.md). GPU checks: `node packages/shader/test/black-hole-check.mjs` (camera frame,
|
|
1724
|
+
round stars, the jet side on, disk detail over time) and `node packages/shader/test/negated-division-check.mjs`
|
|
1725
|
+
(Margo's formulations, and whether the fault is present).
|
|
1726
|
+
|
|
1727
|
+
## Limits
|
|
1728
|
+
|
|
1729
|
+
- 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.
|
|
1730
|
+
- 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.
|
|
1731
|
+
- `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.
|
|
1732
|
+
- Raw meshes cast into `Shadows` only: `VirtualShadows` and `LocalShadows` take no custom caster. SSR, GTAO, SSGI and scene passes do not see them, beyond the depth they write; 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.
|
|
1733
|
+
- 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.
|
|
1734
|
+
- 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.
|
|
1735
|
+
- Storage textures are 2D, one mip level, one sample; `@margoengine/shader/compute-texture` has no 3D or array form.
|
|
1736
|
+
- 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.
|
|
1737
|
+
- `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.
|
|
1738
|
+
|
|
1739
|
+
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).
|
|
1740
|
+
|
|
1741
|
+
Apache-2.0. Optional, tree-shakable package; peers `@margoengine/core`, `@margoengine/materials` and `@margoengine/gltf/pbr` (^0.1.0 || ^1.0.0).
|
|
1742
|
+
|
|
1743
|
+
Build and unit tests: `npm test --workspace @margoengine/shader`. Browser check on a real WebGPU adapter: `node packages/shader/test/browser-check.mjs`.
|
|
1744
|
+
|
|
1745
|
+
## Preview tier contract
|
|
1746
|
+
|
|
1747
|
+
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.
|
|
1748
|
+
|
|
1749
|
+
## Film time
|
|
1750
|
+
|
|
1751
|
+
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`.
|
|
1752
|
+
|
|
1753
|
+
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`:
|
|
1754
|
+
|
|
1755
|
+
```ts
|
|
1756
|
+
import {createMesh} from 'margoengine/materials';
|
|
1757
|
+
import {sphereGeometry} from 'margoengine/geometry';
|
|
1758
|
+
import {NodeMaterial, ShaderClock, color, sin, time} from 'margoengine/shader';
|
|
1759
|
+
import {seek} from 'margoengine/cutscene/seek';
|
|
1760
|
+
import {createStage} from 'margoengine';
|
|
1761
|
+
const stage = await createStage('#viewport', {backend: 'webgpu'});
|
|
1762
|
+
const clock = ShaderClock.attach(stage.engine); // one per engine; 0 until the first frame update
|
|
1763
|
+
const glow = sin(time).mul(0.5).add(0.5);
|
|
1764
|
+
createMesh(stage.engine, sphereGeometry(1, 64, 32), new NodeMaterial({colorNode: color('#ff4020').mul(glow)}));
|
|
1765
|
+
// This scene starts 12 s into the film: the pulse is where a run from 0 had it.
|
|
1766
|
+
await seek(stage.engine, 12, {fps: 30});
|
|
1767
|
+
stage.engine.render({delta: 1 / 30});
|
|
1768
|
+
console.log(clock.time); // 360 steps of 1 / 30 s, then the frame's own
|
|
1769
|
+
```
|
|
1770
|
+
|
|
1771
|
+
Before this, shader `time` was `performance.now()` in seconds, the time since the page opened; it now starts at 0 with the clock.
|