@margoengine/inspector 0.0.0-stage → 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 -0
  2. package/NOTICE +4 -0
  3. package/README.md +622 -2
  4. package/dist/animation.d.ts +53 -0
  5. package/dist/animation.js +234 -0
  6. package/dist/color-D6qetPCJ.js +10 -0
  7. package/dist/color.d.ts +4 -0
  8. package/dist/debug-geometry-D61TEkP9.js +61 -0
  9. package/dist/debug-geometry.d.ts +15 -0
  10. package/dist/edit-state-Dm3G17js.js +4 -0
  11. package/dist/edit-state.d.ts +3 -0
  12. package/dist/edit.d.ts +105 -0
  13. package/dist/edit.js +379 -0
  14. package/dist/errors-D8rc8kzg.js +7 -0
  15. package/dist/frame-panel.d.ts +16 -0
  16. package/dist/frame.d.ts +264 -0
  17. package/dist/frame.js +881 -0
  18. package/dist/gizmo.d.ts +49 -0
  19. package/dist/gizmo.js +131 -0
  20. package/dist/gl.d.ts +89 -0
  21. package/dist/gl.js +284 -0
  22. package/dist/history.d.ts +65 -0
  23. package/dist/history.js +66 -0
  24. package/dist/index.d.ts +122 -0
  25. package/dist/index.js +490 -0
  26. package/dist/mesh-debug.d.ts +115 -0
  27. package/dist/mesh-debug.js +501 -0
  28. package/dist/mesh-source-BSQA_1GQ.js +31 -0
  29. package/dist/packages.d.ts +98 -0
  30. package/dist/packages.js +337 -0
  31. package/dist/remote-relay.d.ts +25 -0
  32. package/dist/remote-relay.js +64 -0
  33. package/dist/remote.d.ts +175 -0
  34. package/dist/remote.js +349 -0
  35. package/dist/resources.d.ts +30 -0
  36. package/dist/resources.js +42 -0
  37. package/dist/shaders.d.ts +122 -0
  38. package/dist/shaders.js +285 -0
  39. package/dist/snapshot.d.ts +47 -0
  40. package/dist/snapshot.js +90 -0
  41. package/dist/textures.d.ts +127 -0
  42. package/dist/textures.js +380 -0
  43. package/dist/tools.d.ts +101 -0
  44. package/dist/tools.js +220 -0
  45. package/dist/tweak.d.ts +86 -0
  46. package/dist/tweak.js +291 -0
  47. package/dist/view-rect-CTC0iGjf.js +23 -0
  48. package/dist/visibility-7_j5J9Nv.js +7 -0
  49. package/package.json +147 -4
@@ -0,0 +1,115 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel, Mesh as MeshHandle } from '@margoengine/core';
3
+ import { type Engine, type EnginePlugin, type FrameGraph } from '@margoengine/core/extension';
4
+ /** What a {@link MeshDebugView} shows. */
5
+ export type MeshDebugMode = 'shaded' | 'wireframe' | 'vertices' | 'wireframe-vertices' | 'uv0' | 'uv1' | 'vertex-colors' | 'material-ids';
6
+ /** `#rgb` or `#rrggbb` (sRGB), or linear `[r, g, b]` in 0..1. */
7
+ export type MeshDebugColor = string | readonly [number, number, number];
8
+ /** Options of {@link MeshDebugView}; every one is live through {@link MeshDebugView.set}. */
9
+ export interface MeshDebugViewOptions {
10
+ /**
11
+ * `'wireframe'` (every triangle edge), `'vertices'` (a dot on every vertex), `'wireframe-vertices'` (both), `'uv0'` or
12
+ * `'uv1'` (a checker over that UV set), `'vertex-colors'`, `'material-ids'` (one colour per material) or `'shaded'`
13
+ * (plain camera-lit shading). Default `'wireframe'`.
14
+ */
15
+ mode?: MeshDebugMode;
16
+ /**
17
+ * True keeps the mesh's own picture: lines and dots draw over it, and the checker, vertex colours, material colours
18
+ * and shading multiply it. False replaces the picture: camera-lit shading under the lines and dots, a lit checker or
19
+ * material colour, unlit vertex colours. `null` restores the default: true for the three wire and dot modes, false
20
+ * for the others.
21
+ */
22
+ multiply?: boolean | null;
23
+ /** Meshes to draw, from the view's scene; meshes without triangles are skipped. Default `null`: every mesh of it. */
24
+ meshes?: Iterable<MeshHandle> | null;
25
+ /** False draws nothing and frees the view's mesh buffers within two frames. Default true. */
26
+ enabled?: boolean;
27
+ /** Edge colour. Default `'#72e8cc'`. */
28
+ wireColor?: MeshDebugColor;
29
+ /** Edge width in drawing-buffer pixels, 0 to 64. Default 1. */
30
+ wireWidth?: number;
31
+ /** Vertex dot colour. Default `'#ffb326'`. */
32
+ vertexColor?: MeshDebugColor;
33
+ /** Vertex dot radius in drawing-buffer pixels, 0 to 64. Default 3. */
34
+ vertexRadius?: number;
35
+ /** Checker squares per UV unit along each axis, above 0 and at most 4096. Default 10. */
36
+ uvScale?: number;
37
+ /** The checker's two colours; the first covers the square at UV (0, 0). Default `['#f0f0f0', '#3a6ea5']`. */
38
+ uvColors?: readonly [MeshDebugColor, MeshDebugColor];
39
+ /** Surface colour of the camera-lit shading under `shaded`, wire and dot modes. Default `'#a0a0a0'`. */
40
+ diffuseColor?: MeshDebugColor;
41
+ /** Highlight colour of the camera-lit shading. Default `'#303030'`. */
42
+ specularColor?: MeshDebugColor;
43
+ /** Highlight exponent, 1 to 10000. Default 32. */
44
+ specularPower?: number;
45
+ /**
46
+ * Colours of the first materials of `'material-ids'`, in the order the view first draws them (at most 4096); later
47
+ * materials get generated hues. Default `[]`.
48
+ */
49
+ materialColors?: readonly MeshDebugColor[];
50
+ }
51
+ /** The settings in effect: every option filled in, `multiply` resolved for the mode. */
52
+ export type MeshDebugViewSettings = Readonly<Required<Omit<MeshDebugViewOptions, 'multiply' | 'meshes'>> & {
53
+ multiply: boolean;
54
+ meshes: readonly MeshHandle[] | null;
55
+ }>;
56
+ /**
57
+ * A debug view of mesh data: wireframe, vertex dots, a UV checker, vertex colours, material colours or plain camera-lit
58
+ * shading, over or in place of each mesh's picture. Draws core meshes and gltf/pbr nodes (also materials meshes), with
59
+ * their live skinned or morphed vertices and instance matrices, after the transparent surfaces.
60
+ *
61
+ * `MeshDebugView.attach(engine, { mode: 'uv0' })`; WebGPU or the WebGL2 compatibility layer.
62
+ * @throws TypeError or RangeError for an invalid option.
63
+ * @throws MargoError `'unsupported'` on native WebGL2, `'disposed'` after `dispose()`.
64
+ */
65
+ export declare class MeshDebugView implements EnginePlugin {
66
+ readonly name: string;
67
+ private settings;
68
+ /** The caller's `multiply`, null while the mode decides. */
69
+ private multiplied;
70
+ private colors;
71
+ private ids;
72
+ private nextId;
73
+ private frame;
74
+ private engine?;
75
+ private disposed;
76
+ private layout?;
77
+ private module?;
78
+ private single?;
79
+ private readonly pipelines;
80
+ private readonly records;
81
+ private readonly uploads;
82
+ private readonly values;
83
+ private readonly attachments;
84
+ constructor(options?: MeshDebugViewOptions);
85
+ /** Creates the view and attaches it to the engine's active scene. */
86
+ static attach(engine: EngineKernel, options?: MeshDebugViewOptions): MeshDebugView;
87
+ /** The settings in effect, defaults filled in and `multiply` resolved for the mode. Frozen; change with `set`. */
88
+ get options(): MeshDebugViewSettings;
89
+ /**
90
+ * Changes settings from the next frame; omitted ones keep their value. All are checked before any changes.
91
+ * @throws TypeError or RangeError for an unknown option or an invalid value; MargoError `'disposed'`.
92
+ */
93
+ set(options: MeshDebugViewOptions): this;
94
+ /** Forgets which material got which colour, so `'material-ids'` assigns them again in draw order. */
95
+ resetMaterialIds(): void;
96
+ setup(engine: Engine): void;
97
+ registerPasses(graph: FrameGraph): void;
98
+ /**
99
+ * Frees what the last drawn frame did not use (removed meshes, replaced geometry). It runs from the pass, not from
100
+ * `onPreUpdate`, which a pick runs between two frames too.
101
+ */
102
+ private sweep;
103
+ /** The buffer holding `key`'s data, written when `tag` first differs. */
104
+ private upload;
105
+ /** The draws of this view of the frame. */
106
+ private collect;
107
+ private pipeline;
108
+ private record;
109
+ private draw;
110
+ private release;
111
+ onDeviceRestored(engine: Engine): void;
112
+ /** Removes the plugin and releases its buffers; repeat calls are safe. */
113
+ dispose(): void;
114
+ [Symbol.dispose]: () => void;
115
+ }
@@ -0,0 +1,501 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const l=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { i as e, r as t, t as n } from "./errors-D8rc8kzg.js";
5
+ import { n as r, t as i } from "./mesh-source-BSQA_1GQ.js";
6
+ import { n as a, r as o, t as s } from "./view-rect-CTC0iGjf.js";
7
+ import { t as c } from "./visibility-7_j5J9Nv.js";
8
+ import { engineRuntime as __margoRuntime } from "@margoengine/core/extension";
9
+ //#region ../shared/instances.js
10
+ var u = {
11
+ arrayStride: 96,
12
+ stepMode: "instance",
13
+ attributes: [
14
+ 5,
15
+ 6,
16
+ 7,
17
+ 8,
18
+ 9,
19
+ 10
20
+ ].map((e, t) => ({
21
+ shaderLocation: e,
22
+ offset: t * 16,
23
+ format: "float32x4"
24
+ }))
25
+ }, d = (globalThis[Symbol.for("margoengine.frame-resources")] ??= { devices: /* @__PURE__ */ new WeakMap() }).devices;
26
+ function f(e) {
27
+ let t = d.get(e);
28
+ return t || (d.set(e, t = {
29
+ frame: 0,
30
+ open: !1,
31
+ lost: !1,
32
+ views: /* @__PURE__ */ new Set(),
33
+ drawing: 0,
34
+ retired: [],
35
+ written: /* @__PURE__ */ new WeakMap()
36
+ }), e.lost?.then?.(() => {
37
+ t.lost = !0;
38
+ let e = t.retired;
39
+ t.retired = [];
40
+ for (let t of e) t.destroy();
41
+ })), t;
42
+ }
43
+ function p(e, t) {
44
+ let n = f(e);
45
+ return n.open || (n.open = !0, n.frame++, queueMicrotask(n.close ??= () => {
46
+ if (n.open = !1, n.views.clear(), !n.retired.length) return;
47
+ let e = n.retired;
48
+ n.retired = [];
49
+ for (let t of e) t.destroy();
50
+ })), t && n.views.add(t), n.frame;
51
+ }
52
+ function m(e, t) {
53
+ if (!t) return;
54
+ let n = f(e), r = [t, ...n.written.get(t)?.extras ?? []];
55
+ if (n.written.delete(t), !n.lost && n.open && (n.views.size > 1 || n.drawing > 0)) n.retired.push(...r);
56
+ else for (let e of r) e.destroy();
57
+ }
58
+ function h(e, t, n, r) {
59
+ let i = p(e, r), a = f(e), o = a.written.get(t);
60
+ o?.values.length !== n.length && (o && a.retired.push(...o.extras), a.written.set(t, o = {
61
+ frame: 0,
62
+ view: void 0,
63
+ uses: 0,
64
+ values: new Float32Array(n.length),
65
+ extras: []
66
+ }));
67
+ let s = o.frame === i && o.view !== r;
68
+ for (let e = 0; s && e < n.length; e++) s = o.values[e] === n[e];
69
+ if (o.frame !== i || o.view === r || s) {
70
+ o.frame !== i && Object.assign(o, {
71
+ frame: i,
72
+ view: r,
73
+ uses: 0
74
+ }), o.values.set(n), e.queue.writeBuffer(t, 0, n);
75
+ return;
76
+ }
77
+ let c = o.extras[o.uses++] ??= e.createBuffer({
78
+ label: "frame uniform copy",
79
+ size: t.size,
80
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
81
+ });
82
+ return e.queue.writeBuffer(c, 0, n), { buffer: c };
83
+ }
84
+ function g(e, t) {
85
+ let n = /* @__PURE__ */ new Map([[e, t({ buffer: e })]]);
86
+ return { get(r) {
87
+ let i = r?.buffer ?? e, a = n.get(i);
88
+ return a || n.set(i, a = t({ buffer: i })), a;
89
+ } };
90
+ }
91
+ //#endregion
92
+ //#region ../shared/scene-pass.js
93
+ function _() {
94
+ return {
95
+ color: {
96
+ view: void 0,
97
+ loadOp: "load",
98
+ storeOp: "store"
99
+ },
100
+ depth: { view: void 0 }
101
+ };
102
+ }
103
+ function v(e, t, n) {
104
+ let r = e.descriptor.depthStencil.format.includes("stencil");
105
+ return t.view = e.color, t.loadOp = "load", t.storeOp = "store", t.resolveTarget = void 0, n.view = e.depth, n.depthLoadOp = "load", n.depthStoreOp = "store", n.stencilLoadOp = r ? "load" : void 0, n.stencilStoreOp = r ? "store" : void 0, e.attach?.(t, n, !0), e.encoder.beginRenderPass({
106
+ colorAttachments: [t],
107
+ depthStencilAttachment: n
108
+ });
109
+ }
110
+ //#endregion
111
+ //#region ../shared/hdr-format.js
112
+ var y = (e) => typeof e == "string" && e.endsWith("float"), b = (e) => /^#([\da-f]{3}){1,2}$/i.test(e) ? parseInt((e[4] ? e : e.replace(/\w/g, "$&$&")).slice(1), 16) : -1, x = [
113
+ "shaded",
114
+ "wireframe",
115
+ "vertices",
116
+ "wireframe-vertices",
117
+ "uv0",
118
+ "uv1",
119
+ "vertex-colors",
120
+ "material-ids"
121
+ ], S = {
122
+ mode: "wireframe",
123
+ multiply: null,
124
+ meshes: null,
125
+ enabled: !0,
126
+ wireColor: "#72e8cc",
127
+ wireWidth: 1,
128
+ vertexColor: "#ffb326",
129
+ vertexRadius: 3,
130
+ uvScale: 10,
131
+ uvColors: ["#f0f0f0", "#3a6ea5"],
132
+ diffuseColor: "#a0a0a0",
133
+ specularColor: "#303030",
134
+ specularPower: 32,
135
+ materialColors: []
136
+ }, C = (e) => e <= .04045 ? e / 12.92 : ((e + .055) / 1.055) ** 2.4, w = (e) => typeof e == "number" && e >= 0 && e <= 1;
137
+ function T(t, n) {
138
+ if (typeof t == "string") {
139
+ let e = b(t);
140
+ if (e >= 0) return [
141
+ 16,
142
+ 8,
143
+ 0
144
+ ].map((t) => C((e >> t & 255) / 255));
145
+ } else if (Array.isArray(t) && t.length === 3 && t.every(w)) return [
146
+ t[0],
147
+ t[1],
148
+ t[2]
149
+ ];
150
+ throw e(`MeshDebugView ${n} must be '#rgb', '#rrggbb' or three linear numbers in 0..1`, "mesh-debug-view");
151
+ }
152
+ function E(e) {
153
+ let t = e * .6180339887498949 % 1, n = e % 2 ? .75 : .95;
154
+ return [
155
+ 5,
156
+ 3,
157
+ 1
158
+ ].map((e) => {
159
+ let r = (e + t * 6) % 6;
160
+ return C(n * (1 - .7 * Math.max(0, Math.min(r, 4 - r, 1))));
161
+ });
162
+ }
163
+ var D = "\nstruct View {camera:mat4x4f,model:mat4x4f,eye:vec4f,viewport:vec4f,wire:vec4f,dot:vec4f,checkA:vec4f,checkB:vec4f,\n base:vec4f,specular:vec4f,params:vec4f,offsets:vec4f,flags:vec4f}\n@group(0) @binding(0) var<uniform> u:View;\n@group(0) @binding(1) var<storage,read> vertices:array<f32>;\n@group(0) @binding(2) var<storage,read> indices:array<u32>;\nstruct Out {@builtin(position) clip:vec4f,@location(0) bary:vec3f,@location(1) position:vec3f,@location(2) normal:vec3f,\n @location(3) uv:vec4f,@location(4) color:vec3f,@location(5) @interpolate(flat) ab:vec4f,\n @location(6) @interpolate(flat) c:vec3f}\nfn read2(at:u32)->vec2f{return vec2f(vertices[at],vertices[at+1u]);}\nfn read3(at:u32)->vec3f{return vec3f(vertices[at],vertices[at+1u],vertices[at+2u]);}\n@vertex fn vertex(@builtin(vertex_index) id:u32,@location(5) m0:vec4f,@location(6) m1:vec4f,@location(7) m2:vec4f,\n @location(8) m3:vec4f)->Out{\n let model=u.model*mat4x4f(m0,m1,m2,m3);\n let stride=u32(u.offsets.x);let corner=id%3u;let first=id-corner;\n var screen=array<vec2f,3>();\n for(var k=0u;k<3u;k++){\n let q=u.camera*(model*vec4f(read3(indices[first+k]*stride),1.0));\n screen[k]=select(vec2f(-1e6),(q.xy/q.w*vec2f(0.5,-0.5)+0.5)*u.viewport.zw+u.viewport.xy,q.w>0.0);\n }\n let at=indices[id]*stride;\n let world=model*vec4f(read3(at),1.0);\n let a=model[0].xyz;let b=model[1].xyz;let c=model[2].xyz;\n var o:Out;\n o.clip=u.camera*world;\n o.bary=vec3f(f32(corner==0u),f32(corner==1u),f32(corner==2u));\n o.position=world.xyz;\n o.normal=mat3x3f(cross(b,c),cross(c,a),cross(a,b))*read3(at+u32(u.offsets.y));\n o.uv=vec4f(0.0);\n if(u.offsets.z>0.0){\n let t=at+u32(u.offsets.z);\n o.uv=vec4f(read2(t),0.0,0.0);\n if(u.offsets.w>0.0){o.uv=vec4f(o.uv.xy,read2(t+2u));}\n }\n o.color=vec3f(1.0);\n if(u.offsets.w>0.0){o.color=read3(at+u32(u.offsets.w));}\n o.ab=vec4f(screen[0],screen[1]);\n o.c=vec3f(screen[2],select(0.0,1.0,dot(a,cross(b,c))<0.0));\n return o;\n}\nfn encode(c:vec3f)->vec3f{\n if(u.flags.y>0.5){return c;}\n let v=clamp(c,vec3f(0.0),vec3f(1.0));\n return select(1.055*pow(v,vec3f(1.0/2.4))-0.055,v*12.92,v<=vec3f(0.0031308));\n}\n@fragment fn fragment(i:Out,@builtin(front_facing) facing:bool)->@location(0) vec4f{\n let mode=u32(u.params.w);let pass_=u32(u.flags.x);\n let gx=dpdx(i.bary);let gy=dpdy(i.bary);\n let uv=select(i.uv.xy,i.uv.zw,mode==5u)*u.params.z+2e-5;\n let w=max(fwidth(uv),vec2f(1e-5));\n let front=facing!=(i.c.z>0.5);\n if((u.flags.z==1.0&&!front)||(u.flags.z==2.0&&front)){discard;}\n var surface=u.base.rgb;\n if(mode==4u||mode==5u){\n let s=2.0*(abs(fract((uv-0.5*w)*0.5)-0.5)-abs(fract((uv+0.5*w)*0.5)-0.5))/w;\n surface=mix(u.checkA.rgb,u.checkB.rgb,clamp(0.5-0.5*s.x*s.y,0.0,1.0));\n }\n if(mode==6u){surface=i.color;}\n let view=u.eye.xyz-i.position*u.eye.w;\n let ndv=min(abs(dot(i.normal,view))/max(length(i.normal)*length(view),1e-20),1.0);\n if(mode!=6u&&(pass_==0u||mode==0u)){surface=surface*ndv+u.specular.rgb*pow(ndv,u.specular.w);}\n var wire=0.0;var point=0.0;\n if((mode==1u||mode==3u)&&u.params.x>0.0){\n let d=i.bary/max(sqrt(gx*gx+gy*gy),vec3f(1e-8));\n wire=clamp(u.params.x*0.5+0.5-min(d.x,min(d.y,d.z)),0.0,1.0);\n }\n if((mode==2u||mode==3u)&&u.params.y>0.0){\n let p=i.clip.xy;\n let d=min(distance(p,i.ab.xy),min(distance(p,i.ab.zw),distance(p,i.c.xy)));\n point=clamp(u.params.y+0.5-d,0.0,1.0);\n }\n if(pass_==2u){\n let alpha=point+wire*(1.0-point);\n if(alpha<=0.0){discard;}\n let color=(u.wire.rgb*wire*(1.0-point)+u.dot.rgb*point)/alpha;\n return vec4f(encode(color)*alpha,alpha);\n }\n return vec4f(encode(mix(mix(surface,u.wire.rgb,wire),u.dot.rgb,point)),1.0);\n}", O = /* @__PURE__ */ new Float32Array(24);
164
+ O[0] = O[5] = O[10] = O[15] = 1;
165
+ var k = 76, A = 4, j = class d {coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);
166
+ constructor(e = {}) {
167
+ this.name = "inspector:mesh-debug:" + M++, this.multiplied = null, this.ids = /* @__PURE__ */ new WeakMap(), this.nextId = 0, this.frame = -1, this.disposed = !1, this.pipelines = /* @__PURE__ */ new Map(), this.records = /* @__PURE__ */ new Map(), this.uploads = /* @__PURE__ */ new Map(), this.values = new Float32Array(k), this.attachments = _(), this.set(e);
168
+ }
169
+ static attach(e, t) {__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));
170
+ let n = new d(t);
171
+ return l(e).use(n), n;
172
+ }
173
+ get options() {
174
+ return this.settings;
175
+ }
176
+ set(r) {
177
+ if (this.disposed) throw n("disposed", "MeshDebugView was disposed; attach a new MeshDebugView", "mesh-debug-view");
178
+ if (!r || typeof r != "object") throw e("MeshDebugView options must be an object; pass { mode: ... }", "mesh-debug-view");
179
+ for (let t of Object.keys(r)) if (!Object.hasOwn(S, t)) throw e(`MeshDebugView has no option '${t}'; use ${Object.keys(S).join(", ")}`, "mesh-debug-view");
180
+ let i = Object.fromEntries(Object.entries(r).filter(([, e]) => e !== void 0)), a = {
181
+ ...S,
182
+ ...this.settings,
183
+ ...i
184
+ }, o = r.multiply === void 0 ? this.multiplied : r.multiply;
185
+ if (!x.includes(a.mode)) throw e(`MeshDebugView mode must be one of ${x.join(", ")}`, "mesh-debug-view");
186
+ if (o !== null && typeof o != "boolean") throw e("MeshDebugView multiply must be true, false or null", "mesh-debug-view");
187
+ if (typeof a.enabled != "boolean") throw e("MeshDebugView enabled must be true or false", "mesh-debug-view");
188
+ let s = (e, n, r) => {
189
+ let i = a[e];
190
+ if (!(typeof i == "number" && i >= n && i <= r)) throw t(`MeshDebugView ${e} must be a number from ${n} to ${r}`, "mesh-debug-view");
191
+ };
192
+ if (s("wireWidth", 0, 64), s("vertexRadius", 0, 64), s("uvScale", 1e-6, 4096), s("specularPower", 1, 1e4), !Array.isArray(a.uvColors) || a.uvColors.length !== 2) throw e("MeshDebugView uvColors must be two colours", "mesh-debug-view");
193
+ if (!Array.isArray(a.materialColors) || a.materialColors.length > 4096) throw e("MeshDebugView materialColors must be an array of at most 4096 colours", "mesh-debug-view");
194
+ let c = a.meshes;
195
+ if (i.meshes !== void 0 && i.meshes !== null) {
196
+ if (c = typeof i.meshes == "object" && Symbol.iterator in i.meshes ? [...i.meshes] : null, !c || !c.every((e) => e && typeof e == "object" && typeof e.id == "number")) throw e("MeshDebugView meshes must be a list of meshes or null", "mesh-debug-view");
197
+ Object.freeze(c);
198
+ }
199
+ let l = {
200
+ wire: T(a.wireColor, "wireColor"),
201
+ dot: T(a.vertexColor, "vertexColor"),
202
+ a: T(a.uvColors[0], "uvColors[0]"),
203
+ b: T(a.uvColors[1], "uvColors[1]"),
204
+ diffuse: T(a.diffuseColor, "diffuseColor"),
205
+ specular: T(a.specularColor, "specularColor"),
206
+ materials: a.materialColors.map((e, t) => T(e, `materialColors[${t}]`))
207
+ };
208
+ return this.colors = l, this.multiplied = o, this.settings = Object.freeze({
209
+ ...a,
210
+ meshes: c,
211
+ multiply: o ?? (a.mode === "wireframe" || a.mode === "vertices" || a.mode === "wireframe-vertices")
212
+ }), this;
213
+ }
214
+ resetMaterialIds() {
215
+ this.ids = /* @__PURE__ */ new WeakMap(), this.nextId = 0;
216
+ }
217
+ setup(e) {
218
+ if (this.disposed) throw n("disposed", "MeshDebugView was disposed; attach a new MeshDebugView", "mesh-debug-view");
219
+ let t = e.gpu?.limits;
220
+ if (!t || t.maxStorageBuffersInVertexStage === 0) throw n("unsupported", "MeshDebugView reads vertices from storage buffers; create the engine on WebGPU or the WebGL2 compatibility layer", "mesh-debug-view");
221
+ this.engine = e;
222
+ }
223
+ registerPasses(e) {
224
+ e.add({
225
+ name: this.name,
226
+ order: 2.99,
227
+ joins: !0,
228
+ execute: (e) => {
229
+ e.backend === "webgpu" && this.draw(e);
230
+ }
231
+ });
232
+ }
233
+ sweep(e) {
234
+ let t = p(e);
235
+ if (t !== this.frame) {
236
+ this.frame = t;
237
+ for (let [t, n] of this.records) n.used ? n.used = !1 : (m(e, n.uniform), this.records.delete(t));
238
+ for (let [t, n] of this.uploads) n.used ? n.used = !1 : (m(e, n.buffer), this.uploads.delete(t));
239
+ }
240
+ }
241
+ upload(e, n, r, i) {
242
+ let a = this.uploads.get(n);
243
+ if (!a || a.tag !== r) {
244
+ let o = i();
245
+ if (o.byteLength > Math.min(e.limits.maxStorageBufferBindingSize, e.limits.maxBufferSize)) throw t(`MeshDebugView needs a ${o.byteLength}-byte storage buffer, over this device's limit; split the mesh or leave it out of meshes`, "mesh-debug-view");
246
+ a && m(e, a.buffer);
247
+ let s = e.createBuffer({
248
+ size: o.byteLength,
249
+ usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST
250
+ });
251
+ e.queue.writeBuffer(s, 0, o), this.uploads.set(n, a = {
252
+ buffer: s,
253
+ tag: r,
254
+ used: !0
255
+ });
256
+ }
257
+ return a.used = !0, a.buffer;
258
+ }
259
+ collect(e) {
260
+ let t = this.engine, n = e.device, o = t.sceneOf(this) ?? t.scene, s = [], l = /* @__PURE__ */ new Map(), u = this.single ??= (() => {
261
+ let e = n.createBuffer({
262
+ size: 96,
263
+ usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST
264
+ });
265
+ return n.queue.writeBuffer(e, 0, O), e;
266
+ })();
267
+ for (let d of this.settings.meshes ?? o.meshes.values()) {
268
+ let f = d;
269
+ if (o.meshes.get(f.id) !== f || c(t.store, f.id) || !a(e, f)) continue;
270
+ let p = f.geometry;
271
+ if (p) {
272
+ if (!p.indices.length) continue;
273
+ let e = i(p)?.uv, t = e ? 8 : 6, r = this.upload(n, p, e, () => {
274
+ if (!e) return p.vertices;
275
+ let t = p.vertices.length / 6, n = new Float32Array(t * 8);
276
+ for (let r = 0; r < t; r++) n.set(p.vertices.subarray(r * 6, r * 6 + 6), r * 8), n.set(e.subarray(r * 2, r * 2 + 2), r * 8 + 6);
277
+ return n;
278
+ });
279
+ s.push({
280
+ key: f,
281
+ matrix: f.matrix,
282
+ vertex: r,
283
+ offset: 0,
284
+ size: r.size,
285
+ index: this.upload(n, p.indices, p.indices, () => p.indices),
286
+ count: p.indices.length,
287
+ instances: u,
288
+ copies: 1,
289
+ stride: t,
290
+ uvAt: e ? 6 : 0,
291
+ colorAt: 0,
292
+ side: +!f.material.data[6],
293
+ material: f.material
294
+ });
295
+ continue;
296
+ }
297
+ let m = r(d);
298
+ if (!m) continue;
299
+ let h = l.get(m.model);
300
+ if (!h) {
301
+ l.set(m.model, h = /* @__PURE__ */ new Map());
302
+ for (let e of m.model.pickingPrimitives) {
303
+ let t = h.get(e.node);
304
+ t ? t.push(e) : h.set(e.node, [e]);
305
+ }
306
+ }
307
+ for (let e of h.get(f) ?? []) {
308
+ let t = e.primitive, r = e.side;
309
+ if (t.topology || !t.indices.length || t.instances?.count === 0) continue;
310
+ let i = (e.vertex.usage & GPUBufferUsage.STORAGE) !== 0;
311
+ s.push({
312
+ key: t,
313
+ matrix: f.matrix,
314
+ vertex: i ? e.vertex : this.upload(n, t.vertices, t.vertices, () => t.vertices),
315
+ offset: i ? e.vertexOffset ?? 0 : 0,
316
+ size: t.vertices.byteLength,
317
+ index: this.upload(n, t.indices, t.indices, () => t.indices),
318
+ count: t.indices.length,
319
+ instances: t.instances ? t.instances.upload(n) : u,
320
+ copies: t.instances ? t.instances.count : 1,
321
+ stride: 20,
322
+ uvAt: 12,
323
+ colorAt: 16,
324
+ side: r === "back" ? 2 : +(r === "front"),
325
+ material: t.material
326
+ });
327
+ }
328
+ }
329
+ return s;
330
+ }
331
+ pipeline(e, t) {
332
+ let n = e.descriptor.depthStencil, r = e.descriptor.multisample?.count ?? 1, i = [
333
+ e.format,
334
+ r,
335
+ n.format,
336
+ n.depthCompare,
337
+ t
338
+ ].join(":"), a = this.pipelines.get(i);
339
+ if (a) return a;
340
+ let o = e.device, s = n.depthCompare?.startsWith("greater") ?? !1, c = this.module ??= o.createShaderModule({ code: D }), l = t === 1 ? {
341
+ color: {
342
+ operation: "add",
343
+ srcFactor: "dst",
344
+ dstFactor: "zero"
345
+ },
346
+ alpha: {
347
+ operation: "add",
348
+ srcFactor: "zero",
349
+ dstFactor: "one"
350
+ }
351
+ } : t === 2 ? {
352
+ color: {
353
+ operation: "add",
354
+ srcFactor: "one",
355
+ dstFactor: "one-minus-src-alpha"
356
+ },
357
+ alpha: {
358
+ operation: "add",
359
+ srcFactor: "one",
360
+ dstFactor: "one-minus-src-alpha"
361
+ }
362
+ } : void 0;
363
+ return a = o.createRenderPipeline({
364
+ layout: o.createPipelineLayout({ bindGroupLayouts: [this.layout] }),
365
+ vertex: {
366
+ module: c,
367
+ entryPoint: "vertex",
368
+ buffers: [u]
369
+ },
370
+ fragment: {
371
+ module: c,
372
+ entryPoint: "fragment",
373
+ targets: [{
374
+ format: e.format,
375
+ blend: l
376
+ }]
377
+ },
378
+ primitive: {
379
+ topology: "triangle-list",
380
+ cullMode: "none"
381
+ },
382
+ depthStencil: {
383
+ format: n.format,
384
+ depthCompare: s ? "greater-equal" : "less-equal",
385
+ depthWriteEnabled: t === 0,
386
+ depthBias: s ? A : -4,
387
+ depthBiasSlopeScale: s ? 1 : -1
388
+ },
389
+ multisample: e.descriptor.multisample
390
+ }), this.pipelines.set(i, a), a;
391
+ }
392
+ record(e, t) {
393
+ let n = this.records.get(t.key), r = n && (n.vertex !== t.vertex || n.offset !== t.offset || n.size !== t.size || n.index !== t.index);
394
+ if (n && r && (m(e, n.uniform), n = void 0), !n) {
395
+ let r = e.createBuffer({
396
+ size: 304,
397
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
398
+ }), { vertex: i, offset: a, size: o, index: s } = t;
399
+ n = {
400
+ uniform: r,
401
+ vertex: i,
402
+ offset: a,
403
+ size: o,
404
+ index: s,
405
+ used: !0,
406
+ groups: g(r, (t) => e.createBindGroup({
407
+ layout: this.layout,
408
+ entries: [
409
+ {
410
+ binding: 0,
411
+ resource: t
412
+ },
413
+ {
414
+ binding: 1,
415
+ resource: {
416
+ buffer: i,
417
+ offset: a,
418
+ size: o
419
+ }
420
+ },
421
+ {
422
+ binding: 2,
423
+ resource: { buffer: s }
424
+ }
425
+ ]
426
+ }))
427
+ }, this.records.set(t.key, n);
428
+ }
429
+ return n.used = !0, n;
430
+ }
431
+ draw(e) {
432
+ let t = this.settings, n = e.device;
433
+ if (this.disposed || (this.sweep(n), !t.enabled)) return;
434
+ this.layout ??= n.createBindGroupLayout({ entries: [
435
+ {
436
+ binding: 0,
437
+ visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
438
+ buffer: {}
439
+ },
440
+ {
441
+ binding: 1,
442
+ visibility: GPUShaderStage.VERTEX,
443
+ buffer: { type: "read-only-storage" }
444
+ },
445
+ {
446
+ binding: 2,
447
+ visibility: GPUShaderStage.VERTEX,
448
+ buffer: { type: "read-only-storage" }
449
+ }
450
+ ] });
451
+ let r = this.collect(e);
452
+ if (!r.length) return;
453
+ let i = x.indexOf(t.mode), a = t.multiply ? i >= 1 && i <= 3 ? 2 : 1 : 0, c = this.pipeline(e, a), l = this.values, u = this.colors, d = e.camera, f = d.matrix, p = f[3] === 0 && f[7] === 0 && f[11] === 0;
454
+ l.set(f);
455
+ for (let e = 0; e < 3; e++) l[32 + e] = d.position[e] - (p ? d.target[e] : 0);
456
+ l[35] = +!p, l.set(o(e) ?? [
457
+ 0,
458
+ 0,
459
+ e.width,
460
+ e.height
461
+ ], 36), l.set(u.wire, 40), l.set(u.dot, 44), l.set(u.a, 48), l.set(u.b, 52), l.set(u.specular, 60), l[63] = t.specularPower, l.set([
462
+ t.wireWidth,
463
+ t.vertexRadius,
464
+ t.uvScale,
465
+ i
466
+ ], 64), l[72] = a, l[73] = +(y(e.format) || e.format.endsWith("-srgb"));
467
+ let m = r.map((r) => {
468
+ let i = this.record(n, r);
469
+ l.set(r.matrix, 16);
470
+ let a = u.diffuse;
471
+ if (t.mode === "material-ids") {
472
+ let e = this.ids.get(r.material);
473
+ e === void 0 && this.ids.set(r.material, e = this.nextId++), a = u.materials[e] ?? E(e);
474
+ }
475
+ return l.set(a, 56), l[68] = r.stride, l[69] = r.stride === 20 ? 4 : 3, l[70] = r.uvAt, l[71] = r.colorAt, l[74] = r.side, i.groups.get(h(n, i.uniform, l, e.view ?? e));
476
+ }), g = v(e, this.attachments.color, this.attachments.depth);
477
+ s(g, e), g.setPipeline(c), r.forEach((e, t) => {
478
+ g.setBindGroup(0, m[t]), g.setVertexBuffer(0, e.instances), g.draw(e.count, e.copies);
479
+ }), g.end();
480
+ }
481
+ release() {
482
+ let e = this.engine?.gpu;
483
+ if (e) {
484
+ for (let t of this.records.values()) m(e, t.uniform);
485
+ for (let t of this.uploads.values()) m(e, t.buffer);
486
+ m(e, this.single);
487
+ }
488
+ this.records.clear(), this.uploads.clear(), this.pipelines.clear(), this.single = this.layout = this.module = void 0;
489
+ }
490
+ onDeviceRestored(e) {
491
+ this.release(), this.setup(e);
492
+ }
493
+ dispose() {
494
+ this.disposed || (this.disposed = !0, this.engine?.sceneOf(this)?.removePlugin(this.name), this.release(), this.engine = void 0);
495
+ }
496
+ [Symbol.dispose ?? Symbol()]() {
497
+ this.dispose();
498
+ }
499
+ }, M = 0;
500
+ //#endregion
501
+ export { j as MeshDebugView };
@@ -0,0 +1,31 @@
1
+ //#region ../shared/mesh-source.js
2
+ var e = Symbol.for("margoengine.mesh-sources.v1"), t = globalThis[e] ?? /* @__PURE__ */ new WeakMap();
3
+ globalThis[e] || Object.defineProperty(globalThis, e, { value: t });
4
+ var n = Symbol.for("margoengine.geometry-surfaces.v1"), r = globalThis[n] ?? /* @__PURE__ */ new WeakMap();
5
+ globalThis[n] || Object.defineProperty(globalThis, n, { value: r });
6
+ function i(e) {
7
+ return r.get(e);
8
+ }
9
+ function a(e) {
10
+ let n = e && t.get(e);
11
+ return n && !n.model.disposed ? n : void 0;
12
+ }
13
+ function o(e) {
14
+ if (e?.geometry) return {
15
+ kind: "core",
16
+ geometry: e.geometry
17
+ };
18
+ let n = e && t.get(e);
19
+ if (!n || n.model.disposed) return null;
20
+ try {
21
+ e.check?.();
22
+ } catch {
23
+ return null;
24
+ }
25
+ return {
26
+ kind: "pbr",
27
+ source: n
28
+ };
29
+ }
30
+ //#endregion
31
+ export { a as n, o as r, i as t };