reze-engine 0.69.8 → 0.69.9

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.
@@ -1,304 +1,304 @@
1
- // fs() shell assembly. The graph computes only `final_color`; everything around it —
2
- // texture sample, alpha discard, lighting context, built-in gates, and the FSOut/mask
3
- // write — is composed here from two orthogonal, engine-owned axes:
4
- // RenderClass ("auto" | "eye" | "hair") — stencil/cull/draw-order + eye rear-gate +
5
- // hair over-eyes alpha. See render-class.ts.
6
- // AlphaMode ("opaque" | "hashed") — standard threshold discard vs Wyman hashed.
7
- // A style group supplies both; this file turns them into the WGSL shell around fsBody.
8
- // See docs/style-groups-spec.md §5, §7.
9
-
10
- import { NODES_WGSL } from "../shaders/materials/nodes"
11
- import { COMMON_MATERIAL_PRELUDE_WGSL, DISSOLVE_WGSL, commonFsOutWgsl } from "../shaders/materials/common"
12
- import { sceneIdWriteWgsl } from "../shaders/passes/scene-contract"
13
- import type { AlphaMode, RenderClass, StyleBlend } from "./render-class"
14
-
15
- // ── Module-scope declarations ──
16
- // hair: the over-eyes pipeline-override constant (a second pipeline is compiled with
17
- // IS_OVER_EYES=1). hashed: the Wyman & McGuire object-space hashed-alpha helpers.
18
- const HAIR_OVER_EYES_DECL = `override IS_OVER_EYES: bool = false;
19
-
20
- `
21
-
22
- const HASHED_ALPHA_DECLS = `fn _hash3d_wm(a: vec3f) -> f32 {
23
- return _hash33(a).x * 0.5 + 0.5;
24
- }
25
- fn hashed_alpha_threshold(co: vec3f) -> f32 {
26
- let alphaHashScale: f32 = 1.0;
27
- let max_deriv = max(length(dpdx(co)), length(dpdy(co)));
28
- let pix_scale = 1.0 / max(alphaHashScale * max_deriv, 1e-6);
29
- let pix_scale_log = log2(pix_scale);
30
- let px_lo = exp2(floor(pix_scale_log));
31
- let px_hi = exp2(ceil(pix_scale_log));
32
- let a_lo = _hash3d_wm(floor(px_lo * co));
33
- let a_hi = _hash3d_wm(floor(px_hi * co));
34
- let fac = fract(pix_scale_log);
35
- let x = mix(a_lo, a_hi, fac);
36
- let a = min(fac, 1.0 - fac);
37
- let one_a = 1.0 - a;
38
- let denom = 1.0 / max(2.0 * a * one_a, 1e-6);
39
- let one_x = 1.0 - x;
40
- let case_lo = (x * x) * denom;
41
- let case_mid = (x - 0.5 * a) / max(one_a, 1e-6);
42
- let case_hi = 1.0 - (one_x * one_x) * denom;
43
- var threshold = select(case_hi, select(case_lo, case_mid, x >= a), x < one_a);
44
- return clamp(threshold, 1e-6, 1.0);
45
- }
46
-
47
- `
48
-
49
- // Eye's built-in rear-view gate (open-shell PMX heads don't occlude the eye from behind,
50
- // so gate by camera-vs-face hemisphere via the 頭 bone; discard drops color + depth +
51
- // the stencil stamp together). Injected between the view vectors and the lighting setup.
52
- const EYE_REAR_GATE = `
53
- if (material.headBoneIndex >= 0.0) {
54
- let hm = skinMats[u32(material.headBoneIndex)];
55
- let faceDir = -normalize(hm[2].xyz);
56
- if (dot(faceDir, v) < -0.15) { discard; }
57
- }
58
- `
59
-
60
- const PLAIN_SAMPLE = ` let tex_s = textureSample(diffuseTexture, diffuseSampler, input.uv);
61
- `
62
-
63
- // ── Adjust-tier uniforms — fixed 16-vec4f block (256 B) shared by the single material
64
- // bind group layout; non-graph draws bind a zero buffer. ──
65
- const STYLE_UNIFORMS_WGSL = `struct StyleUniforms { p: array<vec4f, 16> };
66
- @group(2) @binding(4) var<uniform> style: StyleUniforms;
67
-
68
- `
69
-
70
- function decls(renderClass: RenderClass, alphaMode: AlphaMode): string {
71
- // The dissolve helpers are ALWAYS declared, unlike the hashed-alpha ones.
72
- // They cost nothing on a material that never dissolves — the branch that
73
- // calls them is uniform across a draw and folds away — and making them
74
- // conditional would mean deciding at COMPILE time which materials may ever
75
- // come apart, which is the one thing a runtime value must not need.
76
- return (
77
- DISSOLVE_WGSL +
78
- (alphaMode === "hashed" ? HASHED_ALPHA_DECLS : "") +
79
- (renderClass === "hair" ? HAIR_OVER_EYES_DECL : "")
80
- )
81
- }
82
-
83
- // fs() header up to and including the graph body's context locals. Composed so the
84
- // hand-written material shaders' local names (tex_color, n, v, l, sun, amb, shadow) are
85
- // preserved exactly — the registry's context nodes and emit functions reference them.
86
- function prelude(renderClass: RenderClass, alphaMode: AlphaMode, blend: StyleBlend): string {
87
- // ADDITIVE NEVER GATES ON ALPHA. Its blend adds colour and reads no alpha at
88
- // all, so a surface painted this way carries its picture in RGB and leaves
89
- // alpha at zero — a game's sky layers do exactly that. Discarding on alpha
90
- // throws every one of those fragments away before the blend can add them,
91
- // which is what made X309's nebula and starfield invisible while its cloud
92
- // dome (opaque) came through.
93
- const discard =
94
- blend === "additive"
95
- ? ""
96
- : alphaMode === "hashed"
97
- ? " if (alpha < hashed_alpha_threshold(input.restPos)) { discard; }"
98
- : " if (alpha < 0.001) { discard; }"
99
- const gate = renderClass === "eye" ? EYE_REAR_GATE : ""
100
- // Double-sided shading, winding-independent: a normal pointing away from the
101
- // camera means we're seeing the surface's other side — flip it. Only genuinely
102
- // camera-averted fragments change (front surfaces have dot(n,v) > 0 and are
103
- // untouched), unlike a front_facing test, which PMX's clockwise winding
104
- // inverts. Fixes inner skirt linings (裙子白1-style flipped-normal copies)
105
- // shading near-black through sheer outer layers. Eye is exempt: its normals
106
- // shade as authored.
107
- const flip =
108
- renderClass === "eye" ? "" : "\n n = select(-n, n, dot(n, v) >= 0.0);"
109
- return `@fragment fn fs(input: VertexOutput) -> FSOut {
110
- ${PLAIN_SAMPLE} // The see-through window (#xray): her clothes are not drawn inside it.
111
- if (rz_xray_cut(input.position, material.materialId)) { discard; }
112
- // MMD alpha semantics: material alpha × texture alpha, capped at 1 as MMD
113
- // does (a PMX can author alpha above 1; blended, it burns the material white).
114
- let alpha = saturate(material.alpha * tex_s.a);
115
- ${discard}
116
-
117
- // ── Dissolve ──
118
- //
119
- // A fragment is either THERE or it is not: the flake is thrown away rather
120
- // than faded. A fade would be an opacity slider — she would go see-through
121
- // and you would read the wall through her hair — while a threshold takes her
122
- // apart in pieces, which is the thing being asked for. The depth prepass runs
123
- // this identical test (rz_dissolve_threshold, shared), so depth and colour
124
- // agree about which pieces are gone.
125
- //
126
- // The surviving edge glows: fragments within RZ_DISSOLVE_EDGE of the front
127
- // are the ones about to go, and lighting them is what makes the boundary read
128
- // as burning away rather than as a stencil moving over her.
129
- var rz_burn = 0.0;
130
- if (material.dissolve < 0.9995) {
131
- // PER FRAGMENT, from the bind-pose position: the pieces are the noise's,
132
- // grit inside clumps, never the mesh's triangles, so a large face comes
133
- // apart as finely as a small one. The prepass, the shadow map and the
134
- // outline hull run the same function on the same interpolated input, so
135
- // every pass agrees about which flakes are gone.
136
- let rz_t = rz_dissolve_threshold(input.restPos);
137
- if (rz_t > material.dissolve) { discard; }
138
- // Put OUT as the last of her goes. Near zero the front is wider than what
139
- // is left of the surface, so every surviving fragment sits inside it and
140
- // the final scraps are pure glow — a body that ends as a handful of white
141
- // specks rather than as a body. The taper costs nothing while she is mostly
142
- // there, because it is already 1 by a fifth of the way in.
143
- rz_burn = smoothstep(material.dissolve - RZ_DISSOLVE_EDGE, material.dissolve, rz_t)
144
- * smoothstep(0.0, 0.22, material.dissolve);
145
- }
146
-
147
- var n = safe_normal(input.normal);
148
- let v = normalize(camera.viewPos - input.worldPos);${flip}
149
- ${gate}
150
- // The key: the directional light this draw's layers take — the sun unless a
151
- // light on its own layer stands in. The shadow stays the sun's atlas, as the
152
- // game keeps the scene's shadow under a character's own key.
153
- let rz_key = rzMainLight();
154
- let l = -light.lights[rz_key].direction.xyz;
155
- // NO KEY WHERE NONE REACHES: rzMainLight falls back to the sun's slot, and
156
- // a sun kept off this draw's layers — the cast's alone, beside a stage lit
157
- // only by its own lamps — must not light it through the fallback.
158
- let rz_keyed = (light.dirLayers[rz_key] & objectLight.layers.x) != 0u;
159
- let sun = select(vec3f(0.0), light.lights[rz_key].color.xyz * light.lights[rz_key].color.w, rz_keyed);
160
- // Lit through the see-through window: what it reveals would otherwise wear
161
- // the shadow of the clothes it cut, which reads as dirt rather than as cloth.
162
- let shadow = select(sampleShadow(input.worldPos, n), 1.0, rz_xray_inside(input.position));
163
- // The ambient: this object's own where loaded data gave it one — the game
164
- // gives every renderer its own — else the world's flat colour or the HDRI's
165
- // irradiance at this normal.
166
- let amb = rzObjectAmbient(n);
167
- let tex_color = tex_s.rgb;
168
- // The normal the lamps' diffuse layer is lit by, for a principled walk to
169
- // compute it on the way (rzLightsDiffuseOnce). n is final from here on.
170
- _rzLampN = n;
171
- `
172
- }
173
-
174
- // Tail of fs(): consumes `final_color` + locals, writes FSOut. hashed forces output
175
- // alpha to 1 (the discard already did the cutout); hair scales alpha for the over-eyes
176
- // pass when IS_OVER_EYES is compiled true.
177
- function epilogue(renderClass: RenderClass, alphaMode: AlphaMode, hasOpacity: boolean, blend: StyleBlend, takesLight: boolean): string {
178
- // A graph that computes its own opacity wins, including over hashed: hashed
179
- // writes 1 because its discard already decided the cutout, and a graph asking
180
- // for a curve is asking for the opposite of a cutout. Additive writes 1 for a
181
- // third reason: its colour blend ignores src alpha entirely, so the only thing
182
- // alpha still reaches is the aux target's coverage — and a sky layer that
183
- // reported zero coverage would be invisible to bloom and to the composite.
184
- const alphaBase =
185
- blend === "additive" ? "1.0" : hasOpacity ? "final_opacity" : alphaMode === "hashed" ? "1.0" : "alpha"
186
- // Empty while ids are off, so the epilogue is exactly what it was. The values
187
- // ride in the per-draw material uniform (see MaterialUniforms), which is what
188
- // keeps this working through the indirect-draw path.
189
- const ID_WRITE = sceneIdWriteWgsl("out", "u32(material.materialId)", "u32(material.objectId)")
190
- // The positional lights, ADDED to whatever the graph decided and tinted by
191
- // the surface's own texture colour — a red lamp on a blue dress must not wash
192
- // it toward white. Deliberately outside the graph: this layer does not
193
- // re-ramp, because two ramped terminators crossing a cheek read as plastic.
194
- //
195
- // With no lights rzLightsDiffuse returns exactly zero and its loop never
196
- // runs, so every scene that declares none renders bit-for-bit as it did
197
- // before lights existed. That is the property this whole feature is gated on.
198
- // Modulated by `albedo`, a named local that TODAY is exactly tex_color — the
199
- // raw texture. That is an approximation with a known failure: a graph that
200
- // recolours a surface is lit by a colour it no longer shows. The local exists
201
- // so the fix has an address — when graphs gain an optional albedo output
202
- // (material-track era), it lands here and every light is corrected at once,
203
- // instead of a hunt through the epilogue's string templates.
204
- //
205
- // ONLY ON A GRAPH THAT TAKES LIGHT. An emission-only graph — Unlit, a stage's
206
- // painted sheet — is Blender's Emission shader, which no lamp reaches; adding
207
- // the lamps to it turned X340's floor shadow, a white-RGB picture at a soft
208
- // alpha, into a glowing disc under the spot above it.
209
- //
210
- // The model's fill (Engine.setModelFill) rides here too, as brightness: the
211
- // surface colour times the fill, on every pixel of her alike. In the graph's
212
- // ambient an NPR ramp would read it as LIGHT — sliding it would move her
213
- // shadows, and under a hard step flip whole regions at once. After the graph
214
- // it lifts her evenly and leaves every shadow where it is.
215
- const LIT = takesLight ? ` + (rzLightsDiffuseOnce(input.worldPos, n) + objectLight.fill.rgb) * albedo` : ""
216
- // The cast's shadow on a stage the sun cannot reach under its roof
217
- // (rzRoofedCastShadow), over everything the surface took — the lamps
218
- // included, since they are what light a closed room. Zero off a stage.
219
- const CAST = takesLight
220
- ? ` out.color = vec4f(out.color.rgb * mix(vec3f(1.0), light.castShadow.rgb, rzRoofedCastShadow(input.worldPos) * light.castShadow.w), out.color.a);\n`
221
- : ""
222
-
223
- const ALBEDO = ` let albedo = tex_color;
224
- `
225
- // The dissolve's burning edge, ADDED after the graph and after the lights —
226
- // it is emission, not a surface colour, so nothing may ramp or shadow it. Zero
227
- // on every fragment of every material that is not dissolving, which is what
228
- // keeps this out of the way of a scene that never uses it.
229
- const BURN = ` + RZ_BURN_COLOR * rz_burn`
230
- // The scene fog, last, as the game lays it over a lit surface; an
231
- // emission-only graph takes none (the game's effect shaders have no fog).
232
- // A premultiplied colour takes its fog premultiplied too: the haze a pane
233
- // adds is the haze over its own coverage, the rest arrives through what is
234
- // behind it (the game scales its fog by the output alpha the same way).
235
- const fogOver = blend === "premultiplied" ? " * out.color.a" : ""
236
- const FOG = takesLight
237
- ? ` out.color = vec4f(mix(mix(out.color.rgb, light.fog[0].rgb${fogOver}, input.fog.x), light.fog[2].rgb${fogOver}, input.fog.y), out.color.a);\n`
238
- : ""
239
- // MULTIPLY WRITES A FILTER, NOT A COLOUR. What it darkens was lit already —
240
- // the iris under an eye shadow took the sun and its own glow — so the shade
241
- // takes no light of its own: lit, a light-grey shadow came out brighter than
242
- // the eye and multiplied it WHITER. The multiplier is the surface's own
243
- // colour, its texture times the PMX diffuse as every look's base is, or what
244
- // an emission-only graph paints, which is already a colour no light reaches.
245
- // Faded by coverage here (the blend reads no alpha), capped at 1 so it can
246
- // only darken, and with no lamps, burn or fog — all three are light. The aux
247
- // is kept by the blend, so the mask written is never stored.
248
- if (blend === "multiply") {
249
- const filter = takesLight ? "tex_color * material.diffuseColor" : "final_color"
250
- return ` var out: FSOut;
251
- out.color = vec4f(mix(vec3f(1.0), saturate(${filter}), ${alphaBase}), ${alphaBase});
252
- out.mask = vec4f(0.0);
253
- ${ID_WRITE} return out;
254
- `
255
- }
256
- if (renderClass === "hair") {
257
- return `${ALBEDO} var outAlpha = ${alphaBase};
258
- if (IS_OVER_EYES) { outAlpha = ${alphaBase} * 0.25; }
259
-
260
- var out: FSOut;
261
- out.color = vec4f(final_color${LIT}${BURN}, outAlpha);
262
- ${CAST}${FOG} out.color = rz_finite(out.color);
263
- out.mask = vec4f(objectLight.bloom.x, 1.0, _rzSubsurface, out.color.a);
264
- ${ID_WRITE} return out;
265
- `
266
- }
267
- return `${ALBEDO} var out: FSOut;
268
- out.color = vec4f(final_color${LIT}${BURN}, ${alphaBase});
269
- ${CAST}${FOG} out.color = rz_finite(out.color);
270
- out.mask = vec4f(objectLight.bloom.x, 1.0, _rzSubsurface, out.color.a);
271
- ${ID_WRITE} return out;
272
- `
273
- }
274
-
275
- /**
276
- * Assemble a full WGSL module: shared node library + bindings/skinning prelude, optional
277
- * StyleUniforms, render-class/alpha-mode declarations, the composed fs() shell, and the
278
- * graph's node body.
279
- */
280
- export function assembleModule(
281
- renderClass: RenderClass,
282
- alphaMode: AlphaMode,
283
- fsBody: string,
284
- includeStyleUniforms: boolean,
285
- hasOpacity = false,
286
- blend: StyleBlend = "over",
287
- takesLight = true,
288
- ): string {
289
- return (
290
- NODES_WGSL +
291
- COMMON_MATERIAL_PRELUDE_WGSL +
292
- // Exactly where it sat inside the prelude constant. It moved out because
293
- // the id attachment is probed at init and this module is assembled per
294
- // compile, which is late enough to know the answer.
295
- commonFsOutWgsl() +
296
- (includeStyleUniforms ? STYLE_UNIFORMS_WGSL : "") +
297
- decls(renderClass, alphaMode) +
298
- prelude(renderClass, alphaMode, blend) +
299
- fsBody +
300
- "\n" +
301
- epilogue(renderClass, alphaMode, hasOpacity, blend, takesLight) +
302
- "}\n"
303
- )
304
- }
1
+ // fs() shell assembly. The graph computes only `final_color`; everything around it —
2
+ // texture sample, alpha discard, lighting context, built-in gates, and the FSOut/mask
3
+ // write — is composed here from two orthogonal, engine-owned axes:
4
+ // RenderClass ("auto" | "eye" | "hair") — stencil/cull/draw-order + eye rear-gate +
5
+ // hair over-eyes alpha. See render-class.ts.
6
+ // AlphaMode ("opaque" | "hashed") — standard threshold discard vs Wyman hashed.
7
+ // A style group supplies both; this file turns them into the WGSL shell around fsBody.
8
+ // See docs/style-groups-spec.md §5, §7.
9
+
10
+ import { NODES_WGSL } from "../shaders/materials/nodes"
11
+ import { COMMON_MATERIAL_PRELUDE_WGSL, DISSOLVE_WGSL, commonFsOutWgsl } from "../shaders/materials/common"
12
+ import { sceneIdWriteWgsl } from "../shaders/passes/scene-contract"
13
+ import type { AlphaMode, RenderClass, StyleBlend } from "./render-class"
14
+
15
+ // ── Module-scope declarations ──
16
+ // hair: the over-eyes pipeline-override constant (a second pipeline is compiled with
17
+ // IS_OVER_EYES=1). hashed: the Wyman & McGuire object-space hashed-alpha helpers.
18
+ const HAIR_OVER_EYES_DECL = `override IS_OVER_EYES: bool = false;
19
+
20
+ `
21
+
22
+ const HASHED_ALPHA_DECLS = `fn _hash3d_wm(a: vec3f) -> f32 {
23
+ return _hash33(a).x * 0.5 + 0.5;
24
+ }
25
+ fn hashed_alpha_threshold(co: vec3f) -> f32 {
26
+ let alphaHashScale: f32 = 1.0;
27
+ let max_deriv = max(length(dpdx(co)), length(dpdy(co)));
28
+ let pix_scale = 1.0 / max(alphaHashScale * max_deriv, 1e-6);
29
+ let pix_scale_log = log2(pix_scale);
30
+ let px_lo = exp2(floor(pix_scale_log));
31
+ let px_hi = exp2(ceil(pix_scale_log));
32
+ let a_lo = _hash3d_wm(floor(px_lo * co));
33
+ let a_hi = _hash3d_wm(floor(px_hi * co));
34
+ let fac = fract(pix_scale_log);
35
+ let x = mix(a_lo, a_hi, fac);
36
+ let a = min(fac, 1.0 - fac);
37
+ let one_a = 1.0 - a;
38
+ let denom = 1.0 / max(2.0 * a * one_a, 1e-6);
39
+ let one_x = 1.0 - x;
40
+ let case_lo = (x * x) * denom;
41
+ let case_mid = (x - 0.5 * a) / max(one_a, 1e-6);
42
+ let case_hi = 1.0 - (one_x * one_x) * denom;
43
+ var threshold = select(case_hi, select(case_lo, case_mid, x >= a), x < one_a);
44
+ return clamp(threshold, 1e-6, 1.0);
45
+ }
46
+
47
+ `
48
+
49
+ // Eye's built-in rear-view gate (open-shell PMX heads don't occlude the eye from behind,
50
+ // so gate by camera-vs-face hemisphere via the 頭 bone; discard drops color + depth +
51
+ // the stencil stamp together). Injected between the view vectors and the lighting setup.
52
+ const EYE_REAR_GATE = `
53
+ if (material.headBoneIndex >= 0.0) {
54
+ let hm = skinMats[u32(material.headBoneIndex)];
55
+ let faceDir = -normalize(hm[2].xyz);
56
+ if (dot(faceDir, v) < -0.15) { discard; }
57
+ }
58
+ `
59
+
60
+ const PLAIN_SAMPLE = ` let tex_s = textureSample(diffuseTexture, diffuseSampler, input.uv);
61
+ `
62
+
63
+ // ── Adjust-tier uniforms — fixed 16-vec4f block (256 B) shared by the single material
64
+ // bind group layout; non-graph draws bind a zero buffer. ──
65
+ const STYLE_UNIFORMS_WGSL = `struct StyleUniforms { p: array<vec4f, 16> };
66
+ @group(2) @binding(4) var<uniform> style: StyleUniforms;
67
+
68
+ `
69
+
70
+ function decls(renderClass: RenderClass, alphaMode: AlphaMode): string {
71
+ // The dissolve helpers are ALWAYS declared, unlike the hashed-alpha ones.
72
+ // They cost nothing on a material that never dissolves — the branch that
73
+ // calls them is uniform across a draw and folds away — and making them
74
+ // conditional would mean deciding at COMPILE time which materials may ever
75
+ // come apart, which is the one thing a runtime value must not need.
76
+ return (
77
+ DISSOLVE_WGSL +
78
+ (alphaMode === "hashed" ? HASHED_ALPHA_DECLS : "") +
79
+ (renderClass === "hair" ? HAIR_OVER_EYES_DECL : "")
80
+ )
81
+ }
82
+
83
+ // fs() header up to and including the graph body's context locals. Composed so the
84
+ // hand-written material shaders' local names (tex_color, n, v, l, sun, amb, shadow) are
85
+ // preserved exactly — the registry's context nodes and emit functions reference them.
86
+ function prelude(renderClass: RenderClass, alphaMode: AlphaMode, blend: StyleBlend): string {
87
+ // ADDITIVE NEVER GATES ON ALPHA. Its blend adds colour and reads no alpha at
88
+ // all, so a surface painted this way carries its picture in RGB and leaves
89
+ // alpha at zero — a game's sky layers do exactly that. Discarding on alpha
90
+ // throws every one of those fragments away before the blend can add them,
91
+ // which is what made X309's nebula and starfield invisible while its cloud
92
+ // dome (opaque) came through.
93
+ const discard =
94
+ blend === "additive"
95
+ ? ""
96
+ : alphaMode === "hashed"
97
+ ? " if (alpha < hashed_alpha_threshold(input.restPos)) { discard; }"
98
+ : " if (alpha < 0.001) { discard; }"
99
+ const gate = renderClass === "eye" ? EYE_REAR_GATE : ""
100
+ // Double-sided shading, winding-independent: a normal pointing away from the
101
+ // camera means we're seeing the surface's other side — flip it. Only genuinely
102
+ // camera-averted fragments change (front surfaces have dot(n,v) > 0 and are
103
+ // untouched), unlike a front_facing test, which PMX's clockwise winding
104
+ // inverts. Fixes inner skirt linings (裙子白1-style flipped-normal copies)
105
+ // shading near-black through sheer outer layers. Eye is exempt: its normals
106
+ // shade as authored.
107
+ const flip =
108
+ renderClass === "eye" ? "" : "\n n = select(-n, n, dot(n, v) >= 0.0);"
109
+ return `@fragment fn fs(input: VertexOutput) -> FSOut {
110
+ ${PLAIN_SAMPLE} // The see-through window (#xray): her clothes are not drawn inside it.
111
+ if (rz_xray_cut(input.position, material.materialId)) { discard; }
112
+ // MMD alpha semantics: material alpha × texture alpha, capped at 1 as MMD
113
+ // does (a PMX can author alpha above 1; blended, it burns the material white).
114
+ let alpha = saturate(material.alpha * tex_s.a);
115
+ ${discard}
116
+
117
+ // ── Dissolve ──
118
+ //
119
+ // A fragment is either THERE or it is not: the flake is thrown away rather
120
+ // than faded. A fade would be an opacity slider — she would go see-through
121
+ // and you would read the wall through her hair — while a threshold takes her
122
+ // apart in pieces, which is the thing being asked for. The depth prepass runs
123
+ // this identical test (rz_dissolve_threshold, shared), so depth and colour
124
+ // agree about which pieces are gone.
125
+ //
126
+ // The surviving edge glows: fragments within RZ_DISSOLVE_EDGE of the front
127
+ // are the ones about to go, and lighting them is what makes the boundary read
128
+ // as burning away rather than as a stencil moving over her.
129
+ var rz_burn = 0.0;
130
+ if (material.dissolve < 0.9995) {
131
+ // PER FRAGMENT, from the bind-pose position: the pieces are the noise's,
132
+ // grit inside clumps, never the mesh's triangles, so a large face comes
133
+ // apart as finely as a small one. The prepass, the shadow map and the
134
+ // outline hull run the same function on the same interpolated input, so
135
+ // every pass agrees about which flakes are gone.
136
+ let rz_t = rz_dissolve_threshold(input.restPos);
137
+ if (rz_t > material.dissolve) { discard; }
138
+ // Put OUT as the last of her goes. Near zero the front is wider than what
139
+ // is left of the surface, so every surviving fragment sits inside it and
140
+ // the final scraps are pure glow — a body that ends as a handful of white
141
+ // specks rather than as a body. The taper costs nothing while she is mostly
142
+ // there, because it is already 1 by a fifth of the way in.
143
+ rz_burn = smoothstep(material.dissolve - RZ_DISSOLVE_EDGE, material.dissolve, rz_t)
144
+ * smoothstep(0.0, 0.22, material.dissolve);
145
+ }
146
+
147
+ var n = safe_normal(input.normal);
148
+ let v = normalize(camera.viewPos - input.worldPos);${flip}
149
+ ${gate}
150
+ // The key: the directional light this draw's layers take — the sun unless a
151
+ // light on its own layer stands in. The shadow stays the sun's atlas, as the
152
+ // game keeps the scene's shadow under a character's own key.
153
+ let rz_key = rzMainLight();
154
+ let l = -light.lights[rz_key].direction.xyz;
155
+ // NO KEY WHERE NONE REACHES: rzMainLight falls back to the sun's slot, and
156
+ // a sun kept off this draw's layers — the cast's alone, beside a stage lit
157
+ // only by its own lamps — must not light it through the fallback.
158
+ let rz_keyed = (light.dirLayers[rz_key] & rzDrawLayers()) != 0u;
159
+ let sun = select(vec3f(0.0), light.lights[rz_key].color.xyz * light.lights[rz_key].color.w, rz_keyed);
160
+ // Lit through the see-through window: what it reveals would otherwise wear
161
+ // the shadow of the clothes it cut, which reads as dirt rather than as cloth.
162
+ let shadow = select(sampleShadow(input.worldPos, n), 1.0, rz_xray_inside(input.position));
163
+ // The ambient: this object's own where loaded data gave it one — the game
164
+ // gives every renderer its own — else the world's flat colour or the HDRI's
165
+ // irradiance at this normal.
166
+ let amb = rzObjectAmbient(n);
167
+ let tex_color = tex_s.rgb;
168
+ // The normal the lamps' diffuse layer is lit by, for a principled walk to
169
+ // compute it on the way (rzLightsDiffuseOnce). n is final from here on.
170
+ _rzLampN = n;
171
+ `
172
+ }
173
+
174
+ // Tail of fs(): consumes `final_color` + locals, writes FSOut. hashed forces output
175
+ // alpha to 1 (the discard already did the cutout); hair scales alpha for the over-eyes
176
+ // pass when IS_OVER_EYES is compiled true.
177
+ function epilogue(renderClass: RenderClass, alphaMode: AlphaMode, hasOpacity: boolean, blend: StyleBlend, takesLight: boolean): string {
178
+ // A graph that computes its own opacity wins, including over hashed: hashed
179
+ // writes 1 because its discard already decided the cutout, and a graph asking
180
+ // for a curve is asking for the opposite of a cutout. Additive writes 1 for a
181
+ // third reason: its colour blend ignores src alpha entirely, so the only thing
182
+ // alpha still reaches is the aux target's coverage — and a sky layer that
183
+ // reported zero coverage would be invisible to bloom and to the composite.
184
+ const alphaBase =
185
+ blend === "additive" ? "1.0" : hasOpacity ? "final_opacity" : alphaMode === "hashed" ? "1.0" : "alpha"
186
+ // Empty while ids are off, so the epilogue is exactly what it was. The values
187
+ // ride in the per-draw material uniform (see MaterialUniforms), which is what
188
+ // keeps this working through the indirect-draw path.
189
+ const ID_WRITE = sceneIdWriteWgsl("out", "u32(material.materialId)", "u32(material.objectId)")
190
+ // The positional lights, ADDED to whatever the graph decided and tinted by
191
+ // the surface's own texture colour — a red lamp on a blue dress must not wash
192
+ // it toward white. Deliberately outside the graph: this layer does not
193
+ // re-ramp, because two ramped terminators crossing a cheek read as plastic.
194
+ //
195
+ // With no lights rzLightsDiffuse returns exactly zero and its loop never
196
+ // runs, so every scene that declares none renders bit-for-bit as it did
197
+ // before lights existed. That is the property this whole feature is gated on.
198
+ // Modulated by `albedo`, a named local that TODAY is exactly tex_color — the
199
+ // raw texture. That is an approximation with a known failure: a graph that
200
+ // recolours a surface is lit by a colour it no longer shows. The local exists
201
+ // so the fix has an address — when graphs gain an optional albedo output
202
+ // (material-track era), it lands here and every light is corrected at once,
203
+ // instead of a hunt through the epilogue's string templates.
204
+ //
205
+ // ONLY ON A GRAPH THAT TAKES LIGHT. An emission-only graph — Unlit, a stage's
206
+ // painted sheet — is Blender's Emission shader, which no lamp reaches; adding
207
+ // the lamps to it turned X340's floor shadow, a white-RGB picture at a soft
208
+ // alpha, into a glowing disc under the spot above it.
209
+ //
210
+ // The model's fill (Engine.setModelFill) rides here too, as brightness: the
211
+ // surface colour times the fill, on every pixel of her alike. In the graph's
212
+ // ambient an NPR ramp would read it as LIGHT — sliding it would move her
213
+ // shadows, and under a hard step flip whole regions at once. After the graph
214
+ // it lifts her evenly and leaves every shadow where it is.
215
+ const LIT = takesLight ? ` + (rzLightsDiffuseOnce(input.worldPos, n) + objectLight.fill.rgb) * albedo` : ""
216
+ // The cast's shadow on a stage the sun cannot reach under its roof
217
+ // (rzRoofedCastShadow), over everything the surface took — the lamps
218
+ // included, since they are what light a closed room. Zero off a stage.
219
+ const CAST = takesLight
220
+ ? ` out.color = vec4f(out.color.rgb * mix(vec3f(1.0), light.castShadow.rgb, rzRoofedCastShadow(input.worldPos) * light.castShadow.w), out.color.a);\n`
221
+ : ""
222
+
223
+ const ALBEDO = ` let albedo = tex_color;
224
+ `
225
+ // The dissolve's burning edge, ADDED after the graph and after the lights —
226
+ // it is emission, not a surface colour, so nothing may ramp or shadow it. Zero
227
+ // on every fragment of every material that is not dissolving, which is what
228
+ // keeps this out of the way of a scene that never uses it.
229
+ const BURN = ` + RZ_BURN_COLOR * rz_burn`
230
+ // The scene fog, last, as the game lays it over a lit surface; an
231
+ // emission-only graph takes none (the game's effect shaders have no fog).
232
+ // A premultiplied colour takes its fog premultiplied too: the haze a pane
233
+ // adds is the haze over its own coverage, the rest arrives through what is
234
+ // behind it (the game scales its fog by the output alpha the same way).
235
+ const fogOver = blend === "premultiplied" ? " * out.color.a" : ""
236
+ const FOG = takesLight
237
+ ? ` out.color = vec4f(mix(mix(out.color.rgb, light.fog[0].rgb${fogOver}, input.fog.x), light.fog[2].rgb${fogOver}, input.fog.y), out.color.a);\n`
238
+ : ""
239
+ // MULTIPLY WRITES A FILTER, NOT A COLOUR. What it darkens was lit already —
240
+ // the iris under an eye shadow took the sun and its own glow — so the shade
241
+ // takes no light of its own: lit, a light-grey shadow came out brighter than
242
+ // the eye and multiplied it WHITER. The multiplier is the surface's own
243
+ // colour, its texture times the PMX diffuse as every look's base is, or what
244
+ // an emission-only graph paints, which is already a colour no light reaches.
245
+ // Faded by coverage here (the blend reads no alpha), capped at 1 so it can
246
+ // only darken, and with no lamps, burn or fog — all three are light. The aux
247
+ // is kept by the blend, so the mask written is never stored.
248
+ if (blend === "multiply") {
249
+ const filter = takesLight ? "tex_color * material.diffuseColor" : "final_color"
250
+ return ` var out: FSOut;
251
+ out.color = vec4f(mix(vec3f(1.0), saturate(${filter}), ${alphaBase}), ${alphaBase});
252
+ out.mask = vec4f(0.0);
253
+ ${ID_WRITE} return out;
254
+ `
255
+ }
256
+ if (renderClass === "hair") {
257
+ return `${ALBEDO} var outAlpha = ${alphaBase};
258
+ if (IS_OVER_EYES) { outAlpha = ${alphaBase} * 0.25; }
259
+
260
+ var out: FSOut;
261
+ out.color = vec4f(final_color${LIT}${BURN}, outAlpha);
262
+ ${CAST}${FOG} out.color = rz_finite(out.color);
263
+ out.mask = vec4f(objectLight.bloom.x, 1.0, _rzSubsurface, out.color.a);
264
+ ${ID_WRITE} return out;
265
+ `
266
+ }
267
+ return `${ALBEDO} var out: FSOut;
268
+ out.color = vec4f(final_color${LIT}${BURN}, ${alphaBase});
269
+ ${CAST}${FOG} out.color = rz_finite(out.color);
270
+ out.mask = vec4f(objectLight.bloom.x, 1.0, _rzSubsurface, out.color.a);
271
+ ${ID_WRITE} return out;
272
+ `
273
+ }
274
+
275
+ /**
276
+ * Assemble a full WGSL module: shared node library + bindings/skinning prelude, optional
277
+ * StyleUniforms, render-class/alpha-mode declarations, the composed fs() shell, and the
278
+ * graph's node body.
279
+ */
280
+ export function assembleModule(
281
+ renderClass: RenderClass,
282
+ alphaMode: AlphaMode,
283
+ fsBody: string,
284
+ includeStyleUniforms: boolean,
285
+ hasOpacity = false,
286
+ blend: StyleBlend = "over",
287
+ takesLight = true,
288
+ ): string {
289
+ return (
290
+ NODES_WGSL +
291
+ COMMON_MATERIAL_PRELUDE_WGSL +
292
+ // Exactly where it sat inside the prelude constant. It moved out because
293
+ // the id attachment is probed at init and this module is assembled per
294
+ // compile, which is late enough to know the answer.
295
+ commonFsOutWgsl() +
296
+ (includeStyleUniforms ? STYLE_UNIFORMS_WGSL : "") +
297
+ decls(renderClass, alphaMode) +
298
+ prelude(renderClass, alphaMode, blend) +
299
+ fsBody +
300
+ "\n" +
301
+ epilogue(renderClass, alphaMode, hasOpacity, blend, takesLight) +
302
+ "}\n"
303
+ )
304
+ }
package/src/index.ts CHANGED
@@ -20,6 +20,7 @@ export {
20
20
  type MaterialPresetMap,
21
21
  type ModelTransform,
22
22
  type SceneLight,
23
+ type CastKey,
23
24
  RENDERING_LAYER_DEFAULT,
24
25
  RENDERING_LAYER_CHARACTER,
25
26
  type ModelAttachment,