@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,122 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel } from '@margoengine/core';
3
+ import { type Engine, type EnginePlugin } from '@margoengine/core/extension';
4
+ import { EditHistory } from './history.js';
5
+ /** The shape of a `@margoengine/materials` WgslMaterial that this editor relies on. */
6
+ export interface WgslMaterialShape {
7
+ readonly wgsl: string;
8
+ readonly shading?: string;
9
+ readonly uniforms: Record<string, number | ArrayLike<number>>;
10
+ readonly textures: Record<string, unknown>;
11
+ copy(source: WgslMaterialShape): unknown;
12
+ }
13
+ /** A mesh whose `material` can be read and assigned: a `@margoengine/materials` `createMesh` result. */
14
+ export interface ShaderMesh {
15
+ material: unknown;
16
+ readonly name?: string;
17
+ }
18
+ /** One compiler message, placed in the edited WGSL. */
19
+ export interface ShaderDiagnostic {
20
+ type: 'error' | 'warning' | 'info';
21
+ message: string;
22
+ /** 1-based line and column in the edited WGSL; 0 when the message points outside it (the engine's own code). */
23
+ line: number;
24
+ column: number;
25
+ }
26
+ /** What one edit did. */
27
+ export interface ShaderEditResult {
28
+ /** True when the mesh now draws the edited WGSL; false when it was refused and the old material is back. */
29
+ ok: boolean;
30
+ /** Shader modules the device built from the edited WGSL within the wait (0: not drawn yet, or no device). */
31
+ modules: number;
32
+ diagnostics: ShaderDiagnostic[];
33
+ }
34
+ /** Options for `recompileShader`. */
35
+ export interface RecompileOptions {
36
+ /** The device that draws the mesh (`engine.gpu`). Without one the edit is swapped in unchecked. */
37
+ device?: GPUDevice | null;
38
+ /** Most milliseconds to wait for the mesh to draw the edit, 0 to 60,000. Default 3,000. */
39
+ timeoutMs?: number;
40
+ /** Milliseconds to keep collecting modules after the first one (other passes of the same frame). Default 50. */
41
+ settleMs?: number;
42
+ /** Records the swap, so undo puts the old WGSL back. */
43
+ history?: EditHistory;
44
+ }
45
+ /** True when `material` has the WgslMaterial shape this editor edits. */
46
+ export declare function isWgslMaterial(material: unknown): material is WgslMaterialShape;
47
+ /**
48
+ * Swaps `mesh`'s WgslMaterial for one running `wgsl`, with the same uniforms, textures and other values, once the
49
+ * device's compiler accepts it. The check compiles the module text the device built for the mesh's current WGSL with
50
+ * the edit in its place (labelled `check-wgsl:inspector-shaders`), so a broken edit is never drawn: drawing an invalid
51
+ * pipeline would invalidate the frame's commands. The first edit of a material draws one frame with a copy of it to
52
+ * learn that text. A refused edit resolves `ok: false` with the messages, lines and columns counted in `wgsl`.
53
+ *
54
+ * ```ts
55
+ * const result = await recompileShader(mesh, editedWgsl, { device: engine.gpu });
56
+ * if (!result.ok) console.log(result.diagnostics);
57
+ * ```
58
+ */
59
+ export declare function recompileShader(mesh: ShaderMesh, wgsl: string, options?: RecompileOptions): Promise<ShaderEditResult>;
60
+ /** `ShaderEditor` options. */
61
+ export interface ShaderEditorOptions {
62
+ /** The meshes to offer, or a function listing them (called on `refresh`). Meshes not drawing a WgslMaterial are left out. */
63
+ meshes?: readonly ShaderMesh[] | (() => readonly ShaderMesh[]);
64
+ /** Element for the panel. Default `document.body`. */
65
+ parent?: HTMLElement;
66
+ /** Undo history (pass `inspector.history` to share the Inspector's). Default a new one. */
67
+ history?: EditHistory;
68
+ /** Apply after each pause in typing. Default true. */
69
+ live?: boolean;
70
+ /** The pause, in milliseconds, 0 to 10,000. Default 400. */
71
+ delayMs?: number;
72
+ /** Passed to `recompileShader`. Default 3,000. */
73
+ timeoutMs?: number;
74
+ }
75
+ /**
76
+ * A DOM panel that edits the WGSL of each mesh drawing a `@margoengine/materials` WgslMaterial and recompiles it in
77
+ * place: `ShaderEditor.attach(engine, { meshes: [mesh] })`. Typing applies after a pause (`live`), compiler errors
78
+ * list under the text with their line, and a failed edit leaves the mesh drawing its last good shader.
79
+ */
80
+ export declare class ShaderEditor implements EnginePlugin {
81
+ readonly name = "inspector:shaders";
82
+ readonly element: HTMLElement;
83
+ readonly history: EditHistory;
84
+ private engine?;
85
+ private readonly options;
86
+ private readonly select;
87
+ private readonly textarea;
88
+ private readonly status;
89
+ private readonly list;
90
+ private items;
91
+ private current;
92
+ private timer?;
93
+ private pending;
94
+ private disposed;
95
+ private applying;
96
+ private readonly unlisten;
97
+ /** The last result shown. */
98
+ result?: ShaderEditResult;
99
+ static attach(engine: EngineKernel, options?: ShaderEditorOptions): ShaderEditor;
100
+ constructor(options?: ShaderEditorOptions);
101
+ setup(engine: Engine): void;
102
+ /** The meshes offered now (those drawing a WgslMaterial). */
103
+ get meshes(): readonly ShaderMesh[];
104
+ /** The WGSL in the editor. */
105
+ get text(): string;
106
+ set text(value: string);
107
+ /** Adds a mesh to the list (no effect when listed or not drawing a WgslMaterial) and returns its index, or -1. */
108
+ add(mesh: ShaderMesh): number;
109
+ /** Lists the meshes again from `options.meshes`. */
110
+ refresh(): void;
111
+ /** Shows mesh `index`'s WGSL (its material's current text). */
112
+ show(index: number): void;
113
+ /**
114
+ * Recompiles the selected mesh with `wgsl` (default: the editor's text) and shows the outcome. Edits run one at a
115
+ * time in order; each resolves with its own result.
116
+ */
117
+ apply(wgsl?: string): Promise<ShaderEditResult>;
118
+ private report;
119
+ private fill;
120
+ dispose(): void;
121
+ [Symbol.dispose](): void;
122
+ }
@@ -0,0 +1,285 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const n=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { n as e } from "./errors-D8rc8kzg.js";
5
+ import { EditHistory as t } from "./history.js";
6
+ import { engineRuntime as __margoRuntime } from "@margoengine/core/extension";
7
+ //#region src/shaders.ts
8
+ function r(e) {
9
+ let t = e;
10
+ return !!t && typeof t.wgsl == "string" && !!t.uniforms && typeof t.uniforms == "object" && !!t.textures && typeof t.textures == "object" && typeof t.copy == "function";
11
+ }
12
+ var i = /* @__PURE__ */ new WeakMap();
13
+ function a(e) {
14
+ let t = typeof e?.getCompilationInfo == "function" ? e.getCompilationInfo() : void 0;
15
+ return t?.catch(() => void 0), t;
16
+ }
17
+ function o(e, t, n) {
18
+ if (typeof e.pushErrorScope != "function") return t();
19
+ e.pushErrorScope("validation");
20
+ try {
21
+ return t();
22
+ } finally {
23
+ n.push(e.popErrorScope().then((e) => e?.message ?? null, () => null));
24
+ }
25
+ }
26
+ function s(e, t) {
27
+ let n = i.get(e);
28
+ if (!n) {
29
+ let t = {
30
+ watches: /* @__PURE__ */ new Set(),
31
+ module: e.createShaderModule,
32
+ pipeline: e.createRenderPipeline
33
+ };
34
+ i.set(e, n = t), e.createShaderModule = function(n) {
35
+ let r = [...t.watches].filter((e) => typeof n?.code == "string" && n.code.includes(e.wgsl));
36
+ if (!r.length) return t.module.call(this, n);
37
+ let i = [], s = o(e, () => t.module.call(this, n), i), c = a(s);
38
+ for (let e of r) e.modules.set(s, n.code), e.infos.set(s, c), e.scoped.push(...i);
39
+ return s;
40
+ }, e.createRenderPipeline = function(n) {
41
+ let r = [...t.watches].filter((e) => e.modules.has(n?.vertex?.module) || e.modules.has(n?.fragment?.module));
42
+ if (!r.length) return t.pipeline.call(this, n);
43
+ let i = [], a = o(e, () => t.pipeline.call(this, n), i);
44
+ for (let e of r) e.scoped.push(...i);
45
+ return a;
46
+ };
47
+ }
48
+ let r = {
49
+ wgsl: t,
50
+ modules: /* @__PURE__ */ new Map(),
51
+ infos: /* @__PURE__ */ new Map(),
52
+ scoped: []
53
+ }, s = n;
54
+ return s.watches.add(r), () => (s.watches.delete(r), s.watches.size || (e.createShaderModule = s.module, e.createRenderPipeline = s.pipeline, i.delete(e)), r);
55
+ }
56
+ var c = (e) => new Promise((t) => setTimeout(t, e));
57
+ function l(e, t, n, r) {
58
+ let i = e.lastIndexOf(t);
59
+ if (i < 0 || !n) return [0, 0];
60
+ let a = n - e.slice(0, i).split("\n").length + 1, o = a === 1 ? r - (i - e.lastIndexOf("\n", i - 1) - 1) : r;
61
+ return a >= 1 && a <= t.split("\n").length ? [a, Math.max(1, o)] : [0, 0];
62
+ }
63
+ var u = (e) => Object.fromEntries(Object.entries(e).map(([e, t]) => [e, typeof t == "number" ? t : Array.from(t)])), d = /* @__PURE__ */ new WeakMap(), f = (e) => /\bfn\s+displace\b/.test(e);
64
+ async function p(e, t, n, r, a, o) {
65
+ let l = s(e, r), u = i.get(e), d;
66
+ try {
67
+ t.material = n;
68
+ let e = performance.now(), i = () => [...u.watches].some((e) => e.wgsl === r && e.modules.size);
69
+ for (; !i() && performance.now() - e < a;) await c(Math.min(16, a));
70
+ i() && await c(o);
71
+ } finally {
72
+ d = l();
73
+ }
74
+ return d;
75
+ }
76
+ async function m(e, t, n, r) {
77
+ let i = [], a = /* @__PURE__ */ new Set(), o = (e) => {
78
+ let t = `${e.type}:${e.line}:${e.column}:${e.message}`;
79
+ a.has(t) || (a.add(t), i.push(e));
80
+ };
81
+ for (let [n, i] of e) {
82
+ let e = await t.get(n);
83
+ for (let t of e?.messages ?? []) {
84
+ let [e, n] = l(i, r, t.lineNum, t.linePos);
85
+ o({
86
+ type: t.type,
87
+ message: t.message,
88
+ line: e,
89
+ column: n
90
+ });
91
+ }
92
+ }
93
+ for (let e of await Promise.all(n)) e && !i.some((e) => e.type === "error") && o({
94
+ type: "error",
95
+ message: e,
96
+ line: 0,
97
+ column: 0
98
+ });
99
+ return i;
100
+ }
101
+ async function h(e, t, n = {}) {
102
+ let i = e?.material;
103
+ if (!r(i)) throw TypeError("recompileShader needs a mesh drawing a WgslMaterial; pass a createMesh result whose material is a @margoengine/materials WgslMaterial");
104
+ if (typeof t != "string") throw TypeError("recompileShader needs WGSL text; pass a string");
105
+ let { device: s = null, timeoutMs: c = 3e3, settleMs: l = 50, history: h } = n;
106
+ if (!Number.isFinite(c) || c < 0 || c > 6e4) throw RangeError("recompileShader timeoutMs must be 0 to 60000; pass a number of milliseconds in range");
107
+ if (!Number.isFinite(l) || l < 0 || l > c) throw RangeError("recompileShader settleMs must be 0 to timeoutMs; pass a smaller number of milliseconds");
108
+ if (t === i.wgsl) return {
109
+ ok: !0,
110
+ modules: 0,
111
+ diagnostics: []
112
+ };
113
+ let _;
114
+ try {
115
+ let e = i.constructor;
116
+ _ = new e({
117
+ wgsl: t,
118
+ shading: i.shading,
119
+ uniforms: u(i.uniforms),
120
+ textures: { ...i.textures }
121
+ }), _.copy(i);
122
+ } catch (e) {
123
+ return {
124
+ ok: !1,
125
+ modules: 0,
126
+ diagnostics: [{
127
+ type: "error",
128
+ message: String(e?.message ?? e),
129
+ line: 0,
130
+ column: 0
131
+ }]
132
+ };
133
+ }
134
+ let v = 0;
135
+ if (s) {
136
+ let n = d.get(i), r = i.clone;
137
+ if (!n && typeof r == "function") {
138
+ let t = r.call(i), a = await p(s, e, t, i.wgsl, c, l);
139
+ e.material = i, t.dispose?.(), d.set(i, n = [...new Set(a.modules.values())]);
140
+ }
141
+ let u = /* @__PURE__ */ new Map(), y = /* @__PURE__ */ new Map(), b = [];
142
+ for (let e of n ?? []) {
143
+ let n = e.lastIndexOf(i.wgsl);
144
+ if (n < 0) continue;
145
+ let r = f(i.wgsl) && !f(t) ? "\nfn displace(i: Input) -> vec3f { return vec3f(0.0); }\n" : "", c = e.slice(0, n) + t + e.slice(n + i.wgsl.length) + r, l = o(s, () => s.createShaderModule({
146
+ label: "check-wgsl:inspector-shaders",
147
+ code: c
148
+ }), b);
149
+ y.set(l, a(l)), u.set(l, c);
150
+ }
151
+ let x = await m(u, y, b, t);
152
+ if (v += u.size, x.some((e) => e.type === "error")) return {
153
+ ok: !1,
154
+ modules: v,
155
+ diagnostics: x
156
+ };
157
+ let S = await p(s, e, _, t, c, l), C = await m(S.modules, S.infos, S.scoped, t);
158
+ v += S.modules.size, S.modules.size && d.set(_, [...new Set(S.modules.values())]);
159
+ let w = [...x, ...C.filter((e) => !x.some((t) => t.message === e.message))];
160
+ return C.some((e) => e.type === "error") ? (e.material = i, {
161
+ ok: !1,
162
+ modules: v,
163
+ diagnostics: w
164
+ }) : (g(h, e, i, _), {
165
+ ok: !0,
166
+ modules: v,
167
+ diagnostics: w
168
+ });
169
+ }
170
+ return e.material = _, g(h, e, i, _), {
171
+ ok: !0,
172
+ modules: v,
173
+ diagnostics: []
174
+ };
175
+ }
176
+ function g(e, t, n, r) {
177
+ e?.record({
178
+ label: "Edit shader",
179
+ undo: () => t.material = n,
180
+ redo: () => t.material = r
181
+ });
182
+ }
183
+ var _ = "\n:host{position:fixed;right:12px;bottom:12px;width:min(520px,calc(100vw - 24px));max-height:calc(100dvh - 24px);overflow:auto;z-index:10001;display:block;color:#202226;background:#fafbfc;border:1px solid #b9bec7;border-radius:4px;font:12px/1.4 system-ui;letter-spacing:0}\n*{box-sizing:border-box}h2{font-size:14px;margin:0;padding:10px 12px;border-bottom:1px solid #d5d9df}.row{display:flex;gap:8px;align-items:center;padding:6px 12px}\nselect{flex:1;min-width:0;font:inherit}textarea{display:block;width:calc(100% - 24px);margin:0 12px;min-height:220px;font:12px/1.45 ui-monospace,Menlo,Consolas,monospace;tab-size:2;white-space:pre;resize:vertical}\nbutton{font:inherit}.status{color:#5d636b}.status[data-state=error]{color:#b42318}ol{margin:4px 12px 10px;padding-left:20px;color:#b42318;font:12px/1.4 ui-monospace,Menlo,Consolas,monospace}\n", v = class i {coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);
184
+ static attach(e, t = {}) {__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));
185
+ let r = new i(t);
186
+ return n(e).use(r), r;
187
+ }
188
+ constructor(e = {}) {
189
+ this.name = "inspector:shaders", this.items = [], this.current = -1, this.pending = Promise.resolve({
190
+ ok: !0,
191
+ modules: 0,
192
+ diagnostics: []
193
+ }), this.disposed = !1, this.applying = !1;
194
+ let n = e.delayMs ?? 400;
195
+ if (!Number.isFinite(n) || n < 0 || n > 1e4) throw RangeError("ShaderEditor delayMs must be 0 to 10000; pass a number of milliseconds in range");
196
+ this.options = e, this.history = e.history ?? new t();
197
+ let r = e.parent ?? document.body, i = r.ownerDocument;
198
+ this.element = i.createElement("div"), this.element.dataset.margoShaderEditor = "";
199
+ let a = this.element.attachShadow({ mode: "open" }), o = i.createElement("style"), s = i.createElement("h2"), c = i.createElement("div"), l = i.createElement("div"), u = i.createElement("button");
200
+ o.textContent = _, s.textContent = "Shaders", c.className = l.className = "row", this.select = i.createElement("select"), this.select.setAttribute("aria-label", "Mesh"), this.textarea = i.createElement("textarea"), this.textarea.spellcheck = !1, this.textarea.setAttribute("aria-label", "WGSL"), u.textContent = "Apply", this.status = i.createElement("span"), this.status.className = "status", this.status.setAttribute("role", "status"), this.list = i.createElement("ol"), c.append(this.select), l.append(u, this.status), a.append(o, s, c, this.textarea, l, this.list), r.append(this.element), this.select.addEventListener("change", () => this.show(Number(this.select.value))), u.addEventListener("click", () => void this.apply()), this.textarea.addEventListener("input", () => {
201
+ this.options.live !== !1 && (clearTimeout(this.timer), this.timer = setTimeout(() => void this.apply(), n));
202
+ }), this.unlisten = this.history.onChange(() => {
203
+ this.applying || this.show(this.current);
204
+ }), this.refresh();
205
+ }
206
+ setup(t) {
207
+ if (this.disposed || this.engine) throw e("attached", "ShaderEditor is disposed or already attached; create a new ShaderEditor");
208
+ this.engine = t;
209
+ }
210
+ get meshes() {
211
+ return this.items;
212
+ }
213
+ get text() {
214
+ return this.textarea.value;
215
+ }
216
+ set text(e) {
217
+ this.textarea.value = e;
218
+ }
219
+ add(e) {
220
+ return r(e?.material) ? (this.items.includes(e) || (this.items.push(e), this.options.meshes = [...this.items], this.fill()), this.current < 0 && this.show(0), this.items.indexOf(e)) : -1;
221
+ }
222
+ refresh() {
223
+ let e = this.options.meshes, t = typeof e == "function" ? e() : e ?? [], n = this.items[this.current];
224
+ this.items = t.filter((e) => r(e?.material)), this.fill();
225
+ let i = n ? this.items.indexOf(n) : -1;
226
+ this.show(i >= 0 ? i : this.items.length ? 0 : -1);
227
+ }
228
+ show(e) {
229
+ if (e >= this.items.length) throw RangeError(`No mesh ${e}; pick an index below ${this.items.length}`);
230
+ this.current = e, this.select.value = String(e);
231
+ let t = this.items[e]?.material;
232
+ this.textarea.value = r(t) ? t.wgsl : "", this.textarea.disabled = e < 0;
233
+ }
234
+ apply(e = this.textarea.value) {
235
+ clearTimeout(this.timer);
236
+ let t = this.items[this.current];
237
+ if (!t) return Promise.reject(/* @__PURE__ */ RangeError("ShaderEditor has no mesh selected; add a WgslMaterial mesh first"));
238
+ let n = async () => {
239
+ if (this.disposed) return {
240
+ ok: !1,
241
+ modules: 0,
242
+ diagnostics: []
243
+ };
244
+ this.status.textContent = "Compiling", this.status.dataset.state = "busy", this.applying = !0;
245
+ let n;
246
+ try {
247
+ n = await h(t, e, {
248
+ device: this.engine?.gpu ?? null,
249
+ history: this.history,
250
+ timeoutMs: this.options.timeoutMs,
251
+ settleMs: Math.min(50, this.options.timeoutMs ?? 3e3)
252
+ });
253
+ } finally {
254
+ this.applying = !1;
255
+ }
256
+ return this.disposed || this.report(n), n;
257
+ };
258
+ return this.pending = this.pending.then(n, n);
259
+ }
260
+ report(e) {
261
+ this.result = e;
262
+ let t = e.diagnostics.filter((e) => e.type === "error");
263
+ this.status.dataset.state = e.ok ? "ok" : "error", this.status.textContent = e.ok ? e.modules ? "Compiled" : "Applied; not drawn yet" : `${t.length} error${t.length === 1 ? "" : "s"}; the mesh keeps its last good shader`;
264
+ let n = this.element.ownerDocument;
265
+ this.list.replaceChildren(...e.diagnostics.map((e) => {
266
+ let t = n.createElement("li");
267
+ return t.textContent = `${e.line ? `${e.line}:${e.column} ` : ""}${e.type}: ${e.message}`, t;
268
+ }));
269
+ }
270
+ fill() {
271
+ let e = this.element.ownerDocument;
272
+ this.select.replaceChildren(...this.items.map((t, n) => {
273
+ let r = e.createElement("option");
274
+ return r.value = String(n), r.textContent = t.name || `Mesh ${n + 1}`, r;
275
+ }));
276
+ }
277
+ dispose() {
278
+ this.disposed || (this.disposed = !0, clearTimeout(this.timer), this.unlisten(), this.element.remove(), this.items = [], this.engine?.sceneOf(this)?.removePlugin(this.name));
279
+ }
280
+ [Symbol.dispose]() {
281
+ this.dispose();
282
+ }
283
+ };
284
+ //#endregion
285
+ export { v as ShaderEditor, r as isWgslMaterial, h as recompileShader };
@@ -0,0 +1,47 @@
1
+ import type { Engine, Mesh } from '@margoengine/core/extension';
2
+ /** One mesh as saved: its place in the tree, transform, visibility and core PBR material values. */
3
+ export interface MeshSnapshot {
4
+ /** Engine id; restore matches meshes by it. */
5
+ id: number;
6
+ name: string;
7
+ /** Parent id, -1 for a root. Informational: restore does not reparent. */
8
+ parent: number;
9
+ visible: boolean;
10
+ position: [number, number, number];
11
+ /** Euler angles in the engine's units (radians). */
12
+ rotation: [number, number, number];
13
+ scale: [number, number, number];
14
+ /** Core PBR material values; colour is linear RGB. Null for a mesh without a material. */
15
+ material: {
16
+ color: [number, number, number];
17
+ roughness: number;
18
+ metalness: number;
19
+ doubleSided: boolean;
20
+ } | null;
21
+ }
22
+ /** A saved scene: plain JSON, safe to `JSON.stringify` and keep in a file. */
23
+ export interface SceneSnapshot {
24
+ format: 'margoengine.scene-snapshot';
25
+ version: 1;
26
+ meshes: MeshSnapshot[];
27
+ }
28
+ /** What `restoreSnapshot` did: meshes updated, and ids in the snapshot with no live mesh. */
29
+ export interface RestoreResult {
30
+ applied: number;
31
+ missing: number[];
32
+ }
33
+ /**
34
+ * The state of `meshes` as plain JSON: names, visibility, transforms and core PBR material values. Take it from an
35
+ * inspector with `inspector.snapshot()`.
36
+ */
37
+ export declare function snapshotMeshes(engine: Engine, meshes: Iterable<Mesh>): SceneSnapshot;
38
+ /** Checks the shape of untrusted snapshot data and returns it typed. */
39
+ export declare function parseSnapshot(data: unknown): SceneSnapshot;
40
+ /**
41
+ * Writes a snapshot's values onto the live meshes with the same ids and reports how many it updated. The whole
42
+ * snapshot is checked before anything changes, so a bad file leaves the scene as it was. A shared material changes for
43
+ * every mesh using it, as when editing it by hand.
44
+ * @throws TypeError / RangeError for a malformed snapshot or a value the engine rejects (a colour out of range),
45
+ * MargoError `'state'` after `engine.dispose()`.
46
+ */
47
+ export declare function restoreSnapshot(engine: Engine, snapshot: unknown): RestoreResult;
@@ -0,0 +1,90 @@
1
+ import { MargoError as e } from "@margoengine/math/errors";
2
+ //#region src/snapshot.ts
3
+ var t = (e) => [
4
+ e.x,
5
+ e.y,
6
+ e.z
7
+ ];
8
+ function n(e, n) {
9
+ let r = [];
10
+ for (let i of n) {
11
+ let n = i.material?.data;
12
+ r.push({
13
+ id: i.id,
14
+ name: i.name,
15
+ parent: e.store.parents[i.id],
16
+ visible: i.visible,
17
+ position: t(i.position),
18
+ rotation: t(i.rotation),
19
+ scale: t(i.scale),
20
+ material: n ? {
21
+ color: [
22
+ n[0],
23
+ n[1],
24
+ n[2]
25
+ ],
26
+ roughness: n[4],
27
+ metalness: n[5],
28
+ doubleSided: !!n[6]
29
+ } : null
30
+ });
31
+ }
32
+ return {
33
+ format: "margoengine.scene-snapshot",
34
+ version: 1,
35
+ meshes: r
36
+ };
37
+ }
38
+ var r = (e, t) => {
39
+ if (!Array.isArray(e) || e.length !== 3 || e.some((e) => typeof e != "number" || !Number.isFinite(e))) throw TypeError(`Scene snapshot ${t} must be three finite numbers; save it again with snapshotMeshes`);
40
+ return !0;
41
+ };
42
+ function i(e) {
43
+ let t = e;
44
+ if (!t || typeof t != "object" || t.format !== "margoengine.scene-snapshot") throw TypeError("Not a scene snapshot; pass the object snapshotMeshes returned or its parsed JSON");
45
+ if (t.version !== 1) throw RangeError(`Scene snapshot version ${String(t.version)} is not supported; this build reads version 1`);
46
+ if (!Array.isArray(t.meshes)) throw TypeError("Scene snapshot needs a meshes array; save it again");
47
+ for (let e of t.meshes) {
48
+ if (!e || !Number.isInteger(e.id) || typeof e.name != "string" || typeof e.visible != "boolean") throw TypeError("Scene snapshot mesh needs an integer id, a name and visible; save it again");
49
+ if (r(e.position, "position"), r(e.rotation, "rotation"), r(e.scale, "scale"), e.material !== null && (r(e.material?.color, "material color"), typeof e.material.doubleSided != "boolean")) throw TypeError("Scene snapshot material needs doubleSided true or false");
50
+ }
51
+ return t;
52
+ }
53
+ function a(t, r) {
54
+ if (t.disposed) throw new e("state", "Engine is disposed; restore into a live engine");
55
+ let a = i(r), s = {
56
+ applied: 0,
57
+ missing: []
58
+ }, c = [];
59
+ for (let e of a.meshes) {
60
+ let n = t.meshes.get(e.id);
61
+ n ? c.push([n, e]) : s.missing.push(e.id);
62
+ }
63
+ let l = c.map(([e]) => ({
64
+ mesh: e,
65
+ state: n(t, [e]).meshes[0]
66
+ }));
67
+ try {
68
+ for (let [e, t] of c) o(e, t);
69
+ } catch (e) {
70
+ for (let { mesh: e, state: t } of l) o(e, t);
71
+ throw e;
72
+ }
73
+ return s.applied = c.length, s;
74
+ }
75
+ function o(e, t) {
76
+ e.name = t.name, e.visible = t.visible;
77
+ for (let [n, r] of [
78
+ ["position", t.position],
79
+ ["rotation", t.rotation],
80
+ ["scale", t.scale]
81
+ ]) e[n].x = r[0], e[n].y = r[1], e[n].z = r[2];
82
+ t.material && e.material && e.material.set({
83
+ color: t.material.color,
84
+ roughness: t.material.roughness,
85
+ metalness: t.material.metalness,
86
+ doubleSided: t.material.doubleSided
87
+ });
88
+ }
89
+ //#endregion
90
+ export { i as parseSnapshot, a as restoreSnapshot, n as snapshotMeshes };
@@ -0,0 +1,127 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ /** One live captured texture, including render targets, storage images and unbound material maps. */
3
+ export interface InspectorTexture {
4
+ id: number;
5
+ label: string;
6
+ width: number;
7
+ height: number;
8
+ depthOrArrayLayers: number;
9
+ dimension: GPUTextureDimension;
10
+ format: GPUTextureFormat;
11
+ mipLevelCount: number;
12
+ sampleCount: number;
13
+ usage: number;
14
+ }
15
+ /** Display the original RGBA/RGB or an isolated channel as grayscale. */
16
+ export type TextureChannel = 'rgba' | 'rgb' | 'r' | 'g' | 'b' | 'a';
17
+ /** Preview settings, all optional. Values are loaded exactly from one mip without filtering. */
18
+ export interface TexturePreviewOptions {
19
+ /** Default 0. */
20
+ mip?: number;
21
+ /** Array/cube face or 3D depth slice at this mip. Default 0. */
22
+ layer?: number;
23
+ /** Default rgba. */
24
+ channel?: TextureChannel;
25
+ /** Depth/stencil aspect. Default depth-only for combined formats, otherwise all. */
26
+ aspect?: GPUTextureAspect;
27
+ /** Multiply source values before display mapping. Default 1. */
28
+ exposure?: number;
29
+ /** Maps (value - range[0]) / (range[1] - range[0]), then clamps for display. Default [0,1]. */
30
+ range?: readonly [number, number];
31
+ /** Stops waiting for readback; no global operation is cancelled. Default unset. */
32
+ signal?: AbortSignal;
33
+ }
34
+ /** Display pixels in top-left row order, including the exact selected mip's dimensions. */
35
+ export interface TexturePreview {
36
+ width: number;
37
+ height: number;
38
+ data: Uint8ClampedArray;
39
+ }
40
+ /** Explicit startup instrumentation, never installed by importing this module. */
41
+ export interface TextureCaptureOptions {
42
+ /** Default navigator.gpu when present. Null captures only explicitly watched devices. */
43
+ gpu?: GPU | null;
44
+ /** Add TEXTURE_BINDING to captured creation descriptors for preview. Default true; application descriptors are not mutated. */
45
+ inspectable?: boolean;
46
+ signal?: AbortSignal;
47
+ }
48
+ /** Tracks textures from device creation, so a panel opened later still sees textures created before it. */
49
+ export declare class TextureCapture {
50
+ private readonly options;
51
+ private readonly records;
52
+ private readonly ids;
53
+ private readonly watched;
54
+ private readonly cleanup;
55
+ private readonly listeners;
56
+ private next;
57
+ private disposed;
58
+ private readonly lifetime;
59
+ private readonly abort;
60
+ /** Install before Engine.create or before creating/loading app textures. */
61
+ static start(options?: TextureCaptureOptions): TextureCapture;
62
+ constructor(options?: TextureCaptureOptions);
63
+ private alive;
64
+ private wrap;
65
+ /** Watches future adapters/devices from this GPU, including restoration requests. Idempotent per GPU. */
66
+ watchGPU(gpu: GPU): void;
67
+ /** Watches future devices from a previously requested adapter. */
68
+ watchAdapter(adapter: GPUAdapter): void;
69
+ /** Watches new textures of an existing device. Earlier textures must be register()ed explicitly. */
70
+ watchDevice(device: GPUDevice): void;
71
+ /** The device was lost: its textures are no longer previewable (called by `watchLost`). */
72
+ private lostDevice;
73
+ private forgetDevice;
74
+ /** Registers a known earlier texture, without modifying its usage. Returns its stable capture id. */
75
+ register(device: GPUDevice, texture: GPUTexture): number;
76
+ /** Registers swapchain textures when requested. Call before the first canvas frame to include them. */
77
+ watchCanvas(context: GPUCanvasContext): void;
78
+ /** Snapshot of all live captured textures; collected and destroyed resources are omitted. */
79
+ list(): InspectorTexture[];
80
+ /** Runs after resource creation/destruction. Returns the unsubscribe function. */
81
+ onChange(listener: () => void): () => void;
82
+ private changed;
83
+ /** Reads one mip/layer through a format-correct, unfiltered GPU shader. Integer and HDR data use explicit display range. */
84
+ preview(id: number, options?: TexturePreviewOptions): Promise<TexturePreview>;
85
+ private wait;
86
+ /** Stops capture, removes owned wrappers and forgets metadata. User textures are never destroyed. */
87
+ dispose(): void;
88
+ [Symbol.dispose](): void;
89
+ }
90
+ /** A texture list, dimensions/format/mip metadata, and channel/mip/layer controls. */
91
+ export interface TextureViewerOptions {
92
+ /** Default document.body. */
93
+ parent?: HTMLElement | ShadowRoot;
94
+ signal?: AbortSignal;
95
+ }
96
+ /** DOM texture explorer; attach after the scene has loaded using its startup capture. */
97
+ export declare class TextureViewer {
98
+ readonly capture: TextureCapture;
99
+ private readonly options;
100
+ readonly element: HTMLFieldSetElement;
101
+ readonly canvas: HTMLCanvasElement;
102
+ private readonly list;
103
+ private readonly mip;
104
+ private readonly layer;
105
+ private readonly channel;
106
+ private readonly aspect;
107
+ private readonly exposure;
108
+ private readonly rangeMin;
109
+ private readonly rangeMax;
110
+ private readonly status;
111
+ private readonly metadata;
112
+ private readonly stop;
113
+ private disposed;
114
+ private request;
115
+ private pending?;
116
+ private readonly abort;
117
+ static attach(capture: TextureCapture, options?: TextureViewerOptions): TextureViewer;
118
+ constructor(capture: TextureCapture, options?: TextureViewerOptions);
119
+ /** Updates live metadata/list while preserving the selected resource. */
120
+ refresh(): void;
121
+ /** Displays a resource and optional subresource/channel selection. Resolves after its pixels are visible. */
122
+ select(id: number, options?: TexturePreviewOptions): Promise<void>;
123
+ private render;
124
+ /** Removes the panel and cancels its pending preview. Capture and user textures remain owned by the caller. */
125
+ dispose(): void;
126
+ [Symbol.dispose](): void;
127
+ }