@playcanvas/inspector 0.1.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 (77) hide show
  1. package/LICENSE +19 -0
  2. package/README.md +110 -0
  3. package/package.json +62 -0
  4. package/src/asset-usage.js +108 -0
  5. package/src/asset-view.js +370 -0
  6. package/src/camera-view.js +128 -0
  7. package/src/debug.js +31 -0
  8. package/src/describe.js +302 -0
  9. package/src/entity-inspector-script.js +130 -0
  10. package/src/frame-graph-view.js +767 -0
  11. package/src/hierarchy-view.js +475 -0
  12. package/src/index.js +4 -0
  13. package/src/input/fly-controller.js +116 -0
  14. package/src/input/input.js +299 -0
  15. package/src/input/math.js +8 -0
  16. package/src/input/orbit-controller.js +158 -0
  17. package/src/input/pose.js +207 -0
  18. package/src/inspector.js +3293 -0
  19. package/src/instance-survey.js +50 -0
  20. package/src/list-view.js +410 -0
  21. package/src/material-view.js +197 -0
  22. package/src/memory-view.js +344 -0
  23. package/src/mesh-view.js +235 -0
  24. package/src/model.js +170 -0
  25. package/src/node-model.js +404 -0
  26. package/src/physics-debug.js +527 -0
  27. package/src/physics-view.js +314 -0
  28. package/src/picker/picker.js +545 -0
  29. package/src/picker/render-pass-picker.js +206 -0
  30. package/src/property-view.js +628 -0
  31. package/src/render-target-view.js +288 -0
  32. package/src/renderers/texture-renderer-shaders.js +139 -0
  33. package/src/renderers/texture-renderer.js +430 -0
  34. package/src/renderers/wire-renderer.js +954 -0
  35. package/src/script-view.js +288 -0
  36. package/src/shader-view.js +287 -0
  37. package/src/styles.js +918 -0
  38. package/src/texture-view.js +186 -0
  39. package/src/tooltip.js +72 -0
  40. package/src/viewport-tools.js +695 -0
  41. package/types/asset-usage.d.ts +23 -0
  42. package/types/asset-view.d.ts +94 -0
  43. package/types/camera-view.d.ts +45 -0
  44. package/types/debug.d.ts +14 -0
  45. package/types/describe.d.ts +43 -0
  46. package/types/entity-inspector-script.d.ts +87 -0
  47. package/types/frame-graph-view.d.ts +155 -0
  48. package/types/hierarchy-view.d.ts +172 -0
  49. package/types/index.d.ts +3 -0
  50. package/types/input/fly-controller.d.ts +42 -0
  51. package/types/input/input.d.ts +192 -0
  52. package/types/input/math.d.ts +1 -0
  53. package/types/input/orbit-controller.d.ts +63 -0
  54. package/types/input/pose.d.ts +126 -0
  55. package/types/inspector.d.ts +1304 -0
  56. package/types/instance-survey.d.ts +35 -0
  57. package/types/list-view.d.ts +151 -0
  58. package/types/material-view.d.ts +63 -0
  59. package/types/memory-view.d.ts +95 -0
  60. package/types/mesh-view.d.ts +89 -0
  61. package/types/model.d.ts +104 -0
  62. package/types/node-model.d.ts +54 -0
  63. package/types/physics-debug.d.ts +254 -0
  64. package/types/physics-view.d.ts +81 -0
  65. package/types/picker/picker.d.ts +255 -0
  66. package/types/picker/render-pass-picker.d.ts +47 -0
  67. package/types/property-view.d.ts +189 -0
  68. package/types/render-target-view.d.ts +98 -0
  69. package/types/renderers/texture-renderer-shaders.d.ts +9 -0
  70. package/types/renderers/texture-renderer.d.ts +231 -0
  71. package/types/renderers/wire-renderer.d.ts +347 -0
  72. package/types/script-view.d.ts +56 -0
  73. package/types/shader-view.d.ts +46 -0
  74. package/types/styles.d.ts +22 -0
  75. package/types/texture-view.d.ts +30 -0
  76. package/types/tooltip.d.ts +17 -0
  77. package/types/viewport-tools.d.ts +237 -0
@@ -0,0 +1,344 @@
1
+ import {
2
+ BUFFER_DYNAMIC, BUFFER_GPUDYNAMIC, BUFFER_STATIC, BUFFER_STREAM, IndexBuffer, INDEXFORMAT_UINT16, INDEXFORMAT_UINT32, INDEXFORMAT_UINT8, StorageBuffer, VertexBuffer
3
+ } from 'playcanvas';
4
+
5
+ import { describeValue, isUniformBuffer } from './describe.js';
6
+ import { collectMeshInstances } from './instance-survey.js';
7
+ import { formatBytes, makeSection, push, read, reflectRows } from './model.js';
8
+ import { vertexFormatValue } from './node-model.js';
9
+ import { formatUniformBuffer } from './shader-view.js';
10
+
11
+ /** @import { AppBase } from 'playcanvas' */
12
+ /** @import { UniformBuffer } from 'playcanvas' */
13
+ /** @import { Asset } from 'playcanvas' */
14
+ /** @import { GraphicsDevice } from 'playcanvas' */
15
+ /** @import { GraphNode } from 'playcanvas' */
16
+ /** @import { Material } from 'playcanvas' */
17
+ /** @import { Described } from './describe.js' */
18
+ /** @import { ListRow } from './list-view.js' */
19
+ /** @import { PropertySection } from './model.js' */
20
+
21
+ /**
22
+ * @typedef {VertexBuffer|IndexBuffer|UniformBuffer|StorageBuffer} Buffer
23
+ * @ignore
24
+ */
25
+
26
+ /**
27
+ * Something a buffer was found to belong to.
28
+ *
29
+ * @typedef {object} BufferOwner
30
+ * @property {string} role - What the buffer holds for it, such as 'vertices'.
31
+ * @property {string} label - The owner's name.
32
+ * @property {GraphNode|Asset|Material|null} target - What to link to, or null when there is nothing to
33
+ * show.
34
+ * @ignore
35
+ */
36
+
37
+ // buffer properties the model shows explicitly, or that are plumbing
38
+ const SKIP_BUFFER = [
39
+ 'device', 'impl', 'storage', 'format', 'numBytes', 'numVertices', 'numIndices', 'byteSize', 'usage', 'persistent',
40
+ 'id', 'allocation', 'vaoKeyPart'
41
+ ];
42
+
43
+ /** What the list can be narrowed to, as selector options. */
44
+ const BUFFER_KINDS = [
45
+ ['all', 'all'], ['vertex', 'vertex'], ['index', 'index'], ['uniform', 'uniform'], ['storage', 'storage']
46
+ ];
47
+
48
+ const KIND_NAMES = { vertex: 'VertexBuffer', index: 'IndexBuffer', uniform: 'UniformBuffer', storage: 'StorageBuffer' };
49
+
50
+ const USAGE_NAMES = {
51
+ [BUFFER_STATIC]: 'BUFFER_STATIC',
52
+ [BUFFER_DYNAMIC]: 'BUFFER_DYNAMIC',
53
+ [BUFFER_STREAM]: 'BUFFER_STREAM',
54
+ [BUFFER_GPUDYNAMIC]: 'BUFFER_GPUDYNAMIC'
55
+ };
56
+
57
+ // what each index buffer of a mesh holds, by render style: triangles, then the lazily built edges
58
+ // and points
59
+ const INDEX_ROLES = ['indices', 'wireframe indices', 'point indices'];
60
+
61
+ const INDEX_FORMAT_NAMES = {
62
+ [INDEXFORMAT_UINT8]: 'UINT8',
63
+ [INDEXFORMAT_UINT16]: 'UINT16',
64
+ [INDEXFORMAT_UINT32]: 'UINT32'
65
+ };
66
+
67
+ /** @type {WeakMap<object, number>} */
68
+ const ids = new WeakMap();
69
+ let nextId = 1;
70
+
71
+ /**
72
+ * @param {Buffer} buffer - A buffer.
73
+ * @returns {number} An id that stays the same for the lifetime of the buffer, since buffers carry
74
+ * no name of their own.
75
+ */
76
+ function idOf(buffer) {
77
+ let id = ids.get(buffer);
78
+ if (id === undefined) {
79
+ id = nextId++;
80
+ ids.set(buffer, id);
81
+ }
82
+ return id;
83
+ }
84
+
85
+ /**
86
+ * @param {*} buffer - A buffer.
87
+ * @returns {'vertex'|'index'|'uniform'|'storage'|null} Its kind, or null for anything else.
88
+ */
89
+ function bufferKind(buffer) {
90
+ if (buffer instanceof VertexBuffer) return 'vertex';
91
+ if (buffer instanceof IndexBuffer) return 'index';
92
+ if (isUniformBuffer(buffer)) return 'uniform';
93
+ if (buffer instanceof StorageBuffer) return 'storage';
94
+ return null;
95
+ }
96
+
97
+ /**
98
+ * @param {Buffer} buffer - A buffer.
99
+ * @returns {number} Its size in bytes.
100
+ */
101
+ function bufferBytes(buffer) {
102
+ const b = /** @type {any} */ (buffer);
103
+ return b.numBytes ?? b.byteSize ?? b.format?.byteSize ?? 0;
104
+ }
105
+
106
+ /**
107
+ * @param {Buffer} buffer - A buffer.
108
+ * @returns {string} What it holds, in a few words.
109
+ */
110
+ function contentText(buffer) {
111
+ const b = /** @type {any} */ (buffer);
112
+ switch (bufferKind(buffer)) {
113
+ case 'vertex':
114
+ return `${b.numVertices} vertices, ${b.format?.elements?.length ?? 0} elements${b.format?.instancing ? ', instancing' : ''}`;
115
+ case 'index':
116
+ return `${b.numIndices} indices, ${INDEX_FORMAT_NAMES[b.format] ?? b.format}`;
117
+ case 'uniform':
118
+ return `${b.format?.uniforms?.length ?? 0} uniforms`;
119
+ default:
120
+ return 'storage';
121
+ }
122
+ }
123
+
124
+ /**
125
+ * @param {GraphNode|null} node - The node a mesh instance draws at.
126
+ * @returns {string} Its name, after its parent's when it has one below the root: imported models
127
+ * often give every mesh node the same name, and the parent tells them apart.
128
+ */
129
+ function nodeLabel(node) {
130
+ if (!node) return '(no node)';
131
+ const parent = node.parent;
132
+ return parent?.parent ? `${parent.name} › ${node.name}` : node.name;
133
+ }
134
+
135
+ /**
136
+ * Finds what the buffers on the device belong to. No buffer records its owner, so the owners are
137
+ * found from the other end: every mesh instance of the components and layers, see
138
+ * {@link collectMeshInstances}, gives its mesh's geometry and its material's uniforms, the
139
+ * immediate renderer gives the batches of debug lines,
140
+ * loaded render assets give the geometry of meshes not drawn right now, and the device gives its
141
+ * own quad. Storage buffers and the per-draw uniform pool are
142
+ * held privately by their users and stay unattributed.
143
+ *
144
+ * @param {AppBase} app - The app.
145
+ * @returns {Map<Buffer, BufferOwner[]>} The owners of each attributed buffer.
146
+ */
147
+ function bufferOwners(app) {
148
+ /** @type {Map<Buffer, BufferOwner[]>} */
149
+ const owners = new Map();
150
+ const add = (buffer, owner) => {
151
+ if (!buffer) return;
152
+ let list = owners.get(buffer);
153
+ if (!list) {
154
+ list = [];
155
+ owners.set(buffer, list);
156
+ }
157
+ list.push(owner);
158
+ };
159
+
160
+ // a material shared by many instances owns one buffer, so it is listed once
161
+ const materials = new Set();
162
+ for (const { instance } of collectMeshInstances(app)) {
163
+ const node = instance.node ?? null;
164
+ const label = nodeLabel(node);
165
+ const mesh = instance.mesh;
166
+ if (mesh) {
167
+ add(mesh.vertexBuffer, { role: 'vertices', label, target: node });
168
+ mesh.indexBuffer?.forEach((indexBuffer, style) => {
169
+ add(indexBuffer, { role: INDEX_ROLES[style] ?? 'indices', label, target: node });
170
+ });
171
+ add(mesh.morph?.vertexBufferIds, { role: 'morph target ids', label, target: node });
172
+ }
173
+ add(/** @type {any} */ (instance)._materialUniformBuffer, { role: 'material uniforms of the instance', label, target: node });
174
+ const material = instance.material;
175
+ if (material && !materials.has(material)) {
176
+ materials.add(material);
177
+ add(/** @type {any} */ (material)._uniformBuffer, { role: 'material uniforms', label: `Material "${material.name}"`, target: material });
178
+ }
179
+ }
180
+
181
+ // debug lines are pushed straight into the visible list each frame rather than added to a
182
+ // layer, so their batches are found through the immediate renderer that owns them
183
+ for (const [layer, batches] of app.scene?.immediate?.batchesMap ?? []) {
184
+ for (const batch of batches.map?.values() ?? []) {
185
+ add(batch.mesh?.vertexBuffer, { role: 'debug lines', label: `Lines on "${layer.name}"`, target: null });
186
+ }
187
+ }
188
+
189
+ for (const asset of app.assets?.list() ?? []) {
190
+ if (asset.type !== 'render' || !asset.loaded) continue;
191
+ const label = `Asset "${asset.name}"`;
192
+ for (const mesh of asset.resource?.meshes ?? []) {
193
+ add(mesh?.vertexBuffer, { role: 'vertices', label, target: asset });
194
+ mesh?.indexBuffer?.forEach((indexBuffer, style) => {
195
+ add(indexBuffer, { role: INDEX_ROLES[style] ?? 'indices', label, target: asset });
196
+ });
197
+ }
198
+ }
199
+
200
+ // the quad every full screen pass draws
201
+ const device = /** @type {any} */ (app.graphicsDevice);
202
+ add(device?.quadVertexBuffer, { role: 'full screen quad vertices', label: 'Graphics device', target: null });
203
+ add(device?.quadIndexBuffer, { role: 'full screen quad indices', label: 'Graphics device', target: null });
204
+ return owners;
205
+ }
206
+
207
+ /**
208
+ * Every buffer the device tracks, largest first. Uniform buffers appear only when persistent, as
209
+ * the rest are slices of the per-frame pool.
210
+ *
211
+ * @param {GraphicsDevice} device - The device.
212
+ * @param {string} [kind] - One of {@link BUFFER_KINDS}.
213
+ * @returns {Buffer[]} The buffers.
214
+ */
215
+ function collectBuffers(device, kind = 'all') {
216
+ const buffers = [...(device.buffers ?? [])].filter(buffer => bufferKind(buffer) && (kind === 'all' || bufferKind(buffer) === kind));
217
+ return buffers.sort((a, b) => bufferBytes(b) - bufferBytes(a) || idOf(a) - idOf(b));
218
+ }
219
+
220
+ /**
221
+ * @param {Buffer} buffer - A buffer.
222
+ * @param {BufferOwner[]|undefined} owners - What it belongs to.
223
+ * @returns {string} A name for it, from its first owner, since buffers carry none of their own.
224
+ */
225
+ function bufferName(buffer, owners) {
226
+ if (!owners?.length) return `${KIND_NAMES[bufferKind(buffer)]} #${idOf(buffer)}`;
227
+ return owners[0].label;
228
+ }
229
+
230
+ /**
231
+ * One row per buffer, largest first, named after what uses it and dimmed when nothing was found.
232
+ *
233
+ * @param {GraphicsDevice} device - The device.
234
+ * @param {Map<Buffer, BufferOwner[]>} owners - The owners of each buffer.
235
+ * @param {string} kind - The kind to list, or 'all'.
236
+ * @returns {ListRow[]} The rows.
237
+ */
238
+ function bufferRows(device, owners, kind) {
239
+ return collectBuffers(device, kind).map((buffer) => {
240
+ const users = owners.get(buffer);
241
+ const name = bufferName(buffer, users);
242
+ const cells = [{ text: name, cls: 'pci-cell-name' }];
243
+ cells.push({ text: bufferKind(buffer), cls: 'pci-cell-tag pci-cell-tag-info' });
244
+ const extra = users && users.length > 1 ? `, ${users.length} users` : '';
245
+ cells.push({ text: `${contentText(buffer)}${users ? ` · ${users[0].role}` : ''}${extra}`, cls: 'pci-cell-info' });
246
+ cells.push({ text: formatBytes(bufferBytes(buffer)), cls: 'pci-cell-info pci-cell-right' });
247
+ const title = `${KIND_NAMES[bufferKind(buffer)]} #${idOf(buffer)}\n${contentText(buffer)}, ${formatBytes(bufferBytes(buffer))}` +
248
+ `${users ? `\n${users[0].role} of ${users[0].label}${extra}` : '\nowner not found'}`;
249
+ return { key: `buffer${idOf(buffer)}`, item: buffer, name, dim: !users, title, cells };
250
+ });
251
+ }
252
+
253
+ /**
254
+ * The totals shown above the list: video memory by kind of resource, the per-frame uniform pool,
255
+ * and the counts of the device caches that grow with the variety of what is drawn.
256
+ *
257
+ * @param {GraphicsDevice} device - The device.
258
+ * @returns {string} The totals, one line per group.
259
+ */
260
+ function memorySummary(device) {
261
+ const vram = /** @type {any} */ (device)._vram ?? {};
262
+ const lines = [];
263
+ lines.push(`VRAM: textures ${formatBytes(vram.tex ?? 0)} · vertex ${formatBytes(vram.vb ?? 0)} · index ${formatBytes(vram.ib ?? 0)}` +
264
+ ` · uniform ${formatBytes(vram.ub ?? 0)} · storage ${formatBytes(vram.sb ?? 0)}`);
265
+ // the texture split is only tracked by profiler builds
266
+ if (vram.texShadow || vram.texAsset || vram.texLightmap) {
267
+ lines.push(`textures: assets ${formatBytes(vram.texAsset ?? 0)} · shadow maps ${formatBytes(vram.texShadow ?? 0)} · lightmaps ${formatBytes(vram.texLightmap ?? 0)}`);
268
+ }
269
+
270
+ // WebGPU carves draws out of large fixed blocks; WebGL2 keeps whole buffers of each size
271
+ // requested, so only the count says anything there
272
+ const pool = /** @type {any} */ (device).dynamicBuffers;
273
+ if (pool?.bufferCount) {
274
+ lines.push(pool.bufferSize ?
275
+ `per-draw uniform pool: ${pool.bufferCount} × ${formatBytes(pool.bufferSize)}` :
276
+ `per-draw uniform pool: ${pool.bufferCount} buffers`);
277
+ }
278
+
279
+ const counts = new Map();
280
+ /** @type {any} */ (device).getResourceCounts?.(counts);
281
+ const names = [['renderPipelines', 'render pipelines'], ['computePipelines', 'compute pipelines'], ['bindGroups', 'bind groups'],
282
+ ['bindGroupFormats', 'bind group formats'], ['drawCommands', 'draw commands'], ['shaders', 'shaders']];
283
+ const parts = names.filter(([key]) => counts.has(key)).map(([key, label]) => `${label} ${counts.get(key)}`);
284
+ if (parts.length) lines.push(parts.join(' · '));
285
+
286
+ return lines.join('\n');
287
+ }
288
+
289
+ /**
290
+ * Everything the property view shows for a buffer: its size and layout, what it was found to
291
+ * belong to (linked), and every other public property.
292
+ *
293
+ * @param {Buffer} buffer - The buffer.
294
+ * @param {{ app: AppBase }} ctx - The app, to find the buffer's owners.
295
+ * @returns {PropertySection[]} The sections.
296
+ */
297
+ function buildBufferModel(buffer, ctx) {
298
+ const sections = [];
299
+ const b = /** @type {any} */ (buffer);
300
+ const kind = bufferKind(buffer);
301
+
302
+ const general = makeSection('buffer', KIND_NAMES[kind] ?? 'Buffer');
303
+ push(general, 'id', describeValue(idOf(buffer)));
304
+ push(general, 'size', { text: formatBytes(bufferBytes(buffer)), cls: 'num' });
305
+ if (kind === 'vertex') {
306
+ push(general, 'vertices', describeValue(b.numVertices));
307
+ if (b.format) push(general, 'vertex format', vertexFormatValue(b.format));
308
+ } else if (kind === 'index') {
309
+ push(general, 'indices', describeValue(b.numIndices));
310
+ push(general, 'index format', { text: INDEX_FORMAT_NAMES[b.format] ?? String(b.format), cls: 'obj' });
311
+ } else if (kind === 'uniform') {
312
+ push(general, 'persistent', read(b, 'persistent'));
313
+ if (b.format) {
314
+ push(general, 'layout', { text: `${b.format.uniforms.length} uniforms`, cls: 'num', code: formatUniformBuffer(b.format) });
315
+ }
316
+ }
317
+ if (b.usage !== undefined) push(general, 'usage', { text: USAGE_NAMES[b.usage] ?? String(b.usage), cls: 'obj' });
318
+ sections.push(general);
319
+
320
+ const owners = bufferOwners(ctx.app).get(buffer) ?? [];
321
+ const usage = makeSection('users', 'Used by');
322
+ push(usage, 'owners', {
323
+ text: owners.length ? `${owners.length} user${owners.length === 1 ? '' : 's'}` :
324
+ 'not found: held by something the panel cannot reach, such as a storage buffer',
325
+ cls: owners.length ? 'obj' : 'null',
326
+ items: owners.slice(0, 50).map(owner => ({
327
+ label: owner.role,
328
+ ...(owner.target ? describeValue(owner.target) : { text: owner.label, cls: 'obj' })
329
+ }))
330
+ });
331
+ if (owners.length > 50) usage.rows.push({ key: 'more', label: '', value: { text: `… ${owners.length - 50} more`, cls: 'null' }, depth: 1 });
332
+ sections.push(usage);
333
+
334
+ const rest = makeSection('props', 'Properties');
335
+ reflectRows(rest, buffer, [], SKIP_BUFFER);
336
+ if (rest.rows.length) sections.push(rest);
337
+
338
+ return sections;
339
+ }
340
+
341
+ export {
342
+ BUFFER_KINDS, bufferBytes, bufferKind, bufferOwners, bufferRows, buildBufferModel, collectBuffers, idOf,
343
+ memorySummary, nodeLabel
344
+ };
@@ -0,0 +1,235 @@
1
+ import { Mesh, VertexBuffer } from 'playcanvas';
2
+
3
+ import { describeValue } from './describe.js';
4
+ import { collectMeshInstances } from './instance-survey.js';
5
+ import { nodeLabel } from './memory-view.js';
6
+ import { formatBytes, makeSection, push } from './model.js';
7
+ import { meshInstanceRows, meshRows } from './node-model.js';
8
+
9
+ /** @import { AppBase } from 'playcanvas' */
10
+ /** @import { Asset } from 'playcanvas' */
11
+ /** @import { GraphNode } from 'playcanvas' */
12
+ /** @import { MeshInstance } from 'playcanvas' */
13
+ /** @import { ListRow } from './list-view.js' */
14
+ /** @import { PropertySection } from './model.js' */
15
+
16
+ /**
17
+ * Something a mesh was found to be used by.
18
+ *
19
+ * @typedef {object} MeshUser
20
+ * @property {string} role - How it uses the mesh, such as 'render component'.
21
+ * @property {string} label - Its name.
22
+ * @property {GraphNode|Asset|null} target - What to link to, or null when there is nothing to show.
23
+ * @property {MeshInstance|null} instance - The mesh instance drawing the mesh, when there is one.
24
+ * @ignore
25
+ */
26
+
27
+ /**
28
+ * The meshes found, with what uses each, and how complete the search was.
29
+ *
30
+ * @typedef {object} MeshSurvey
31
+ * @property {Map<Mesh, MeshUser[]>} users - The users of each mesh found.
32
+ * @property {number} instances - How many mesh instances were found drawing them.
33
+ * @property {number} vertexBuffers - How many vertex buffers the device holds.
34
+ * @property {number} unaccounted - How many of those belong to no mesh found and to no instancing
35
+ * data or other known user: the buffers of meshes only the app's own code holds, or buffers made
36
+ * without a mesh.
37
+ * @ignore
38
+ */
39
+
40
+ // most users a mesh lists in the property view; shared primitives are drawn by many
41
+ const MAX_USERS = 100;
42
+
43
+ /**
44
+ * Finds the meshes of the app. Nothing keeps a list of them, so they are found through what uses
45
+ * them: the mesh instances of the components and layers, see {@link collectMeshInstances}; the
46
+ * immediate renderer's batches of debug lines; and the loaded render and model assets, which hold
47
+ * meshes nothing may be drawing. A mesh only the app's own
48
+ * code holds cannot be found, but it still owns a vertex buffer on the device, so the vertex
49
+ * buffers no found mesh owns are counted to tell how complete the list is.
50
+ *
51
+ * @param {AppBase} app - The app.
52
+ * @returns {MeshSurvey} The meshes and what uses them.
53
+ */
54
+ function surveyMeshes(app) {
55
+ /** @type {Map<Mesh, MeshUser[]>} */
56
+ const users = new Map();
57
+ /** @type {Set<object>} */
58
+ const known = new Set();
59
+ const addMesh = (mesh, user) => {
60
+ if (!(mesh instanceof Mesh)) return;
61
+ let list = users.get(mesh);
62
+ if (!list) {
63
+ list = [];
64
+ users.set(mesh, list);
65
+ }
66
+ list.push(user);
67
+ };
68
+
69
+ const instances = collectMeshInstances(app);
70
+ for (const { instance, role } of instances) {
71
+ const node = instance.node ?? null;
72
+ addMesh(instance.mesh, { role, label: nodeLabel(node), target: node, instance });
73
+ known.add(/** @type {any} */ (instance).instancingData?.vertexBuffer);
74
+ }
75
+
76
+ // debug lines are pushed straight into the visible list each frame rather than added to a
77
+ // layer, so their batches are found through the immediate renderer that owns them
78
+ for (const [layer, batches] of app.scene?.immediate?.batchesMap ?? []) {
79
+ for (const batch of batches.map?.values() ?? []) {
80
+ addMesh(batch.mesh, { role: 'debug lines', label: `Lines on "${layer.name}"`, target: null, instance: null });
81
+ }
82
+ }
83
+
84
+ for (const asset of app.assets?.list() ?? []) {
85
+ if (!asset.loaded) continue;
86
+ const label = `Asset "${asset.name}"`;
87
+ if (asset.type === 'render') {
88
+ for (const mesh of asset.resource?.meshes ?? []) addMesh(mesh, { role: 'render asset', label, target: asset, instance: null });
89
+ } else if (asset.type === 'model') {
90
+ for (const instance of asset.resource?.meshInstances ?? []) {
91
+ addMesh(instance?.mesh, { role: 'model asset', label, target: asset, instance: null });
92
+ }
93
+ }
94
+ }
95
+
96
+ const device = /** @type {any} */ (app.graphicsDevice);
97
+ for (const mesh of users.keys()) {
98
+ known.add(mesh.vertexBuffer);
99
+ known.add(/** @type {any} */ (mesh.morph)?.vertexBufferIds);
100
+ }
101
+ known.add(device?.quadVertexBuffer);
102
+
103
+ let vertexBuffers = 0;
104
+ let unaccounted = 0;
105
+ for (const buffer of device?.buffers ?? []) {
106
+ if (!(buffer instanceof VertexBuffer)) continue;
107
+ vertexBuffers++;
108
+ if (!known.has(buffer)) unaccounted++;
109
+ }
110
+
111
+ return { users, instances: instances.length, vertexBuffers, unaccounted };
112
+ }
113
+
114
+ /**
115
+ * @param {Mesh} mesh - A mesh.
116
+ * @returns {number} The bytes of its vertex buffer and index buffers.
117
+ */
118
+ function meshBytes(mesh) {
119
+ let bytes = mesh.vertexBuffer?.numBytes ?? 0;
120
+ for (const indexBuffer of mesh.indexBuffer ?? []) bytes += indexBuffer?.numBytes ?? 0;
121
+ return bytes;
122
+ }
123
+
124
+ /**
125
+ * @param {Mesh} mesh - A mesh.
126
+ * @param {MeshUser[]} users - What uses it.
127
+ * @returns {string} A name for it, from its first user, since meshes carry none of their own.
128
+ */
129
+ function meshName(mesh, users) {
130
+ return users[0]?.label ?? `Mesh #${mesh.id}`;
131
+ }
132
+
133
+ /**
134
+ * @param {Mesh} mesh - A mesh.
135
+ * @returns {string} Its geometry, in a few words.
136
+ */
137
+ function geometryText(mesh) {
138
+ const primitive = mesh.primitive?.[0];
139
+ const drawn = primitive ? `, ${primitive.count} ${primitive.indexed ? 'indices' : 'vertices drawn'}` : '';
140
+ return `${mesh.vertexBuffer?.numVertices ?? 0} verts${drawn}`;
141
+ }
142
+
143
+ /**
144
+ * @param {MeshUser[]} users - What uses a mesh.
145
+ * @returns {number} How many mesh instances draw it.
146
+ */
147
+ function instanceCount(users) {
148
+ return users.reduce((count, user) => count + (user.instance ? 1 : 0), 0);
149
+ }
150
+
151
+ /**
152
+ * One row per mesh found, largest first, dimmed when no mesh instance draws it.
153
+ *
154
+ * @param {MeshSurvey} survey - The meshes found.
155
+ * @returns {ListRow[]} The rows.
156
+ */
157
+ function meshListRows(survey) {
158
+ const meshes = [...survey.users.keys()].sort((a, b) => meshBytes(b) - meshBytes(a) || a.id - b.id);
159
+ return meshes.map((mesh) => {
160
+ const users = survey.users.get(mesh);
161
+ const name = meshName(mesh, users);
162
+ const instances = instanceCount(users);
163
+ const cells = [{ text: name, cls: 'pci-cell-name' }];
164
+ if (mesh.skin) cells.push({ text: 'skinned', cls: 'pci-cell-tag pci-cell-tag-info' });
165
+ if (mesh.morph) cells.push({ text: 'morph', cls: 'pci-cell-tag pci-cell-tag-info' });
166
+ cells.push({ text: `${geometryText(mesh)} · ${instances} instance${instances === 1 ? '' : 's'}`, cls: 'pci-cell-info' });
167
+ cells.push({ text: formatBytes(meshBytes(mesh)), cls: 'pci-cell-info pci-cell-right' });
168
+ const title = `Mesh #${mesh.id}\n${geometryText(mesh)}, ${formatBytes(meshBytes(mesh))}\n` +
169
+ `${instances ? `drawn by ${instances} mesh instance${instances === 1 ? '' : 's'}` : 'drawn by no mesh instance'}` +
170
+ `${users.length > instances ? `, held by ${users[users.length - 1].label}` : ''}`;
171
+ return {
172
+ key: `mesh${mesh.id}`,
173
+ item: mesh,
174
+ name,
175
+ // a shared primitive is named after its first user, so match on any of them
176
+ matches: filter => users.some(user => user.label.toLowerCase().includes(filter)),
177
+ dim: instances === 0,
178
+ title,
179
+ cells
180
+ };
181
+ });
182
+ }
183
+
184
+ /**
185
+ * The line above the list: how many meshes were found, and whether any vertex buffer on the device
186
+ * belongs to none of them.
187
+ *
188
+ * @param {MeshSurvey} survey - The meshes found.
189
+ * @returns {string} The note, or an empty string when every vertex buffer is accounted for.
190
+ */
191
+ function meshNote(survey) {
192
+ if (!survey.unaccounted) return '';
193
+ const count = survey.unaccounted;
194
+ return `${count} of the ${survey.vertexBuffers} vertex buffers on the device belong to no mesh found here: ` +
195
+ 'meshes only the app\'s own code holds, or buffers made without a mesh. The Memory tab lists them.';
196
+ }
197
+
198
+ /**
199
+ * Everything the property view shows for a mesh: its geometry, down to the elements of its vertex
200
+ * format, and what uses it, with each mesh instance opening in place.
201
+ *
202
+ * @param {Mesh} mesh - The mesh.
203
+ * @param {{ app: AppBase }} ctx - The app, to find the mesh's users.
204
+ * @returns {PropertySection[]} The sections.
205
+ */
206
+ function buildMeshModel(mesh, ctx) {
207
+ const users = surveyMeshes(ctx.app).users.get(mesh) ?? [];
208
+
209
+ const general = makeSection('mesh', `Mesh #${mesh.id}`);
210
+ push(general, 'size', { text: formatBytes(meshBytes(mesh)), cls: 'num' });
211
+ general.rows.push(...meshRows(mesh));
212
+
213
+ const usage = makeSection('users', 'Used by');
214
+ const instances = instanceCount(users);
215
+ push(usage, 'users', {
216
+ text: users.length ?
217
+ `${instances} mesh instance${instances === 1 ? '' : 's'}${users.length > instances ? `, ${users.length - instances} other` : ''}` :
218
+ 'none found',
219
+ cls: users.length ? 'obj' : 'null',
220
+ items: users.slice(0, MAX_USERS).map((user) => {
221
+ if (user.instance) {
222
+ const instance = user.instance;
223
+ return { label: user.role, ...describeValue(instance), text: user.label, expand: () => meshInstanceRows(instance) };
224
+ }
225
+ return { label: user.role, ...(user.target ? describeValue(user.target) : { text: user.label, cls: 'obj' }) };
226
+ })
227
+ });
228
+ if (users.length > MAX_USERS) {
229
+ usage.rows.push({ key: 'more', label: '', value: { text: `… ${users.length - MAX_USERS} more`, cls: 'null' }, depth: 1 });
230
+ }
231
+
232
+ return [general, usage];
233
+ }
234
+
235
+ export { buildMeshModel, meshBytes, meshListRows, meshNote, surveyMeshes };