reze-engine 0.69.0 → 0.69.2

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.
@@ -61,6 +61,21 @@ const LINE = DIRECTIVE_LINE;
61
61
  * thing to write, so it has to be the accepted thing to write.
62
62
  */
63
63
  export const DIRECTIVE_NOTE = /(?:^|\s)(?:—|--|\/\/|#)\s/;
64
+ /** The note after the arguments, or "" — see DIRECTIVE_NOTE. */
65
+ function noteOf(rest) {
66
+ const m = DIRECTIVE_NOTE.exec(rest);
67
+ return m ? rest.slice(m.index + m[0].length).trim() : "";
68
+ }
69
+ /** A dial's labels from its note, when the note is written `English | 中文`. */
70
+ function labelsOf(rest) {
71
+ const note = noteOf(rest);
72
+ const bar = note.indexOf("|");
73
+ if (bar < 0)
74
+ return {};
75
+ const label = note.slice(0, bar).trim();
76
+ const labelZh = note.slice(bar + 1).trim();
77
+ return { ...(label ? { label } : {}), ...(labelZh ? { labelZh } : {}) };
78
+ }
64
79
  function argsOf(rest) {
65
80
  // `^` as well as `\s`: the tag's own trailing space is eaten by LINE, so a
66
81
  // note can begin at the very first character — which is what
@@ -166,12 +181,47 @@ export function parseDirectives(wgsl) {
166
181
  errors.push(`${at}: #param needs a WGSL identifier for a name`);
167
182
  return;
168
183
  }
184
+ const labels = labelsOf(m[2]);
185
+ if (kind === "bool") {
186
+ const v = rest[0]?.toLowerCase();
187
+ const on = v === "true" || v === "1" || v === "on";
188
+ const off = v === "false" || v === "0" || v === "off";
189
+ if (rest.length !== 1 || (!on && !off)) {
190
+ errors.push(`${at}: #param bool ${name} needs a default, true or false`);
191
+ return;
192
+ }
193
+ d.params.push({ name, kind: "bool", value: on ? 1 : 0, ...labels });
194
+ return;
195
+ }
196
+ if (kind === "enum") {
197
+ // Each choice is `id` or `id|中文`; a leading `*` marks the default,
198
+ // else the first is.
199
+ const options = [];
200
+ let value = 0;
201
+ for (const raw of rest) {
202
+ const star = raw.startsWith("*");
203
+ const [id, zh] = (star ? raw.slice(1) : raw).split("|");
204
+ if (!id) {
205
+ errors.push(`${at}: #param enum ${name} has an empty choice`);
206
+ return;
207
+ }
208
+ if (star)
209
+ value = options.length;
210
+ options.push({ id, ...(zh ? { labelZh: zh } : {}) });
211
+ }
212
+ if (options.length < 2) {
213
+ errors.push(`${at}: #param enum ${name} needs at least two choices, like "rain|数字雨 dots|点阵"`);
214
+ return;
215
+ }
216
+ d.params.push({ name, kind: "enum", value, options, ...labels });
217
+ return;
218
+ }
169
219
  if (kind === "color") {
170
220
  if (!/^#[0-9a-fA-F]{6}$/.test(rest[0] ?? "")) {
171
221
  errors.push(`${at}: #param color ${name} needs a default like #3b82f6`);
172
222
  return;
173
223
  }
174
- d.params.push({ name, kind: "color", value: rest[0] });
224
+ d.params.push({ name, kind: "color", value: rest[0], ...labels });
175
225
  return;
176
226
  }
177
227
  if (kind === "vec3") {
@@ -180,7 +230,7 @@ export function parseDirectives(wgsl) {
180
230
  errors.push(`${at}: #param vec3 ${name} needs three numbers`);
181
231
  return;
182
232
  }
183
- d.params.push({ name, kind: "vec3", value: v });
233
+ d.params.push({ name, kind: "vec3", value: v, ...labels });
184
234
  return;
185
235
  }
186
236
  if (kind === "float") {
@@ -197,10 +247,10 @@ export function parseDirectives(wgsl) {
197
247
  errors.push(`${at}: #param float ${name} takes both a min and a max, or neither`);
198
248
  return;
199
249
  }
200
- d.params.push({ name, kind: "float", value: v, ...(lo !== null && hi !== null ? { min: lo, max: hi } : {}) });
250
+ d.params.push({ name, kind: "float", value: v, ...(lo !== null && hi !== null ? { min: lo, max: hi } : {}), ...labels });
201
251
  return;
202
252
  }
203
- errors.push(`${at}: #param kind must be float, color or vec3`);
253
+ errors.push(`${at}: #param kind must be float, color, vec3, bool or enum`);
204
254
  return;
205
255
  }
206
256
  case "halfres":
@@ -1 +1 @@
1
- {"version":3,"file":"ground.d.ts","sourceRoot":"","sources":["../../../src/shaders/passes/ground.ts"],"names":[],"mappings":"AAoFA;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,UAAQ,GAAG,MAAM,CAsWrD;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,kBAAkB,QAAS,CAAA;AACxC,eAAO,MAAM,gBAAgB,QAAS,CAAA;AAEtC;;;oEAGoE;AACpE,eAAO,MAAM,iBAAiB,OAAO,CAAA;AAErC;;;;;;;;;GASG;AACH,eAAO,MAAM,sBAAsB,+oCAiClC,CAAA"}
1
+ {"version":3,"file":"ground.d.ts","sourceRoot":"","sources":["../../../src/shaders/passes/ground.ts"],"names":[],"mappings":"AAoFA;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,UAAQ,GAAG,MAAM,CAqWrD;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,kBAAkB,QAAS,CAAA;AACxC,eAAO,MAAM,gBAAgB,QAAS,CAAA;AAEtC;;;oEAGoE;AACpE,eAAO,MAAM,iBAAiB,OAAO,CAAA;AAErC;;;;;;;;;GASG;AACH,eAAO,MAAM,sBAAsB,+oCAiClC,CAAA"}
@@ -92,7 +92,7 @@ struct GroundShadowMat {
92
92
  fadeEnd: f32, shadowStrength: f32, gridPattern: f32, gridSpacing: f32,
93
93
  gridLineWidth: f32, gridLineOpacity: f32, noiseStrength: f32, opacity: f32,
94
94
  gridLineColor: vec3f, mirror: f32,
95
- mirrorBlur: f32, _pad17: f32, shadowSoftness: f32, groundY: f32,
95
+ mirrorBlur: f32, mirrorReflectivity: f32, shadowSoftness: f32, groundY: f32,
96
96
  // Every shadow caster in one sphere, refreshed per frame. w = radius; 0 means
97
97
  // nothing casts, negative means "do not use this" (a rigid caster has no
98
98
  // sphere, so a scene with a stage keeps the taps). See rzShadowPossible.
@@ -384,47 +384,46 @@ ${pcfWgsl("shadowAtlas", "suv", `${1 / SHADOW_ATLAS_SIZE}`, "compareZ", "acc", "
384
384
  // with it — you could not have a bare grid over a photo, which is most of
385
385
  // what a grid is for. It is its own layer now: the ground plane keeps an
386
386
  // alpha, and the grid is simply on or off.
387
- // FRESNEL over the reflection. A real polished floor is mostly its own
388
- // colour looking straight down and nearly a mirror toward the horizon
389
- // (Schlick's falloff, (1 - cos)^5), so where the mirror has something to
390
- // show, the surface thins as the view grazes. Opacity is therefore the
391
- // floor's coverage LOOKING STRAIGHT DOWN. Where nothing reflected, and with
392
- // the mirror off, the surface is untouched: the far floor does not dissolve
393
- // into an empty target.
387
+ // REFLECTION IS NOT TRANSPARENCY. A solid glossy floor reflects: its colour
388
+ // and its reflection ADD, in a share set by the material and the angle, and
389
+ // how see-through the floor is has nothing to do with it. So the two are two
390
+ // dials. Opacity is the surface's coverage, for compositing over a photo or a
391
+ // key. Reflectivity is Schlick's F0, the share reflected looking straight
392
+ // down; Fresnel takes it toward 1 as the view grazes, (1 - cos)^5. 1 is a true
393
+ // mirror at every angle.
394
394
  let viewCos = clamp(dot(n, normalize(camera.viewPos - i.worldPos)), 0.0, 1.0);
395
- let fresnel = pow(1.0 - viewCos, 5.0);
396
- let surfA = edgeFade * material.opacity * (1.0 - fresnel * material.mirror * reflA);
395
+ let f0 = clamp(material.mirrorReflectivity, 0.0, 1.0);
396
+ let fresnel = f0 + (1.0 - f0) * pow(1.0 - viewCos, 5.0);
397
+ let surfA = edgeFade * material.opacity;
397
398
  let gridA = gridLine * material.gridLineOpacity * edgeFade;
398
- // The mirror covers only what it actually REFLECTS. The backdrop no longer
399
- // rides in the reflection target — it clears transparent — so the floor keeps
400
- // its own colour everywhere the cast is not standing, which is the difference
401
- // between an MMD stage floor and a mirror of the sky.
402
- let mirrA = material.mirror * edgeFade * reflA;
399
+ // The mirror covers only what it actually REFLECTS. The backdrop does not
400
+ // ride in the reflection target (it clears transparent), so the floor keeps
401
+ // its own colour everywhere the cast is not standing: an MMD stage floor,
402
+ // not a mirror of the sky.
403
+ let mirrA = material.mirror * edgeFade * reflA * fresnel;
403
404
  // As opacity drops the received shadow becomes a translucent dark layer
404
405
  // (Blender's Shadow Catcher), so models still feel grounded on a photo or a
405
- // 360 backdrop. Colourless by construction: it darkens by covering. The
406
- // MIRROR subsumes it: the reflection already carries the received shadow,
407
- // and a catcher stacked on top would darken the same shadow twice.
408
- let catchA = dark * 0.65 * edgeFade * (1.0 - material.opacity) * (1.0 - mirrA);
406
+ // 360 backdrop. Colourless by construction: it darkens by covering. Where the
407
+ // reflection lies over it, the reflection's own shadow shows instead.
408
+ let catchA = dark * 0.65 * edgeFade * (1.0 - material.opacity);
409
409
 
410
- // FOUR LAYERS, premultiplied, bottom to top: reflection, received shadow,
411
- // ground surface, grid. Each with its own coverage, none scaling another —
412
- // ground opacity REVEALS the mirror rather than the mirror carrying a
413
- // strength of its own.
414
- // reflShadowed is ALREADY premultiplied by its coverage (reflA): the HDR
415
- // target stores colour weighted by its own alpha. So the layer's colour takes
416
- // the mirror's switch and the fade, not reflA a second time — that squared
417
- // coverage dimmed every edge, and every pixel once the blur spread it.
418
- var pm = reflShadowed * material.mirror * edgeFade;
419
- var cov = mirrA;
420
- // Shadow catcher over the reflection-or-nothing: black, it covers.
421
- pm = pm * (1.0 - catchA);
422
- cov = catchA + cov * (1.0 - catchA);
410
+ // FOUR LAYERS, premultiplied, bottom to top: received shadow, ground
411
+ // surface, reflection, grid. The reflection over the surface is the energy
412
+ // split itself: what the floor reflects it does not diffuse, so the surface
413
+ // under it keeps (1 - F) of itself, and a floor at opacity 0 still mirrors,
414
+ // the way glass does.
415
+ var pm = vec3f(0.0);
416
+ var cov = catchA;
423
417
  // Surface over shadow.
424
418
  pm = baseColor * surfA + pm * (1.0 - surfA);
425
419
  cov = surfA + cov * (1.0 - surfA);
426
- // Grid over surface. Unshadowed, as it has always been — a painted line reads
427
- // as paint, and darkening it was never what the mix did either.
420
+ // Reflection over the surface. reflShadowed is ALREADY premultiplied by its
421
+ // coverage (reflA): the HDR target stores colour weighted by its own alpha,
422
+ // so it takes the switch, the fade and Fresnel, never reflA a second time.
423
+ pm = reflShadowed * (material.mirror * edgeFade * fresnel) + pm * (1.0 - mirrA);
424
+ cov = mirrA + cov * (1.0 - mirrA);
425
+ // Grid over everything. Unshadowed, as it has always been: a painted line
426
+ // reads as paint.
428
427
  pm = material.gridLineColor * gridA + pm * (1.0 - gridA);
429
428
  cov = gridA + cov * (1.0 - gridA);
430
429
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "reze-engine",
3
- "version": "0.69.0",
3
+ "version": "0.69.2",
4
4
  "description": "A lightweight WebGPU engine for real-time 3D MMD/PMX model rendering",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
package/src/engine.ts CHANGED
@@ -1049,6 +1049,17 @@ interface ModelInstance {
1049
1049
  * writes ONE float into each of them and needs no other reason to hold a
1050
1050
  * block: the whole 16-float copy exists only for materials that morph. */
1051
1051
  materialUniformBuffers: GPUBuffer[]
1052
+ /** The material each of `materialUniformBuffers` belongs to, by index. Names,
1053
+ * not PMX indices: a material with no faces draws nothing and has no buffer,
1054
+ * so the two lists do not line up with the PMX's own. */
1055
+ materialNames: string[]
1056
+ /** How much of each named material is still there, as setMaterialDissolve
1057
+ * last asked. Absent = whole. A material wears the lower of this and the
1058
+ * model's own `dissolve`. */
1059
+ materialDissolve: Map<string, number>
1060
+ /** What each material buffer was last written, so a frame that changes
1061
+ * nothing writes nothing. */
1062
+ dissolveWritten: number[]
1052
1063
  /** The outline hulls' own uniforms, for the materials that have them.
1053
1064
  *
1054
1065
  * A SEPARATE LIST because they are a separate buffer: the hull pass binds 32
@@ -5662,7 +5673,7 @@ export class Engine {
5662
5673
  // KIND comes from the declaration, never from the runtime type of the
5663
5674
  // value: a caller handing a number to a colour must not silently turn a
5664
5675
  // vec3f field into an f32 and shift every field after it.
5665
- const isVec = p.kind !== "float"
5676
+ const isVec = p.kind === "color" || p.kind === "vec3"
5666
5677
  const align = isVec ? 16 : 4
5667
5678
  const offset = Math.ceil(cursor / align) * align
5668
5679
  layout.set(p.name, { offset: offset / 4, comps: isVec ? 3 : 1 })
@@ -11900,6 +11911,11 @@ export class Engine {
11900
11911
  /** Mirror softness, 0–1: 0 a polished mirror, 1 the softest blur level,
11901
11912
  * scaled by how far the reflected geometry sits behind the surface. */
11902
11913
  mirrorBlur?: number
11914
+ /** How much the mirror reflects looking straight down, 0–1 (Schlick's F0);
11915
+ * Fresnel takes it toward 1 as the view grazes. 1 (default) is a true
11916
+ * mirror. Independent of `opacity`, which is only how see-through the
11917
+ * floor is: the reflection lies OVER the floor's colour. */
11918
+ mirrorReflectivity?: number
11903
11919
  /** How soft the received shadow's edge is, 0–1. 0 (default) is the sharp
11904
11920
  * kernel this has always used, to the bit; 1 spreads the taps fourteen
11905
11921
  * times as wide, which is the edge an overcast sky throws.
@@ -11935,6 +11951,7 @@ export class Engine {
11935
11951
  opacity: 1.0,
11936
11952
  mirror: false,
11937
11953
  mirrorBlur: 0,
11954
+ mirrorReflectivity: 1,
11938
11955
  shadowSoftness: 0,
11939
11956
  ...options,
11940
11957
  }
@@ -15623,6 +15640,9 @@ export class Engine {
15623
15640
  objectId: (this.lastObjectId = this.lastObjectId >= GROUND_OBJECT_ID - 1 ? 1 : this.lastObjectId + 1),
15624
15641
  dissolve: 1,
15625
15642
  materialUniformBuffers: [],
15643
+ materialNames: [],
15644
+ materialDissolve: new Map(),
15645
+ dissolveWritten: [],
15626
15646
  outlineUniformBuffers: [],
15627
15647
  outlineByMaterial: new Map(),
15628
15648
  cullModelIndex: 0,
@@ -15882,6 +15902,7 @@ export class Engine {
15882
15902
  opacity: number
15883
15903
  mirror: boolean
15884
15904
  mirrorBlur: number
15905
+ mirrorReflectivity: number
15885
15906
  shadowSoftness: number
15886
15907
  }) {
15887
15908
  const {
@@ -15899,6 +15920,7 @@ export class Engine {
15899
15920
  opacity,
15900
15921
  mirror,
15901
15922
  mirrorBlur,
15923
+ mirrorReflectivity,
15902
15924
  shadowSoftness,
15903
15925
  } = opts
15904
15926
  // Shadow map is already created in setupPipelines()
@@ -15928,6 +15950,8 @@ export class Engine {
15928
15950
  this.groundMirror = gb[15]
15929
15951
  gb[16] = Math.min(Math.max(mirrorBlur, 0), 1)
15930
15952
  this.groundMirrorBlur = gb[16]
15953
+ // gb[17] — reflectivity, the mirror's F0. Was padding.
15954
+ gb[17] = Math.min(Math.max(mirrorReflectivity, 0), 1)
15931
15955
  // gb[18] — shadow edge softness. Was padding; the shader reads it as the
15932
15956
  // Vogel disk's radius, and 0 takes the sharp nine-tap path unchanged.
15933
15957
  gb[18] = Math.min(Math.max(shadowSoftness, 0), 1)
@@ -16233,6 +16257,8 @@ export class Engine {
16233
16257
  )
16234
16258
  inst.gpuBuffers.push(materialUniformBuffer)
16235
16259
  inst.materialUniformBuffers.push(materialUniformBuffer)
16260
+ inst.materialNames.push(mat.name)
16261
+ inst.dissolveWritten.push(1)
16236
16262
  if (morphedMaterials.has(pmxMaterialIndex)) {
16237
16263
  const base = this.materialUniformData(mat, sphereMode, headBoneIndex, materialId, modelId)
16238
16264
  morphTargets.push({
@@ -18530,31 +18556,75 @@ export class Engine {
18530
18556
  const v = Math.min(1, Math.max(0, value))
18531
18557
  if (inst.dissolve === v) return true
18532
18558
  inst.dissolve = v
18533
- // Offset 60: the sixteenth float of MaterialUniforms. One four-byte write
18534
- // per material rather than the whole block — the block only exists as a
18535
- // copy for materials that morph.
18536
- const one = new Float32Array([v])
18537
- for (const buffer of inst.materialUniformBuffers) {
18538
- this.device.queue.writeBuffer(buffer, 60, one)
18559
+ this.writeDissolve(inst)
18560
+ return true
18561
+ }
18562
+
18563
+ /**
18564
+ * Take some of one model's MATERIALS apart: the stockings, the jacket, a hat
18565
+ * — by material name, 1 whole, 0 gone. The same dissolve the whole model
18566
+ * comes apart by (setModelDissolve), with the same burning front, honoured by
18567
+ * the colour pass, the depth prepass, the shadow map and the outline; it is
18568
+ * only narrowed to the materials named. Each replaces the last set: a name
18569
+ * left out is whole again, and null makes them all whole.
18570
+ *
18571
+ * A material wears the lower of this and the model's own dissolve, so a
18572
+ * model coming apart takes these with it.
18573
+ */
18574
+ setMaterialDissolve(modelName: string, values: Readonly<Record<string, number>> | null): boolean {
18575
+ const inst = this.modelInstances.get(modelName)
18576
+ if (!inst) return false
18577
+ const next = new Map<string, number>()
18578
+ if (values) {
18579
+ for (const [name, value] of Object.entries(values)) {
18580
+ const v = Math.min(1, Math.max(0, Number.isFinite(value) ? value : 1))
18581
+ if (v < 1) next.set(name, v)
18582
+ }
18539
18583
  }
18540
- // And the hulls, which bind their own 32 bytes of edge data rather than the
18541
- // material block — so this is a different buffer at a different offset, and
18542
- // missing it left a dissolved character standing in her own outline.
18543
- for (const buffer of inst.outlineUniformBuffers) {
18544
- this.device.queue.writeBuffer(buffer, RZ_OUTLINE_DISSOLVE_OFFSET, one)
18584
+ inst.materialDissolve = next
18585
+ this.writeDissolve(inst)
18586
+ return true
18587
+ }
18588
+
18589
+ /** What setMaterialDissolve last set for one material, 1 when whole. */
18590
+ getMaterialDissolve(modelName: string, materialName: string): number {
18591
+ return this.modelInstances.get(modelName)?.materialDissolve.get(materialName) ?? 1
18592
+ }
18593
+
18594
+ /**
18595
+ * Each material's dissolve into its buffers: the lower of the model's and its
18596
+ * own. Only buffers whose value moved are written.
18597
+ *
18598
+ * Offset 60 is the sixteenth float of MaterialUniforms, which the colour pass,
18599
+ * the depth prepass and the shadow map all bind. The hulls bind their own 32
18600
+ * bytes of edge data, so they are a different buffer at a different offset —
18601
+ * missing them left a dissolved character standing in her own outline.
18602
+ */
18603
+ private writeDissolve(inst: ModelInstance): void {
18604
+ const one = new Float32Array(1)
18605
+ let moved = false
18606
+ for (let i = 0; i < inst.materialNames.length; i++) {
18607
+ const name = inst.materialNames[i]
18608
+ const v = Math.min(inst.dissolve, inst.materialDissolve.get(name) ?? 1)
18609
+ if (inst.dissolveWritten[i] === v) continue
18610
+ inst.dissolveWritten[i] = v
18611
+ moved = true
18612
+ one[0] = v
18613
+ this.device.queue.writeBuffer(inst.materialUniformBuffers[i], 60, one)
18614
+ const hull = inst.outlineByMaterial.get(name)
18615
+ if (hull) this.device.queue.writeBuffer(hull.buffer, RZ_OUTLINE_DISSOLVE_OFFSET, one)
18545
18616
  }
18546
18617
  // The morph path rebuilds a material's block from its `base` copy and
18547
18618
  // uploads it whole, which would put the old value straight back. Patching
18548
18619
  // `base` is what keeps a face that is morphing while she dissolves from
18549
18620
  // coming back solid for those frames; `last` is cleared so the next
18550
18621
  // comparison genuinely re-uploads rather than deciding nothing moved.
18551
- if (inst.materialMorphTargets) {
18622
+ if (moved && inst.materialMorphTargets) {
18552
18623
  for (const t of inst.materialMorphTargets) {
18553
- t.base[15] = v
18624
+ t.base[15] = Math.min(inst.dissolve, inst.materialDissolve.get(t.materialName) ?? 1)
18554
18625
  t.last[15] = Number.NaN
18555
18626
  }
18556
18627
  }
18557
- return true
18558
18628
  }
18559
18629
 
18560
18630
  /**
package/src/index.ts CHANGED
@@ -110,6 +110,7 @@ export {
110
110
  DIRECTIVE_NOTE,
111
111
  type EffectDirectives,
112
112
  type EffectParamDecl,
113
+ type EffectParamOption,
113
114
  } from "./shaders/directives"
114
115
  export {
115
116
  Model,
@@ -52,15 +52,34 @@
52
52
  */
53
53
  export type EffectAnchor = { bone: string; trail: boolean; along?: number; step?: number }
54
54
 
55
- /** A knob an effect exposes, for a host to build a control from. */
55
+ /** One choice of an `enum` dial: its id, and a Chinese label after a `|`. */
56
+ export type EffectParamOption = { id: string; labelZh?: string }
57
+
58
+ /**
59
+ * A knob an effect exposes, for a host to build a control from.
60
+ *
61
+ * `bool` and `enum` are one f32 in the shader like `float`: a switch reads 0 or
62
+ * 1, a choice reads its option's index. They differ only in the control a host
63
+ * draws — a switch, a list — which is the whole reason to declare them: a
64
+ * slider from 0 to 3 that means "rain, dots, circuit, grid" is a dial nobody
65
+ * can read.
66
+ *
67
+ * `label`/`labelZh` come from a note written `— English | 中文`. A note without
68
+ * the `|` is only a note, as it always was.
69
+ */
56
70
  export type EffectParamDecl = {
57
71
  name: string
58
- kind: "float" | "color" | "vec3"
59
- /** Numbers for float/vec3; `#rrggbb` for a colour, which the host converts. */
72
+ kind: "float" | "color" | "vec3" | "bool" | "enum"
73
+ /** Numbers for float/vec3, 0 or 1 for bool, the option's index for enum;
74
+ * `#rrggbb` for a colour, which the host converts. */
60
75
  value: number | [number, number, number] | string
61
76
  /** float only, and only when the author gave a range. */
62
77
  min?: number
63
78
  max?: number
79
+ /** enum only: the choices, in index order. */
80
+ options?: EffectParamOption[]
81
+ label?: string
82
+ labelZh?: string
64
83
  }
65
84
 
66
85
  export type EffectDirectives = {
@@ -196,6 +215,22 @@ const LINE = DIRECTIVE_LINE
196
215
  */
197
216
  export const DIRECTIVE_NOTE = /(?:^|\s)(?:—|--|\/\/|#)\s/
198
217
 
218
+ /** The note after the arguments, or "" — see DIRECTIVE_NOTE. */
219
+ function noteOf(rest: string): string {
220
+ const m = DIRECTIVE_NOTE.exec(rest)
221
+ return m ? rest.slice(m.index + m[0].length).trim() : ""
222
+ }
223
+
224
+ /** A dial's labels from its note, when the note is written `English | 中文`. */
225
+ function labelsOf(rest: string): { label?: string; labelZh?: string } {
226
+ const note = noteOf(rest)
227
+ const bar = note.indexOf("|")
228
+ if (bar < 0) return {}
229
+ const label = note.slice(0, bar).trim()
230
+ const labelZh = note.slice(bar + 1).trim()
231
+ return { ...(label ? { label } : {}), ...(labelZh ? { labelZh } : {}) }
232
+ }
233
+
199
234
  function argsOf(rest: string): string[] {
200
235
  // `^` as well as `\s`: the tag's own trailing space is eaten by LINE, so a
201
236
  // note can begin at the very first character — which is what
@@ -304,12 +339,46 @@ export function parseDirectives(wgsl: string): DirectiveResult {
304
339
  errors.push(`${at}: #param needs a WGSL identifier for a name`)
305
340
  return
306
341
  }
342
+ const labels = labelsOf(m[2])
343
+ if (kind === "bool") {
344
+ const v = rest[0]?.toLowerCase()
345
+ const on = v === "true" || v === "1" || v === "on"
346
+ const off = v === "false" || v === "0" || v === "off"
347
+ if (rest.length !== 1 || (!on && !off)) {
348
+ errors.push(`${at}: #param bool ${name} needs a default, true or false`)
349
+ return
350
+ }
351
+ d.params.push({ name, kind: "bool", value: on ? 1 : 0, ...labels })
352
+ return
353
+ }
354
+ if (kind === "enum") {
355
+ // Each choice is `id` or `id|中文`; a leading `*` marks the default,
356
+ // else the first is.
357
+ const options: EffectParamOption[] = []
358
+ let value = 0
359
+ for (const raw of rest) {
360
+ const star = raw.startsWith("*")
361
+ const [id, zh] = (star ? raw.slice(1) : raw).split("|")
362
+ if (!id) {
363
+ errors.push(`${at}: #param enum ${name} has an empty choice`)
364
+ return
365
+ }
366
+ if (star) value = options.length
367
+ options.push({ id, ...(zh ? { labelZh: zh } : {}) })
368
+ }
369
+ if (options.length < 2) {
370
+ errors.push(`${at}: #param enum ${name} needs at least two choices, like "rain|数字雨 dots|点阵"`)
371
+ return
372
+ }
373
+ d.params.push({ name, kind: "enum", value, options, ...labels })
374
+ return
375
+ }
307
376
  if (kind === "color") {
308
377
  if (!/^#[0-9a-fA-F]{6}$/.test(rest[0] ?? "")) {
309
378
  errors.push(`${at}: #param color ${name} needs a default like #3b82f6`)
310
379
  return
311
380
  }
312
- d.params.push({ name, kind: "color", value: rest[0] })
381
+ d.params.push({ name, kind: "color", value: rest[0], ...labels })
313
382
  return
314
383
  }
315
384
  if (kind === "vec3") {
@@ -318,7 +387,7 @@ export function parseDirectives(wgsl: string): DirectiveResult {
318
387
  errors.push(`${at}: #param vec3 ${name} needs three numbers`)
319
388
  return
320
389
  }
321
- d.params.push({ name, kind: "vec3", value: v as [number, number, number] })
390
+ d.params.push({ name, kind: "vec3", value: v as [number, number, number], ...labels })
322
391
  return
323
392
  }
324
393
  if (kind === "float") {
@@ -335,10 +404,10 @@ export function parseDirectives(wgsl: string): DirectiveResult {
335
404
  errors.push(`${at}: #param float ${name} takes both a min and a max, or neither`)
336
405
  return
337
406
  }
338
- d.params.push({ name, kind: "float", value: v, ...(lo !== null && hi !== null ? { min: lo, max: hi } : {}) })
407
+ d.params.push({ name, kind: "float", value: v, ...(lo !== null && hi !== null ? { min: lo, max: hi } : {}), ...labels })
339
408
  return
340
409
  }
341
- errors.push(`${at}: #param kind must be float, color or vec3`)
410
+ errors.push(`${at}: #param kind must be float, color, vec3, bool or enum`)
342
411
  return
343
412
  }
344
413
  case "halfres":
@@ -96,7 +96,7 @@ struct GroundShadowMat {
96
96
  fadeEnd: f32, shadowStrength: f32, gridPattern: f32, gridSpacing: f32,
97
97
  gridLineWidth: f32, gridLineOpacity: f32, noiseStrength: f32, opacity: f32,
98
98
  gridLineColor: vec3f, mirror: f32,
99
- mirrorBlur: f32, _pad17: f32, shadowSoftness: f32, groundY: f32,
99
+ mirrorBlur: f32, mirrorReflectivity: f32, shadowSoftness: f32, groundY: f32,
100
100
  // Every shadow caster in one sphere, refreshed per frame. w = radius; 0 means
101
101
  // nothing casts, negative means "do not use this" (a rigid caster has no
102
102
  // sphere, so a scene with a stage keeps the taps). See rzShadowPossible.
@@ -390,47 +390,46 @@ ${pcfWgsl("shadowAtlas", "suv", `${1 / SHADOW_ATLAS_SIZE}`, "compareZ", "acc", "
390
390
  // with it — you could not have a bare grid over a photo, which is most of
391
391
  // what a grid is for. It is its own layer now: the ground plane keeps an
392
392
  // alpha, and the grid is simply on or off.
393
- // FRESNEL over the reflection. A real polished floor is mostly its own
394
- // colour looking straight down and nearly a mirror toward the horizon
395
- // (Schlick's falloff, (1 - cos)^5), so where the mirror has something to
396
- // show, the surface thins as the view grazes. Opacity is therefore the
397
- // floor's coverage LOOKING STRAIGHT DOWN. Where nothing reflected, and with
398
- // the mirror off, the surface is untouched: the far floor does not dissolve
399
- // into an empty target.
393
+ // REFLECTION IS NOT TRANSPARENCY. A solid glossy floor reflects: its colour
394
+ // and its reflection ADD, in a share set by the material and the angle, and
395
+ // how see-through the floor is has nothing to do with it. So the two are two
396
+ // dials. Opacity is the surface's coverage, for compositing over a photo or a
397
+ // key. Reflectivity is Schlick's F0, the share reflected looking straight
398
+ // down; Fresnel takes it toward 1 as the view grazes, (1 - cos)^5. 1 is a true
399
+ // mirror at every angle.
400
400
  let viewCos = clamp(dot(n, normalize(camera.viewPos - i.worldPos)), 0.0, 1.0);
401
- let fresnel = pow(1.0 - viewCos, 5.0);
402
- let surfA = edgeFade * material.opacity * (1.0 - fresnel * material.mirror * reflA);
401
+ let f0 = clamp(material.mirrorReflectivity, 0.0, 1.0);
402
+ let fresnel = f0 + (1.0 - f0) * pow(1.0 - viewCos, 5.0);
403
+ let surfA = edgeFade * material.opacity;
403
404
  let gridA = gridLine * material.gridLineOpacity * edgeFade;
404
- // The mirror covers only what it actually REFLECTS. The backdrop no longer
405
- // rides in the reflection target — it clears transparent — so the floor keeps
406
- // its own colour everywhere the cast is not standing, which is the difference
407
- // between an MMD stage floor and a mirror of the sky.
408
- let mirrA = material.mirror * edgeFade * reflA;
405
+ // The mirror covers only what it actually REFLECTS. The backdrop does not
406
+ // ride in the reflection target (it clears transparent), so the floor keeps
407
+ // its own colour everywhere the cast is not standing: an MMD stage floor,
408
+ // not a mirror of the sky.
409
+ let mirrA = material.mirror * edgeFade * reflA * fresnel;
409
410
  // As opacity drops the received shadow becomes a translucent dark layer
410
411
  // (Blender's Shadow Catcher), so models still feel grounded on a photo or a
411
- // 360 backdrop. Colourless by construction: it darkens by covering. The
412
- // MIRROR subsumes it: the reflection already carries the received shadow,
413
- // and a catcher stacked on top would darken the same shadow twice.
414
- let catchA = dark * 0.65 * edgeFade * (1.0 - material.opacity) * (1.0 - mirrA);
412
+ // 360 backdrop. Colourless by construction: it darkens by covering. Where the
413
+ // reflection lies over it, the reflection's own shadow shows instead.
414
+ let catchA = dark * 0.65 * edgeFade * (1.0 - material.opacity);
415
415
 
416
- // FOUR LAYERS, premultiplied, bottom to top: reflection, received shadow,
417
- // ground surface, grid. Each with its own coverage, none scaling another —
418
- // ground opacity REVEALS the mirror rather than the mirror carrying a
419
- // strength of its own.
420
- // reflShadowed is ALREADY premultiplied by its coverage (reflA): the HDR
421
- // target stores colour weighted by its own alpha. So the layer's colour takes
422
- // the mirror's switch and the fade, not reflA a second time — that squared
423
- // coverage dimmed every edge, and every pixel once the blur spread it.
424
- var pm = reflShadowed * material.mirror * edgeFade;
425
- var cov = mirrA;
426
- // Shadow catcher over the reflection-or-nothing: black, it covers.
427
- pm = pm * (1.0 - catchA);
428
- cov = catchA + cov * (1.0 - catchA);
416
+ // FOUR LAYERS, premultiplied, bottom to top: received shadow, ground
417
+ // surface, reflection, grid. The reflection over the surface is the energy
418
+ // split itself: what the floor reflects it does not diffuse, so the surface
419
+ // under it keeps (1 - F) of itself, and a floor at opacity 0 still mirrors,
420
+ // the way glass does.
421
+ var pm = vec3f(0.0);
422
+ var cov = catchA;
429
423
  // Surface over shadow.
430
424
  pm = baseColor * surfA + pm * (1.0 - surfA);
431
425
  cov = surfA + cov * (1.0 - surfA);
432
- // Grid over surface. Unshadowed, as it has always been — a painted line reads
433
- // as paint, and darkening it was never what the mix did either.
426
+ // Reflection over the surface. reflShadowed is ALREADY premultiplied by its
427
+ // coverage (reflA): the HDR target stores colour weighted by its own alpha,
428
+ // so it takes the switch, the fade and Fresnel, never reflA a second time.
429
+ pm = reflShadowed * (material.mirror * edgeFade * fresnel) + pm * (1.0 - mirrA);
430
+ cov = mirrA + cov * (1.0 - mirrA);
431
+ // Grid over everything. Unshadowed, as it has always been: a painted line
432
+ // reads as paint.
434
433
  pm = material.gridLineColor * gridA + pm * (1.0 - gridA);
435
434
  cov = gridA + cov * (1.0 - gridA);
436
435