@margoengine/shader 0.1.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/LICENSE +201 -201
  2. package/NOTICE +4 -4
  3. package/README.md +1920 -1771
  4. package/dist/attribute.d.ts +28 -0
  5. package/dist/black-hole.js +3 -3
  6. package/dist/clock-BLGNexlt.js +3 -3
  7. package/dist/{compute-D-BghbXj.js → compute-CXGG9qvI.js} +76 -70
  8. package/dist/compute-texture.js +3 -3
  9. package/dist/compute-volume.js +3 -3
  10. package/dist/compute.d.ts +8 -2
  11. package/dist/{control-DvjfV7R0.js → control-CFjkGPBk.js} +1 -1
  12. package/dist/deform.js +2 -2
  13. package/dist/editor-pass.js +17 -17
  14. package/dist/effects.js +2 -2
  15. package/dist/glsl-material.js +2 -2
  16. package/dist/glsl-pass.js +5 -5
  17. package/dist/glsl.js +18 -18
  18. package/dist/gpu-DQJk2xAv.js +55 -0
  19. package/dist/graph.js +2 -2
  20. package/dist/index.d.ts +1 -0
  21. package/dist/index.js +103 -8
  22. package/dist/{lighting-Dx8_RsBz.js → lighting-JU9yQPfM.js} +2 -2
  23. package/dist/lighting.js +1 -1
  24. package/dist/{material-CU7p-Q8u.js → material-C6bpqlnE.js} +1 -1
  25. package/dist/{material-REzUrXtu.js → material-CZ8V1FeA.js} +95 -71
  26. package/dist/material.d.ts +9 -4
  27. package/dist/{node-DzKv9CF2.js → node-B6yoIC9V.js} +126 -126
  28. package/dist/node.d.ts +7 -1
  29. package/dist/noise.js +1 -1
  30. package/dist/pass.d.ts +1 -0
  31. package/dist/pass.js +24 -21
  32. package/dist/{post-DC62ZleD.js → post-DLpZ110L.js} +17 -17
  33. package/dist/{raw-D0W8U3Qa.js → raw-0AYej3Ak.js} +422 -273
  34. package/dist/raw.d.ts +125 -15
  35. package/dist/raw.js +1 -1
  36. package/dist/readback.js +13 -12
  37. package/dist/serialization.js +12 -12
  38. package/dist/shadertoy.js +6 -6
  39. package/dist/shared/caster.d.ts +159 -152
  40. package/dist/shared/fog.d.ts +33 -33
  41. package/dist/shared/fractal.d.ts +9 -9
  42. package/dist/shared/msaa.d.ts +30 -25
  43. package/dist/shared/stack.d.ts +22 -22
  44. package/dist/subgroups.js +4 -4
  45. package/dist/{texture-D6vy0bam.js → texture-BawKO_h9.js} +1 -1
  46. package/dist/texture-array.js +2 -2
  47. package/dist/utils.js +32 -32
  48. package/package.json +151 -151
  49. package/dist/gpu-DQ5Jmggz.js +0 -31
@@ -1,9 +1,9 @@
1
- // @margo/core-built 0.1.0
1
+ // @margo/core-built 1.0.0
2
2
  import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
3
 
4
- import { t as e } from "./clock-BLGNexlt.js";
5
- import { t } from "./errors-CsQwshHA.js";
6
- import { r as n, t as r } from "./view-rect-Bm1ac-TK.js";
4
+ import { t as e } from "./errors-CsQwshHA.js";
5
+ import { r as t, t as n } from "./view-rect-Bm1ac-TK.js";
6
+ import { t as r } from "./clock-BLGNexlt.js";
7
7
  import { t as i } from "./display-BrJM_Qkd.js";
8
8
  import { parseColor as a } from "@margoengine/math/color";
9
9
  import { MargoError as o } from "@margoengine/math/errors";
@@ -65,12 +65,12 @@ var f = (e, t, n, r) => u({
65
65
  name: t,
66
66
  setter: n
67
67
  }, e, r);
68
- function p(e, n, r) {
69
- let { value: i } = e;
70
- if (typeof i == "function") return e.device !== n && (e.made = i(e.device = n)), e.made;
68
+ function p(t, n, r) {
69
+ let { value: i } = t;
70
+ if (typeof i == "function") return t.device !== n && (t.made = i(t.device = n)), t.made;
71
71
  if (i != null) {
72
- if (e.device ??= n, e.device === n) return i;
73
- e.told || (e.told = !0, r?.onError(t("state", `${e.name} lost with the device; pass a function or call ${e.setter}`, "borrowed-lost")));
72
+ if (t.device ??= n, t.device === n) return i;
73
+ t.told || (t.told = !0, r?.onError(e("state", `${t.name} lost with the device; pass a function or call ${t.setter}`, "borrowed-lost")));
74
74
  }
75
75
  }
76
76
  function m(e) {
@@ -108,8 +108,8 @@ function C(e, t) {
108
108
  if (!/^[A-Za-z]\w*$/.test(e) || S.test(e)) throw TypeError(`${t} name ${JSON.stringify(e)} is not a usable WGSL identifier; use letters, digits and _, not a WGSL keyword or a prelude name (camera, mesh, uniforms, margo*)`);
109
109
  return e;
110
110
  }
111
- var w = (e, t, n) => {
112
- for (let r of e.matchAll(RegExp(`@${t}\\s+fn\\s+([A-Za-z_]\\w*)`, "g"))) if (r[1] !== n) return r[1];
111
+ var w = (e, t, n = []) => {
112
+ for (let r of e.matchAll(RegExp(`@${t}\\s+fn\\s+([A-Za-z_]\\w*)`, "g"))) if (!n.includes(r[1])) return r[1];
113
113
  }, T = (e) => g.test(e) || e === "mat3x3f" || e === "mat4x4f", E = (e, t) => Math.ceil(e / t) * t, D = `${i.replace("pbrNeutral", "margoNeutral")}fn margoSRGB(x:vec3f)->vec3f {return select(x*12.92,1.055*pow(x,vec3f(1.0/2.4))-0.055,x>=vec3f(0.0031308));}
114
114
  fn margoDisplay(c:vec4f)->vec4f {if(camera.encoding==0.0){return c;}let x=margoNeutral(max(c.rgb,vec3f(0)));if(camera.encoding==2.0){return vec4f(x,c.a);}return vec4f(margoSRGB(x),c.a);}
115
115
  fn margoEncode(c:vec4f)->vec4f {if(camera.encoding!=1.0){return c;}return vec4f(margoSRGB(max(c.rgb,vec3f(0))),c.a);}
@@ -118,9 +118,65 @@ struct MargoMesh { world:mat4x4f, normal:mat3x3f, pickId:u32 }
118
118
  @group(0) @binding(0) var<uniform> camera:MargoCamera;
119
119
  @group(0) @binding(1) var<uniform> mesh:MargoMesh;
120
120
  struct MargoGBuffer { @location(0) normal:vec4f, @location(1) ambient:vec4f }
121
- fn margoGBuffer(normal:vec3f,position:vec3f,ambient:vec3f)->MargoGBuffer {return MargoGBuffer(vec4f(normalize((camera.view*vec4f(normal,0)).xyz),-(camera.view*vec4f(position,1)).z),vec4f(ambient,1));}`, O = "struct MargoBefore { viewProjection:mat4x4f, world:mat4x4f, time:f32, valid:f32 }\n@group(0) @binding(2) var<uniform> margoBefore:MargoBefore;\nstruct MargoVelocity { @builtin(position) @invariant clip:vec4f, @location(0) previous:vec4f }\nfn margoVelocity(position:vec3f,before:vec3f)->MargoVelocity {return MargoVelocity(camera.viewProjection*mesh.world*vec4f(position,1),margoBefore.viewProjection*margoBefore.world*vec4f(before,1));}\n", ee = "\nstruct MargoMotion { @location(0) velocity:vec2f, @location(1) depth:f32 }\n@fragment fn margoVelocityFragment(i:MargoVelocity)->MargoMotion {var o:MargoMotion;o.velocity=vec2f(0);o.depth=-1;\n if(i.previous.w>0&&margoBefore.valid>0){o.velocity=i.clip.xy/camera.resolution-(i.previous.xy/i.previous.w*vec2f(0.5,-0.5)+0.5);o.depth=i.previous.z/i.previous.w;}return o;}\n", te = "@fragment fn margoPick()->@location(0) u32 {return mesh.pickId;}\n", ne = 112, re = 128, ie = /* @__PURE__ */ new WeakMap(), ae = /* @__PURE__ */ new WeakMap(), k = /* @__PURE__ */ new WeakMap(), A = /* @__PURE__ */ new WeakMap(), j = /* @__PURE__ */ new WeakMap(), M = /* @__PURE__ */ new WeakMap(), N = /* @__PURE__ */ new WeakMap(), P = /* @__PURE__ */ new WeakMap(), F = () => GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT;
122
- function I(e, t = !1) {
123
- let n = t ? ae : ie, r = n.get(e);
121
+ fn margoGBuffer(normal:vec3f,position:vec3f,ambient:vec3f)->MargoGBuffer {return MargoGBuffer(vec4f(normalize((camera.view*vec4f(normal,0)).xyz),-(camera.view*vec4f(position,1)).z),vec4f(ambient,1));}`, O = "struct MargoMaterial { position:vec3f, normal:vec3f, view:vec3f, base:vec3f, metal:f32, rough:f32, ambient:vec3f }", k = "\nstruct MargoCapture { @location(0) unused:vec4f }\nfn margoCapture(m:MargoMaterial)->MargoCapture {return MargoCapture(vec4f(0));}", A = /* @__PURE__ */ new Map(), j = 0, M = (e) => {
122
+ let t = A.get(e);
123
+ return t === void 0 && (A.size >= 64 && A.clear(), A.set(e, t = ++j)), t;
124
+ }, ee = "struct MargoBefore { viewProjection:mat4x4f, world:mat4x4f, time:f32, valid:f32, relativeCurrent:mat4x4f, relativePrevious:mat4x4f, origin:vec4f }\n@group(0) @binding(2) var<uniform> margoBefore:MargoBefore;\nstruct MargoVelocity { @builtin(position) @invariant clip:vec4f, @location(0) previous:vec4f, @location(1) current:vec4f }\nfn margoVelocity(position:vec3f,before:vec3f)->MargoVelocity {return MargoVelocity(camera.viewProjection*mesh.world*vec4f(position,1),margoBefore.relativePrevious*vec4f((margoBefore.world*vec4f(before,1)).xyz-margoBefore.origin.xyz,1),margoBefore.relativeCurrent*vec4f((mesh.world*vec4f(position,1)).xyz-margoBefore.origin.xyz,1));}\n", te = "\nstruct MargoMotion { @location(0) velocity:vec4f, @location(1) depth:f32 }\n@fragment fn margoVelocityFragment(i:MargoVelocity)->MargoMotion {var o:MargoMotion;o.velocity=vec4f(0,0,0,1);o.depth=-1;\n if(i.previous.w>0&&margoBefore.valid>0){let margoDepth=i.previous.z/i.previous.w;let margoNow=select(i.clip.xy/camera.resolution,i.current.xy/i.current.w*vec2f(0.5,-0.5)+0.5,i.current.w>0);o.velocity=vec4f(margoNow-(i.previous.xy/i.previous.w*vec2f(0.5,-0.5)+0.5),select(0.0,log2(margoDepth),margoDepth>0),1);o.depth=margoDepth;}return o;}\n", ne = "@fragment fn margoPick()->@location(0) u32 {return mesh.pickId;}\n", re = 112, ie = 128;
125
+ function ae(e, t, n) {
126
+ if (!t || typeof t != "object") throw TypeError(`${e} struct must be an object of field types`);
127
+ let r = [], i = 0;
128
+ for (let [a, o] of Object.entries(t)) {
129
+ C(a, `${e} field`);
130
+ let t = `${e} field ${a}`;
131
+ if (typeof o == "string" || !o || typeof o != "object") {
132
+ if (!T(o)) throw TypeError(`${t} needs a type from 'f32' to 'vec4f', their i32/u32 variants, 'mat3x3f' or 'mat4x4f', or {struct} or {type, count}`);
133
+ let e = E(i, y(o));
134
+ r.push({
135
+ name: a,
136
+ type: o,
137
+ offset: e
138
+ }), i = e + b(o);
139
+ continue;
140
+ }
141
+ let { count: s } = o;
142
+ if (s !== void 0 && (!Number.isInteger(s) || s < 1)) throw RangeError(`${t} count must be a positive integer`);
143
+ let c = E(i, 16);
144
+ if (o.struct) {
145
+ let e = ae(t, o.struct, n), l = `Raw${n.length}_${a}`;
146
+ n.push({
147
+ type: l,
148
+ fields: e.fields
149
+ }), r.push({
150
+ name: a,
151
+ type: l,
152
+ offset: c,
153
+ count: s,
154
+ stride: e.size,
155
+ fields: e.fields
156
+ }), i = c + e.size * (s ?? 1);
157
+ continue;
158
+ }
159
+ let l = o.type;
160
+ if (s === void 0 || !l || !T(l)) throw TypeError(`${t} needs {struct} for a nested struct, or {type, count} with type 'f32' to 'vec4f', i32/u32 variants, 'mat3x3f' or 'mat4x4f' for an array`);
161
+ let u = E(b(l), y(l));
162
+ if (u % 16) throw TypeError(`${t}: elements of a uniform array sit 16 bytes apart, so ${l} does not fit; use vec3, vec4, a matrix or a struct, or put it in a storage buffer`);
163
+ r.push({
164
+ name: a,
165
+ type: l,
166
+ offset: c,
167
+ count: s,
168
+ stride: u
169
+ }), i = c + u * s;
170
+ }
171
+ if (!r.length) throw TypeError(`${e} struct needs at least one field`);
172
+ return {
173
+ fields: r,
174
+ size: E(i, 16)
175
+ };
176
+ }
177
+ var oe = /* @__PURE__ */ new WeakMap(), se = /* @__PURE__ */ new WeakMap(), N = /* @__PURE__ */ new WeakMap(), P = /* @__PURE__ */ new WeakMap(), F = /* @__PURE__ */ new WeakMap(), I = /* @__PURE__ */ new WeakMap(), L = /* @__PURE__ */ new WeakMap(), R = /* @__PURE__ */ new WeakMap(), z = () => GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT;
178
+ function B(e, t = !1) {
179
+ let n = t ? se : oe, r = n.get(e);
124
180
  return r || (r = e.createBindGroupLayout({
125
181
  label: t ? "shader:raw:velocity" : "shader:raw:frame",
126
182
  entries: (t ? [
@@ -129,14 +185,14 @@ function I(e, t = !1) {
129
185
  2
130
186
  ] : [0, 1]).map((e) => ({
131
187
  binding: e,
132
- visibility: F(),
188
+ visibility: z(),
133
189
  buffer: { type: "uniform" }
134
190
  }))
135
191
  }), n.set(e, r)), r;
136
192
  }
137
- function L(e, t = {}) {
138
- let n = k.get(e);
139
- n || k.set(e, n = /* @__PURE__ */ new Map());
193
+ function V(e, t = {}) {
194
+ let n = N.get(e);
195
+ n || N.set(e, n = /* @__PURE__ */ new Map());
140
196
  let r = {
141
197
  magFilter: "linear",
142
198
  minFilter: "linear",
@@ -144,9 +200,9 @@ function L(e, t = {}) {
144
200
  }, i = JSON.stringify(r), a = n.get(i);
145
201
  return a || n.set(i, a = e.createSampler(r)), a;
146
202
  }
147
- function R(e, t) {
148
- let n = P.get(e);
149
- n || P.set(e, n = /* @__PURE__ */ new Map());
203
+ function H(e, t) {
204
+ let n = R.get(e);
205
+ n || R.set(e, n = /* @__PURE__ */ new Map());
150
206
  let r = t.dimension ?? "2d", i = t.sampleType ?? "float", a = r + i, o = n.get(a);
151
207
  if (!o) {
152
208
  let t = r === "cube" ? 6 : 1, s = i === "sint" || i === "uint", c = i === "depth", l = e.createTexture({
@@ -188,24 +244,24 @@ function R(e, t) {
188
244
  }
189
245
  return o;
190
246
  }
191
- function oe(e, t, n) {
247
+ function ce(e, t, n) {
192
248
  if (typeof t.buffer == "function") return t.buffer(e);
193
- let r = M.get(t.buffer);
194
- r || M.set(t.buffer, r = f(t.buffer, "RawShaderMaterial storage buffer", "assign a new buffer", e));
249
+ let r = I.get(t.buffer);
250
+ r || I.set(t.buffer, r = f(t.buffer, "RawShaderMaterial storage buffer", "assign a new buffer", e));
195
251
  let i = p(r, e, n);
196
252
  if (i) return i;
197
- let a = N.get(e);
198
- return a || N.set(e, a = e.createBuffer({
253
+ let a = L.get(e);
254
+ return a || L.set(e, a = e.createBuffer({
199
255
  label: "shader:raw:storage-stand-in",
200
256
  size: 256,
201
257
  usage: GPUBufferUsage.STORAGE
202
258
  })), a;
203
259
  }
204
- function se(e, t, n) {
205
- let r = t.sampleType ?? "float", i = r === "float", a = (n) => r === "depth" ? L(e, {
260
+ function le(e, t, n) {
261
+ let r = t.sampleType ?? "float", i = r === "float", a = (n) => r === "depth" ? V(e, {
206
262
  compare: "less-equal",
207
263
  ...t.sampler
208
- }) : i ? t.sampler || !n ? L(e, t.sampler) : n : L(e, {
264
+ }) : i ? t.sampler || !n ? V(e, t.sampler) : n : V(e, {
209
265
  ...t.sampler,
210
266
  magFilter: "nearest",
211
267
  minFilter: "nearest",
@@ -213,19 +269,19 @@ function se(e, t, n) {
213
269
  }), o = t.texture;
214
270
  if (o && typeof o != "function" && typeof o.bind == "function") {
215
271
  let n = o.bind(e, !0);
216
- return n ? [n[0], a(n[1])] : [R(e, t), a()];
272
+ return n ? [n[0], a(n[1])] : [H(e, t), a()];
217
273
  }
218
- if (!o) return [R(e, t), a()];
219
- let s = j.get(o);
220
- if (s || j.set(o, s = f(o, "RawShaderMaterial texture", "assign a new texture", e)), o = p(s, e, n) ?? null, !o) return [R(e, t), a()];
274
+ if (!o) return [H(e, t), a()];
275
+ let s = F.get(o);
276
+ if (s || F.set(o, s = f(o, "RawShaderMaterial texture", "assign a new texture", e)), o = p(s, e, n) ?? null, !o) return [H(e, t), a()];
221
277
  let c = o;
222
278
  if (typeof o.createView == "function") {
223
- let e = o, n = t.dimension ?? "2d", r = A.get(e);
224
- r || A.set(e, r = /* @__PURE__ */ new Map()), c = r.get(n) ?? e.createView({ dimension: n }), r.set(n, c);
279
+ let e = o, n = t.dimension ?? "2d", r = P.get(e);
280
+ r || P.set(e, r = /* @__PURE__ */ new Map()), c = r.get(n) ?? e.createView({ dimension: n }), r.set(n, c);
225
281
  }
226
282
  return [c, a()];
227
283
  }
228
- var z = {
284
+ var U = {
229
285
  normal: h,
230
286
  additive: {
231
287
  color: {
@@ -275,75 +331,67 @@ var z = {
275
331
  operation: "add"
276
332
  }
277
333
  }
278
- }, ce = 0, B = class {
334
+ }, ue = 0, W = class {
279
335
  constructor(e) {
280
- if (this.gpu = /* @__PURE__ */ new Map(), this.revision = 0, this.compiled = 0, this.vertexCode = "", this.vertexName = "", this.fragmentName = "", !e || typeof e != "object") throw TypeError("RawShaderMaterial needs {vertexShader, ...}");
281
- if (this.name = e.name ?? "raw:" + ce++, this.entries = {
336
+ if (this.gpu = /* @__PURE__ */ new Map(), this.revision = 0, this.compiled = 0, this.uniformChanges = 0, this.vertexCode = "", this.vertexName = "", this.fragmentName = "", !e || typeof e != "object") throw TypeError("RawShaderMaterial needs {vertexShader, ...}");
337
+ if (this.name = e.name ?? "raw:" + ue++, this.entries = {
282
338
  vertex: e.vertexEntry,
283
339
  fragment: e.fragmentEntry
284
- }, this.transparent = e.transparent ?? !1, this.blending = e.blending ?? "normal", this.depthTest = e.depthTest ?? !0, this.depthCompare = e.depthCompare ?? "greater-equal", this.depthBias = e.depthBias ?? 0, this.depthBiasSlopeScale = e.depthBiasSlopeScale ?? 0, this.alphaToCoverage = e.alphaToCoverage ?? !1, this.depthWrite = e.depthWrite ?? !0, this.cull = e.cull ?? "back", this.colorWrite = e.colorWrite ?? !0, this.wireframe = e.wireframe ?? !1, this.gbufferName = e.gbufferEntry, this.velocityName = e.velocityEntry, this.groups = e.groups ?? [], this.groups.length > 2 || this.groups.some((e) => typeof e != "function")) throw TypeError("RawShaderMaterial groups must be at most two functions of the device, for @group(2) and @group(3)");
340
+ }, this.transparent = e.transparent ?? !1, this.blending = e.blending ?? "normal", this.depthTest = e.depthTest ?? !0, this.depthCompare = e.depthCompare ?? "greater-equal", this.depthBias = e.depthBias ?? 0, this.depthBiasSlopeScale = e.depthBiasSlopeScale ?? 0, this.alphaToCoverage = e.alphaToCoverage ?? !1, this.depthWrite = e.depthWrite ?? !0, this.cull = e.cull ?? "back", this.colorWrite = e.colorWrite ?? !0, this.wireframe = e.wireframe ?? !1, this.gbufferName = e.gbufferEntry, this.captureName = e.captureEntry, this.velocityName = e.velocityEntry, this.groups = e.groups ?? [], this.groups.length > 2 || this.groups.some((e) => typeof e != "function")) throw TypeError("RawShaderMaterial groups must be at most two functions of the device, for @group(2) and @group(3)");
285
341
  this.setCode(e.vertexShader, e.fragmentShader);
286
- let t = [], n = 0, r = {};
287
- this.uniforms = r;
288
- for (let [i, a] of Object.entries(e.uniforms ?? {})) {
289
- if (C(i, "RawShaderMaterial uniform"), !a || typeof a != "object" || !("value" in a)) throw TypeError(`RawShaderMaterial uniform ${i} must be {value, type?}`);
290
- let { count: e } = a;
291
- if (e !== void 0 && (!Number.isInteger(e) || e < 1)) throw RangeError(`RawShaderMaterial uniform ${i} count must be a positive integer`);
292
- if (a.struct) {
293
- let o = [], s = 0;
294
- for (let [e, t] of Object.entries(a.struct)) {
295
- if (C(e, `RawShaderMaterial uniform ${i} field`), !T(t)) throw TypeError(`RawShaderMaterial uniform ${i} field ${e} needs a type from 'f32' to 'vec4f', their i32/u32 variants, 'mat3x3f' or 'mat4x4f'`);
296
- let n = E(s, y(t));
297
- o.push({
298
- name: e,
299
- type: t,
300
- offset: n
301
- }), s = n + b(t);
302
- }
303
- if (!o.length) throw TypeError(`RawShaderMaterial uniform ${i} struct needs at least one field`);
304
- let c = E(s, 16), l = E(n, 16);
305
- t.push({
306
- name: i,
307
- type: "Raw_" + i,
342
+ let t = [], n = [], r = 0, i = {};
343
+ this.uniforms = i;
344
+ for (let [a, o] of Object.entries(e.uniforms ?? {})) {
345
+ if (C(a, "RawShaderMaterial uniform"), !o || typeof o != "object" || !("value" in o)) throw TypeError(`RawShaderMaterial uniform ${a} must be {value, type?}`);
346
+ let { count: e } = o;
347
+ if (e !== void 0 && (!Number.isInteger(e) || e < 1)) throw RangeError(`RawShaderMaterial uniform ${a} count must be a positive integer`);
348
+ if (o.struct) {
349
+ let { fields: s, size: c } = ae(`RawShaderMaterial uniform ${a}`, o.struct, n), l = E(r, 16);
350
+ n.push({
351
+ type: "Raw_" + a,
352
+ fields: s
353
+ }), t.push({
354
+ name: a,
355
+ type: "Raw_" + a,
308
356
  offset: l,
309
357
  count: e,
310
358
  stride: c,
311
- fields: o
312
- }), n = l + c * (e ?? 1), r[i] = a;
359
+ fields: s
360
+ }), r = l + c * (e ?? 1), i[a] = o;
313
361
  continue;
314
362
  }
315
363
  if (e !== void 0) {
316
- let o = a.type;
317
- if (!o || !T(o)) throw TypeError(`RawShaderMaterial uniform ${i} is an array, so it needs type ('f32' to 'vec4f', i32/u32 variants, 'mat3x3f' or 'mat4x4f')`);
318
- let s = E(b(o), y(o));
319
- if (s % 16) throw TypeError(`RawShaderMaterial uniform ${i}: elements of a uniform array sit 16 bytes apart, so ${o} does not fit; use vec3, vec4, a matrix or a struct, or put it in a storage buffer`);
320
- let c = E(n, 16);
364
+ let n = o.type;
365
+ if (!n || !T(n)) throw TypeError(`RawShaderMaterial uniform ${a} is an array, so it needs type ('f32' to 'vec4f', i32/u32 variants, 'mat3x3f' or 'mat4x4f')`);
366
+ let s = E(b(n), y(n));
367
+ if (s % 16) throw TypeError(`RawShaderMaterial uniform ${a}: elements of a uniform array sit 16 bytes apart, so ${n} does not fit; use vec3, vec4, a matrix or a struct, or put it in a storage buffer`);
368
+ let c = E(r, 16);
321
369
  t.push({
322
- name: i,
323
- type: o,
370
+ name: a,
371
+ type: n,
324
372
  offset: c,
325
373
  count: e,
326
374
  stride: s
327
- }), n = c + s * e, r[i] = a;
375
+ }), r = c + s * e, i[a] = o;
328
376
  continue;
329
377
  }
330
- let o = a.value, s = typeof o == "number" ? 1 : typeof o == "string" ? 3 : o?.length, c = a.type ?? {
378
+ let s = o.value, c = typeof s == "number" ? 1 : typeof s == "string" ? 3 : s?.length, l = o.type ?? {
331
379
  1: "f32",
332
380
  2: "vec2f",
333
381
  3: "vec3f",
334
382
  4: "vec4f",
335
383
  9: "mat3x3f",
336
384
  16: "mat4x4f"
337
- }[s];
338
- if (!c || !T(c)) throw TypeError(`RawShaderMaterial uniform ${i} has no WGSL type; give type ('f32' to 'vec4f', i32/u32 variants, 'mat3x3f' or 'mat4x4f')`);
339
- let l = Math.ceil(n / y(c)) * y(c);
385
+ }[c];
386
+ if (!l || !T(l)) throw TypeError(`RawShaderMaterial uniform ${a} has no WGSL type; give type ('f32' to 'vec4f', i32/u32 variants, 'mat3x3f' or 'mat4x4f')`);
387
+ let u = Math.ceil(r / y(l)) * y(l);
340
388
  t.push({
341
- name: i,
342
- type: c,
343
- offset: l
344
- }), n = l + b(c), r[i] = a.type ? a : Object.assign(a, { type: c });
389
+ name: a,
390
+ type: l,
391
+ offset: u
392
+ }), r = u + b(l), i[a] = o.type ? o : Object.assign(o, { type: l });
345
393
  }
346
- this.members = t, this.size = t.length ? Math.ceil(n / 16) * 16 : 0, this.bytes = new Uint8Array(this.size), this.data = new DataView(this.bytes.buffer), this.textures = {};
394
+ this.members = t, this.structs = n, this.size = t.length ? Math.ceil(r / 16) * 16 : 0, this.bytes = new Uint8Array(this.size), this.data = new DataView(this.bytes.buffer), this.textures = {};
347
395
  for (let [t, n] of Object.entries(e.textures ?? {})) {
348
396
  C(t, "RawShaderMaterial texture");
349
397
  let e = m(n) && "texture" in n ? n : { texture: n };
@@ -386,30 +434,31 @@ var z = {
386
434
  setCode(e, t) {
387
435
  if (typeof e != "string" || !e.trim()) throw TypeError("RawShaderMaterial vertexShader must be WGSL source with a @vertex fn");
388
436
  if (t !== void 0 && typeof t != "string") throw TypeError("RawShaderMaterial fragmentShader must be WGSL source or undefined");
389
- let n = this.entries.vertex ?? w(e, "vertex"), r = this.entries.fragment ?? w(t ?? e, "fragment", this.gbufferName);
437
+ let n = this.entries.vertex ?? w(e, "vertex"), r = this.entries.fragment ?? w(t ?? e, "fragment", [this.gbufferName, this.captureName]);
390
438
  if (!n) throw TypeError(`RawShaderMaterial ${this.name} has no @vertex fn; add one or pass vertexEntry`);
391
439
  if (!r) throw TypeError(`RawShaderMaterial ${this.name} has no @fragment fn; add one to fragmentShader (or vertexShader) or pass fragmentEntry`);
392
440
  if (this.gbufferName && !RegExp(`@fragment\\s+fn\\s+${this.gbufferName}\\b`).test(t ?? e)) throw TypeError(`RawShaderMaterial ${this.name} has no @fragment fn ${this.gbufferName}; add it beside the colour fragment or drop gbufferEntry`);
441
+ if (this.captureName && !RegExp(`@fragment\\s+fn\\s+${this.captureName}\\b`).test(t ?? e)) throw TypeError(`RawShaderMaterial ${this.name} has no @fragment fn ${this.captureName}; add it beside the colour fragment or drop captureEntry`);
393
442
  if (this.velocityName && !RegExp(`@vertex\\s+fn\\s+${this.velocityName}\\b`).test(e)) throw TypeError(`RawShaderMaterial ${this.name} has no @vertex fn ${this.velocityName}; add it to vertexShader or drop velocityEntry`);
394
443
  this.vertexCode = e, this.fragmentCode = t, this.vertexName = n, this.fragmentName = r, this.error = void 0, this.revision++;
395
444
  for (let e of this.gpu.values()) e.modules.clear(), e.pipelines.clear();
396
445
  }
397
- prelude(e) {
398
- let t = [D], n = e?.layout ?? [];
399
- n.length && t.push(`struct Attributes {\n${n.map((e, t) => ` @location(${t}) ${e.name}:${e.type},`).join("\n")}\n}`);
400
- for (let e of this.members) e.fields && t.push(`struct ${e.type} {\n${e.fields.map((e, t) => ` ${t ? "" : "@align(16) "}${e.name}:${e.type},`).join("\n")}\n}`);
401
- this.velocityName && t.push(O), this.members.length && t.push(`struct Uniforms {\n${this.members.map((e) => ` ${e.name}:${e.count === void 0 ? e.type : `array<${e.type},${e.count}>`},`).join("\n")}\n}\n@group(1) @binding(0) var<uniform> uniforms:Uniforms;`), Object.entries(this.textures).forEach(([e, n], r) => {
446
+ prelude(e, t = !1) {
447
+ let n = [D], r = e?.layout ?? [];
448
+ r.length && n.push(`struct Attributes {\n${r.map((e, t) => ` @location(${t}) ${e.name}:${e.type},`).join("\n")}\n}`);
449
+ for (let e of this.structs) n.push(`struct ${e.type} {\n${e.fields.map((e, t) => ` ${t ? "" : "@align(16) "}${e.name}:${e.count === void 0 ? e.type : `array<${e.type},${e.count}>`},`).join("\n")}\n}`);
450
+ this.velocityName && n.push(ee), (this.captureName || /\bmargoCapture\s*\(/.test(this.fragmentCode ?? this.vertexCode)) && n.push(t ? O : O + k), this.members.length && n.push(`struct Uniforms {\n${this.members.map((e) => ` ${e.name}:${e.count === void 0 ? e.type : `array<${e.type},${e.count}>`},`).join("\n")}\n}\n@group(1) @binding(0) var<uniform> uniforms:Uniforms;`), Object.entries(this.textures).forEach(([e, t], r) => {
402
451
  let i = {
403
452
  float: "f32",
404
453
  "unfilterable-float": "f32",
405
454
  sint: "i32",
406
455
  uint: "u32",
407
456
  depth: ""
408
- }[n.sampleType ?? "float"], a = (n.dimension ?? "2d").replace("-", "_");
409
- t.push(`@group(1) @binding(${1 + 2 * r}) var ${e}:texture_${i ? a + "<" + i + ">" : "depth_" + a};\n@group(1) @binding(${2 + 2 * r}) var ${e}Sampler:sampler${i ? "" : "_comparison"};`);
457
+ }[t.sampleType ?? "float"], a = (t.dimension ?? "2d").replace("-", "_");
458
+ n.push(`@group(1) @binding(${1 + 2 * r}) var ${e}:texture_${i ? a + "<" + i + ">" : "depth_" + a};\n@group(1) @binding(${2 + 2 * r}) var ${e}Sampler:sampler${i ? "" : "_comparison"};`);
410
459
  });
411
- let r = 1 + 2 * Object.keys(this.textures).length;
412
- return Object.entries(this.storage).forEach(([e, n], i) => t.push(`@group(1) @binding(${r + i}) var<storage,${n.access ?? "read"}> ${e}:array<${n.type}>;`)), t.join("\n") + "\n";
460
+ let i = 1 + 2 * Object.keys(this.textures).length;
461
+ return Object.entries(this.storage).forEach(([e, t], r) => n.push(`@group(1) @binding(${i + r}) var<storage,${t.access ?? "read"}> ${e}:array<${t.type}>;`)), n.join("\n") + "\n";
413
462
  }
414
463
  code(e, t) {
415
464
  return this.prelude(t) + (e === "fragment" ? this.fragmentCode ?? this.vertexCode : this.vertexCode);
@@ -428,8 +477,8 @@ var z = {
428
477
  blend() {
429
478
  let e = this.blending;
430
479
  if (typeof e != "string") return e;
431
- if (!(e in z) && e !== "none") throw TypeError(`RawShaderMaterial ${this.name} blending must be none, normal, additive, subtractive, multiply, premultiplied or a GPUBlendState`);
432
- return e === "normal" && !this.transparent ? void 0 : z[e];
480
+ if (!(e in U) && e !== "none") throw TypeError(`RawShaderMaterial ${this.name} blending must be none, normal, additive, subtractive, multiply, premultiplied or a GPUBlendState`);
481
+ return e === "normal" && !this.transparent ? void 0 : U[e];
433
482
  }
434
483
  prepare(e, t, n) {
435
484
  n && (this.drawnBy = n);
@@ -438,27 +487,27 @@ var z = {
438
487
  let t = Object.values(this.textures), n = [];
439
488
  this.size && n.push({
440
489
  binding: 0,
441
- visibility: F(),
490
+ visibility: z(),
442
491
  buffer: { type: "uniform" }
443
492
  }), t.forEach((e, t) => {
444
493
  let r = e.sampleType ?? "float";
445
494
  n.push({
446
495
  binding: 1 + 2 * t,
447
- visibility: F(),
496
+ visibility: z(),
448
497
  texture: {
449
498
  sampleType: r,
450
499
  viewDimension: e.dimension ?? "2d"
451
500
  }
452
501
  }, {
453
502
  binding: 2 + 2 * t,
454
- visibility: F(),
503
+ visibility: z(),
455
504
  sampler: { type: r === "float" ? "filtering" : r === "depth" ? "comparison" : "non-filtering" }
456
505
  });
457
506
  }), Object.values(this.storage).forEach((e, r) => {
458
507
  let i = (e.access ?? "read") === "read";
459
508
  n.push({
460
509
  binding: 1 + 2 * t.length + r,
461
- visibility: i ? F() : GPUShaderStage.FRAGMENT,
510
+ visibility: i ? z() : GPUShaderStage.FRAGMENT,
462
511
  buffer: { type: i ? "read-only-storage" : "storage" }
463
512
  });
464
513
  });
@@ -469,7 +518,7 @@ var z = {
469
518
  r = {
470
519
  layout: a,
471
520
  groupLayouts: o,
472
- pipelineLayout: e.createPipelineLayout({ bindGroupLayouts: [I(e), ...o] }),
521
+ pipelineLayout: e.createPipelineLayout({ bindGroupLayouts: [B(e), ...o] }),
473
522
  bound: [],
474
523
  extras: i.map((e) => e.group),
475
524
  modules: /* @__PURE__ */ new Map(),
@@ -487,9 +536,9 @@ var z = {
487
536
  }
488
537
  if (r.layout) {
489
538
  let t = this.size ? [r.buffer] : [], i = Object.values(this.textures), a = n?.engine;
490
- for (let n of i) t.push(...se(e, n, a));
539
+ for (let n of i) t.push(...le(e, n, a));
491
540
  let o = Object.values(this.storage);
492
- for (let n of o) t.push(oe(e, n, a));
541
+ for (let n of o) t.push(ce(e, n, a));
493
542
  if (!r.group || t.some((e, t) => e !== r.bound[t])) {
494
543
  r.bound = t;
495
544
  let n = [], a = 0;
@@ -516,17 +565,28 @@ var z = {
516
565
  }
517
566
  return r;
518
567
  }
568
+ uniformVersion() {
569
+ if (!this.size) return 0;
570
+ for (let e of this.members) this.write(e);
571
+ let e = this.uniformSeen;
572
+ return (!e || e.some((e, t) => e !== this.bytes[t])) && ((this.uniformSeen ??= new Uint8Array(this.size)).set(this.bytes), e && this.uniformChanges++), this.uniformChanges;
573
+ }
519
574
  write(e) {
520
- let t = this.uniforms[e.name]?.value;
521
- if (e.count === void 0 && !e.fields) return this.put(e.type, e.offset, t, e.name);
522
- let n = _(e.type), r = t, i = e.count !== void 0 && !e.fields && typeof r?.[0] == "number", a = e.count ?? 1;
523
- if ((e.count === void 0 ? 1 : i ? r.length / n : r?.length) !== a) throw RangeError(`RawShaderMaterial ${this.name} uniform ${e.name} needs ${a} element${a > 1 ? "s" : ""}; assign a matching value`);
524
- for (let o = 0; o < a; o++) {
525
- let a = e.count === void 0 ? t : i ? Array.prototype.slice.call(r, o * n, (o + 1) * n) : r[o], s = e.offset + o * e.stride, c = e.count === void 0 ? e.name : `${e.name}[${o}]`;
526
- if (!e.fields) this.put(e.type, s, a, c);
527
- else for (let t of e.fields) this.put(t.type, s + t.offset, a?.[t.name], `${c}.${t.name}`);
575
+ this.store(e, e.offset, this.uniforms[e.name]?.value, e.name);
576
+ }
577
+ store(e, t, n, r) {
578
+ if (e.count === void 0 && !e.fields) return this.put(e.type, t, n, r);
579
+ if (e.count === void 0) return this.fields(e, t, n, r);
580
+ let i = _(e.type), a = n, o = !e.fields && typeof a?.[0] == "number";
581
+ if ((o ? a.length / i : a?.length) !== e.count) throw RangeError(`RawShaderMaterial ${this.name} uniform ${r} needs ${e.count} element${e.count > 1 ? "s" : ""}; assign a matching value`);
582
+ for (let n = 0; n < e.count; n++) {
583
+ let s = o ? Array.prototype.slice.call(a, n * i, (n + 1) * i) : a[n], c = t + n * e.stride;
584
+ e.fields ? this.fields(e, c, s, `${r}[${n}]`) : this.put(e.type, c, s, `${r}[${n}]`);
528
585
  }
529
586
  }
587
+ fields(e, t, n, r) {
588
+ for (let i of e.fields) this.store(i, t + i.offset, n?.[i.name], `${r}.${i.name}`);
589
+ }
530
590
  put(e, t, n, r) {
531
591
  let i = _(e), o = typeof n == "number" && i === 1 ? [n] : (typeof n == "string" || typeof n == "number") && e === "vec3f" ? Array.from(a(n)) : typeof n == "object" && n ? Array.from(n) : [];
532
592
  if (o.length !== i || o.some((e) => !Number.isFinite(e))) throw RangeError(`RawShaderMaterial ${this.name} uniform ${r} needs ${i} finite number${i > 1 ? "s" : ""} for ${e}; assign a matching value`);
@@ -539,15 +599,20 @@ var z = {
539
599
  get writesGBuffer() {
540
600
  return !!this.gbufferName;
541
601
  }
542
- target(e, t, n) {
543
- let r = t?.descriptor.depthStencil?.format;
602
+ captureCode(e, t) {
603
+ let n = this.prelude(e, !0) + (this.fragmentCode ?? this.vertexCode), r = t.declarations(n);
604
+ if (!/fn\s+margoCapture\s*\(\s*\w+\s*:\s*MargoMaterial\s*\)/.test(r)) throw new o("unsupported", `RawShaderMaterial ${this.name}: this effect's capture takes no MargoMaterial; add raw meshes with captureEntry to SSR, SSGI, SceneTargets or LightBounce`);
605
+ return this.prelude(e, !0) + r + "\n" + (this.fragmentCode ?? this.vertexCode);
606
+ }
607
+ target(e, t, n, r = "rg16float", i) {
608
+ let a = t?.descriptor.depthStencil?.format;
544
609
  if (e === "shadow") return {
545
610
  entry: /\bdiscard\b/.test(this.fragmentCode ?? this.vertexCode) ? this.fragmentName : void 0,
546
611
  targets: [],
547
612
  depthStencil: {
548
613
  format: "depth32float",
549
614
  depthWriteEnabled: !0,
550
- depthCompare: "less-equal"
615
+ depthCompare: n
551
616
  }
552
617
  };
553
618
  if (e === "pick") return {
@@ -562,32 +627,53 @@ var z = {
562
627
  };
563
628
  if (e === "velocity") return {
564
629
  entry: "margoVelocityFragment",
565
- targets: [{ format: "rg16float" }, { format: "r32float" }],
630
+ targets: [{ format: r }, { format: "r32float" }],
566
631
  depthStencil: {
567
- format: r,
632
+ format: a,
568
633
  depthWriteEnabled: !1,
569
634
  depthCompare: "equal"
570
635
  }
571
636
  };
637
+ if (e === "captureDepth") return {
638
+ entry: this.fragmentName,
639
+ targets: (i?.targets ?? []).map((e) => ({
640
+ format: e.format,
641
+ writeMask: 0
642
+ })),
643
+ depthStencil: {
644
+ format: a,
645
+ depthWriteEnabled: !0,
646
+ depthCompare: "greater-equal"
647
+ }
648
+ };
649
+ if (e === "capture") return {
650
+ entry: this.captureName,
651
+ targets: [...i?.targets ?? []],
652
+ depthStencil: {
653
+ format: a,
654
+ depthWriteEnabled: !0,
655
+ depthCompare: "greater-equal"
656
+ }
657
+ };
572
658
  if (e === "gbuffer") return {
573
659
  entry: this.gbufferName,
574
660
  targets: [{ format: "rgba16float" }, { format: "rgba16float" }],
575
661
  depthStencil: {
576
- format: r,
662
+ format: a,
577
663
  depthWriteEnabled: !1,
578
664
  depthCompare: n
579
665
  }
580
666
  };
581
- let i = this.blend();
667
+ let o = this.blend();
582
668
  return {
583
669
  entry: this.fragmentName,
584
670
  targets: [{
585
671
  format: t.format,
586
- ...i ? { blend: i } : {},
672
+ ...o ? { blend: o } : {},
587
673
  writeMask: this.colorWrite ? 15 : 0
588
674
  }],
589
- depthStencil: r && {
590
- format: r,
675
+ depthStencil: a && {
676
+ format: a,
591
677
  depthWriteEnabled: this.depthWrite,
592
678
  depthCompare: this.depthTest ? this.depthCompare : "always",
593
679
  ...this.bias()
@@ -600,72 +686,72 @@ var z = {
600
686
  depthBiasSlopeScale: this.depthBiasSlopeScale
601
687
  } : {};
602
688
  }
603
- pipeline(e, t, n, r, i, a, s = "equal") {
604
- let c = r.drawTopology, l = c.endsWith("strip") && r.indexFormat, u = a?.descriptor.multisample?.count ?? 1, d = a?.descriptor.depthStencil?.format, f = `${i}|${r.layoutKey}|${c}|${l || ""}|${a?.format}|${u}|${d}|${s}|${this.state()}`, p = t.pipelines.get(f);
605
- if (p) return p.pipeline;
606
- p = { state: "pending" }, t.pipelines.set(f, p);
607
- let m = (e) => {
608
- let i = e + "|" + r.layoutKey, a = t.modules.get(i);
689
+ pipeline(e, t, n, r, i, a, s = "equal", c = "rg16float", l) {
690
+ let u = i === "capture" && l ? this.captureCode(r, l) : void 0, d = (u === void 0 ? "" : M(u)) + (l ? "|" + l.targets.map((e) => e.format).join(",") : ""), f = r.drawTopology, p = f.endsWith("strip") && r.indexFormat, m = a?.descriptor.multisample?.count ?? 1, h = a?.descriptor.depthStencil?.format, g = `${i}|${r.layoutKey}|${f}|${p || ""}|${a?.format}|${m}|${h}|${s}|${c}|${d}|${this.state()}`, _ = t.pipelines.get(g);
691
+ if (_) return _.pipeline;
692
+ _ = { state: "pending" }, t.pipelines.set(g, _);
693
+ let v = (e) => {
694
+ let i = e + "|" + r.layoutKey + (e === "capture" ? "|" + M(u) : ""), a = t.modules.get(i);
609
695
  if (!a) {
610
- let o = e === "pick" ? this.prelude(r) + te : e === "velocity" ? this.code("vertex", r) + ee : this.code(e, r);
696
+ let o = e === "pick" ? this.prelude(r) + ne : e === "velocity" ? this.code("vertex", r) + te : e === "capture" ? u : this.code(e, r);
611
697
  a = n.createShaderModule({
612
698
  label: `shader:raw:${this.name}:${e}`,
613
699
  code: o
614
- }), t.modules.set(i, a), V.set(a, a.getCompilationInfo?.().catch(() => void 0) ?? Promise.resolve(void 0));
700
+ }), t.modules.set(i, a), G.set(a, a.getCompilationInfo?.().catch(() => void 0) ?? Promise.resolve(void 0));
615
701
  }
616
702
  return a;
617
703
  };
618
704
  n.pushErrorScope?.("validation");
619
- let { entry: h, targets: g, depthStencil: _ } = this.target(i, a, s), v = i === "velocity", y = m(v ? "velocity" : "vertex"), b = i === "pick" ? m("pick") : v || this.fragmentCode === void 0 ? y : m("fragment"), x = n.popErrorScope?.(), S = {
705
+ let { entry: y, targets: b, depthStencil: x } = this.target(i, a, s, c, l), S = i === "velocity", C = v(S ? "velocity" : "vertex"), w = i === "pick" ? v("pick") : i === "capture" ? v("capture") : S || this.fragmentCode === void 0 ? C : v("fragment"), T = n.popErrorScope?.(), E = {
620
706
  label: "shader:raw:" + this.name,
621
- layout: v ? t.velocityLayout ??= n.createPipelineLayout({ bindGroupLayouts: [I(n, !0), ...t.groupLayouts] }) : t.pipelineLayout,
707
+ layout: S ? t.velocityLayout ??= n.createPipelineLayout({ bindGroupLayouts: [B(n, !0), ...t.groupLayouts] }) : t.pipelineLayout,
622
708
  vertex: {
623
- module: y,
624
- entryPoint: v ? this.velocityName : this.vertexName,
709
+ module: C,
710
+ entryPoint: S ? this.velocityName : this.vertexName,
625
711
  buffers: r.buffers()
626
712
  },
627
- ...h ? { fragment: {
628
- module: b,
629
- entryPoint: h,
630
- targets: g
713
+ ...y ? { fragment: {
714
+ module: w,
715
+ entryPoint: y,
716
+ targets: b
631
717
  } } : {},
632
718
  primitive: {
633
- topology: c,
634
- cullMode: i === "shadow" || v ? "none" : this.cull,
635
- ...l ? { stripIndexFormat: l } : {}
719
+ topology: f,
720
+ cullMode: i === "shadow" || S ? "none" : this.cull,
721
+ ...p ? { stripIndexFormat: p } : {}
636
722
  },
637
- ..._ && { depthStencil: c.startsWith("triangle") ? _ : {
638
- ..._,
723
+ ...x && { depthStencil: f.startsWith("triangle") ? x : {
724
+ ...x,
639
725
  depthBias: 0,
640
726
  depthBiasSlopeScale: 0
641
727
  } },
642
728
  multisample: {
643
- count: u,
644
- ...i === "color" && u > 1 && this.alphaToCoverage ? { alphaToCoverageEnabled: !0 } : {}
729
+ count: m,
730
+ ...i === "color" && m > 1 && this.alphaToCoverage ? { alphaToCoverageEnabled: !0 } : {}
645
731
  }
646
- }, C = p;
647
- if (typeof n.createRenderPipelineAsync != "function" || a && !d) return C.pipeline = n.createRenderPipeline(S), C.state = "ready", this.compiled++, C.pipeline;
648
- let w = this.prelude(r).split("\n").length - 1, T = this.revision, E = async (e) => {
649
- if (C.state = "failed", T !== this.revision) return;
732
+ }, D = _;
733
+ if (typeof n.createRenderPipelineAsync != "function" || a && !h || i === "capture" || i === "captureDepth") return D.pipeline = n.createRenderPipeline(E), D.state = "ready", this.compiled++, D.pipeline;
734
+ let O = (u === void 0 ? this.prelude(r) : u.slice(0, u.length - (this.fragmentCode ?? this.vertexCode).length)).split("\n").length - 1, k = this.revision, A = async (e) => {
735
+ if (D.state = "failed", k !== this.revision) return;
650
736
  let t = e?.message ?? String(e);
651
- for (let [e, n] of [["vertex", y], ["fragment", b]]) {
652
- let r = (await V.get(n))?.messages.find((e) => e.type === "error");
737
+ for (let [e, n] of [["vertex", C], ["fragment", w]]) {
738
+ let r = (await G.get(n))?.messages.find((e) => e.type === "error");
653
739
  if (r) {
654
- let n = r.lineNum - w;
740
+ let n = r.lineNum - O;
655
741
  t = `${e}Shader ${n > 0 ? `line ${n}:${r.linePos}` : `prelude line ${r.lineNum}`}: ${r.message}`;
656
742
  break;
657
743
  }
658
744
  }
659
745
  let n = new o("failed", `RawShaderMaterial ${this.name} did not compile (${t}); fix the WGSL and assign vertexShader/fragmentShader again`);
660
746
  this.error = n, this.onError ? this.onError(n) : console.error(n);
661
- }, D = Promise.all([x, n.createRenderPipelineAsync(S)]).then(([e, t]) => {
662
- if (e) return E(e);
663
- C.pipeline = t, C.state = "ready", this.compiled++;
664
- }).catch(E);
665
- e.track(D);
666
- }
667
- }, V = /* @__PURE__ */ new WeakMap(), H = /* @__PURE__ */ new WeakMap();
668
- function U(e, t, n, r) {
747
+ }, j = Promise.all([T, n.createRenderPipelineAsync(E)]).then(([e, t]) => {
748
+ if (e) return A(e);
749
+ D.pipeline = t, D.state = "ready", this.compiled++;
750
+ }).catch(A);
751
+ e.track(j);
752
+ }
753
+ }, G = /* @__PURE__ */ new WeakMap(), K = /* @__PURE__ */ new WeakMap();
754
+ function q(e, t, n, r) {
669
755
  let i = e.createBuffer({
670
756
  label: n,
671
757
  size: r.byteLength,
@@ -673,9 +759,9 @@ function U(e, t, n, r) {
673
759
  });
674
760
  return e.queue.writeBuffer(i, 0, r), i;
675
761
  }
676
- function W(e, t, n, r) {
677
- let i = H.get(e);
678
- i || H.set(e, i = /* @__PURE__ */ new Map());
762
+ function J(e, t, n, r) {
763
+ let i = K.get(e);
764
+ i || K.set(e, i = /* @__PURE__ */ new Map());
679
765
  let a = 2166136261;
680
766
  for (let e = 0; e < r.length; e++) a = Math.imul(a ^ r[e], 16777619);
681
767
  let o = `${t}:${r.length}:${a}`, s = i.get(o);
@@ -686,7 +772,7 @@ function W(e, t, n, r) {
686
772
  if (n === r.length) return e.users++, e;
687
773
  }
688
774
  let c = {
689
- buffer: U(e, t, n, r),
775
+ buffer: q(e, t, n, r),
690
776
  users: 1,
691
777
  usage: t,
692
778
  label: n,
@@ -695,27 +781,27 @@ function W(e, t, n, r) {
695
781
  };
696
782
  return s.push(c), c;
697
783
  }
698
- function G(e, t) {
784
+ function Y(e, t) {
699
785
  if (t.key === void 0) return;
700
- let n = H.get(e), r = n.get(t.key);
786
+ let n = K.get(e), r = n.get(t.key);
701
787
  r.splice(r.indexOf(t), 1), r.length || n.delete(t.key), t.key = t.words = void 0;
702
788
  }
703
- function K(e, t) {
704
- !t || --t.users || (G(e, t), t.buffer.destroy());
789
+ function X(e, t) {
790
+ !t || --t.users || (Y(e, t), t.buffer.destroy());
705
791
  }
706
- function q(e, t, n) {
707
- if (t.users === 1) return G(e, t), t.fresh = !1, t;
792
+ function Z(e, t, n) {
793
+ if (t.users === 1) return Y(e, t), t.fresh = !1, t;
708
794
  t.users--;
709
795
  let { usage: r, label: i } = t;
710
796
  return {
711
- buffer: U(e, r, i, n),
797
+ buffer: q(e, r, i, n),
712
798
  users: 1,
713
799
  usage: r,
714
800
  label: i,
715
801
  fresh: !0
716
802
  };
717
803
  }
718
- var J = class {
804
+ var de = class {
719
805
  constructor(e) {
720
806
  this.step = e, this.attributes = [], this.stride = 0, this.count = 0, this.capacity = 0, this.words = /* @__PURE__ */ new Uint32Array(), this.floats = /* @__PURE__ */ new Float32Array(), this.ints = /* @__PURE__ */ new Int32Array(), this.start = Infinity, this.end = 0, this.full = !0;
721
807
  }
@@ -735,13 +821,13 @@ var J = class {
735
821
  }
736
822
  upload(e, t) {
737
823
  if (!this.attributes.length) {
738
- K(e, t);
824
+ X(e, t);
739
825
  return;
740
826
  }
741
827
  let n = Math.max(4, this.capacity * this.stride);
742
- return !t || this.full || t.buffer.size < n ? (K(e, t), t = W(e, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST, "shader:raw:" + this.step, this.words)) : this.end > this.start && (t = q(e, t, this.words), t.fresh || e.queue.writeBuffer(t.buffer, this.start * this.stride, this.words.buffer, this.start * this.stride, (this.end - this.start) * this.stride)), this.full = !1, this.start = Infinity, this.end = 0, t;
828
+ return !t || this.full || t.buffer.size < n ? (X(e, t), t = J(e, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST, "shader:raw:" + this.step, this.words)) : this.end > this.start && (t = Z(e, t, this.words), t.fresh || e.queue.writeBuffer(t.buffer, this.start * this.stride, this.words.buffer, this.start * this.stride, (this.end - this.start) * this.stride)), this.full = !1, this.start = Infinity, this.end = 0, t;
743
829
  }
744
- }, Y = [
830
+ }, fe = [
745
831
  1,
746
832
  0,
747
833
  0,
@@ -758,16 +844,16 @@ var J = class {
758
844
  0,
759
845
  0,
760
846
  1
761
- ], X = class {
847
+ ], pe = class {
762
848
  constructor(e) {
763
849
  if (this.drawRange = {
764
850
  start: 0,
765
851
  count: Infinity
766
852
  }, this.streams = {
767
- vertex: new J("vertex"),
768
- instance: new J("instance")
769
- }, this.map = /* @__PURE__ */ new Map(), this.indices = null, this.indexDirty = !0, this.key = "", this.disposed = !1, this.changes = 0, this.world = /* @__PURE__ */ new Float32Array(16), this.object = /* @__PURE__ */ new Float32Array(28), !(e?.material instanceof B)) throw TypeError("RawMesh needs {material: new RawShaderMaterial(...)}");
770
- if (this.material = e.material, this.matrix = Float32Array.from(e.matrix ?? Y), this.matrix.length !== 16) throw RangeError("RawMesh matrix needs 16 numbers (column-major)");
853
+ vertex: new de("vertex"),
854
+ instance: new de("instance")
855
+ }, this.map = /* @__PURE__ */ new Map(), this.indices = null, this.indexDirty = !0, this.key = "", this.disposed = !1, this.changes = 0, this.world = /* @__PURE__ */ new Float32Array(16), this.object = /* @__PURE__ */ new Float32Array(28), !(e?.material instanceof W)) throw TypeError("RawMesh needs {material: new RawShaderMaterial(...)}");
856
+ if (this.material = e.material, this.matrix = Float32Array.from(e.matrix ?? fe), this.matrix.length !== 16) throw RangeError("RawMesh matrix needs 16 numbers (column-major)");
771
857
  this.mesh = e.mesh ?? null, this.visible = e.visible ?? !0, this.renderOrder = e.renderOrder ?? 0, this.instanceCount = e.instanceCount, this.vertexCount = e.vertexCount, this.topology = e.topology ?? "triangle-list", this.frustumCulled = e.frustumCulled ?? !0, this.bounds = e.bounds ?? null;
772
858
  for (let [t, n] of Object.entries(e.attributes ?? {})) this.define(t, n);
773
859
  this.restructure(), e.index && this.setIndex(e.index);
@@ -814,7 +900,7 @@ var J = class {
814
900
  setAttribute(e, t, n) {
815
901
  this.alive(), this.changed();
816
902
  let r = this.map.get(e);
817
- if (Z(t)) {
903
+ if (me(t)) {
818
904
  if (!r || r.type !== t.type || r.step !== (t.step ?? "vertex")) return r && this.streams[r.step].attributes.splice(this.streams[r.step].attributes.indexOf(r), 1), this.define(e, t), this.restructure(), this;
819
905
  t = t.data;
820
906
  }
@@ -842,7 +928,8 @@ var J = class {
842
928
  return this.indexDirty = !0, this;
843
929
  }
844
930
  get shadowVersion() {
845
- return this.changes + this.material.compiled;
931
+ let e = this.owner?.engine, t = e && this.worldMatrix(e), n = this.seenWorld;
932
+ return this.material !== this.seenMaterial && (this.seenMaterial && this.changes++, this.seenMaterial = this.material), t && (!n || n.some((e, n) => e !== t[n])) && (n && this.changes++, (this.seenWorld ??= /* @__PURE__ */ new Float32Array(16)).set(t)), this.changes + this.material.compiled + this.material.uniformVersion();
846
933
  }
847
934
  invalidateShadow() {
848
935
  this.changes++;
@@ -850,6 +937,9 @@ var J = class {
850
937
  drawShadow(e) {
851
938
  this.owner?.shadow(this, e);
852
939
  }
940
+ drawLocalShadow(e) {
941
+ this.owner?.localShadow(this, e);
942
+ }
853
943
  dispose() {
854
944
  this.release(), this.owner?.remove(this), this.disposed = !0;
855
945
  }
@@ -898,7 +988,7 @@ var J = class {
898
988
  return !1;
899
989
  }
900
990
  define(e, t) {
901
- if (C(e, "RawMesh attribute"), !Z(t) || !g.test(t.type)) throw TypeError(`RawMesh attribute ${e} needs {data, type} with type f32, vec2f-vec4f or their i32/u32 variants`);
991
+ if (C(e, "RawMesh attribute"), !me(t) || !g.test(t.type)) throw TypeError(`RawMesh attribute ${e} needs {data, type} with type f32, vec2f-vec4f or their i32/u32 variants`);
902
992
  let n = t.step ?? "vertex";
903
993
  if (n !== "vertex" && n !== "instance") throw TypeError(`RawMesh attribute ${e} step must be vertex or instance`);
904
994
  if (!this.map.has(e) && this.map.size >= 16) throw RangeError("RawMesh supports at most 16 attributes (the WebGPU vertex attribute limit); remove an attribute or pack them together.");
@@ -937,7 +1027,7 @@ var J = class {
937
1027
  e.vertex,
938
1028
  e.instance,
939
1029
  e.index
940
- ]) K(e.device, t);
1030
+ ]) X(e.device, t);
941
1031
  this.gpu = void 0, this.streams.vertex.full = this.streams.instance.full = this.indexDirty = !0;
942
1032
  }
943
1033
  }
@@ -955,7 +1045,7 @@ var J = class {
955
1045
  device: e,
956
1046
  object: e.createBuffer({
957
1047
  label: "shader:raw:mesh",
958
- size: re,
1048
+ size: ie,
959
1049
  usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
960
1050
  }),
961
1051
  groups: /* @__PURE__ */ new Map()
@@ -969,7 +1059,7 @@ var J = class {
969
1059
  t[16] = m * v, t[17] = h * v, t[18] = g * v, t[20] = (f * s - p * o) * v, t[21] = (p * a - d * s) * v, t[22] = (d * o - f * a) * v, t[24] = (o * u - s * l) * v, t[25] = (s * c - a * u) * v, t[26] = (a * l - o * c) * v, (!i || i.some((e, n) => !Object.is(e, t[n]))) && (e.queue.writeBuffer(r.object, 0, t), (r.written ??= /* @__PURE__ */ new Float32Array(28)).set(t));
970
1060
  }
971
1061
  r.group = r.groups.get(t), r.group || (r.group = e.createBindGroup({
972
- layout: I(e),
1062
+ layout: B(e),
973
1063
  entries: [{
974
1064
  binding: 0,
975
1065
  resource: { buffer: t }
@@ -979,12 +1069,12 @@ var J = class {
979
1069
  }]
980
1070
  }), r.groups.set(t, r.group)), r.vertex = this.streams.vertex.upload(e, r.vertex), r.instance = this.streams.instance.upload(e, r.instance);
981
1071
  let o = this.drawTopology !== this.topology, s = this.streams.vertex.attributes.length ? Math.min(this.streams.vertex.count, this.vertexCount ?? Infinity) : this.vertexCount ?? 0, c = o ? this.edges(s) : this.indices;
982
- if (r.wire !== o && (r.wire = o, this.indexDirty = !0), !c) K(e, r.index), r.index = void 0;
1072
+ if (r.wire !== o && (r.wire = o, this.indexDirty = !0), !c) X(e, r.index), r.index = void 0;
983
1073
  else if (this.indexDirty || !r.index) {
984
1074
  let t = Math.ceil(c.byteLength / 4) * 4 || 4, n = new Uint8Array(t);
985
1075
  n.set(new Uint8Array(c.buffer, c.byteOffset, c.byteLength));
986
1076
  let i = new Uint32Array(n.buffer);
987
- r.index?.users === 1 && r.index.buffer.size >= t ? (r.index = q(e, r.index, i), e.queue.writeBuffer(r.index.buffer, 0, n)) : (K(e, r.index), r.index = W(e, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST, "shader:raw:index", i));
1077
+ r.index?.users === 1 && r.index.buffer.size >= t ? (r.index = Z(e, r.index, i), e.queue.writeBuffer(r.index.buffer, 0, n)) : (X(e, r.index), r.index = J(e, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST, "shader:raw:index", i));
988
1078
  }
989
1079
  this.indexDirty = !1;
990
1080
  let l = this.streams.vertex, u = this.streams.instance, d = c ? c.length : l.attributes.length ? Math.min(l.count, this.vertexCount ?? Infinity) : this.vertexCount ?? 0, f = u.attributes.length ? Math.min(u.count, this.instanceCount ?? Infinity) : this.instanceCount ?? 1, p = Math.min(Math.max(0, Math.floor(this.drawRange.start) || 0), d), m = Math.min(Math.max(0, Math.floor(this.drawRange.count)), d - p);
@@ -1001,7 +1091,7 @@ var J = class {
1001
1091
  (i.index !== c || i.format !== o) && e.setIndexBuffer(i.index = c, i.format = o), e.drawIndexed(n, r, t);
1002
1092
  } else e.draw(n, r, t);
1003
1093
  }
1004
- }, Z = (e) => !!e && typeof e == "object" && "data" in e && typeof e.type == "string";
1094
+ }, me = (e) => !!e && typeof e == "object" && "data" in e && typeof e.type == "string";
1005
1095
  function Q(e, t, n) {
1006
1096
  let r = _(t), i = v(t);
1007
1097
  if (!e || typeof e.length != "number" || e.length % r) throw RangeError(`RawMesh attribute ${n} needs a multiple of ${r} numbers for ${t}`);
@@ -1015,16 +1105,16 @@ function $(e, t) {
1015
1105
  a.pipeline !== n && e.setPipeline(n = a.pipeline), e.setBindGroup(0, a.mesh.gpu.group), t && t !== r && (e.setBindGroup(1, r = t), a.gpu.extras.forEach((t, n) => e.setBindGroup(2 + n, t))), a.mesh.draw(e, a.call[0], a.call[1], a.call[2], i);
1016
1106
  }
1017
1107
  }
1018
- var le = class t {coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);
1108
+ var he = class e {coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);
1019
1109
  get pass() {
1020
1110
  return this.passes;
1021
1111
  }
1022
1112
  get kernel() {
1023
1113
  return this.engine;
1024
1114
  }
1025
- static attach(e, n) {__margoAssertCore(e,__margoCoreRequirement("0.1.0",import.meta.url));
1026
- let r = new t(n);
1027
- return e.use(r), r;
1115
+ static attach(t, n) {__margoAssertCore(t,__margoCoreRequirement("1.0.0",import.meta.url));
1116
+ let r = new e(n);
1117
+ return t.use(r), r;
1028
1118
  }
1029
1119
  constructor(e = {}) {
1030
1120
  if (this.stats = {
@@ -1032,11 +1122,11 @@ var le = class t {coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url
1032
1122
  drawCalls: 0,
1033
1123
  culled: 0,
1034
1124
  pending: 0
1035
- }, this.watchers = /* @__PURE__ */ new Set(), this.meshes = /* @__PURE__ */ new Set(), this.jobs = /* @__PURE__ */ new Set(), this.shadowCameras = [], this.shadowPass = 0, this.shadowWritten = [], this.passes = 0, this.cameraData = /* @__PURE__ */ new Float32Array(60), this.view = /* @__PURE__ */ new Float64Array(16), this.inverse = /* @__PURE__ */ new Float64Array(16), this.velocityStates = /* @__PURE__ */ new Map(), this.beforeData = /* @__PURE__ */ new Float32Array(36), this.name = e.name ?? "shader:raw", this.opaqueOrder = e.opaqueOrder ?? .5, this.transparentOrder = e.transparentOrder ?? 7, !this.name || typeof this.name != "string") throw TypeError("RawShaders name must be a non-empty string");
1125
+ }, this.watchers = /* @__PURE__ */ new Set(), this.meshes = /* @__PURE__ */ new Set(), this.jobs = /* @__PURE__ */ new Set(), this.shadowCameras = [], this.shadowPass = 0, this.shadowWritten = [], this.localCameras = [], this.localWritten = [], this.localSlots = /* @__PURE__ */ new Map(), this.passes = 0, this.cameraData = /* @__PURE__ */ new Float32Array(60), this.view = /* @__PURE__ */ new Float64Array(16), this.inverse = /* @__PURE__ */ new Float64Array(16), this.velocityStates = /* @__PURE__ */ new Map(), this.beforeData = /* @__PURE__ */ new Float32Array(72), this.captureCameras = [], this.captureSlots = /* @__PURE__ */ new Map(), this.disposers = /* @__PURE__ */ new Set(), this.name = e.name ?? "shader:raw", this.opaqueOrder = e.opaqueOrder ?? .5, this.transparentOrder = e.transparentOrder ?? 7, !this.name || typeof this.name != "string") throw TypeError("RawShaders name must be a non-empty string");
1036
1126
  if (!Number.isFinite(this.opaqueOrder) || !Number.isFinite(this.transparentOrder)) throw RangeError("RawShaders opaqueOrder and transparentOrder must be finite numbers");
1037
1127
  }
1038
1128
  add(e) {
1039
- if (!(e instanceof X)) throw TypeError("RawShaders.add needs a RawMesh");
1129
+ if (!(e instanceof pe)) throw TypeError("RawShaders.add needs a RawMesh");
1040
1130
  if (e.owner && e.owner !== this) throw new o("attached", "RawMesh already belongs to another RawShaders; remove it there first");
1041
1131
  e.alive(), e.owner = this, this.meshes.add(e);
1042
1132
  for (let t of this.watchers) t.added(e);
@@ -1058,10 +1148,10 @@ var le = class t {coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url
1058
1148
  };
1059
1149
  this.jobs.add(e), e.then(t, t);
1060
1150
  }
1061
- setup(t) {
1062
- if (this.engine && this.engine !== t) throw new o("attached", `${this.name} is attached to another engine; create a new RawShaders`);
1063
- if (!t.gpu) throw new o("unsupported", "RawShaders requires WebGPU; see https://margoengine.com/errors#webgpu");
1064
- this.engine = t, this.device = t.gpu ?? void 0, e.hold(t, this);
1151
+ setup(e) {
1152
+ if (this.engine && this.engine !== e) throw new o("attached", `${this.name} is attached to another engine; create a new RawShaders`);
1153
+ if (!e.gpu) throw new o("unsupported", "RawShaders requires WebGPU; see https://margoengine.com/errors#webgpu");
1154
+ this.engine = e, this.device = e.gpu ?? void 0, r.hold(e, this);
1065
1155
  }
1066
1156
  registerPasses(e) {
1067
1157
  e.add({
@@ -1077,9 +1167,20 @@ var le = class t {coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url
1077
1167
  onDeviceRestored(e) {
1078
1168
  this.release(), this.device = e.gpu ?? void 0;
1079
1169
  }
1170
+ setCapture(e) {
1171
+ if (!e || typeof e.declarations != "function" || typeof e.begin != "function" || !Array.isArray(e.targets)) throw TypeError("Invalid RawShaders capture hook; pass an object with declarations() and begin() functions and a targets array");
1172
+ return this.capture = e, () => {
1173
+ this.capture === e && (this.capture = void 0);
1174
+ };
1175
+ }
1176
+ onDispose(e) {
1177
+ if (typeof e != "function") throw TypeError("RawShaders onDispose needs a function");
1178
+ return this.disposers.add(e), () => this.disposers.delete(e);
1179
+ }
1080
1180
  dispose() {
1081
- let t = this.engine;
1082
- this.release(), this.engine = this.device = void 0, e.release(t, this), t?.sceneOf(this)?.removePlugin(this.name);
1181
+ let e = this.engine;
1182
+ for (let e of [...this.disposers]) e();
1183
+ this.disposers.clear(), this.release(), this.engine = this.device = void 0, r.release(e, this), e?.sceneOf(this)?.removePlugin(this.name);
1083
1184
  }
1084
1185
  [Symbol.dispose ?? Symbol()]() {
1085
1186
  this.dispose();
@@ -1089,8 +1190,12 @@ var le = class t {coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url
1089
1190
  for (let t of this.meshes) t.release(), (e && t.material.gpu.get(e))?.buffer?.destroy(), e && t.material.gpu.delete(e);
1090
1191
  this.camera?.destroy(), this.camera = void 0;
1091
1192
  for (let e of [...this.velocityStates.keys()]) this.releaseVelocity(e);
1092
- for (let e of this.shadowCameras) e.destroy();
1093
- this.shadowCameras.length = this.shadowWritten.length = 0, this.shadowEncoder = void 0;
1193
+ for (let e of [
1194
+ ...this.shadowCameras,
1195
+ ...this.localCameras,
1196
+ ...this.captureCameras
1197
+ ]) e?.destroy();
1198
+ this.captureCameras.length = 0, this.captureEncoder = void 0, this.captureSlots.clear(), this.shadowCameras.length = this.shadowWritten.length = 0, this.localCameras.length = this.localWritten.length = 0, this.localEncoder = void 0, this.localSlots.clear(), this.shadowEncoder = void 0;
1094
1199
  }
1095
1200
  cameraBuffer(e) {
1096
1201
  return e.createBuffer({
@@ -1100,23 +1205,23 @@ var le = class t {coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url
1100
1205
  });
1101
1206
  }
1102
1207
  writeCamera(e) {
1103
- let t = e.device;
1104
- this.camera ??= this.cameraBuffer(t);
1208
+ let n = e.device;
1209
+ this.camera ??= this.cameraBuffer(n);
1105
1210
  let r = e.format.includes("float") ? 0 : e.format.endsWith("-srgb") ? 2 : 1;
1106
- return t.queue.writeBuffer(this.camera, 0, this.cameraBlock(e.camera, e.camera.matrix, e.width, e.height, e.delta, r, n(e))), this.camera;
1211
+ return n.queue.writeBuffer(this.camera, 0, this.cameraBlock(e.camera, e.camera.matrix, e.width, e.height, e.delta, r, t(e))), this.camera;
1107
1212
  }
1108
- cameraBlock(t, n, r, i, a, o, s) {
1109
- let c = this.cameraData, u = l(this.view, t), d = this.inverse;
1213
+ cameraBlock(e, t, n, i, a, o, s) {
1214
+ let c = this.cameraData, u = l(this.view, e), d = this.inverse;
1110
1215
  for (let e = 0; e < 3; e++) {
1111
1216
  for (let t = 0; t < 3; t++) d[t * 4 + e] = u[e * 4 + t];
1112
1217
  d[12 + e] = -(u[e * 4] * u[12] + u[e * 4 + 1] * u[13] + u[e * 4 + 2] * u[14]), d[e * 4 + 3] = 0;
1113
1218
  }
1114
1219
  d[15] = 1, c.set(u, 0);
1115
- for (let e = 0; e < 4; e++) for (let t = 0; t < 4; t++) c[16 + e * 4 + t] = n[t] * d[e * 4] + n[4 + t] * d[e * 4 + 1] + n[8 + t] * d[e * 4 + 2] + n[12 + t] * d[e * 4 + 3];
1116
- return c.set(n, 32), c.set(t.position, 48), c[51] = e.find(this.engine)?.time ?? 0, c[52] = r, c[53] = i, c[54] = a, c[55] = o, s ? c.set(s, 56) : c.set([
1220
+ for (let e = 0; e < 4; e++) for (let n = 0; n < 4; n++) c[16 + e * 4 + n] = t[n] * d[e * 4] + t[4 + n] * d[e * 4 + 1] + t[8 + n] * d[e * 4 + 2] + t[12 + n] * d[e * 4 + 3];
1221
+ return c.set(t, 32), c.set(e.position, 48), c[51] = r.find(this.engine)?.time ?? 0, c[52] = n, c[53] = i, c[54] = a, c[55] = o, s ? c.set(s, 56) : c.set([
1117
1222
  0,
1118
1223
  0,
1119
- r,
1224
+ n,
1120
1225
  i
1121
1226
  ], 56), c;
1122
1227
  }
@@ -1124,30 +1229,40 @@ var le = class t {coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url
1124
1229
  return ++this.passes;
1125
1230
  }
1126
1231
  shadow(e, { context: t, pass: n, matrix: r, cascade: i }) {
1127
- let a = this.device, o = this.engine, s = e.material;
1128
- if (!a || !o || t.device !== a || !e.visible || s.transparent) return;
1129
- let c = e.worldMatrix(o);
1130
- if (!c || e.culled(c, r)) return;
1232
+ this.depthCaster(e, t, n, r, i, this.shadowCameras, this.shadowWritten, "less-equal");
1233
+ }
1234
+ localShadow(e, { context: t, pass: n, matrix: r, depthCompare: i = "greater" }) {
1235
+ if (i !== "greater" && i !== "less-equal") throw RangeError("Invalid local shadow depthCompare; pass 'greater' or 'less-equal'");
1236
+ this.localEncoder !== t.encoder && (this.localEncoder = t.encoder, this.localSlots.clear());
1237
+ let a = this.localSlots.get(n);
1238
+ a === void 0 && this.localSlots.set(n, a = this.localSlots.size), this.depthCaster(e, t, n, r, a, this.localCameras, this.localWritten, i);
1239
+ }
1240
+ depthCaster(e, t, n, r, i, a, o, s) {
1241
+ let c = this.device, l = this.engine, u = e.material;
1242
+ if (!c || !l || t.device !== c || !e.visible || u.transparent) return;
1243
+ let d = e.worldMatrix(l);
1244
+ if (!d || e.culled(d, r)) return;
1131
1245
  this.shadowEncoder !== t.encoder && (this.shadowEncoder = t.encoder, this.shadowPass = this.nextPass());
1132
- let l = this.shadowCameras[i] ??= this.cameraBuffer(a);
1133
- if (this.shadowWritten[i] !== t.encoder) {
1134
- this.shadowWritten[i] = t.encoder;
1246
+ let f = a[i] ??= this.cameraBuffer(c);
1247
+ if (o[i] !== t.encoder) {
1248
+ o[i] = t.encoder;
1135
1249
  let e = this.cameraBlock(t.camera, r, t.width, t.height, t.delta, 0);
1136
- e.set(Y, 0), e.set(r, 16), a.queue.writeBuffer(l, 0, e);
1250
+ e.set(fe, 0), e.set(r, 16), c.queue.writeBuffer(f, 0, e);
1137
1251
  }
1138
- let u = e.upload(a, l, c);
1139
- if (!u) return;
1140
- let d = s.prepare(a, this.shadowPass, this), f = s.pipeline(this, d, a, e, "shadow");
1141
- f && $(n, [{
1252
+ let p = e.upload(c, f, d);
1253
+ if (!p) return;
1254
+ let m = u.prepare(c, this.shadowPass, this), h = u.pipeline(this, m, c, e, "shadow", void 0, s);
1255
+ h && $(n, [{
1142
1256
  mesh: e,
1143
- pipeline: f,
1144
- gpu: d,
1145
- call: u,
1257
+ pipeline: h,
1258
+ gpu: m,
1259
+ call: p,
1146
1260
  distance: 0
1147
1261
  }]);
1148
1262
  }
1149
1263
  draw(e, t, n, r, i, a) {
1150
1264
  let o = e, s = this.device, c = this.engine;
1265
+ if (t === "capture") return this.drawCapture(o, s, c);
1151
1266
  if (t !== "occlusion" || !a || o.backend !== "webgpu" || !s || !c || o.device !== s) return;
1152
1267
  let l = this.nextPass(), u = [], d;
1153
1268
  for (let e of this.meshes) {
@@ -1169,67 +1284,101 @@ var le = class t {coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url
1169
1284
  }
1170
1285
  $(a.pass, u);
1171
1286
  }
1172
- drawVelocity(e, t) {
1173
- let r = t.context, i = this.device, a = this.engine;
1287
+ drawCapture(e, t, n) {
1288
+ let r = this.capture;
1289
+ if (!r || e.backend !== "webgpu" || !t || !n || e.device !== t) return;
1290
+ let i = this.nextPass(), a = [], o, s;
1291
+ for (let c of this.meshes) {
1292
+ let l = c.material;
1293
+ if (!c.visible || l.transparent || !l.depthWrite) continue;
1294
+ let u = c.worldMatrix(n);
1295
+ if (!u || c.culled(u, e.camera.matrix)) continue;
1296
+ s ??= r.begin(), o ??= this.captureCamera(e, t, s);
1297
+ let d = c.upload(t, o, u);
1298
+ if (!d) continue;
1299
+ let f = l.captureName ? "capture" : "captureDepth", p = l.prepare(t, i, this), m = l.pipeline(this, p, t, c, f, e, "greater-equal", void 0, r);
1300
+ m && a.push({
1301
+ mesh: c,
1302
+ pipeline: m,
1303
+ gpu: p,
1304
+ call: d,
1305
+ distance: 0
1306
+ });
1307
+ }
1308
+ s && $(s, a);
1309
+ }
1310
+ captureCamera(e, n, r) {
1311
+ this.captureEncoder !== e.encoder && (this.captureEncoder = e.encoder, this.captureSlots.clear());
1312
+ let i = this.captureSlots.get(r), a = i === void 0;
1313
+ i === void 0 && this.captureSlots.set(r, i = this.captureSlots.size);
1314
+ let o = this.captureCameras[i] ??= this.cameraBuffer(n);
1315
+ if (a) {
1316
+ let r = e.format.includes("float") ? 0 : e.format.endsWith("-srgb") ? 2 : 1;
1317
+ n.queue.writeBuffer(o, 0, this.cameraBlock(e.camera, e.camera.matrix, e.width, e.height, e.delta, r, t(e)));
1318
+ }
1319
+ return o;
1320
+ }
1321
+ drawVelocity(e, n) {
1322
+ let r = n.context, i = this.device, a = this.engine, o = n.targets?.[0]?.format;
1174
1323
  if (r.backend !== "webgpu" || !i || !a || r.device !== i || !this.camera) return;
1175
- let o = this.velocityStates.get(t.key);
1176
- o || this.velocityStates.set(t.key, o = {
1324
+ let s = this.velocityStates.get(n.key);
1325
+ s || this.velocityStates.set(n.key, s = {
1177
1326
  camera: this.cameraBuffer(i),
1178
1327
  frame: 0,
1179
1328
  meshes: /* @__PURE__ */ new Map()
1180
- }), o.frame++;
1181
- let s = t.camera, c = s.subarray(0, 16), l = this.nextPass(), u = [], d;
1329
+ }), s.frame++;
1330
+ let c = n.camera, l = n.relative, u = c.subarray(0, 16), d = this.nextPass(), f = [], p;
1182
1331
  for (let e of this.meshes) {
1183
- let t = e.material;
1184
- if (!e.visible || t.transparent || !t.velocityName) continue;
1185
- let f = e.worldMatrix(a);
1186
- if (!f || e.culled(f, c)) continue;
1187
- if (d === void 0) {
1188
- let e = this.cameraBlock(r.camera, c, r.width, r.height, r.delta, 0, n(r));
1189
- d = e[51], i.queue.writeBuffer(o.camera, 0, e);
1332
+ let n = e.material;
1333
+ if (!e.visible || n.transparent || !n.velocityName) continue;
1334
+ let m = e.worldMatrix(a);
1335
+ if (!m || e.culled(m, u)) continue;
1336
+ if (p === void 0) {
1337
+ let e = this.cameraBlock(r.camera, u, r.width, r.height, r.delta, 0, t(r));
1338
+ p = e[51], i.queue.writeBuffer(s.camera, 0, e);
1190
1339
  }
1191
- let p = e.upload(i, this.camera, f), m = e.gpu?.object;
1192
- if (!p || !m) continue;
1193
- let h = o.meshes.get(e);
1194
- if (!h || h.object !== m) {
1195
- h?.before.destroy();
1340
+ let h = e.upload(i, this.camera, m), g = e.gpu?.object;
1341
+ if (!h || !g) continue;
1342
+ let _ = s.meshes.get(e);
1343
+ if (!_ || _.object !== g) {
1344
+ _?.before.destroy();
1196
1345
  let t = i.createBuffer({
1197
1346
  label: "shader:raw:before",
1198
- size: 144,
1347
+ size: 288,
1199
1348
  usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
1200
1349
  });
1201
- h = {
1350
+ _ = {
1202
1351
  before: t,
1203
- object: m,
1352
+ object: g,
1204
1353
  world: /* @__PURE__ */ new Float32Array(16),
1205
1354
  frame: -1,
1206
1355
  group: i.createBindGroup({
1207
- layout: I(i, !0),
1356
+ layout: B(i, !0),
1208
1357
  entries: [
1209
- o.camera,
1210
- m,
1358
+ s.camera,
1359
+ g,
1211
1360
  t
1212
1361
  ].map((e, t) => ({
1213
1362
  binding: t,
1214
1363
  resource: { buffer: e }
1215
1364
  }))
1216
1365
  })
1217
- }, o.meshes.set(e, h);
1366
+ }, s.meshes.set(e, _);
1218
1367
  }
1219
- let g = h.frame === o.frame - 1 && s[34] > 0 && o.time !== void 0, _ = this.beforeData;
1220
- _.set(s.subarray(16, 32), 0), _.set(g ? h.world : f, 16), _[32] = g ? o.time : d, _[33] = +g, i.queue.writeBuffer(h.before, 0, _), h.world.set(f), h.frame = o.frame;
1221
- let v = t.prepare(i, l, this), y = t.pipeline(this, v, i, e, "velocity", r);
1222
- y && u.push({
1368
+ let v = _.frame === s.frame - 1 && c[34] > 0 && s.time !== void 0, y = this.beforeData;
1369
+ y.set(c.subarray(16, 32), 0), y.set(v ? _.world : m, 16), y[32] = v ? s.time : p, y[33] = +v, l?.length === 36 ? (y.set(l.subarray(0, 32), 36), y.set(l.subarray(32, 35), 68)) : (y.set(c.subarray(0, 32), 36), y[68] = y[69] = y[70] = 0), y[71] = 1, i.queue.writeBuffer(_.before, 0, y), _.world.set(m), _.frame = s.frame;
1370
+ let b = n.prepare(i, d, this), x = n.pipeline(this, b, i, e, "velocity", r, "equal", o);
1371
+ x && f.push({
1223
1372
  mesh: e,
1224
- pipeline: y,
1225
- gpu: v,
1226
- call: p,
1227
- group: h.group
1373
+ pipeline: x,
1374
+ gpu: b,
1375
+ call: h,
1376
+ group: _.group
1228
1377
  });
1229
1378
  }
1230
- d !== void 0 && (o.time = d);
1231
- let f = { slots: [] };
1232
- for (let t of u) e.setPipeline(t.pipeline), e.setBindGroup(0, t.group), t.gpu.group && (e.setBindGroup(1, t.gpu.group), t.gpu.extras.forEach((t, n) => e.setBindGroup(2 + n, t))), t.mesh.draw(e, t.call[0], t.call[1], t.call[2], f);
1379
+ p !== void 0 && (s.time = p);
1380
+ let m = { slots: [] };
1381
+ for (let t of f) e.setPipeline(t.pipeline), e.setBindGroup(0, t.group), t.gpu.group && (e.setBindGroup(1, t.gpu.group), t.gpu.extras.forEach((t, n) => e.setBindGroup(2 + n, t))), t.mesh.draw(e, t.call[0], t.call[1], t.call[2], m);
1233
1382
  }
1234
1383
  releaseVelocity(e) {
1235
1384
  let t = this.velocityStates.get(e);
@@ -1241,24 +1390,24 @@ var le = class t {coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url
1241
1390
  }
1242
1391
  execute(e, t) {
1243
1392
  if (t || (this.stats.meshes = this.stats.drawCalls = this.stats.culled = 0), e.backend !== "webgpu" || !this.device || !this.engine || e.device !== this.device || !this.meshes.size) return;
1244
- let n = this.device, i = this.engine, a = e.camera.position, o = [], s = this.nextPass(), c;
1245
- for (let r of this.meshes) {
1246
- let l = r.material;
1247
- if (!r.visible || l.transparent !== t) continue;
1248
- let u = r.worldMatrix(i);
1393
+ let r = this.device, i = this.engine, a = e.camera.position, o = [], s = this.nextPass(), c;
1394
+ for (let n of this.meshes) {
1395
+ let l = n.material;
1396
+ if (!n.visible || l.transparent !== t) continue;
1397
+ let u = n.worldMatrix(i);
1249
1398
  if (!u) continue;
1250
- if (r.culled(u, e.camera.matrix)) {
1399
+ if (n.culled(u, e.camera.matrix)) {
1251
1400
  this.stats.culled++;
1252
1401
  continue;
1253
1402
  }
1254
1403
  c ??= this.writeCamera(e);
1255
- let d = r.upload(n, c, u);
1404
+ let d = n.upload(r, c, u);
1256
1405
  if (!d) continue;
1257
- let f = l.prepare(n, s, this), p = l.pipeline(this, f, n, r, "color", e);
1258
- if (this.watchers.size && l.pipeline(this, f, n, r, "pick"), !p) continue;
1406
+ let f = l.prepare(r, s, this), p = l.pipeline(this, f, r, n, "color", e);
1407
+ if (this.watchers.size && l.pipeline(this, f, r, n, "pick"), !p) continue;
1259
1408
  let m = u[12] - a[0], h = u[13] - a[1], g = u[14] - a[2];
1260
1409
  o.push({
1261
- mesh: r,
1410
+ mesh: n,
1262
1411
  pipeline: p,
1263
1412
  gpu: f,
1264
1413
  call: d,
@@ -1281,10 +1430,10 @@ var le = class t {coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url
1281
1430
  ...l ? { stencilReadOnly: !0 } : {}
1282
1431
  }
1283
1432
  });
1284
- r(u, e), $(u, o), this.stats.meshes += o.length, this.stats.drawCalls += o.length, u.end();
1433
+ n(u, e), $(u, o), this.stats.meshes += o.length, this.stats.drawCalls += o.length, u.end();
1285
1434
  }
1286
- }, ue = class e {
1287
- static attach(t, n) {__margoAssertCore(t,__margoCoreRequirement("0.1.0",import.meta.url));
1435
+ }, ge = class e {
1436
+ static attach(t, n) {__margoAssertCore(t,__margoCoreRequirement("1.0.0",import.meta.url));
1288
1437
  if (!n.engine) throw new o("state", "Attach RawShaders to the engine before RawPicking.attach");
1289
1438
  let r = new e(n);
1290
1439
  r.remove = t.addOverlay(r), n.watchers.add(r);
@@ -1320,7 +1469,7 @@ var le = class t {coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url
1320
1469
  let u = s.upload(n, i, l);
1321
1470
  if (!u) continue;
1322
1471
  let d = c.prepare(n, a, t), f = c.pipeline(t, d, n, s, "pick");
1323
- f && (this.id[0] = e.firstId + this.hits.length, n.queue.writeBuffer(s.gpu.object, ne, this.id), this.hits.push(s), o.push({
1472
+ f && (this.id[0] = e.firstId + this.hits.length, n.queue.writeBuffer(s.gpu.object, re, this.id), this.hits.push(s), o.push({
1324
1473
  mesh: s,
1325
1474
  pipeline: f,
1326
1475
  gpu: d,
@@ -1348,4 +1497,4 @@ var le = class t {coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url
1348
1497
  }
1349
1498
  };
1350
1499
  //#endregion
1351
- export { f as a, p as c, le as i, u as l, ue as n, d as o, B as r, m as s, X as t };
1500
+ export { f as a, p as c, he as i, u as l, ge as n, d as o, W as r, m as s, pe as t };