reze-engine 0.69.8 → 0.70.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/_dbg-loader.mjs +1100 -0
  2. package/dist/camera-mount.d.ts +57 -0
  3. package/dist/camera-mount.d.ts.map +1 -0
  4. package/dist/camera-mount.js +249 -0
  5. package/dist/camera.d.ts +11 -0
  6. package/dist/camera.d.ts.map +1 -1
  7. package/dist/camera.js +31 -7
  8. package/dist/engine.d.ts +130 -2
  9. package/dist/engine.d.ts.map +1 -1
  10. package/dist/engine.js +476 -12
  11. package/dist/graph/compile.js +1 -1
  12. package/dist/graph/registry.d.ts.map +1 -1
  13. package/dist/graph/registry.js +19 -2
  14. package/dist/graph/slots.js +117 -117
  15. package/dist/index.d.ts +3 -2
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/model.d.ts +35 -0
  18. package/dist/model.d.ts.map +1 -1
  19. package/dist/model.js +170 -0
  20. package/dist/shaders/materials/common.d.ts +11 -1
  21. package/dist/shaders/materials/common.d.ts.map +1 -1
  22. package/dist/shaders/materials/common.js +571 -548
  23. package/dist/shaders/passes/cull.d.ts +1 -1
  24. package/dist/shaders/passes/cull.d.ts.map +1 -1
  25. package/dist/shaders/passes/cull.js +4 -1
  26. package/dist/shaders/passes/motion-blur.d.ts +35 -0
  27. package/dist/shaders/passes/motion-blur.d.ts.map +1 -0
  28. package/dist/shaders/passes/motion-blur.js +166 -0
  29. package/dist/shaders/passes/particles.d.ts.map +1 -1
  30. package/dist/shaders/passes/particles.js +13 -2
  31. package/dist/shaders/passes/shadow.d.ts +1 -1
  32. package/dist/shaders/passes/shadow.d.ts.map +1 -1
  33. package/package.json +1 -1
  34. package/src/camera-mount.ts +281 -0
  35. package/src/camera.ts +27 -4
  36. package/src/engine.ts +21741 -21249
  37. package/src/graph/compile.ts +1 -1
  38. package/src/graph/registry.ts +20 -3
  39. package/src/graph/slots.ts +304 -304
  40. package/src/index.ts +4 -1
  41. package/src/model.ts +193 -0
  42. package/src/shaders/materials/common.ts +706 -682
  43. package/src/shaders/passes/cull.ts +4 -1
  44. package/src/shaders/passes/motion-blur.ts +171 -0
  45. package/src/shaders/passes/particles.ts +14 -2
@@ -28,70 +28,70 @@ import { WORLD_AMBIENT_WGSL } from "../lights";
28
28
  * the shadow map then shades half the moved iris with its own unmoved copy.
29
29
  * Reads `objectLight.jelly` and `material.materialId`, which the including
30
30
  * module declares. */
31
- export const JELLY_VERTEX_WGSL = /* wgsl */ `
32
- fn _rzJellyTurn(q: vec2f, a: f32) -> vec2f {
33
- let c = cos(a);
34
- let s = sin(a);
35
- return vec2f(c * q.x - s * q.y, s * q.x + c * q.y);
36
- }
37
-
38
- /**
39
- * Where the jelly puts an iris vertex. The iris is the part of the eye the eye
40
- * bones carry, so it is moved as a whole, in bind space before skinning:
41
- * scaled about its centre (the CPU composes the blink's spring, the lid's
42
- * press and her motion's knock into one scale), turned and drifted a hair on
43
- * the spring, brought forward a hair, and rolled about the eye bone with a
44
- * closing expression — inside the white, which stays where it is. A highlight
45
- * layer (this draw's material is one of jelly[1].w's) takes the iris's move,
46
- * then its own scale, turn and tremble, before the roll. Vertices take it by their weight on the eye bones
47
- * (jelly[2].w, jelly[3].w), so nothing else on the face moves.
48
- */
49
- fn rzJellyVertex(p: vec3f, joints: vec4<u32>, nw: vec4f) -> vec3f {
50
- let j = objectLight.jelly;
51
- let ids = u32(j[1].w);
52
- let mid = u32(material.materialId);
53
- let hl = mid > 0u && (mid == (ids & 4095u) || mid == (ids >> 12u));
54
- var out = p;
55
- for (var e = 0u; e < 2u; e++) {
56
- let bone = j[2u + e].w;
57
- if (bone < 0.0) { continue; }
58
- let b = u32(bone);
59
- let w = dot(nw, select(vec4f(0.0), vec4f(1.0), joints == vec4<u32>(b)));
60
- if (w <= 0.0) { continue; }
61
- let c = j[e].xyz;
62
- // A rig that carries both eyes on one bone: each vertex follows its own side.
63
- if (j[2].w == j[3].w && e == 0u && distance(p.xy, j[1].xy) < distance(p.xy, j[0].xy)) { continue; }
64
- if (j[2].w == j[3].w && e == 1u && distance(p.xy, j[0].xy) <= distance(p.xy, j[1].xy)) { continue; }
65
- let t = j[4u + e];
66
- let m = j[6u + e];
67
- let h = j[10u + e];
68
- var q = _rzJellyTurn((p.xy - c.xy) * t.xy, t.z) + m.xy;
69
- // Forward is −Z (MMD faces −Z).
70
- var push = h.z;
71
- if (hl) {
72
- // Sliding over the iris's dome on its own, a highlight sheet a hair in
73
- // front of it would sink into it where the dome bulges more and the two
74
- // fight for depth; so it comes forward by as far as it slid — a slope of
75
- // one, steeper than the dome anywhere it draws.
76
- let before = q;
77
- q = _rzJellyTurn(q * h.xy, t.w) + m.zw;
78
- push += length(q - before);
79
- }
80
- var moved = vec3f(c.xy + q, p.z - push);
81
- let roll = j[8u + e];
82
- if (roll.w != 0.0) {
83
- let d = moved - roll.xyz;
84
- let rd = _rzJellyTurn(d.yz, roll.w);
85
- moved = roll.xyz + vec3f(d.x, rd.x, rd.y);
86
- }
87
- out = mix(p, moved, w);
88
- }
89
- return out;
90
- }
31
+ export const JELLY_VERTEX_WGSL = /* wgsl */ `
32
+ fn _rzJellyTurn(q: vec2f, a: f32) -> vec2f {
33
+ let c = cos(a);
34
+ let s = sin(a);
35
+ return vec2f(c * q.x - s * q.y, s * q.x + c * q.y);
36
+ }
37
+
38
+ /**
39
+ * Where the jelly puts an iris vertex. The iris is the part of the eye the eye
40
+ * bones carry, so it is moved as a whole, in bind space before skinning:
41
+ * scaled about its centre (the CPU composes the blink's spring, the lid's
42
+ * press and her motion's knock into one scale), turned and drifted a hair on
43
+ * the spring, brought forward a hair, and rolled about the eye bone with a
44
+ * closing expression — inside the white, which stays where it is. A highlight
45
+ * layer (this draw's material is one of jelly[1].w's) takes the iris's move,
46
+ * then its own scale, turn and tremble, before the roll. Vertices take it by their weight on the eye bones
47
+ * (jelly[2].w, jelly[3].w), so nothing else on the face moves.
48
+ */
49
+ fn rzJellyVertex(p: vec3f, joints: vec4<u32>, nw: vec4f) -> vec3f {
50
+ let j = objectLight.jelly;
51
+ let ids = u32(j[1].w);
52
+ let mid = u32(material.materialId);
53
+ let hl = mid > 0u && (mid == (ids & 4095u) || mid == (ids >> 12u));
54
+ var out = p;
55
+ for (var e = 0u; e < 2u; e++) {
56
+ let bone = j[2u + e].w;
57
+ if (bone < 0.0) { continue; }
58
+ let b = u32(bone);
59
+ let w = dot(nw, select(vec4f(0.0), vec4f(1.0), joints == vec4<u32>(b)));
60
+ if (w <= 0.0) { continue; }
61
+ let c = j[e].xyz;
62
+ // A rig that carries both eyes on one bone: each vertex follows its own side.
63
+ if (j[2].w == j[3].w && e == 0u && distance(p.xy, j[1].xy) < distance(p.xy, j[0].xy)) { continue; }
64
+ if (j[2].w == j[3].w && e == 1u && distance(p.xy, j[0].xy) <= distance(p.xy, j[1].xy)) { continue; }
65
+ let t = j[4u + e];
66
+ let m = j[6u + e];
67
+ let h = j[10u + e];
68
+ var q = _rzJellyTurn((p.xy - c.xy) * t.xy, t.z) + m.xy;
69
+ // Forward is −Z (MMD faces −Z).
70
+ var push = h.z;
71
+ if (hl) {
72
+ // Sliding over the iris's dome on its own, a highlight sheet a hair in
73
+ // front of it would sink into it where the dome bulges more and the two
74
+ // fight for depth; so it comes forward by as far as it slid — a slope of
75
+ // one, steeper than the dome anywhere it draws.
76
+ let before = q;
77
+ q = _rzJellyTurn(q * h.xy, t.w) + m.zw;
78
+ push += length(q - before);
79
+ }
80
+ var moved = vec3f(c.xy + q, p.z - push);
81
+ let roll = j[8u + e];
82
+ if (roll.w != 0.0) {
83
+ let d = moved - roll.xyz;
84
+ let rd = _rzJellyTurn(d.yz, roll.w);
85
+ moved = roll.xyz + vec3f(d.x, rd.x, rd.y);
86
+ }
87
+ out = mix(p, moved, w);
88
+ }
89
+ return out;
90
+ }
91
91
  `;
92
92
  /** A model's ObjectLight as WGSL declares it (see the layout below). One copy
93
93
  * for every pass that binds it, so their layouts cannot drift. */
94
- export const OBJECT_LIGHT_STRUCT_WGSL = "struct ObjectLight { layers: vec4u, ambient: vec4f, sh: array<vec4f, 9>, fill: vec4f, jelly: array<vec4f, 12>, bloom: vec4f, xray: array<vec4f, 4>, xrayMask: array<vec4u, 16> }";
94
+ export const OBJECT_LIGHT_STRUCT_WGSL = "struct ObjectLight { layers: vec4u, ambient: vec4f, sh: array<vec4f, 9>, fill: vec4f, jelly: array<vec4f, 12>, bloom: vec4f, xray: array<vec4f, 4>, xrayMask: array<vec4u, 16>, matLayers: array<vec4u, 128> }";
95
95
  /**
96
96
  * The see-through window (#xray): a rectangle on the frame, in pixels —
97
97
  * xray[0] is (left, top, right, bottom), xray[3].x is 1 while a window is open
@@ -100,278 +100,301 @@ export const OBJECT_LIGHT_STRUCT_WGSL = "struct ObjectLight { layers: vec4u, amb
100
100
  * the fragment's own position, so it sits where the lens is, whatever moves
101
101
  * behind it. Declared after the pass's own `objectLight` binding.
102
102
  */
103
- export const XRAY_WGSL = /* wgsl */ `
104
- fn rz_xray_inside(fp: vec4f) -> bool {
105
- if (objectLight.xray[3].x < 0.5) { return false; }
106
- let r = objectLight.xray[0];
107
- return fp.x >= r.x && fp.y >= r.y && fp.x <= r.z && fp.y <= r.w;
108
- }
109
- fn rz_xray_cut(fp: vec4f, materialId: f32) -> bool {
110
- let i = u32(materialId);
111
- if (i >= 512u) { return false; }
112
- let word = objectLight.xrayMask[i / 128u][(i / 32u) % 4u];
113
- if (((word >> (i % 32u)) & 1u) == 0u) { return false; }
114
- return rz_xray_inside(fp);
115
- }
103
+ export const XRAY_WGSL = /* wgsl */ `
104
+ fn rz_xray_inside(fp: vec4f) -> bool {
105
+ if (objectLight.xray[3].x < 0.5) { return false; }
106
+ let r = objectLight.xray[0];
107
+ return fp.x >= r.x && fp.y >= r.y && fp.x <= r.z && fp.y <= r.w;
108
+ }
109
+ fn rz_xray_cut(fp: vec4f, materialId: f32) -> bool {
110
+ let i = u32(materialId);
111
+ if (i >= 512u) { return false; }
112
+ let word = objectLight.xrayMask[i / 128u][(i / 32u) % 4u];
113
+ if (((word >> (i % 32u)) & 1u) == 0u) { return false; }
114
+ return rz_xray_inside(fp);
115
+ }
116
116
  `;
117
- export const COMMON_BINDINGS_WGSL = /* wgsl */ `
118
-
119
- struct CameraUniforms {
120
- view: mat4x4f,
121
- projection: mat4x4f,
122
- viewPos: vec3f,
123
- /** Render-target height in device pixels. */
124
- viewportHeight: f32,
125
- /** The scene clock in seconds — what the time node reads. Paused with the
126
- * transport and stepped exactly by an export, so an animated material lands
127
- * in the file where it stood on screen. (No backticks in here: this WGSL
128
- * lives in a template literal and one would end it.) */
129
- time: f32,
130
- // NOTHING AFTER THIS. A trailing vec3f aligns to 16 and pushes the struct to
131
- // 176 bytes against a 160-byte buffer, which fails validation on every
132
- // pipeline at once; ending on the f32 rounds the struct to exactly 160.
133
- };
134
-
135
- struct Light {
136
- direction: vec4f,
137
- color: vec4f,
138
- };
139
-
140
- struct LightUniforms {
141
- ambientColor: vec4f,
142
- lights: array<Light, 4>,
143
- /** Irradiance SH of the HDRI world; [0].w is the on-flag. */
144
- sh: array<vec4f, 9>,
145
- /** The scene fog (Engine.setSceneFog): haze (colour, amount), (distance,
146
- * height), then the second layer the same. Amount 0 is none. */
147
- fog: array<vec4f, 4>,
148
- /** The cast's shadow on a stage (Engine.setStageCastShadow): colour, amount;
149
- * amount 0 is off. Then the view-projection its map was drawn with. */
150
- castShadow: vec4f,
151
- castVP: mat4x4f,
152
- /** The rendering layers each directional light reaches, slot by slot — a
153
- * draw is lit by the first whose bits it shares (rzMainLight). */
154
- dirLayers: vec4u,
155
- };
156
-
157
- // Per-material uniforms. Every material binds this layout even if it ignores fields;
158
- // the engine keeps one bind group layout across all material pipelines. The PMX
159
- // classic-material fields (ambient/specular/shininess) are carried for graph nodes that
160
- // want them; most graphs read only diffuseColor + alpha.
161
- struct MaterialUniforms {
162
- diffuseColor: vec3f, // PMX diffuse rgb — the material_diffuse node reads this
163
- alpha: f32, // 0 → discard; <1 → transparent draw call
164
- ambient: vec3f, // PMX ambient rgb
165
- shininess: f32, // PMX specular power
166
- specular: vec3f, // PMX specular rgb
167
- sphereMode: f32, // 0 none · 1 multiply (sph) · 2 add (spa)
168
- // Skeleton index of the 頭 (head) bone, or -1. Lets the eye shader gate
169
- // the post-alpha-eye stencil by camera-vs-face hemisphere.
170
- headBoneIndex: f32,
171
- // The draw's identity, for the id attachment: which material, which object.
172
- // They ride HERE, in padding this struct already carried, so the buffer's
173
- // size and layout are untouched and the indirect-draw path keeps working —
174
- // the ids arrive with the same per-draw uniform the material already binds,
175
- // rather than needing a channel of their own. Zero while ids are off, and
176
- // zero is the reserved "nothing" value, so reading them then is not wrong,
177
- // just empty. f32 because the buffer is written as floats; the shader casts.
178
- materialId: f32,
179
- objectId: f32,
180
- // How much of this material is still THERE: 1 whole, 0 gone. Rides the last
181
- // of the padding this struct already carried, for the same reason the ids do
182
- // — the buffer's size and layout are untouched, so the indirect-draw path and
183
- // every existing pipeline keep working, and a material that never dissolves
184
- // pays one float it was already paying.
185
- //
186
- // A material morph rebuilds this block from its base copy, which is why the
187
- // engine writes the value into that copy as well as into the live buffer: a
188
- // face morphing while she dissolves must not come back solid for those frames.
189
- dissolve: f32,
190
- };
191
-
192
- struct VertexOutput {
193
- // @invariant: the opaque depth prepass rasterises this same skinned position
194
- // through a DIFFERENT shader module, and the colour pass then depth-tests
195
- // less-equal against what it wrote. Without invariance a backend is free to
196
- // optimise the two position computations differently, and a one-ulp
197
- // disagreement is a pixel of missing character. Invariance pins both to the
198
- // same result; it costs only that freedom.
199
- @builtin(position) @invariant position: vec4f,
200
- @location(0) normal: vec3f,
201
- @location(1) uv: vec2f,
202
- @location(2) worldPos: vec3f,
203
- // Bind-pose object-space position (the raw pre-skin vertex attribute). Procedural
204
- // textures (noise bump, sparkle, Generated-coord gradients) key off this instead of
205
- // worldPos so the pattern rides with the surface — otherwise the mesh swims through a
206
- // world-static noise field under any skinning deformation or root (センター) motion.
207
- // At rest skinMats are identity so restPos == worldPos, which is why existing noise-
208
- // scale constants stay valid without retuning.
209
- @location(3) restPos: vec3f,
210
- /** The scene fog's two amounts, computed PER VERTEX as the game does — see
211
- * Engine.setSceneFog — and interpolated across the face. */
212
- @location(5) fog: vec2f,
213
- /** The vertex colour, RGBA — white on a mesh that carries none. A PMX keeps
214
- * it in its first additional UV (what a converted game stage writes there:
215
- * a plant's occlusion rides in its alpha). The attribute node reads it. */
216
- @location(6) vcolor: vec4f,
217
- /** The second UV set — a PMX's second additional UV (xy), else the first
218
- * UV again. The uv_map node's uv2. */
219
- @location(7) uv2: vec2f,
220
- };
221
-
222
- /** One fog layer's amount at a vertex of view depth d and world height y. */
223
- fn _rzFogAmount(d: f32, y: f32, col: vec4f, p: vec4f) -> f32 {
224
- if (col.w <= 0.0) { return 0.0; }
225
- let f = clamp(d * p.x + p.y, 0.0, 1.0);
226
- let h = clamp((p.z - y) / p.w, -1.0, 1.0);
227
- return (1.0 - clamp(f - (1.0 - f) * h, 0.0, 1.0)) * col.w;
228
- }
229
-
230
- // One view-projection per shadow cascade, inner to outer — the volumes built
231
- // by shadow-cascades.ts, in the same order.
232
- struct LightVP { viewProj: array<mat4x4f, ${SHADOW_CASCADES.length}>, };
233
-
234
- @group(0) @binding(0) var<uniform> camera: CameraUniforms;
235
- @group(0) @binding(1) var<uniform> light: LightUniforms;
236
- @group(0) @binding(2) var diffuseSampler: sampler;
237
- // The sun's shadow atlas: every cascade in its own tile — see shadow-cascades.ts.
238
- @group(0) @binding(3) var shadowAtlas: texture_depth_2d;
239
- @group(0) @binding(4) var shadowSampler: sampler_comparison;
240
- @group(0) @binding(5) var<uniform> lightVP: LightVP;
241
- // The world's own sky, for a surface that REFLECTS it rather than merely being
242
- // lit by it. Equirect, in the same layout and the same linear radiance the
243
- // composite draws the dome from, and mipped — a rough surface reads a coarser
244
- // level, which is what a prefiltered environment is for. A scene with no HDRI
245
- // has the 1x1 fallback bound here; rzWorldSpecular checks the SH flag and
246
- // answers with the flat ambient instead, so nothing samples the placeholder.
247
- @group(0) @binding(8) var worldEnvTexture: texture_2d<f32>;
248
- // The cast's own shadow map for a stage's floor — see _rzCastShadow.
249
- @group(0) @binding(10) var castShadowMap: texture_depth_2d;
250
-
251
- /** The stage's reflection probe (Engine.captureReflectionProbe): where it was
252
- * captured (xyz) and its strength (w); the box it projects onto, min with the
253
- * on-flag in w, then max with the local flag in w (1: outside the box the
254
- * sky stands in). Off (boxMin.w 0) the sky stands in everywhere. */
255
- struct ProbeUniforms {
256
- center: vec4f,
257
- boxMin: vec4f,
258
- boxMax: vec4f,
259
- };
260
- // A cube, GGX-prefiltered down its mips — see rzProbeSpecular in nodes.ts.
261
- @group(0) @binding(11) var probeCube: texture_cube<f32>;
262
- @group(0) @binding(12) var<uniform> probe: ProbeUniforms;
263
-
264
117
  /**
265
- * How much of the cast stands between this point and the stage's shadow
266
- * direction, 0–1 — setStageCastShadow. A 5×5 comparison filter at 1.5 texels:
267
- * the game blurs its character shadow before laying it, and a single tap reads
268
- * as a stencil.
118
+ * The rendering layers this draw is on: its material's own where the model
119
+ * gives it some (objectLight.matLayers, by the 1-based materialId, up to 511),
120
+ * else the model's. A game lights its renderers one by one — URP hands each
121
+ * object its own few lamps — and a converted stage is one model of many such
122
+ * renderers, so the bits a light is tested against have to be able to differ
123
+ * from material to material. Zero, which every model leaves there, is "the
124
+ * model's". Declared after the pass's own `objectLight` and `material` bindings.
269
125
  */
270
- fn _rzCastShadow(wp: vec3f) -> f32 {
271
- if (light.castShadow.w <= 0.0) { return 0.0; }
272
- let c = light.castVP * vec4f(wp, 1.0);
273
- let ndc = c.xyz / c.w;
274
- if (abs(ndc.x) >= 1.0 || abs(ndc.y) >= 1.0 || ndc.z <= 0.0 || ndc.z >= 1.0) { return 0.0; }
275
- let uv = vec2f(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5);
276
- let ts = 1.5 / f32(textureDimensions(castShadowMap).x);
277
- var lit = 0.0;
278
- for (var y = -2; y <= 2; y++) {
279
- for (var x = -2; x <= 2; x++) {
280
- lit += textureSampleCompareLevel(castShadowMap, shadowSampler, uv + vec2f(f32(x), f32(y)) * ts, ndc.z - 0.001);
281
- }
282
- }
283
- return 1.0 - lit / 25.0;
284
- }
285
- @group(1) @binding(0) var<storage, read> skinMats: array<mat4x4f>;
286
- // What this object's lighting is, apart from the scene's, as the game's
287
- // pipeline gives each renderer its own:
288
- // layers.x its rendering-layer bits, which decide the lights that reach it —
289
- // a stage's daylight and the cast's key are two lights on two
290
- // layers, as the game lights them;
291
- // ambient.x 1 while it has an ambient of its own (Engine.setModelAmbient),
292
- // 0 for the world's;
293
- // sh that ambient's irradiance, folded as the world's (ibl.ts);
294
- // fill.rgb its fill (Engine.setModelFill), added after its graph times its
295
- // surface colour — zero for a model that has none.
296
- // jelly its jelly eyes (Engine.setModelJellyEyes, jelly-eyes.ts), not
297
- // lighting but per-model all the same, so it rides here:
298
- // [0] left iris centre (bind space), strength — 0 is off
299
- // [1] right iris centre, the highlight layers' materialIds
300
- // (a + b·4096, 0 none)
301
- // [2] left iris half extents, closure, eye bone (−1 none)
302
- // [3] the right's
303
- // [4] left scale x, y, twist, highlight turn (radians)
304
- // [5] the right's
305
- // [6] left drift x, y, highlight's own offset x, y (bind units)
306
- // [7] the right's
307
- // [8] left eye bone's head (the roll's pivot), roll (radians)
308
- // [9] the right's
309
- // [10] left highlight scale x, y, forward push (bind units), 0
310
- // [11] the right's
311
- // bloom.x 1 while it feeds the bloom, 0 when it is left out
312
- // (Engine.setModelBloom): the bloom mask its surfaces and
313
- // outlines write.
314
- ${OBJECT_LIGHT_STRUCT_WGSL}
315
- @group(1) @binding(1) var<uniform> objectLight: ObjectLight;
316
- ${XRAY_WGSL}
317
-
318
- ${JELLY_VERTEX_WGSL}
319
- /** The light arriving at a surface of this object facing n: its own ambient
320
- * where loaded data gave it one (a stage's probes, a character's), else the
321
- * world's. The same polynomial rzWorldAmbient evaluates. */
322
- fn rzObjectAmbient(n: vec3f) -> vec3f {
323
- if (objectLight.ambient.x < 0.5) { return rzWorldAmbient(n); }
324
- let s = objectLight.sh;
325
- let c = s[0].xyz + s[1].xyz * n.y + s[2].xyz * n.z + s[3].xyz * n.x
326
- + s[4].xyz * (n.x * n.y) + s[5].xyz * (n.y * n.z) + s[6].xyz * (3.0 * n.z * n.z - 1.0)
327
- + s[7].xyz * (n.x * n.z) + s[8].xyz * (n.x * n.x - n.y * n.y);
328
- return max(c, vec3f(0.0));
329
- }
330
-
331
- /** The directional light slot that lights this draw: the first whose layers
332
- * it shares, else the sun's. */
333
- fn rzMainLight() -> u32 {
334
- for (var k = 0u; k < 4u; k++) {
335
- if ((light.dirLayers[k] & objectLight.layers.x) != 0u) { return k; }
336
- }
337
- return 0u;
338
- }
339
- @group(2) @binding(0) var diffuseTexture: texture_2d<f32>;
340
- @group(2) @binding(1) var<uniform> material: MaterialUniforms;
341
- // Reserved for future sphere/toon graph nodes; graphs that don't read them get the
342
- // 1×1 white fallback bound here.
343
- @group(2) @binding(2) var toonTexture: texture_2d<f32>;
344
- @group(2) @binding(3) var sphereTexture: texture_2d<f32>;
345
- // Extra maps supplied by the STYLE GROUP rather than by the PMX — the lightmap /
346
- // ILM / ramp textures a Blender-authored look is built on. A PMX material carries
347
- // exactly one image, and this whole family of shading encodes shadow thresholds,
348
- // specular masks and material IDs in the channels of a second and third. Unset
349
- // slots get the 1×1 white fallback, so a graph reading one that was never
350
- // supplied sees white rather than garbage.
351
- @group(2) @binding(5) var groupTexture0: texture_2d<f32>;
352
- @group(2) @binding(6) var groupTexture1: texture_2d<f32>;
353
- @group(2) @binding(7) var groupTexture2: texture_2d<f32>;
354
- @group(2) @binding(8) var groupTexture3: texture_2d<f32>;
355
-
356
- // Four-bone blended normals can cancel to ~zero on physics-driven parts
357
- // (opposing bone rotations at 50/50 weights) — normalize(0) is 0/0 = NaN,
358
- // which poisons the whole shading stack and flashes through bloom. Fall
359
- // back to up for degenerate normals instead.
360
- // A fragment's colour as it may leave the material: every channel finite. A NaN
361
- // or Inf from any graph on any GPU is one pixel here, written as nothing; let
362
- // through, it blooms into a block and the skin blur smears it into bars. Read
363
- // off the exponent bits, which fast math cannot fold away.
364
- fn rz_finite(c: vec4f) -> vec4f {
365
- let e = bitcast<vec4u>(c) & vec4u(0x7f800000u);
366
- return select(vec4f(0.0), c, e != vec4u(0x7f800000u));
367
- }
368
-
369
- fn safe_normal(nIn: vec3f) -> vec3f {
370
- let l2 = dot(nIn, nIn);
371
- if (l2 < 1e-12) { return vec3f(0.0, 1.0, 0.0); }
372
- return nIn * inverseSqrt(l2);
373
- }
374
-
126
+ export const DRAW_LAYERS_WGSL = /* wgsl */ `
127
+ fn rzDrawLayers() -> u32 {
128
+ let i = u32(material.materialId);
129
+ if (i >= 512u) { return objectLight.layers.x; }
130
+ let own = objectLight.matLayers[i / 4u][i % 4u];
131
+ return select(objectLight.layers.x, own, own != 0u);
132
+ }
133
+ `;
134
+ export const COMMON_BINDINGS_WGSL = /* wgsl */ `
135
+
136
+ struct CameraUniforms {
137
+ view: mat4x4f,
138
+ projection: mat4x4f,
139
+ viewPos: vec3f,
140
+ /** Render-target height in device pixels. */
141
+ viewportHeight: f32,
142
+ /** The scene clock in seconds — what the time node reads. Paused with the
143
+ * transport and stepped exactly by an export, so an animated material lands
144
+ * in the file where it stood on screen. (No backticks in here: this WGSL
145
+ * lives in a template literal and one would end it.) */
146
+ time: f32,
147
+ // NOTHING AFTER THIS. A trailing vec3f aligns to 16 and pushes the struct to
148
+ // 176 bytes against a 160-byte buffer, which fails validation on every
149
+ // pipeline at once; ending on the f32 rounds the struct to exactly 160.
150
+ };
151
+
152
+ struct Light {
153
+ direction: vec4f,
154
+ color: vec4f,
155
+ };
156
+
157
+ struct LightUniforms {
158
+ ambientColor: vec4f,
159
+ lights: array<Light, 4>,
160
+ /** Irradiance SH of the HDRI world; [0].w is the on-flag. */
161
+ sh: array<vec4f, 9>,
162
+ /** The scene fog (Engine.setSceneFog): haze (colour, amount), (distance,
163
+ * height), then the second layer the same. Amount 0 is none. */
164
+ fog: array<vec4f, 4>,
165
+ /** The cast's shadow on a stage (Engine.setStageCastShadow): colour, amount;
166
+ * amount 0 is off. Then the view-projection its map was drawn with. */
167
+ castShadow: vec4f,
168
+ castVP: mat4x4f,
169
+ /** The rendering layers each directional light reaches, slot by slot — a
170
+ * draw is lit by the first whose bits it shares (rzMainLight). */
171
+ dirLayers: vec4u,
172
+ };
173
+
174
+ // Per-material uniforms. Every material binds this layout even if it ignores fields;
175
+ // the engine keeps one bind group layout across all material pipelines. The PMX
176
+ // classic-material fields (ambient/specular/shininess) are carried for graph nodes that
177
+ // want them; most graphs read only diffuseColor + alpha.
178
+ struct MaterialUniforms {
179
+ diffuseColor: vec3f, // PMX diffuse rgb — the material_diffuse node reads this
180
+ alpha: f32, // 0 → discard; <1 → transparent draw call
181
+ ambient: vec3f, // PMX ambient rgb
182
+ shininess: f32, // PMX specular power
183
+ specular: vec3f, // PMX specular rgb
184
+ sphereMode: f32, // 0 none · 1 multiply (sph) · 2 add (spa)
185
+ // Skeleton index of the 頭 (head) bone, or -1. Lets the eye shader gate
186
+ // the post-alpha-eye stencil by camera-vs-face hemisphere.
187
+ headBoneIndex: f32,
188
+ // The draw's identity, for the id attachment: which material, which object.
189
+ // They ride HERE, in padding this struct already carried, so the buffer's
190
+ // size and layout are untouched and the indirect-draw path keeps working —
191
+ // the ids arrive with the same per-draw uniform the material already binds,
192
+ // rather than needing a channel of their own. Zero while ids are off, and
193
+ // zero is the reserved "nothing" value, so reading them then is not wrong,
194
+ // just empty. f32 because the buffer is written as floats; the shader casts.
195
+ materialId: f32,
196
+ objectId: f32,
197
+ // How much of this material is still THERE: 1 whole, 0 gone. Rides the last
198
+ // of the padding this struct already carried, for the same reason the ids do
199
+ // — the buffer's size and layout are untouched, so the indirect-draw path and
200
+ // every existing pipeline keep working, and a material that never dissolves
201
+ // pays one float it was already paying.
202
+ //
203
+ // A material morph rebuilds this block from its base copy, which is why the
204
+ // engine writes the value into that copy as well as into the live buffer: a
205
+ // face morphing while she dissolves must not come back solid for those frames.
206
+ dissolve: f32,
207
+ };
208
+
209
+ struct VertexOutput {
210
+ // @invariant: the opaque depth prepass rasterises this same skinned position
211
+ // through a DIFFERENT shader module, and the colour pass then depth-tests
212
+ // less-equal against what it wrote. Without invariance a backend is free to
213
+ // optimise the two position computations differently, and a one-ulp
214
+ // disagreement is a pixel of missing character. Invariance pins both to the
215
+ // same result; it costs only that freedom.
216
+ @builtin(position) @invariant position: vec4f,
217
+ @location(0) normal: vec3f,
218
+ @location(1) uv: vec2f,
219
+ @location(2) worldPos: vec3f,
220
+ // Bind-pose object-space position (the raw pre-skin vertex attribute). Procedural
221
+ // textures (noise bump, sparkle, Generated-coord gradients) key off this instead of
222
+ // worldPos so the pattern rides with the surface — otherwise the mesh swims through a
223
+ // world-static noise field under any skinning deformation or root (センター) motion.
224
+ // At rest skinMats are identity so restPos == worldPos, which is why existing noise-
225
+ // scale constants stay valid without retuning.
226
+ @location(3) restPos: vec3f,
227
+ /** The scene fog's two amounts, computed PER VERTEX as the game does — see
228
+ * Engine.setSceneFog — and interpolated across the face. */
229
+ @location(5) fog: vec2f,
230
+ /** The vertex colour, RGBA — white on a mesh that carries none. A PMX keeps
231
+ * it in its first additional UV (what a converted game stage writes there:
232
+ * a plant's occlusion rides in its alpha). The attribute node reads it. */
233
+ @location(6) vcolor: vec4f,
234
+ /** The second UV set — a PMX's second additional UV (xy), else the first
235
+ * UV again. The uv_map node's uv2. */
236
+ @location(7) uv2: vec2f,
237
+ };
238
+
239
+ /** One fog layer's amount at a vertex of view depth d and world height y. */
240
+ fn _rzFogAmount(d: f32, y: f32, col: vec4f, p: vec4f) -> f32 {
241
+ if (col.w <= 0.0) { return 0.0; }
242
+ let f = clamp(d * p.x + p.y, 0.0, 1.0);
243
+ let h = clamp((p.z - y) / p.w, -1.0, 1.0);
244
+ return (1.0 - clamp(f - (1.0 - f) * h, 0.0, 1.0)) * col.w;
245
+ }
246
+
247
+ // One view-projection per shadow cascade, inner to outer — the volumes built
248
+ // by shadow-cascades.ts, in the same order.
249
+ struct LightVP { viewProj: array<mat4x4f, ${SHADOW_CASCADES.length}>, };
250
+
251
+ @group(0) @binding(0) var<uniform> camera: CameraUniforms;
252
+ @group(0) @binding(1) var<uniform> light: LightUniforms;
253
+ @group(0) @binding(2) var diffuseSampler: sampler;
254
+ // The sun's shadow atlas: every cascade in its own tile — see shadow-cascades.ts.
255
+ @group(0) @binding(3) var shadowAtlas: texture_depth_2d;
256
+ @group(0) @binding(4) var shadowSampler: sampler_comparison;
257
+ @group(0) @binding(5) var<uniform> lightVP: LightVP;
258
+ // The world's own sky, for a surface that REFLECTS it rather than merely being
259
+ // lit by it. Equirect, in the same layout and the same linear radiance the
260
+ // composite draws the dome from, and mipped — a rough surface reads a coarser
261
+ // level, which is what a prefiltered environment is for. A scene with no HDRI
262
+ // has the 1x1 fallback bound here; rzWorldSpecular checks the SH flag and
263
+ // answers with the flat ambient instead, so nothing samples the placeholder.
264
+ @group(0) @binding(8) var worldEnvTexture: texture_2d<f32>;
265
+ // The cast's own shadow map for a stage's floor — see _rzCastShadow.
266
+ @group(0) @binding(10) var castShadowMap: texture_depth_2d;
267
+
268
+ /** The stage's reflection probe (Engine.captureReflectionProbe): where it was
269
+ * captured (xyz) and its strength (w); the box it projects onto, min with the
270
+ * on-flag in w, then max with the local flag in w (1: outside the box the
271
+ * sky stands in). Off (boxMin.w 0) the sky stands in everywhere. */
272
+ struct ProbeUniforms {
273
+ center: vec4f,
274
+ boxMin: vec4f,
275
+ boxMax: vec4f,
276
+ };
277
+ // A cube, GGX-prefiltered down its mips — see rzProbeSpecular in nodes.ts.
278
+ @group(0) @binding(11) var probeCube: texture_cube<f32>;
279
+ @group(0) @binding(12) var<uniform> probe: ProbeUniforms;
280
+
281
+ /**
282
+ * How much of the cast stands between this point and the stage's shadow
283
+ * direction, 0–1 — setStageCastShadow. A 5×5 comparison filter at 1.5 texels:
284
+ * the game blurs its character shadow before laying it, and a single tap reads
285
+ * as a stencil.
286
+ */
287
+ fn _rzCastShadow(wp: vec3f) -> f32 {
288
+ if (light.castShadow.w <= 0.0) { return 0.0; }
289
+ let c = light.castVP * vec4f(wp, 1.0);
290
+ let ndc = c.xyz / c.w;
291
+ if (abs(ndc.x) >= 1.0 || abs(ndc.y) >= 1.0 || ndc.z <= 0.0 || ndc.z >= 1.0) { return 0.0; }
292
+ let uv = vec2f(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5);
293
+ let ts = 1.5 / f32(textureDimensions(castShadowMap).x);
294
+ var lit = 0.0;
295
+ for (var y = -2; y <= 2; y++) {
296
+ for (var x = -2; x <= 2; x++) {
297
+ lit += textureSampleCompareLevel(castShadowMap, shadowSampler, uv + vec2f(f32(x), f32(y)) * ts, ndc.z - 0.001);
298
+ }
299
+ }
300
+ return 1.0 - lit / 25.0;
301
+ }
302
+ @group(1) @binding(0) var<storage, read> skinMats: array<mat4x4f>;
303
+ // What this object's lighting is, apart from the scene's, as the game's
304
+ // pipeline gives each renderer its own:
305
+ // layers.x its rendering-layer bits, which decide the lights that reach it —
306
+ // a stage's daylight and the cast's key are two lights on two
307
+ // layers, as the game lights them;
308
+ // ambient.x 1 while it has an ambient of its own (Engine.setModelAmbient),
309
+ // 0 for the world's;
310
+ // sh that ambient's irradiance, folded as the world's (ibl.ts);
311
+ // fill.rgb its fill (Engine.setModelFill), added after its graph times its
312
+ // surface colour — zero for a model that has none.
313
+ // jelly its jelly eyes (Engine.setModelJellyEyes, jelly-eyes.ts), not
314
+ // lighting but per-model all the same, so it rides here:
315
+ // [0] left iris centre (bind space), strength — 0 is off
316
+ // [1] right iris centre, the highlight layers' materialIds
317
+ // (a + b·4096, 0 none)
318
+ // [2] left iris half extents, closure, eye bone (−1 none)
319
+ // [3] the right's
320
+ // [4] left scale x, y, twist, highlight turn (radians)
321
+ // [5] the right's
322
+ // [6] left drift x, y, highlight's own offset x, y (bind units)
323
+ // [7] the right's
324
+ // [8] left eye bone's head (the roll's pivot), roll (radians)
325
+ // [9] the right's
326
+ // [10] left highlight scale x, y, forward push (bind units), 0
327
+ // [11] the right's
328
+ // bloom.x 1 while it feeds the bloom, 0 when it is left out
329
+ // (Engine.setModelBloom): the bloom mask its surfaces and
330
+ // outlines write.
331
+ ${OBJECT_LIGHT_STRUCT_WGSL}
332
+ @group(1) @binding(1) var<uniform> objectLight: ObjectLight;
333
+ ${XRAY_WGSL}
334
+
335
+ ${JELLY_VERTEX_WGSL}
336
+ /** The light arriving at a surface of this object facing n: its own ambient
337
+ * where loaded data gave it one (a stage's probes, a character's), else the
338
+ * world's. The same polynomial rzWorldAmbient evaluates. */
339
+ fn rzObjectAmbient(n: vec3f) -> vec3f {
340
+ if (objectLight.ambient.x < 0.5) { return rzWorldAmbient(n); }
341
+ let s = objectLight.sh;
342
+ let c = s[0].xyz + s[1].xyz * n.y + s[2].xyz * n.z + s[3].xyz * n.x
343
+ + s[4].xyz * (n.x * n.y) + s[5].xyz * (n.y * n.z) + s[6].xyz * (3.0 * n.z * n.z - 1.0)
344
+ + s[7].xyz * (n.x * n.z) + s[8].xyz * (n.x * n.x - n.y * n.y);
345
+ return max(c, vec3f(0.0));
346
+ }
347
+
348
+ /** The directional light slot that lights this draw: a light kept to layers
349
+ * of its own that this draw is on (the cast's key, beside a stage's sun),
350
+ * else the first whose layers it shares, else the sun's. A light that
351
+ * reaches every layer stands in for nobody. */
352
+ fn rzMainLight() -> u32 {
353
+ let mine = rzDrawLayers();
354
+ for (var k = 1u; k < 4u; k++) {
355
+ if (light.dirLayers[k] != 0xffffffffu && (light.dirLayers[k] & mine) != 0u) { return k; }
356
+ }
357
+ for (var k = 0u; k < 4u; k++) {
358
+ if ((light.dirLayers[k] & mine) != 0u) { return k; }
359
+ }
360
+ return 0u;
361
+ }
362
+ @group(2) @binding(0) var diffuseTexture: texture_2d<f32>;
363
+ @group(2) @binding(1) var<uniform> material: MaterialUniforms;
364
+ // Reserved for future sphere/toon graph nodes; graphs that don't read them get the
365
+ // 1×1 white fallback bound here.
366
+ @group(2) @binding(2) var toonTexture: texture_2d<f32>;
367
+ @group(2) @binding(3) var sphereTexture: texture_2d<f32>;
368
+ // Extra maps supplied by the STYLE GROUP rather than by the PMX — the lightmap /
369
+ // ILM / ramp textures a Blender-authored look is built on. A PMX material carries
370
+ // exactly one image, and this whole family of shading encodes shadow thresholds,
371
+ // specular masks and material IDs in the channels of a second and third. Unset
372
+ // slots get the 1×1 white fallback, so a graph reading one that was never
373
+ // supplied sees white rather than garbage.
374
+ @group(2) @binding(5) var groupTexture0: texture_2d<f32>;
375
+ @group(2) @binding(6) var groupTexture1: texture_2d<f32>;
376
+ @group(2) @binding(7) var groupTexture2: texture_2d<f32>;
377
+ @group(2) @binding(8) var groupTexture3: texture_2d<f32>;
378
+
379
+ // Four-bone blended normals can cancel to ~zero on physics-driven parts
380
+ // (opposing bone rotations at 50/50 weights) — normalize(0) is 0/0 = NaN,
381
+ // which poisons the whole shading stack and flashes through bloom. Fall
382
+ // back to up for degenerate normals instead.
383
+ // A fragment's colour as it may leave the material: every channel finite. A NaN
384
+ // or Inf from any graph on any GPU is one pixel here, written as nothing; let
385
+ // through, it blooms into a block and the skin blur smears it into bars. Read
386
+ // off the exponent bits, which fast math cannot fold away.
387
+ fn rz_finite(c: vec4f) -> vec4f {
388
+ let e = bitcast<vec4u>(c) & vec4u(0x7f800000u);
389
+ return select(vec4f(0.0), c, e != vec4u(0x7f800000u));
390
+ }
391
+
392
+ fn safe_normal(nIn: vec3f) -> vec3f {
393
+ let l2 = dot(nIn, nIn);
394
+ if (l2 < 1e-12) { return vec3f(0.0, 1.0, 0.0); }
395
+ return nIn * inverseSqrt(l2);
396
+ }
397
+
375
398
  `;
376
399
  // ─── Shadow sampler (3×3 PCF, cascade-selected) ─────────────────────
377
400
  // Normal-bias 0.08, depth-bias 0.001 NDC; the lookup is sunShadowWgsl in
@@ -382,117 +405,117 @@ fn safe_normal(nIn: vec3f) -> vec3f {
382
405
  // merely a default: past every cascade there is no occlusion information, and
383
406
  // comparing against unrelated depths would silently shadow any stage deeper
384
407
  // than the boxes.
385
- const SAMPLE_SHADOW_WGSL = /* wgsl */ `
386
- ${sunShadowWgsl("_rzSun", "shadowAtlas", "shadowSampler", "lightVP.viewProj")}
387
-
388
- /** The sun's cast shadow alone, without sampleShadow's facing test: what a
389
- * character's ramp is min'd with (its own N·L carries the terminator). */
390
- fn rzSunOcclusion(worldPos: vec3f, n: vec3f) -> f32 {
391
- let castAmt = light.lights[0].direction.w;
392
- if (castAmt <= 0.0) { return 1.0; }
393
- let a = _rzSunLocate(worldPos + n * 0.08);
394
- if (a.w < 0.0) { return 1.0; }
395
- return mix(1.0, _rzSunTaps(a), castAmt);
396
- }
397
-
398
- fn sampleShadow(worldPos: vec3f, n: vec3f) -> f32 {
399
- // THE SCENE'S ONE SHADOW SWITCH, and it lives on the sun because the sun is
400
- // the only thing that casts. Lit is the answer when it is off: returning 0
401
- // would be "fully shadowed", the opposite of what a disabled shadow means.
402
- let castAmt = light.lights[0].direction.w;
403
- if (castAmt <= 0.0) { return 1.0; }
404
- // A surface turned from the sun is in its own shade — when the sun is what
405
- // keys it. Under a key of its own layer the atlas is only the occluders'
406
- // shadow, and the key's N·L decides its terminator.
407
- if (rzMainLight() == 0u && dot(n, -light.lights[0].direction.xyz) <= 0.0) { return 0.0; }
408
- let a = _rzSunLocate(worldPos + n * 0.08);
409
- if (a.w < 0.0) { return 1.0; }
410
- return mix(1.0, _rzSunTaps(a), castAmt);
411
- }
412
-
413
- /**
414
- * The cast's shadow on a stage surface where the stage ROOFS the cast from the
415
- * sun, 0–1 — setStageCastShadow on a graph-drawn stage (a GLB's). Under open
416
- * sky the sun's own map already lays the cast's shadow, and laying this one too
417
- * doubled it; under a ceiling the sun reaches neither the floor nor her, the
418
- * lamps cast nothing, and she stood on the floor with no shadow at all. So
419
- * per pixel: find the point of the cast that throws this shadow (the cast
420
- * map's nearest depth, walked back toward the light along the map's z row),
421
- * step off her toward the light, and ask the sun's map whether it reaches
422
- * there. Lit: the sun shadow has it, answer 0. Shadowed: this is the only
423
- * shadow she gets. Zero on everything that is not a stage (objectLight
424
- * layers.y).
425
- */
426
- fn rzRoofedCastShadow(wp: vec3f) -> f32 {
427
- if (light.castShadow.w <= 0.0 || objectLight.layers.y == 0u) { return 0.0; }
428
- let cover = _rzCastShadow(wp);
429
- if (cover <= 0.0) { return 0.0; }
430
- let ndc = (light.castVP * vec4f(wp, 1.0)).xyz;
431
- let size = vec2i(textureDimensions(castShadowMap));
432
- let px = vec2i(vec2f(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5) * vec2f(size));
433
- // The nearest of her over the filter's footprint: a penumbra texel's own
434
- // depth may be the cleared 1.
435
- var occ = 1.0;
436
- for (var y = -2; y <= 2; y += 2) {
437
- for (var x = -2; x <= 2; x += 2) {
438
- occ = min(occ, textureLoad(castShadowMap, clamp(px + vec2i(x, y), vec2i(0), size - 1), 0));
439
- }
440
- }
441
- if (occ >= ndc.z) { return 0.0; }
442
- // Orthographic: depth grows away from the light at |g| per unit.
443
- let g = vec3f(light.castVP[0].z, light.castVP[1].z, light.castVP[2].z);
444
- let k = length(g);
445
- let q = wp - (g / k) * ((ndc.z - occ) / k + 0.5);
446
- return cover * (1.0 - rzSunOcclusion(q, vec3f(0.0)));
447
- }
448
-
408
+ const SAMPLE_SHADOW_WGSL = /* wgsl */ `
409
+ ${sunShadowWgsl("_rzSun", "shadowAtlas", "shadowSampler", "lightVP.viewProj")}
410
+
411
+ /** The sun's cast shadow alone, without sampleShadow's facing test: what a
412
+ * character's ramp is min'd with (its own N·L carries the terminator). */
413
+ fn rzSunOcclusion(worldPos: vec3f, n: vec3f) -> f32 {
414
+ let castAmt = light.lights[0].direction.w;
415
+ if (castAmt <= 0.0) { return 1.0; }
416
+ let a = _rzSunLocate(worldPos + n * 0.08);
417
+ if (a.w < 0.0) { return 1.0; }
418
+ return mix(1.0, _rzSunTaps(a), castAmt);
419
+ }
420
+
421
+ fn sampleShadow(worldPos: vec3f, n: vec3f) -> f32 {
422
+ // THE SCENE'S ONE SHADOW SWITCH, and it lives on the sun because the sun is
423
+ // the only thing that casts. Lit is the answer when it is off: returning 0
424
+ // would be "fully shadowed", the opposite of what a disabled shadow means.
425
+ let castAmt = light.lights[0].direction.w;
426
+ if (castAmt <= 0.0) { return 1.0; }
427
+ // A surface turned from the sun is in its own shade — when the sun is what
428
+ // keys it. Under a key of its own layer the atlas is only the occluders'
429
+ // shadow, and the key's N·L decides its terminator.
430
+ if (rzMainLight() == 0u && dot(n, -light.lights[0].direction.xyz) <= 0.0) { return 0.0; }
431
+ let a = _rzSunLocate(worldPos + n * 0.08);
432
+ if (a.w < 0.0) { return 1.0; }
433
+ return mix(1.0, _rzSunTaps(a), castAmt);
434
+ }
435
+
436
+ /**
437
+ * The cast's shadow on a stage surface where the stage ROOFS the cast from the
438
+ * sun, 0–1 — setStageCastShadow on a graph-drawn stage (a GLB's). Under open
439
+ * sky the sun's own map already lays the cast's shadow, and laying this one too
440
+ * doubled it; under a ceiling the sun reaches neither the floor nor her, the
441
+ * lamps cast nothing, and she stood on the floor with no shadow at all. So
442
+ * per pixel: find the point of the cast that throws this shadow (the cast
443
+ * map's nearest depth, walked back toward the light along the map's z row),
444
+ * step off her toward the light, and ask the sun's map whether it reaches
445
+ * there. Lit: the sun shadow has it, answer 0. Shadowed: this is the only
446
+ * shadow she gets. Zero on everything that is not a stage (objectLight
447
+ * layers.y).
448
+ */
449
+ fn rzRoofedCastShadow(wp: vec3f) -> f32 {
450
+ if (light.castShadow.w <= 0.0 || objectLight.layers.y == 0u) { return 0.0; }
451
+ let cover = _rzCastShadow(wp);
452
+ if (cover <= 0.0) { return 0.0; }
453
+ let ndc = (light.castVP * vec4f(wp, 1.0)).xyz;
454
+ let size = vec2i(textureDimensions(castShadowMap));
455
+ let px = vec2i(vec2f(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5) * vec2f(size));
456
+ // The nearest of her over the filter's footprint: a penumbra texel's own
457
+ // depth may be the cleared 1.
458
+ var occ = 1.0;
459
+ for (var y = -2; y <= 2; y += 2) {
460
+ for (var x = -2; x <= 2; x += 2) {
461
+ occ = min(occ, textureLoad(castShadowMap, clamp(px + vec2i(x, y), vec2i(0), size - 1), 0));
462
+ }
463
+ }
464
+ if (occ >= ndc.z) { return 0.0; }
465
+ // Orthographic: depth grows away from the light at |g| per unit.
466
+ let g = vec3f(light.castVP[0].z, light.castVP[1].z, light.castVP[2].z);
467
+ let k = length(g);
468
+ let q = wp - (g / k) * ((ndc.z - occ) / k + 0.5);
469
+ return cover * (1.0 - rzSunOcclusion(q, vec3f(0.0)));
470
+ }
471
+
449
472
  `;
450
473
  // ─── Skinning vertex shader ─────────────────────────────────────────
451
474
  // Four-bone linear blend skinning. Renormalizes weights when they don't sum to 1
452
475
  // (PMX models occasionally ship with unnormalized weights on extras like hair tips).
453
476
  // VS normalize on the outgoing normal is skipped — interpolation denormalizes it
454
477
  // anyway and every fragment shader does `normalize(input.normal)` as its first line.
455
- const COMMON_VS_WGSL = /* wgsl */ `
456
-
457
- @vertex fn vs(
458
- @location(0) position: vec3f,
459
- @location(1) normal: vec3f,
460
- @location(2) uv: vec2f,
461
- @location(3) joints0: vec4<u32>,
462
- @location(4) weights0: vec4<f32>,
463
- // The extra stream (Engine: the model's attribute buffer, slot 4).
464
- @location(5) vcolor: vec4<f32>,
465
- @location(6) uv2: vec2<f32>
466
- ) -> VertexOutput {
467
- var output: VertexOutput;
468
- output.vcolor = vcolor;
469
- output.uv2 = uv2;
470
- let weightSum = weights0.x + weights0.y + weights0.z + weights0.w;
471
- let invWeightSum = select(1.0, 1.0 / weightSum, weightSum > 0.0001);
472
- let nw = select(vec4f(1.0, 0.0, 0.0, 0.0), weights0 * invWeightSum, weightSum > 0.0001);
473
- var pos4 = vec4f(position, 1.0);
474
- if (objectLight.jelly[0].w > 0.0) { pos4 = vec4f(rzJellyVertex(position, joints0, nw), 1.0); }
475
- var skinnedPos = vec4f(0.0);
476
- var skinnedNrm = vec3f(0.0);
477
- for (var i = 0u; i < 4u; i++) {
478
- let m = skinMats[joints0[i]];
479
- let w = nw[i];
480
- skinnedPos += (m * pos4) * w;
481
- skinnedNrm += (mat3x3f(m[0].xyz, m[1].xyz, m[2].xyz) * normal) * w;
482
- }
483
- output.position = camera.projection * camera.view * vec4f(skinnedPos.xyz, 1.0);
484
- output.normal = skinnedNrm;
485
- output.uv = uv;
486
- output.worldPos = skinnedPos.xyz;
487
- output.restPos = position;
488
- let viewZ = (camera.view * vec4f(skinnedPos.xyz, 1.0)).z;
489
- output.fog = vec2f(
490
- _rzFogAmount(viewZ, skinnedPos.y, light.fog[0], light.fog[1]),
491
- _rzFogAmount(viewZ, skinnedPos.y, light.fog[2], light.fog[3]),
492
- );
493
- return output;
494
- }
495
-
478
+ const COMMON_VS_WGSL = /* wgsl */ `
479
+
480
+ @vertex fn vs(
481
+ @location(0) position: vec3f,
482
+ @location(1) normal: vec3f,
483
+ @location(2) uv: vec2f,
484
+ @location(3) joints0: vec4<u32>,
485
+ @location(4) weights0: vec4<f32>,
486
+ // The extra stream (Engine: the model's attribute buffer, slot 4).
487
+ @location(5) vcolor: vec4<f32>,
488
+ @location(6) uv2: vec2<f32>
489
+ ) -> VertexOutput {
490
+ var output: VertexOutput;
491
+ output.vcolor = vcolor;
492
+ output.uv2 = uv2;
493
+ let weightSum = weights0.x + weights0.y + weights0.z + weights0.w;
494
+ let invWeightSum = select(1.0, 1.0 / weightSum, weightSum > 0.0001);
495
+ let nw = select(vec4f(1.0, 0.0, 0.0, 0.0), weights0 * invWeightSum, weightSum > 0.0001);
496
+ var pos4 = vec4f(position, 1.0);
497
+ if (objectLight.jelly[0].w > 0.0) { pos4 = vec4f(rzJellyVertex(position, joints0, nw), 1.0); }
498
+ var skinnedPos = vec4f(0.0);
499
+ var skinnedNrm = vec3f(0.0);
500
+ for (var i = 0u; i < 4u; i++) {
501
+ let m = skinMats[joints0[i]];
502
+ let w = nw[i];
503
+ skinnedPos += (m * pos4) * w;
504
+ skinnedNrm += (mat3x3f(m[0].xyz, m[1].xyz, m[2].xyz) * normal) * w;
505
+ }
506
+ output.position = camera.projection * camera.view * vec4f(skinnedPos.xyz, 1.0);
507
+ output.normal = skinnedNrm;
508
+ output.uv = uv;
509
+ output.worldPos = skinnedPos.xyz;
510
+ output.restPos = position;
511
+ let viewZ = (camera.view * vec4f(skinnedPos.xyz, 1.0)).z;
512
+ output.fog = vec2f(
513
+ _rzFogAmount(viewZ, skinnedPos.y, light.fog[0], light.fog[1]),
514
+ _rzFogAmount(viewZ, skinnedPos.y, light.fog[2], light.fog[3]),
515
+ );
516
+ return output;
517
+ }
518
+
496
519
  `;
497
520
  // ─── FS output struct ───────────────────────────────────────────────
498
521
  // Location 0: final radiance+alpha (blended into rg11b10ufloat; the HDR target
@@ -544,122 +567,122 @@ export function commonFsOutWgsl() {
544
567
  * clumps of a few millimetres rather than as single-pixel snow, which at any
545
568
  * distance is just a fade.
546
569
  */
547
- export const DISSOLVE_WGSL = /* wgsl */ `
548
- /** Clump size, in object-space units — MMD's are roughly centimetres.
549
- *
550
- * Raised from 0.42: at that size the pieces are near enough to speckle that a
551
- * departure reads as a fade rather than as a body coming apart, which is the
552
- * thing the clumping exists to avoid. Hand-sized pieces are visible ones. */
553
- const RZ_DISSOLVE_GRAIN: f32 = 1.2;
554
- /** How much the clumps pull a fragment off its own grit value — the whole of
555
- * the LOOK, and none of the rate. See rz_dissolve_threshold. */
556
- const RZ_DISSOLVE_CLUMP: f32 = 0.6;
557
- /** Grit cell, as a fraction of a clump. See rz_dissolve_threshold: this is what
558
- * keeps a material SMALLER than a clump from having one threshold for all of
559
- * it, and it has to be smaller than the SMALLEST material a model carries —
560
- * an eye highlight, a button, a buckle — not merely small. Two and a half
561
- * millimetres on a normal model, which is under all of them. */
562
- const RZ_DISSOLVE_GRIT: f32 = 0.021;
563
- /** How wide the glowing front is, in threshold units. Thin: the front is a
564
- * rim, and a wide one lights whole limbs at once. */
565
- const RZ_DISSOLVE_EDGE: f32 = 0.11;
566
- /** What the front burns with. Emission, added after lighting and after the
567
- * graph — a colour that ramps or takes a shadow reads as paint, not as heat.
568
- * Above 1 on purpose: it is meant to reach the bloom pyramid. Blue-violet,
569
- * the same light the motes leaving her are drawn and lit with. */
570
- const RZ_BURN_COLOR: vec3f = vec3f(0.45, 0.62, 2.40);
571
-
572
- fn rz_dissolve_hash(p: vec3f) -> f32 {
573
- // INTEGER, for exactly the reason _hash33 in nodes.ts is, and its comment
574
- // says it: above 24 bits an f32 loses the low ones. The float hash this
575
- // replaces multiplied three terms into the hundreds of millions and took
576
- // fract() of the product — which past 2^24 is not noise, it is a quantised
577
- // staircase, and wherever that staircase landed on zero the threshold was
578
- // zero. A surface whose threshold is zero never crosses it: it stays behind
579
- // while the rest of her leaves, and it sits inside the burning front the
580
- // whole time she is gone. Those were the white pieces that would not go.
581
- //
582
- // Floored first, unlike _hash33: vec3i() truncates toward zero, so -0.5 and
583
- // +0.5 are the same cell, and half this model is at negative x.
584
- var h = vec3u(vec3i(floor(p)) + vec3i(32768));
585
- h = h * vec3u(1664525u, 1013904223u, 2654435761u);
586
- h = (h.yzx ^ h) * vec3u(2246822519u, 3266489917u, 668265263u);
587
- h = h ^ (h >> vec3u(16u));
588
- return f32((h.x ^ h.y ^ h.z) & 16777215u) * (1.0 / 16777216.0);
589
- }
590
-
591
- /** Value noise over that hash — smooth within a flake, uncorrelated between. */
592
- fn rz_dissolve_field(p: vec3f) -> f32 {
593
- let i = floor(p);
594
- let f = fract(p);
595
- let u = f * f * (3.0 - 2.0 * f);
596
- let c000 = rz_dissolve_hash(i);
597
- let c100 = rz_dissolve_hash(i + vec3f(1.0, 0.0, 0.0));
598
- let c010 = rz_dissolve_hash(i + vec3f(0.0, 1.0, 0.0));
599
- let c110 = rz_dissolve_hash(i + vec3f(1.0, 1.0, 0.0));
600
- let c001 = rz_dissolve_hash(i + vec3f(0.0, 0.0, 1.0));
601
- let c101 = rz_dissolve_hash(i + vec3f(1.0, 0.0, 1.0));
602
- let c011 = rz_dissolve_hash(i + vec3f(0.0, 1.0, 1.0));
603
- let c111 = rz_dissolve_hash(i + vec3f(1.0, 1.0, 1.0));
604
- let x00 = mix(c000, c100, u.x);
605
- let x10 = mix(c010, c110, u.x);
606
- let x01 = mix(c001, c101, u.x);
607
- let x11 = mix(c011, c111, u.x);
608
- return mix(mix(x00, x10, u.y), mix(x01, x11, u.y), u.z);
609
- }
610
-
611
- /**
612
- * The threshold this fragment is measured against.
613
- *
614
- * NOISE ALONE, so the whole body comes apart at once — a hand, a shoulder and
615
- * an ankle all thinning together rather than a line travelling up her. It was
616
- * tilted by height at first, on the argument that a sweep reads as something
617
- * happening TO her; what it actually reads as is a wipe, and a wipe has a
618
- * direction, an edge and a speed the rest of the effect knows nothing about.
619
- * Everywhere at once is also the honest match for what leaves: the motes are
620
- * shed from every limb in the same breath.
621
- *
622
- * TWO SCALES. Clumps alone meant every fragment of a material SMALLER than one
623
- * cell shared a single threshold: an eye highlight, a brow, a button, a hair
624
- * clip. All of it sat inside the glowing front at once, so the piece flashed
625
- * white as a whole and then popped — the two things a disintegration must never
626
- * do. The grit is a per-cell hash at a fraction of the clump, so a part a few
627
- * millimetres across still comes apart in pieces.
628
- *
629
- * THE GRIT IS THE BASE, though, and the clumps only push a fragment off it.
630
- * That ordering is what makes the dissolve smooth, and it is not obvious: the
631
- * two used to be WEIGHTED AND ADDED, and a sum is not uniformly distributed
632
- * however uniform each half is. It piles up in the middle, so most of the
633
- * surface had a threshold near a half — all of it went as the dissolve swept
634
- * through the middle, and what remained was the thin tail near zero. That tail
635
- * was the second stage everyone could see: a body that mostly vanished, then a
636
- * scatter of glowing scraps, then nothing.
637
- *
638
- * WRAPPED, not added. Offsetting a uniform value and taking fract() leaves it
639
- * EXACTLY uniform, where scaling a sum back into range only flattens the middle
640
- * — measured over four hundred thousand samples, the sum removed 12% of her per
641
- * step at the halfway mark and 0.1% at each end (a 110x swing), the scaled sum
642
- * still swung 89x, and the wrap is flat: 5.0% per step from the first flake to
643
- * the last, a ratio of 1.0.
644
- *
645
- * That flatness IS the smoothness. An uneven rate is what produced the two
646
- * stages you could see — a body that mostly vanished at once, then a scatter of
647
- * scraps that took as long again to follow.
648
- *
649
- * The clumping survives the wrap: neighbouring fragments share a clump value,
650
- * so the offset moves them together. What wraps past 1 comes back at 0 and goes
651
- * at the other end instead, which costs a little speckle in a region and buys
652
- * an even rate everywhere.
653
- */
654
- fn rz_dissolve_threshold(restPos: vec3f) -> f32 {
655
- let grit = rz_dissolve_hash(floor(restPos / (RZ_DISSOLVE_GRAIN * RZ_DISSOLVE_GRIT)));
656
- let clump = rz_dissolve_field(restPos / RZ_DISSOLVE_GRAIN) - 0.5;
657
- return fract(grit + clump * RZ_DISSOLVE_CLUMP);
658
- }
570
+ export const DISSOLVE_WGSL = /* wgsl */ `
571
+ /** Clump size, in object-space units — MMD's are roughly centimetres.
572
+ *
573
+ * Raised from 0.42: at that size the pieces are near enough to speckle that a
574
+ * departure reads as a fade rather than as a body coming apart, which is the
575
+ * thing the clumping exists to avoid. Hand-sized pieces are visible ones. */
576
+ const RZ_DISSOLVE_GRAIN: f32 = 1.2;
577
+ /** How much the clumps pull a fragment off its own grit value — the whole of
578
+ * the LOOK, and none of the rate. See rz_dissolve_threshold. */
579
+ const RZ_DISSOLVE_CLUMP: f32 = 0.6;
580
+ /** Grit cell, as a fraction of a clump. See rz_dissolve_threshold: this is what
581
+ * keeps a material SMALLER than a clump from having one threshold for all of
582
+ * it, and it has to be smaller than the SMALLEST material a model carries —
583
+ * an eye highlight, a button, a buckle — not merely small. Two and a half
584
+ * millimetres on a normal model, which is under all of them. */
585
+ const RZ_DISSOLVE_GRIT: f32 = 0.021;
586
+ /** How wide the glowing front is, in threshold units. Thin: the front is a
587
+ * rim, and a wide one lights whole limbs at once. */
588
+ const RZ_DISSOLVE_EDGE: f32 = 0.11;
589
+ /** What the front burns with. Emission, added after lighting and after the
590
+ * graph — a colour that ramps or takes a shadow reads as paint, not as heat.
591
+ * Above 1 on purpose: it is meant to reach the bloom pyramid. Blue-violet,
592
+ * the same light the motes leaving her are drawn and lit with. */
593
+ const RZ_BURN_COLOR: vec3f = vec3f(0.45, 0.62, 2.40);
594
+
595
+ fn rz_dissolve_hash(p: vec3f) -> f32 {
596
+ // INTEGER, for exactly the reason _hash33 in nodes.ts is, and its comment
597
+ // says it: above 24 bits an f32 loses the low ones. The float hash this
598
+ // replaces multiplied three terms into the hundreds of millions and took
599
+ // fract() of the product — which past 2^24 is not noise, it is a quantised
600
+ // staircase, and wherever that staircase landed on zero the threshold was
601
+ // zero. A surface whose threshold is zero never crosses it: it stays behind
602
+ // while the rest of her leaves, and it sits inside the burning front the
603
+ // whole time she is gone. Those were the white pieces that would not go.
604
+ //
605
+ // Floored first, unlike _hash33: vec3i() truncates toward zero, so -0.5 and
606
+ // +0.5 are the same cell, and half this model is at negative x.
607
+ var h = vec3u(vec3i(floor(p)) + vec3i(32768));
608
+ h = h * vec3u(1664525u, 1013904223u, 2654435761u);
609
+ h = (h.yzx ^ h) * vec3u(2246822519u, 3266489917u, 668265263u);
610
+ h = h ^ (h >> vec3u(16u));
611
+ return f32((h.x ^ h.y ^ h.z) & 16777215u) * (1.0 / 16777216.0);
612
+ }
613
+
614
+ /** Value noise over that hash — smooth within a flake, uncorrelated between. */
615
+ fn rz_dissolve_field(p: vec3f) -> f32 {
616
+ let i = floor(p);
617
+ let f = fract(p);
618
+ let u = f * f * (3.0 - 2.0 * f);
619
+ let c000 = rz_dissolve_hash(i);
620
+ let c100 = rz_dissolve_hash(i + vec3f(1.0, 0.0, 0.0));
621
+ let c010 = rz_dissolve_hash(i + vec3f(0.0, 1.0, 0.0));
622
+ let c110 = rz_dissolve_hash(i + vec3f(1.0, 1.0, 0.0));
623
+ let c001 = rz_dissolve_hash(i + vec3f(0.0, 0.0, 1.0));
624
+ let c101 = rz_dissolve_hash(i + vec3f(1.0, 0.0, 1.0));
625
+ let c011 = rz_dissolve_hash(i + vec3f(0.0, 1.0, 1.0));
626
+ let c111 = rz_dissolve_hash(i + vec3f(1.0, 1.0, 1.0));
627
+ let x00 = mix(c000, c100, u.x);
628
+ let x10 = mix(c010, c110, u.x);
629
+ let x01 = mix(c001, c101, u.x);
630
+ let x11 = mix(c011, c111, u.x);
631
+ return mix(mix(x00, x10, u.y), mix(x01, x11, u.y), u.z);
632
+ }
633
+
634
+ /**
635
+ * The threshold this fragment is measured against.
636
+ *
637
+ * NOISE ALONE, so the whole body comes apart at once — a hand, a shoulder and
638
+ * an ankle all thinning together rather than a line travelling up her. It was
639
+ * tilted by height at first, on the argument that a sweep reads as something
640
+ * happening TO her; what it actually reads as is a wipe, and a wipe has a
641
+ * direction, an edge and a speed the rest of the effect knows nothing about.
642
+ * Everywhere at once is also the honest match for what leaves: the motes are
643
+ * shed from every limb in the same breath.
644
+ *
645
+ * TWO SCALES. Clumps alone meant every fragment of a material SMALLER than one
646
+ * cell shared a single threshold: an eye highlight, a brow, a button, a hair
647
+ * clip. All of it sat inside the glowing front at once, so the piece flashed
648
+ * white as a whole and then popped — the two things a disintegration must never
649
+ * do. The grit is a per-cell hash at a fraction of the clump, so a part a few
650
+ * millimetres across still comes apart in pieces.
651
+ *
652
+ * THE GRIT IS THE BASE, though, and the clumps only push a fragment off it.
653
+ * That ordering is what makes the dissolve smooth, and it is not obvious: the
654
+ * two used to be WEIGHTED AND ADDED, and a sum is not uniformly distributed
655
+ * however uniform each half is. It piles up in the middle, so most of the
656
+ * surface had a threshold near a half — all of it went as the dissolve swept
657
+ * through the middle, and what remained was the thin tail near zero. That tail
658
+ * was the second stage everyone could see: a body that mostly vanished, then a
659
+ * scatter of glowing scraps, then nothing.
660
+ *
661
+ * WRAPPED, not added. Offsetting a uniform value and taking fract() leaves it
662
+ * EXACTLY uniform, where scaling a sum back into range only flattens the middle
663
+ * — measured over four hundred thousand samples, the sum removed 12% of her per
664
+ * step at the halfway mark and 0.1% at each end (a 110x swing), the scaled sum
665
+ * still swung 89x, and the wrap is flat: 5.0% per step from the first flake to
666
+ * the last, a ratio of 1.0.
667
+ *
668
+ * That flatness IS the smoothness. An uneven rate is what produced the two
669
+ * stages you could see — a body that mostly vanished at once, then a scatter of
670
+ * scraps that took as long again to follow.
671
+ *
672
+ * The clumping survives the wrap: neighbouring fragments share a clump value,
673
+ * so the offset moves them together. What wraps past 1 comes back at 0 and goes
674
+ * at the other end instead, which costs a little speckle in a region and buys
675
+ * an even rate everywhere.
676
+ */
677
+ fn rz_dissolve_threshold(restPos: vec3f) -> f32 {
678
+ let grit = rz_dissolve_hash(floor(restPos / (RZ_DISSOLVE_GRAIN * RZ_DISSOLVE_GRIT)));
679
+ let clump = rz_dissolve_field(restPos / RZ_DISSOLVE_GRAIN) - 0.5;
680
+ return fract(grit + clump * RZ_DISSOLVE_CLUMP);
681
+ }
659
682
  `;
660
683
  // ─── Convenience: full shared prelude ───────────────────────────────
661
684
  // Material files compose this as `${NODES_WGSL}${COMMON_MATERIAL_PRELUDE_WGSL}` to
662
685
  // pull in everything structural. Each material then adds its own constants + fs().
663
686
  // The FSOut struct is NOT in here any more — see commonFsOutWgsl above. Every
664
687
  // consumer of this constant appends it immediately, which is where it was.
665
- export const COMMON_MATERIAL_PRELUDE_WGSL = COMMON_BINDINGS_WGSL + WORLD_AMBIENT_WGSL + lightsApi(0, 6, "objectLight.layers.x", { binding: 9, sampler: "diffuseSampler" }) + SAMPLE_SHADOW_WGSL + COMMON_VS_WGSL;
688
+ export const COMMON_MATERIAL_PRELUDE_WGSL = COMMON_BINDINGS_WGSL + DRAW_LAYERS_WGSL + WORLD_AMBIENT_WGSL + lightsApi(0, 6, "rzDrawLayers()", { binding: 9, sampler: "diffuseSampler" }) + SAMPLE_SHADOW_WGSL + COMMON_VS_WGSL;