@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
package/dist/frame.js ADDED
@@ -0,0 +1,881 @@
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 { r as t } from "./mesh-source-BSQA_1GQ.js";
6
+ import { engineRuntime as __margoRuntime } from "@margoengine/core/extension";
7
+ import { GPUProfiler as r } from "@margoengine/stats";
8
+ //#region src/frame-panel.ts
9
+ var i = "\n:host{position:fixed;left:12px;bottom:12px;width:520px;max-width:calc(100vw - 24px);z-index:10001;display:block;color:#202226;font:12px/1.4 system-ui;letter-spacing:0}\n*{box-sizing:border-box}section{background:#fafbfc;border:1px solid #b9bec7;border-radius:4px;max-height:min(70dvh,640px);overflow:auto}\nheader{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:8px 12px;border-bottom:1px solid #d5d9df;position:sticky;top:0;background:#fafbfc}\nh2{font-size:14px;margin:0}button{font:inherit;border:1px solid #9aa1ab;border-radius:3px;background:#fff;color:inherit;cursor:pointer;padding:3px 8px}\nbutton:focus-visible,summary:focus-visible{outline:2px solid #087e67;outline-offset:1px}\np,ul{margin:0;padding:6px 12px}ul{padding-left:28px;color:#8a4b00}details{padding:2px 0 2px 12px}summary{cursor:pointer;padding:2px 0}\n.body{padding:4px 12px 10px 0}table{border-collapse:collapse;width:100%;font-variant-numeric:tabular-nums}th,td{text-align:left;padding:2px 6px 2px 0;border-bottom:1px solid #e3e6ea;vertical-align:top}\nth{font-weight:600}.muted{color:#5d636b}td button{padding:0 6px}\n", a = (e) => e === null ? "-" : e.toFixed(3) + " ms", o = (e) => e >= 1048576 ? (e / 1048576).toFixed(2) + " MB" : e >= 1024 ? (e / 1024).toFixed(1) + " KB" : e + " B", s = (e) => e.label || `(${e.passes.join(", ") || "unused"})`, c = (e) => e == null ? "?" : e.toLocaleString("en-US"), l = class {
10
+ constructor(e, t, n) {
11
+ this.onSelect = n, this.doc = e.ownerDocument, this.element = this.doc.createElement("div"), this.element.dataset.margoFrameDebugger = "";
12
+ let r = this.element.attachShadow({ mode: "open" }), a = this.el("style", i), o = this.el("section"), s = this.el("header"), c = this.el("button", "Capture frame");
13
+ c.type = "button", c.addEventListener("click", t), s.append(this.el("h2", "Frame debugger"), c), this.body = this.el("div"), this.body.append(this.el("p", "No capture yet.")), o.append(s, this.body), r.append(a, o), e.append(this.element);
14
+ }
15
+ show(e) {
16
+ let t = e.totals, n = this.body;
17
+ if (n.replaceChildren(this.el("p", `${t.draws} draws (${t.indexedDraws} indexed, ${t.indirectDraws} indirect), ${t.dispatches} dispatches, ${c(t.triangles)} triangles, ${t.renderPasses + t.computePasses} GPU passes. CPU ${a(e.cpuMilliseconds)}, GPU ${a(e.gpuMilliseconds)}. Uploads ${o(t.uploadBytes)} in ${t.uploads} writes; ${t.pipelinesCreated} pipelines compiled this frame.`)), e.note && n.append(this.el("p", e.note, "muted")), e.warnings.length) {
18
+ let t = this.el("ul");
19
+ for (let n of e.warnings) t.append(this.el("li", n));
20
+ n.append(t);
21
+ }
22
+ for (let t of e.graph) {
23
+ let r = t.passes.reduce((e, t) => e + t.commands.length, 0), i = this.details(`${t.name} (${t.owner}${t.order === null ? "" : ", order " + t.order}): ${r} commands, CPU ${a(t.cpuMilliseconds)}, GPU ${a(t.gpuMilliseconds)}`);
24
+ for (let n of t.passes) i.append(this.pass(n, e.pipelines));
25
+ n.append(i);
26
+ }
27
+ let r = this.details(`Plugins (${e.plugins.length})`);
28
+ r.append(this.table([
29
+ "Plugin",
30
+ "Scene",
31
+ "Order",
32
+ "Passes",
33
+ "onPreUpdate"
34
+ ], e.plugins.map((e) => [
35
+ e.name,
36
+ e.scene,
37
+ String(e.order),
38
+ String(e.passes),
39
+ e.preUpdateMilliseconds === null ? "none" : a(e.preUpdateMilliseconds)
40
+ ]))), n.append(r);
41
+ let i = this.details(`Pipelines (${e.pipelines.length})`);
42
+ i.append(this.table([
43
+ "#",
44
+ "Label (passes)",
45
+ "Kind",
46
+ "Cull",
47
+ "Blend",
48
+ "Depth",
49
+ "MSAA",
50
+ "Textures",
51
+ "Samplers",
52
+ "New"
53
+ ], e.pipelines.map((e) => [
54
+ String(e.id),
55
+ s(e),
56
+ e.kind,
57
+ e.cullMode ?? "?",
58
+ e.blend?.join(", ") ?? "?",
59
+ e.depth === void 0 ? "?" : e.depth === null ? "none" : `${e.depth.format} ${e.depth.compare}${e.depth.write ? " write" : ""}`,
60
+ e.samples === void 0 ? "?" : String(e.samples),
61
+ `${e.textures}/16`,
62
+ `${e.samplers}/16`,
63
+ e.createdThisFrame ? "yes" : ""
64
+ ]))), n.append(i);
65
+ let l = e.memory, u = this.details(`GPU memory ${o(l.bytes)} (tracked since attach)`);
66
+ u.append(this.table([
67
+ "Kind",
68
+ "Label",
69
+ "Size"
70
+ ], [
71
+ [
72
+ "buffers",
73
+ `${l.buffers.count} live`,
74
+ o(l.buffers.bytes)
75
+ ],
76
+ [
77
+ "textures",
78
+ `${l.textures.count} live`,
79
+ o(l.textures.bytes)
80
+ ],
81
+ ...l.largest.map((e) => [
82
+ e.kind,
83
+ e.label,
84
+ o(e.bytes)
85
+ ])
86
+ ])), n.append(u);
87
+ }
88
+ dispose() {
89
+ this.element.remove();
90
+ }
91
+ pass(e, t) {
92
+ let n = this.details(`${e.kind} pass ${e.label ? `"${e.label}" ` : ""}(encoder ${e.encoder}): ${e.commands.length} commands, GPU ${a(e.gpuMilliseconds)}`);
93
+ for (let t of e.attachments) {
94
+ let e = t.view ? `${t.view.label || "texture"} ${t.view.format} ${t.view.width}x${t.view.height}${t.view.sampleCount > 1 ? " x" + t.view.sampleCount : ""}` : "view created before attach";
95
+ n.append(this.el("p", `${t.target}${t.target === "color" ? t.index : ""}: ${e}, ${t.loadOp ?? "-"}/${t.storeOp ?? "-"}`, "muted"));
96
+ }
97
+ let r = e.commands.map((e, n) => this.row(n, e, t));
98
+ if (r.length) {
99
+ let e = this.table([
100
+ "#",
101
+ "Command",
102
+ "Count",
103
+ "Instances",
104
+ "Triangles",
105
+ "Pipeline",
106
+ "Groups",
107
+ "Object"
108
+ ], []);
109
+ e.tBodies[0].append(...r), n.append(e);
110
+ }
111
+ return n;
112
+ }
113
+ row(e, t, n) {
114
+ let r = t.pipeline === null ? void 0 : n[t.pipeline], i = t.workgroups === void 0 ? t.bundles === void 0 ? c(t.indexCount ?? t.vertexCount) : `${t.bundles} bundles` : t.workgroups ? t.workgroups.join("x") : "?", a = this.doc.createElement("tr");
115
+ for (let n of [
116
+ String(e),
117
+ t.kind,
118
+ i,
119
+ c(t.instanceCount),
120
+ c(t.triangles),
121
+ r ? `#${r.id} ${r.label}`.trim() : "-",
122
+ t.bindGroups.map((e) => e ?? "-").join(", ")
123
+ ]) a.append(this.el("td", n));
124
+ let o = this.el("td");
125
+ if (t.entities.length) {
126
+ let e = this.el("button", `${t.entities.length} mesh${t.entities.length > 1 ? "es" : ""}`);
127
+ e.type = "button", e.title = "Select in the Inspector", e.addEventListener("click", () => this.onSelect(t.entities[0])), o.append(e);
128
+ }
129
+ return a.append(o), a;
130
+ }
131
+ details(e) {
132
+ let t = this.el("details");
133
+ return t.append(this.el("summary", e)), t;
134
+ }
135
+ table(e, t, n) {
136
+ let r = this.el("table", "", n), i = this.el("tr"), a = this.el("tbody");
137
+ for (let t of e) i.append(this.el("th", t));
138
+ r.append(this.el("thead"), a), r.tHead.append(i);
139
+ for (let e of t) {
140
+ let t = this.el("tr");
141
+ for (let n of e) t.append(this.el("td", n));
142
+ a.append(t);
143
+ }
144
+ return r;
145
+ }
146
+ el(e, t = "", n) {
147
+ let r = this.doc.createElement(e);
148
+ return t && (r.textContent = t), n && (r.className = n), r;
149
+ }
150
+ };
151
+ //#endregion
152
+ //#region src/frame.ts
153
+ function u(e, t, n) {
154
+ let r = Object.hasOwn(e, t), i = e[t];
155
+ if (typeof i != "function") return () => {};
156
+ let a = n(i);
157
+ return e[t] = a, (e) => {
158
+ e[t] === a && (r ? e[t] = i : Reflect.deleteProperty(e, t));
159
+ };
160
+ }
161
+ function d(e, t, n) {
162
+ e.push(() => n(t));
163
+ }
164
+ var f = (e) => e, p = (e) => typeof e == "object" && !!e && typeof e.execute == "function" && typeof e.name == "string";
165
+ function m(e) {
166
+ for (let t of Object.values(e)) if (Array.isArray(t) && t.length && t.every(p)) return t;
167
+ return [];
168
+ }
169
+ var h = 1024, g = (e) => e === "drawIndexedIndirect" ? 20 : 16, _ = (e) => e.constructor?.name ?? "";
170
+ function v(e) {
171
+ let t = /^astc-(\d+)x(\d+)/.exec(e);
172
+ if (t) return 16 / (Number(t[1]) * Number(t[2]));
173
+ if (/^(bc[14]-|etc2-rgb8|eac-r11)/.test(e)) return .5;
174
+ if (/^(bc|etc2|eac)/.test(e)) return 1;
175
+ if (e === "depth32float-stencil8") return 5;
176
+ if (e === "stencil8") return 1;
177
+ if (e === "depth16unorm") return 2;
178
+ let n = /^(rgba|bgra|rg|r)(8|16|32)/.exec(e);
179
+ return n ? n[1].length * Number(n[2]) / 8 : 4;
180
+ }
181
+ function y(e) {
182
+ let t = /^astc-(\d+)x(\d+)/.exec(e.format), [n, r] = t ? [Number(t[1]), Number(t[2])] : /^(bc|etc2|eac)/.test(e.format) ? [4, 4] : [1, 1], i = 0;
183
+ for (let t = 0; t < e.mipLevelCount; t++) {
184
+ let a = e.dimension === "3d" ? Math.max(1, e.depthOrArrayLayers >> t) : e.depthOrArrayLayers;
185
+ i += Math.ceil(Math.max(1, e.width >> t) / n) * Math.ceil(Math.max(1, e.height >> t) / r) * a;
186
+ }
187
+ return Math.ceil(i * n * r * v(e.format) * e.sampleCount);
188
+ }
189
+ function b(e) {
190
+ let { label: t, format: n, width: r, height: i, depthOrArrayLayers: a, sampleCount: o, mipLevelCount: s } = e;
191
+ return {
192
+ label: t,
193
+ format: n,
194
+ width: r,
195
+ height: i,
196
+ depthOrArrayLayers: a,
197
+ sampleCount: o,
198
+ mipLevelCount: s
199
+ };
200
+ }
201
+ var x = (e) => `${e.label || "buffer"} (${e.size} B)`;
202
+ function S(e) {
203
+ let t = [...e.fragment?.targets ?? []].filter((e) => !!e), n = e.depthStencil;
204
+ return {
205
+ topology: e.primitive?.topology ?? "triangle-list",
206
+ cullMode: e.primitive?.cullMode ?? "none",
207
+ formats: t.map((e) => e.format),
208
+ blend: t.map(({ blend: e }) => e ? `${e.color.operation ?? "add"}(${e.color.srcFactor ?? "one"}, ${e.color.dstFactor ?? "zero"})` : "none"),
209
+ depth: n ? {
210
+ format: n.format,
211
+ write: !!n.depthWriteEnabled,
212
+ compare: n.depthCompare ?? "always"
213
+ } : null,
214
+ samples: e.multisample?.count ?? 1
215
+ };
216
+ }
217
+ function C(e, t = 0, n) {
218
+ let r = ArrayBuffer.isView(e) ? e.BYTES_PER_ELEMENT ?? 1 : 1;
219
+ return n === void 0 ? e.byteLength - t * r : n * r;
220
+ }
221
+ function w(e) {
222
+ if (typeof e == "object" && e && Symbol.iterator in e) return [...e];
223
+ let { width: t, height: n = 1, depthOrArrayLayers: r = 1 } = e;
224
+ return [
225
+ t,
226
+ n,
227
+ r
228
+ ];
229
+ }
230
+ function T(e, t, n) {
231
+ return t === null || n === null ? null : e === "triangle-strip" ? Math.max(0, t - 2) * n : !e || e === "triangle-list" ? Math.floor(t / 3) * n : 0;
232
+ }
233
+ var E = class {
234
+ constructor(e) {
235
+ this.profiled = e, this.live = !0, this.start = performance.now(), this.cpu = 0, this.before = {
236
+ name: "(before frame graph)",
237
+ owner: "engine",
238
+ order: null,
239
+ cpu: 0,
240
+ passes: []
241
+ }, this.after = {
242
+ name: "(after frame graph)",
243
+ owner: "engine",
244
+ order: null,
245
+ cpu: 0,
246
+ passes: []
247
+ }, this.graph = [], this.plugins = [], this.current = this.before, this.encoders = 0, this.submits = 0, this.timed = 0, this.resolved = !1, this.shaderModules = 0, this.asyncPipelines = 0, this.bindGroups = 0, this.created = /* @__PURE__ */ new Set(), this.uploads = /* @__PURE__ */ new Map(), this.indirect = [], this.unpatch = [];
248
+ }
249
+ upload(e, t, n) {
250
+ let r = this.uploads.get(e) ?? {
251
+ target: t,
252
+ calls: 0,
253
+ bytes: 0
254
+ };
255
+ r.calls++, r.bytes += n, this.uploads.set(e, r);
256
+ }
257
+ close() {
258
+ this.live = !1, this.cpu = performance.now() - this.start;
259
+ for (let e of this.unpatch.reverse()) e();
260
+ }
261
+ }, D = class i {coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);
262
+ constructor({ parent: e } = {}) {
263
+ this.name = "frame-debugger", this.report = null, this.disposed = !1, this.paused = !1, this.unpatchDevice = [], this.tracked = /* @__PURE__ */ new Set(), this.pipelines = /* @__PURE__ */ new WeakMap(), this.groups = /* @__PURE__ */ new WeakMap(), this.views = /* @__PURE__ */ new WeakMap();
264
+ let t = e === void 0 ? typeof document > "u" ? null : document.body : e;
265
+ t && (this.panel = new l(t, () => this.captureFromPanel(), (e) => this.select(e)));
266
+ }
267
+ static attach(e, t = {}) {__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));
268
+ let r = new i(t);
269
+ try {
270
+ return n(e).use(r), r;
271
+ } catch (e) {
272
+ throw r.dispose(), e;
273
+ }
274
+ }
275
+ setup(t) {
276
+ if (this.disposed || this.engine) throw e("attached", "FrameDebugger is disposed or already attached; create a new FrameDebugger for this engine");
277
+ this.engine = t, t.gpu && this.track(t.gpu);
278
+ }
279
+ onDeviceRestored(e) {
280
+ this.untrack(), e.gpu && this.track(e.gpu);
281
+ }
282
+ capture(e = {}) {
283
+ let t = this.engine;
284
+ if (this.disposed || !t) return Promise.reject(/* @__PURE__ */ Error("FrameDebugger is not attached"));
285
+ if (t.backend !== "webgpu" || !t.gpu) return Promise.reject(/* @__PURE__ */ Error("Frame capture needs WebGPU"));
286
+ let n = this.pending;
287
+ if (!n) {
288
+ let e, r, i = new Promise((t, n) => {
289
+ e = t, r = n;
290
+ }), a = this, o = u(t, "render", (t) => function(n) {
291
+ if (a.pending?.promise !== i) return t.call(this, n);
292
+ a.pending.disarm(), a.record(() => t.call(this, n), e, r);
293
+ });
294
+ n = this.pending = {
295
+ promise: i,
296
+ reject: r,
297
+ disarm: () => {
298
+ o(t), this.pending = void 0;
299
+ }
300
+ };
301
+ }
302
+ if (e.render) try {
303
+ t.render();
304
+ } catch {}
305
+ return n.promise;
306
+ }
307
+ memory() {
308
+ let e = {
309
+ bytes: 0,
310
+ buffers: {
311
+ count: 0,
312
+ bytes: 0
313
+ },
314
+ textures: {
315
+ count: 0,
316
+ bytes: 0
317
+ },
318
+ largest: []
319
+ };
320
+ for (let t of this.tracked) {
321
+ let n = t.ref.deref();
322
+ if (!n) {
323
+ this.tracked.delete(t);
324
+ continue;
325
+ }
326
+ let r = t.kind === "buffer" ? n.size : y(n), i = t.kind === "buffer" ? e.buffers : e.textures;
327
+ i.count++, i.bytes += r, e.bytes += r;
328
+ let a = n;
329
+ e.largest.push({
330
+ kind: t.kind,
331
+ label: t.kind === "buffer" ? n.label || "buffer" : `${a.label || "texture"} ${a.format} ${a.width}x${a.height}${a.sampleCount > 1 ? " x" + a.sampleCount : ""}`,
332
+ bytes: r
333
+ });
334
+ }
335
+ return e.largest = e.largest.sort((e, t) => t.bytes - e.bytes).slice(0, 10), e;
336
+ }
337
+ dispose() {
338
+ if (this.disposed) return;
339
+ this.disposed = !0;
340
+ let e = this.pending;
341
+ e?.disarm(), e?.reject(/* @__PURE__ */ Error("FrameDebugger disposed")), this.untrack(), this.engine?.sceneOf(this)?.removePlugin(this.name), this.engine = void 0, this.panel?.dispose();
342
+ }
343
+ [Symbol.dispose ?? Symbol()]() {
344
+ this.dispose();
345
+ }
346
+ captureFromPanel() {
347
+ let e = this.capture();
348
+ e.catch((e) => this.engine?.onError(e)), requestAnimationFrame(() => {
349
+ this.pending?.promise === e && this.capture({ render: !0 }).catch(() => {});
350
+ });
351
+ }
352
+ select(e) {
353
+ let t = this.engine?.meshes.get(e), n = this.engine?.plugins.get("inspector");
354
+ t && typeof n?.select == "function" && n.select(t);
355
+ }
356
+ track(e) {
357
+ this.device = e;
358
+ let t = this, n = (e, t) => d(this.unpatchDevice, e, t);
359
+ n(e, u(e, "createBuffer", (n) => function(r) {
360
+ let i = n.call(this, r);
361
+ return t.device === e && !t.paused && t.trackResource(i, "buffer"), i;
362
+ })), n(e, u(e, "createTexture", (n) => function(r) {
363
+ let i = n.call(this, r);
364
+ return t.device === e && !t.paused && t.trackResource(i, "texture"), i;
365
+ })), n(e, u(e, "createRenderPipeline", (n) => function(r) {
366
+ let i = n.call(this, r);
367
+ return t.pipelineCreated(e, i, "render", S(r), !0), i;
368
+ })), n(e, u(e, "createComputePipeline", (n) => function(r) {
369
+ let i = n.call(this, r);
370
+ return t.pipelineCreated(e, i, "compute", {}, !0), i;
371
+ })), n(e, u(e, "createRenderPipelineAsync", (n) => function(r) {
372
+ let i = n.call(this, r);
373
+ return t.session?.live && t.session.asyncPipelines++, i.then((n) => t.pipelineCreated(e, n, "render", S(r), !1), () => {}), i;
374
+ })), n(e, u(e, "createComputePipelineAsync", (n) => function(r) {
375
+ let i = n.call(this, r);
376
+ return t.session?.live && t.session.asyncPipelines++, i.then((n) => t.pipelineCreated(e, n, "compute", {}, !1), () => {}), i;
377
+ })), n(e, u(e, "createBindGroup", (n) => function(r) {
378
+ let i = n.call(this, r);
379
+ return t.device === e && (t.groups.set(i, {
380
+ label: r.label ?? "",
381
+ entries: [...r.entries]
382
+ }), t.session?.live && t.session.bindGroups++), i;
383
+ }));
384
+ }
385
+ pipelineCreated(e, t, n, r, i) {
386
+ this.device === e && (this.pipelines.set(t, {
387
+ kind: n,
388
+ fields: r
389
+ }), i && this.session?.live && this.session.created.add(t));
390
+ }
391
+ trackResource(e, t) {
392
+ let n = {
393
+ kind: t,
394
+ ref: new WeakRef(e),
395
+ unpatch: []
396
+ }, r = this.tracked, i = this.views, a = f(e);
397
+ r.add(n), n.unpatch.push(u(a, "destroy", (e) => function() {
398
+ r.delete(n);
399
+ for (let e of n.unpatch) e(f(this));
400
+ return e.call(this);
401
+ })), t === "texture" && n.unpatch.push(u(a, "createView", (e) => function(...t) {
402
+ let n = Reflect.apply(e, this, t);
403
+ return i.set(n, this), n;
404
+ }));
405
+ }
406
+ untrack() {
407
+ for (let e of this.unpatchDevice.reverse()) e();
408
+ this.unpatchDevice = [];
409
+ for (let e of this.tracked) {
410
+ let t = e.ref.deref();
411
+ if (t) for (let n of e.unpatch) n(f(t));
412
+ }
413
+ this.tracked.clear(), this.profiler?.dispose(), this.profiler = void 0, this.device = void 0;
414
+ }
415
+ record(e, t, n) {
416
+ let i = this.engine, a = i.gpu;
417
+ if (a !== this.device && (this.untrack(), this.track(a)), !this.profiler && a.features.has("timestamp-query")) {
418
+ this.paused = !0;
419
+ try {
420
+ this.profiler = new r(a);
421
+ } finally {
422
+ this.paused = !1;
423
+ }
424
+ }
425
+ let o = new E(!!this.profiler?.beginFrame());
426
+ this.session = o, this.instrument(o, i, a);
427
+ try {
428
+ e();
429
+ } catch (e) {
430
+ throw o.close(), n(e), e;
431
+ }
432
+ o.close(), o.profiled && !o.resolved && (this.profiler?.dispose(), this.profiler = void 0), this.finish(o, i).then((e) => {
433
+ this.report = e, this.panel?.show(e), t(e);
434
+ }, n);
435
+ }
436
+ instrumentPlugins(e, t, n, r) {
437
+ let i = 0;
438
+ for (let [a, o] of n) {
439
+ let n = {
440
+ name: a,
441
+ scene: t,
442
+ order: i++,
443
+ passes: r.filter((e) => e.owner === a).length,
444
+ preUpdateMilliseconds: null
445
+ };
446
+ if (e.plugins.push(n), typeof o.onPreUpdate != "function") continue;
447
+ let s;
448
+ try {
449
+ s = u(o, "onPreUpdate", (t) => function(r) {
450
+ if (!e.live) return t.call(this, r);
451
+ let i = performance.now();
452
+ try {
453
+ t.call(this, r);
454
+ } finally {
455
+ n.preUpdateMilliseconds = (n.preUpdateMilliseconds ?? 0) + performance.now() - i;
456
+ }
457
+ });
458
+ } catch {
459
+ continue;
460
+ }
461
+ n.preUpdateMilliseconds = 0, d(e.unpatch, o, s);
462
+ }
463
+ }
464
+ instrument(e, t, n) {
465
+ let r = this, i = (t, n) => d(e.unpatch, t, n);
466
+ for (let n of t.scenes) {
467
+ let t = n.frameGraph;
468
+ this.instrumentPlugins(e, n.name, n.plugins, m(t)), i(t, u(t, "execute", (t) => function(r) {
469
+ if (!e.live) return t.call(this, r);
470
+ r.backend === "webgpu" && (e.main = r.encoder);
471
+ let i = [], a = r.view && {
472
+ id: r.view.id,
473
+ viewport: r.view.viewport,
474
+ scene: n.name
475
+ };
476
+ for (let t of m(this)) {
477
+ let n = {
478
+ name: t.name,
479
+ owner: t.owner ?? (t.name === "main" ? "core" : "app"),
480
+ order: t.order,
481
+ ...a && { view: a },
482
+ cpu: 0,
483
+ passes: []
484
+ };
485
+ e.graph.push(n), d(i, t, u(t, "execute", (t) => function(r) {
486
+ e.current = n;
487
+ let i = performance.now();
488
+ try {
489
+ t.call(this, r);
490
+ } finally {
491
+ n.cpu += performance.now() - i, e.current = e.after;
492
+ }
493
+ }));
494
+ }
495
+ try {
496
+ t.call(this, r);
497
+ } finally {
498
+ for (let e of i) e();
499
+ e.current = e.after;
500
+ }
501
+ }));
502
+ }
503
+ i(n, u(n, "createCommandEncoder", (t) => function(n) {
504
+ let i = t.call(this, n);
505
+ return e.live && r.wrapEncoder(e, i, e.encoders++), i;
506
+ })), i(n, u(n, "createShaderModule", (t) => function(n) {
507
+ return e.live && e.shaderModules++, t.call(this, n);
508
+ }));
509
+ let a = n.queue;
510
+ i(a, u(a, "writeBuffer", (t) => function(n, r, i, a, o) {
511
+ return e.live && e.upload(n, x(n), C(i, a, o)), t.call(this, n, r, i, a, o);
512
+ }));
513
+ let o = f(a);
514
+ if (i(o, u(o, "writeTexture", (t) => function(...n) {
515
+ let [r, i, a] = n;
516
+ return e.live && e.upload(r.texture, r.texture.label || "texture", i.byteLength - (a.offset ?? 0)), Reflect.apply(t, this, n);
517
+ })), i(o, u(o, "copyExternalImageToTexture", (t) => function(...n) {
518
+ let [r = 1, i = 1, a = 1] = w(n[2]), o = n[1].texture;
519
+ return e.live && e.upload(o, o.label || "texture", Math.ceil(r * i * a * v(o.format))), Reflect.apply(t, this, n);
520
+ })), i(a, u(a, "submit", (t) => function(n) {
521
+ return e.live && e.submits++, t.call(this, n);
522
+ })), typeof GPUTexture < "u") {
523
+ let t = this.views;
524
+ i(GPUTexture.prototype, u(GPUTexture.prototype, "createView", (n) => function(r) {
525
+ let i = n.call(this, r);
526
+ return e.live && t.set(i, this), i;
527
+ }));
528
+ }
529
+ }
530
+ wrapEncoder(e, t, n) {
531
+ let r = this, i = this.profiler, a = (t, n) => d(e.unpatch, t, n), o = (t, n) => e.profiled && t === e.main && !n?.timestampWrites ? i?.timestampWrites() : void 0;
532
+ a(t, u(t, "beginRenderPass", (t) => function(i) {
533
+ if (!e.live) return t.call(this, i);
534
+ let a = o(this, i), s = t.call(this, a ? {
535
+ ...i,
536
+ timestampWrites: a
537
+ } : i);
538
+ return r.wrapPass(e, s, {
539
+ kind: "render",
540
+ label: i.label ?? "",
541
+ encoder: n,
542
+ timestamp: a ? e.timed++ : -1,
543
+ attachments: r.attachments(i),
544
+ commands: []
545
+ }), s;
546
+ })), a(t, u(t, "beginComputePass", (t) => function(i) {
547
+ if (!e.live) return t.call(this, i);
548
+ let a = o(this, i), s = t.call(this, a ? {
549
+ ...i,
550
+ timestampWrites: a
551
+ } : i);
552
+ return r.wrapPass(e, s, {
553
+ kind: "compute",
554
+ label: i?.label ?? "",
555
+ encoder: n,
556
+ timestamp: a ? e.timed++ : -1,
557
+ attachments: [],
558
+ commands: []
559
+ }), s;
560
+ })), a(t, u(t, "finish", (t) => function(n) {
561
+ return e.live && this === e.main && (e.resolved = !0, r.copyIndirect(e, this), e.profiled && !i?.resolve(this) && (e.timed = 0)), t.call(this, n);
562
+ }));
563
+ }
564
+ copyIndirect(e, t) {
565
+ let n = e.indirect.filter(({ kind: e, indirect: t }) => {
566
+ let { buffer: n, offset: r } = t;
567
+ return (n.usage & GPUBufferUsage.COPY_SRC) !== 0 && r % 4 == 0 && r + g(e) <= n.size;
568
+ }).slice(0, h);
569
+ if (n.length) {
570
+ this.paused = !0;
571
+ try {
572
+ e.readback = this.device.createBuffer({
573
+ label: "frame-debugger:indirect",
574
+ size: n.length * 20,
575
+ usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
576
+ });
577
+ } finally {
578
+ this.paused = !1;
579
+ }
580
+ n.forEach((n, r) => {
581
+ let i = n.indirect;
582
+ i.slot = r, t.copyBufferToBuffer(i.buffer, i.offset, e.readback, r * 20, g(n.kind));
583
+ });
584
+ }
585
+ }
586
+ wrapPass(e, t, n) {
587
+ e.current.passes.push(n);
588
+ let r = {
589
+ pipeline: null,
590
+ groups: []
591
+ }, i = f(t), a = (t, n) => d(e.unpatch, i, u(i, t, (t) => function(...r) {
592
+ return e.live && n(r), Reflect.apply(t, this, r);
593
+ }));
594
+ a("setPipeline", ([e]) => {
595
+ r.pipeline = e;
596
+ }), a("setBindGroup", ([e, t]) => {
597
+ r.groups[e] = t;
598
+ });
599
+ let o = (t) => a(t, (i) => {
600
+ let a = {
601
+ kind: t,
602
+ pipeline: r.pipeline,
603
+ groups: r.groups.slice(),
604
+ vertex: r.vertex,
605
+ vertexOffset: r.vertexOffset,
606
+ args: []
607
+ };
608
+ t === "executeBundles" ? a.args = [[...i[0]].length] : t.endsWith("Indirect") ? (a.indirect = {
609
+ buffer: i[0],
610
+ offset: Number(i[1] ?? 0),
611
+ slot: -1
612
+ }, t !== "dispatchWorkgroupsIndirect" && e.indirect.push(a)) : a.args = i.map(Number), n.commands.push(a);
613
+ });
614
+ if (n.kind === "render") {
615
+ a("setVertexBuffer", ([e, t, n]) => {
616
+ e === 0 && (r.vertex = t ?? void 0, r.vertexOffset = Number(n ?? 0));
617
+ });
618
+ for (let e of [
619
+ "draw",
620
+ "drawIndexed",
621
+ "drawIndirect",
622
+ "drawIndexedIndirect",
623
+ "executeBundles"
624
+ ]) o(e);
625
+ } else for (let e of ["dispatchWorkgroups", "dispatchWorkgroupsIndirect"]) o(e);
626
+ }
627
+ texture(e) {
628
+ if (!e) return null;
629
+ let t = this.views.get(e) ?? (_(e) === "GPUTexture" || "mipLevelCount" in e ? e : void 0);
630
+ return t ? b(t) : null;
631
+ }
632
+ attachments(e) {
633
+ let t = [];
634
+ [...e.colorAttachments].forEach((e, n) => {
635
+ if (!e) return;
636
+ let r = {
637
+ target: "color",
638
+ index: n,
639
+ view: this.texture(e.view),
640
+ loadOp: e.loadOp,
641
+ storeOp: e.storeOp
642
+ };
643
+ e.resolveTarget && (r.resolveTarget = this.texture(e.resolveTarget)), t.push(r);
644
+ });
645
+ let n = e.depthStencilAttachment;
646
+ if (n) {
647
+ let e = {
648
+ target: "depth",
649
+ index: 0,
650
+ view: this.texture(n.view),
651
+ loadOp: n.depthLoadOp,
652
+ storeOp: n.depthStoreOp,
653
+ readOnly: !!n.depthReadOnly
654
+ };
655
+ n.stencilLoadOp && (e.stencilLoadOp = n.stencilLoadOp), n.stencilStoreOp && (e.stencilStoreOp = n.stencilStoreOp), t.push(e);
656
+ }
657
+ return t;
658
+ }
659
+ binding(e) {
660
+ let t = e.resource, n = e.binding;
661
+ if ("buffer" in t && t.buffer) {
662
+ let { buffer: e, offset: r = 0, size: i } = t;
663
+ return {
664
+ binding: n,
665
+ kind: "buffer",
666
+ resource: `${x(e)} @${r}${i === void 0 ? "" : `+${i}`}`
667
+ };
668
+ }
669
+ let r = this.views.get(t);
670
+ if (r) return {
671
+ binding: n,
672
+ kind: "texture",
673
+ resource: `${r.label || "texture"} ${r.format} ${r.width}x${r.height}`
674
+ };
675
+ switch (_(t)) {
676
+ case "GPUBuffer": return {
677
+ binding: n,
678
+ kind: "buffer",
679
+ resource: x(t)
680
+ };
681
+ case "GPUTexture": return {
682
+ binding: n,
683
+ kind: "texture",
684
+ resource: `${t.label || "texture"} ${t.format}`
685
+ };
686
+ case "GPUTextureView": return {
687
+ binding: n,
688
+ kind: "texture",
689
+ resource: t.label || "texture view (created before attach)"
690
+ };
691
+ case "GPUSampler": return {
692
+ binding: n,
693
+ kind: "sampler",
694
+ resource: t.label || "sampler"
695
+ };
696
+ case "GPUExternalTexture": return {
697
+ binding: n,
698
+ kind: "external-texture",
699
+ resource: "external texture"
700
+ };
701
+ default: return {
702
+ binding: n,
703
+ kind: "unknown",
704
+ resource: "unknown"
705
+ };
706
+ }
707
+ }
708
+ async finish(e, t) {
709
+ let n = this.profiler, r = [], i = {
710
+ gpu: null,
711
+ words: null
712
+ }, a = e.profiled && e.timed > 0 && n ? n.read().then((e) => {
713
+ e !== null && (i.gpu = n.passMilliseconds);
714
+ }, (e) => {
715
+ r.push(`GPU timestamps unusable: ${String(e)}.`);
716
+ }) : void 0, o = e.readback, s = o ? o.mapAsync(GPUMapMode.READ).then(() => {
717
+ i.words = new Uint32Array(o.getMappedRange().slice(0)), o.unmap();
718
+ }, () => {}).finally(() => o.destroy()) : void 0;
719
+ return await Promise.all([a, s]), !e.profiled && !n ? r.push("GPU timing needs Engine.create(canvas, {features: ['timestamp-query']}); pass times are CPU encode times.") : !i.gpu && !r.length && r.push("GPU timestamps were unavailable for this frame (profiler busy or over 128 passes); pass times are CPU encode times."), this.build(e, t, i.gpu, i.words, r);
720
+ }
721
+ build(e, n, r, i, a) {
722
+ let o = /* @__PURE__ */ new Map(), s = /* @__PURE__ */ new Map(), c = [], l = (t, n) => {
723
+ let r = o.get(t);
724
+ if (!r) {
725
+ let i = this.pipelines.get(t);
726
+ r = {
727
+ id: o.size,
728
+ kind: i?.kind ?? n,
729
+ label: t.label ?? "",
730
+ createdThisFrame: e.created.has(t),
731
+ known: !!i,
732
+ passes: [],
733
+ ...i?.fields,
734
+ textures: 0,
735
+ samplers: 0
736
+ }, o.set(t, r);
737
+ }
738
+ return r;
739
+ }, u = (e) => {
740
+ let t = s.get(e);
741
+ if (!t) {
742
+ let n = this.groups.get(e);
743
+ t = {
744
+ id: s.size,
745
+ label: n?.label ?? e.label ?? "",
746
+ entries: n ? n.entries.map((e) => this.binding(e)) : null
747
+ }, s.set(e, t);
748
+ }
749
+ return t;
750
+ }, d, f = (e, r = 0) => {
751
+ if (!e) return [];
752
+ if (!d) {
753
+ d = /* @__PURE__ */ new Map();
754
+ let e = /* @__PURE__ */ new Map();
755
+ for (let r of n.meshes.values()) try {
756
+ let i = t(r);
757
+ if (!i) continue;
758
+ let a;
759
+ if (i.kind === "core") a = [[n.geometryBuffers(i.geometry)?.vertex, 0]];
760
+ else {
761
+ let t = i.source.model, n = e.get(t);
762
+ if (!n) {
763
+ n = /* @__PURE__ */ new Map();
764
+ for (let e of t.pickingPrimitives) {
765
+ let t = n.get(e.node), r = [e.vertex, e.vertexOffset ?? 0];
766
+ t ? t.push(r) : n.set(e.node, [r]);
767
+ }
768
+ e.set(t, n);
769
+ }
770
+ a = n.get(r) ?? [];
771
+ }
772
+ for (let [e, t] of a) {
773
+ if (!e) continue;
774
+ let n = d.get(e);
775
+ n || d.set(e, n = /* @__PURE__ */ new Map());
776
+ let i = n.get(t) ?? [];
777
+ i.includes(r.id) || n.set(t, [...i, r.id].slice(0, 64));
778
+ }
779
+ } catch {}
780
+ }
781
+ return d.get(e)?.get(r) ?? [];
782
+ }, p = {
783
+ draws: 0,
784
+ indexedDraws: 0,
785
+ indirectDraws: 0,
786
+ dispatches: 0,
787
+ triangles: 0,
788
+ instances: 0,
789
+ renderPasses: 0,
790
+ computePasses: 0,
791
+ encoders: e.encoders,
792
+ submits: e.submits,
793
+ pipelinesCreated: e.created.size + e.asyncPipelines,
794
+ shaderModulesCreated: e.shaderModules,
795
+ bindGroupsCreated: e.bindGroups,
796
+ uploads: 0,
797
+ uploadBytes: 0
798
+ }, m = 0, h = 0, g = (e, t, n) => {
799
+ let r = e.pipeline ? l(e.pipeline, t) : null, a = e.groups.map((e) => e ? u(e) : null);
800
+ r && !r.passes.includes(n) && r.passes.push(n);
801
+ let o = {
802
+ kind: e.kind,
803
+ pipeline: r?.id ?? null,
804
+ bindGroups: a.map((e) => e?.id ?? null),
805
+ triangles: null,
806
+ entities: f(e.vertex, e.vertexOffset)
807
+ };
808
+ if (r) {
809
+ let e = 0, t = 0;
810
+ for (let n of a) for (let r of n?.entries ?? []) r.kind === "texture" || r.kind === "external-texture" ? e++ : r.kind === "sampler" && t++;
811
+ r.textures = Math.max(r.textures, e), r.samplers = Math.max(r.samplers, t);
812
+ }
813
+ let s = e.args;
814
+ if (e.indirect) {
815
+ o.indirect = {
816
+ buffer: x(e.indirect.buffer),
817
+ offset: e.indirect.offset
818
+ };
819
+ let t = e.indirect.slot;
820
+ s = i && t >= 0 ? [...i.subarray(t * 5, t * 5 + 5)] : [], e.kind !== "dispatchWorkgroupsIndirect" && !s.length && m++;
821
+ }
822
+ if (e.kind === "executeBundles") o.bundles = s[0], h += s[0];
823
+ else if (e.kind.startsWith("dispatch")) p.dispatches++, o.workgroups = s.length ? [
824
+ s[0],
825
+ s[1] ?? 1,
826
+ s[2] ?? 1
827
+ ] : null;
828
+ else {
829
+ let t = e.kind === "drawIndexed" || e.kind === "drawIndexedIndirect";
830
+ p.draws++, t && p.indexedDraws++, e.indirect && p.indirectDraws++;
831
+ let n = s.length ? s[0] : null, i = s.length ? s[1] ?? 1 : null;
832
+ t ? o.indexCount = n : o.vertexCount = n, o.instanceCount = i, o.triangles = T(r?.topology, n, i), p.triangles += o.triangles ?? 0, p.instances += i ?? 0;
833
+ }
834
+ return o;
835
+ }, _ = [
836
+ e.before,
837
+ ...e.graph,
838
+ e.after
839
+ ].filter((e) => e.owner !== "engine" || e.passes.length).map((e) => {
840
+ let t = e.passes.map((t) => (t.kind === "render" ? p.renderPasses++ : p.computePasses++, {
841
+ kind: t.kind,
842
+ label: t.label,
843
+ encoder: t.encoder,
844
+ gpuMilliseconds: r && t.timestamp >= 0 ? r[t.timestamp] : null,
845
+ attachments: t.attachments,
846
+ commands: t.commands.map((n) => g(n, t.kind, e.name))
847
+ })), n = t.filter((e) => e.gpuMilliseconds !== null);
848
+ return {
849
+ name: e.name,
850
+ owner: e.owner,
851
+ ...e.view && { view: e.view },
852
+ order: e.order,
853
+ cpuMilliseconds: e.cpu,
854
+ gpuMilliseconds: n.length ? n.reduce((e, t) => e + (t.gpuMilliseconds ?? 0), 0) : null,
855
+ passes: t
856
+ };
857
+ });
858
+ for (let t of e.created) l(t, this.pipelines.get(t)?.kind ?? "render");
859
+ let v = [...o.values()];
860
+ for (let e of v) Math.max(e.textures, e.samplers) >= 15 && c.push(`Pipeline #${e.id} "${e.label}" binds ${e.textures} textures and ${e.samplers} samplers; WebGPU guarantees 16 of each per shader stage.`);
861
+ p.pipelinesCreated && c.push(`${p.pipelinesCreated} pipeline(s) compiled during this frame (a likely hitch).`), m && c.push(`${m} indirect draw(s) with unknown counts (arguments buffer without COPY_SRC usage); not in the triangle total.`), h && c.push(`${h} render bundle(s) executed; draws inside bundles are not listed.`);
862
+ let y = [...e.uploads.values()].sort((e, t) => t.bytes - e.bytes);
863
+ for (let e of y) p.uploads += e.calls, p.uploadBytes += e.bytes;
864
+ return {
865
+ timing: r ? "gpu" : "cpu",
866
+ note: a.join(" "),
867
+ cpuMilliseconds: e.cpu,
868
+ gpuMilliseconds: r ? _.reduce((e, t) => e + (t.gpuMilliseconds ?? 0), 0) : null,
869
+ graph: _,
870
+ plugins: e.plugins,
871
+ pipelines: v,
872
+ bindGroups: [...s.values()],
873
+ totals: p,
874
+ uploads: y.slice(0, 20),
875
+ memory: this.memory(),
876
+ warnings: c
877
+ };
878
+ }
879
+ };
880
+ //#endregion
881
+ export { D as FrameDebugger, v as texelBytes, y as textureBytes };