@playcanvas/inspector 0.4.0 → 0.6.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.
@@ -0,0 +1,235 @@
1
+ import {
2
+ SORTMODE_BACK2FRONT, SORTMODE_CUSTOM, SORTMODE_FRONT2BACK, SORTMODE_MANUAL, SORTMODE_MATERIALMESH, SORTMODE_NONE
3
+ } from 'playcanvas';
4
+
5
+ import { describeValue } from './describe.js';
6
+ import { nodeLabel } from './memory-view.js';
7
+ import { makeSection, push, read } from './model.js';
8
+
9
+ /** @import { AppBase, Layer, LayerComposition } from 'playcanvas' */
10
+ /** @import { ListRow } from './list-view.js' */
11
+ /** @import { PropertySection } from './model.js' */
12
+
13
+ /**
14
+ * What the Layers tab offers on a layer, supplied by the inspector.
15
+ *
16
+ * @typedef {object} LayerActions
17
+ * @property {(layer: Layer, hidden: boolean) => void} hide - Hides the layer from the view, or shows
18
+ * it again.
19
+ * @property {(layer: Layer) => boolean} hidden - Whether the inspector hides the layer.
20
+ * @ignore
21
+ */
22
+
23
+ const SORT_MODES = new Map([
24
+ [SORTMODE_NONE, 'none'],
25
+ [SORTMODE_MANUAL, 'manual (draw order)'],
26
+ [SORTMODE_MATERIALMESH, 'material, mesh'],
27
+ [SORTMODE_BACK2FRONT, 'back to front'],
28
+ [SORTMODE_FRONT2BACK, 'front to back'],
29
+ [SORTMODE_CUSTOM, 'custom']
30
+ ]);
31
+
32
+ /**
33
+ * @param {number} mode - A sort mode.
34
+ * @returns {string} Its name.
35
+ */
36
+ function sortModeName(mode) {
37
+ return SORT_MODES.get(mode) ?? String(mode);
38
+ }
39
+
40
+ /**
41
+ * One entry of the composition: a layer's opaque or transparent half, which the composition orders
42
+ * on its own, so a layer's halves can render far apart.
43
+ *
44
+ * @typedef {object} SubLayer
45
+ * @property {Layer} layer - The layer.
46
+ * @property {boolean} transparent - Whether it is the transparent half.
47
+ * @property {boolean} enabled - Whether the composition renders it: the layer and the half enabled.
48
+ * @property {number} index - Its place in the composition.
49
+ * @ignore
50
+ */
51
+
52
+ /**
53
+ * The entries of the composition, in the order it renders them.
54
+ *
55
+ * @param {LayerComposition|null|undefined} composition - The scene's composition.
56
+ * @returns {SubLayer[]} The entries.
57
+ */
58
+ function collectSubLayers(composition) {
59
+ if (!composition) return [];
60
+ return composition.layerList.map((layer, index) => {
61
+ const transparent = !!composition.subLayerList[index];
62
+ return { layer, transparent, enabled: layer.enabled && !!composition.subLayerEnabled[index], index };
63
+ });
64
+ }
65
+
66
+ /**
67
+ * @param {Layer} layer - A layer.
68
+ * @param {boolean} transparent - Whether to count the transparent half.
69
+ * @returns {number} How many of its mesh instances that half draws.
70
+ */
71
+ function instanceCount(layer, transparent) {
72
+ let count = 0;
73
+ for (const instance of layer.meshInstances) {
74
+ if (!!instance.transparent === transparent) count++;
75
+ }
76
+ return count;
77
+ }
78
+
79
+ /**
80
+ * The mesh instances of a half of a layer the last frame drew for a camera, after culling, as the
81
+ * renderer left them. Read without {@link Layer#getCulledInstances}, which would add an entry for a
82
+ * camera that never rendered the layer.
83
+ *
84
+ * @param {Layer} layer - A layer.
85
+ * @param {import('playcanvas').CameraComponent} camera - A camera rendering it. The layer keeps its
86
+ * culled instances by the component's engine camera.
87
+ * @param {boolean} transparent - Which half.
88
+ * @returns {number|null} The count, or null when the layer kept none for the camera.
89
+ */
90
+ function visibleCount(layer, camera, transparent) {
91
+ const culled = /** @type {any} */ (layer)._visibleInstances?.get(camera.camera);
92
+ if (!culled) return null;
93
+ return (transparent ? culled.transparent : culled.opaque)?.length ?? 0;
94
+ }
95
+
96
+ /**
97
+ * @param {Layer} layer - A layer.
98
+ * @returns {import('playcanvas').Light[]} The lights lighting it.
99
+ */
100
+ function layerLights(layer) {
101
+ return /** @type {any} */ (layer)._lights ?? [];
102
+ }
103
+
104
+ /**
105
+ * Makes labels unique within a section, as the rows of a section are keyed by their label, and two
106
+ * cameras or lights can share a name.
107
+ *
108
+ * @returns {(label: string) => string} Gives a label, numbered from its second use.
109
+ */
110
+ function uniqueLabels() {
111
+ const used = new Map();
112
+ return (label) => {
113
+ const n = (used.get(label) ?? 0) + 1;
114
+ used.set(label, n);
115
+ return n === 1 ? label : `${label} (${n})`;
116
+ };
117
+ }
118
+
119
+ /**
120
+ * One row per entry of the composition, in render order, dimmed when it does not render.
121
+ *
122
+ * @param {AppBase} app - The app.
123
+ * @param {(layer: Layer) => boolean} [hidden] - Whether the inspector hides a layer.
124
+ * @returns {ListRow[]} The rows.
125
+ */
126
+ function layerRows(app, hidden = () => false) {
127
+ return collectSubLayers(app.scene?.layers).map(({ layer, transparent, enabled, index }) => {
128
+ const half = transparent ? 'transparent' : 'opaque';
129
+ const cells = [
130
+ { text: String(index), cls: 'pci-cell-index' },
131
+ { text: layer.name, cls: 'pci-cell-name' },
132
+ { text: half, cls: `pci-cell-tag${transparent ? '' : ' pci-cell-tag-info'}` }
133
+ ];
134
+ if (hidden(layer)) cells.push({ text: 'hidden', cls: 'pci-cell-tag' });
135
+ else if (!layer.enabled) cells.push({ text: 'off', cls: 'pci-cell-tag' });
136
+ else if (!enabled) cells.push({ text: `${half} off`, cls: 'pci-cell-tag' });
137
+ const cameras = layer.cameras.length;
138
+ const instances = instanceCount(layer, transparent);
139
+ const splats = /** @type {any} */ (layer).gsplatPlacements?.length ?? 0;
140
+ const info = [`id ${layer.id}`, `${instances} instances`];
141
+ if (splats) info.push(`${splats} splats`);
142
+ info.push(`${cameras} ${cameras === 1 ? 'camera' : 'cameras'}`);
143
+ cells.push({ text: info.join(' · '), cls: 'pci-cell-info' });
144
+ return {
145
+ key: `layer${layer.id}${transparent ? 't' : 'o'}`,
146
+ item: layer,
147
+ name: layer.name,
148
+ // drawing nothing for no camera, the entry costs nothing and shows nothing
149
+ dim: !enabled || cameras === 0,
150
+ title: `${layer.name} (id ${layer.id}), ${half}, ${index} in the composition`,
151
+ cells
152
+ };
153
+ });
154
+ }
155
+
156
+ /**
157
+ * Everything the property view shows for a layer: where its halves render in the composition, how
158
+ * each sorts, the cameras rendering it with what each drew of it last frame, its lights and its mesh
159
+ * instances, and a way to hide it from the view.
160
+ *
161
+ * @param {Layer} layer - The layer.
162
+ * @param {{ app: AppBase, layerActions: LayerActions }} ctx - The app, and what the tab offers.
163
+ * @returns {PropertySection[]} The sections.
164
+ */
165
+ function buildLayerModel(layer, ctx) {
166
+ const composition = ctx.app.scene?.layers ?? null;
167
+ const halves = collectSubLayers(composition).filter(sub => sub.layer === layer);
168
+ const hidden = ctx.layerActions.hidden(layer);
169
+
170
+ const general = makeSection('layer', `Layer "${layer.name}"`);
171
+ push(general, 'id', read(layer, 'id'));
172
+ push(general, 'enabled', { text: String(layer.enabled), cls: 'bool' });
173
+ push(general, 'view', {
174
+ text: hidden ? 'hidden by the inspector' : (layer.enabled ? 'drawn' : 'off in the app'),
175
+ cls: 'obj',
176
+ actions: [{
177
+ text: hidden ? 'Show' : 'Hide',
178
+ title: hidden ? 'Draw the layer again, as the app had it' :
179
+ 'Turn the layer off to see what the view is without it. Reset or closing the panel turns it back on',
180
+ disabled: !hidden && !layer.enabled,
181
+ run: () => ctx.layerActions.hide(layer, !hidden)
182
+ }]
183
+ });
184
+ for (const { transparent, enabled, index } of halves) {
185
+ push(general, transparent ? 'transparent' : 'opaque', {
186
+ text: `${index} in the composition${enabled ? '' : ', off'}`,
187
+ cls: 'obj'
188
+ });
189
+ }
190
+ if (halves.length === 0) push(general, 'composition', { text: 'not in the composition', cls: 'err' });
191
+ push(general, 'opaque sort', { text: sortModeName(layer.opaqueSortMode), cls: 'obj' });
192
+ push(general, 'transparent sort', { text: sortModeName(layer.transparentSortMode), cls: 'obj' });
193
+ push(general, 'clear', {
194
+ text: [layer.clearColorBuffer && 'color', layer.clearDepthBuffer && 'depth', layer.clearStencilBuffer && 'stencil'].filter(Boolean).join(', ') || 'nothing',
195
+ cls: 'obj'
196
+ });
197
+
198
+ const cameras = makeSection('cameras', `Cameras (${layer.cameras.length})`);
199
+ const cameraLabel = uniqueLabels();
200
+ for (const camera of layer.cameras) {
201
+ const entity = camera.entity;
202
+ const drawn = halves.map(({ transparent }) => {
203
+ const count = visibleCount(layer, camera, transparent);
204
+ return count === null ? null : `${count} ${transparent ? 'transparent' : 'opaque'}`;
205
+ }).filter(Boolean);
206
+ push(cameras, cameraLabel(entity ? nodeLabel(entity) : 'camera'), {
207
+ text: drawn.length ? `drew ${drawn.join(', ')}` : 'drew nothing yet',
208
+ cls: 'obj',
209
+ target: entity ?? undefined
210
+ });
211
+ }
212
+ if (layer.cameras.length === 0) push(cameras, 'none', { text: 'no camera renders this layer', cls: 'null' });
213
+
214
+ const lights = layerLights(layer);
215
+ const lightSection = makeSection('lights', `Lights (${lights.length})`);
216
+ const lightLabel = uniqueLabels();
217
+ for (const light of lights) {
218
+ const node = /** @type {any} */ (light)._node;
219
+ push(lightSection, lightLabel(node ? nodeLabel(node) : 'light'), {
220
+ text: `${['directional', 'omni', 'spot'][light.type] ?? light.type}${light.enabled ? '' : ', off'}${light.castShadows ? ', shadows' : ''}`,
221
+ cls: 'obj',
222
+ target: node ?? undefined
223
+ });
224
+ }
225
+
226
+ const content = makeSection('content', 'Content');
227
+ push(content, 'mesh instances', describeValue(layer.meshInstances));
228
+ push(content, 'shadow casters', { text: String(layer.shadowCasters.length), cls: 'num' });
229
+ const splats = /** @type {any} */ (layer).gsplatPlacements;
230
+ if (splats?.length) push(content, 'splat placements', { text: String(splats.length), cls: 'num' });
231
+
232
+ return [general, cameras, lightSection, content];
233
+ }
234
+
235
+ export { buildLayerModel, collectSubLayers, layerRows };
package/src/list-view.js CHANGED
@@ -17,6 +17,8 @@ const GUTTER_GAP = 2;
17
17
  * {@link ListView#onToggle} with the row's item and the new state, without selecting the row.
18
18
  * @property {boolean} [checked] - The state of a checkbox cell.
19
19
  * @property {boolean} [disabled] - Whether a checkbox cell is disabled.
20
+ * @property {string} [field] - What the cell holds, which copies key it by, for a cell whose
21
+ * class does not say, such as a size styled as info.
20
22
  */
21
23
 
22
24
  /**
@@ -0,0 +1,225 @@
1
+ /**
2
+ * A message logged by the page.
3
+ *
4
+ * @typedef {object} LogEntry
5
+ * @ignore
6
+ * @property {number} seq - Its number: later messages have higher numbers.
7
+ * @property {number} time - When it was logged, in milliseconds since the capture started; for a
8
+ * repeated message, when it was last logged.
9
+ * @property {number} frame - The app frame it was logged in, or last logged in.
10
+ * @property {string} level - 'error', 'warn', 'info', 'log' or 'debug'.
11
+ * @property {string} text - The message.
12
+ * @property {number} count - How many times in a row it was logged.
13
+ * @property {string} [stack] - Where an uncaught error was thrown.
14
+ */
15
+
16
+ // the console methods captured, most severe first
17
+ const LEVELS = ['error', 'warn', 'info', 'log', 'debug'];
18
+
19
+ // how many messages are kept, and how much of each
20
+ const CAPACITY = 1000;
21
+ const MAX_TEXT = 2000;
22
+ const MAX_STACK_LINES = 8;
23
+
24
+ /**
25
+ * @param {*} value - A value logged.
26
+ * @returns {string} It as text, the way the console would show it, roughly.
27
+ */
28
+ function format(value) {
29
+ if (typeof value === 'string') return value;
30
+ if (value instanceof Error) return `${value.name}: ${value.message}`;
31
+ if (value === null || typeof value !== 'object') return String(value);
32
+ try {
33
+ const json = JSON.stringify(value);
34
+ if (json !== undefined) return json.length > 300 ? `${json.slice(0, 300)}…` : json;
35
+ } catch {
36
+ // a cycle, or a getter that throws: named by its class below
37
+ }
38
+ return Object.prototype.toString.call(value);
39
+ }
40
+
41
+ /**
42
+ * @param {any[]} args - The arguments of a console call.
43
+ * @returns {string} The message, as the console prints it: a first string's substitutions, such as
44
+ * %s and %d, filled in from the arguments after it, %c styles left out, and the arguments left over
45
+ * joined by spaces.
46
+ */
47
+ function messageOf(args) {
48
+ let rest = args;
49
+ let head = '';
50
+ if (typeof args[0] === 'string') {
51
+ let next = 1;
52
+ head = args[0].replace(/%([sdifoOc%])/g, (match, code) => {
53
+ if (code === '%') return '%';
54
+ if (next >= args.length) return match;
55
+ const value = args[next++];
56
+ if (code === 'c') return '';
57
+ if (code === 'd' || code === 'i') return String(parseInt(value, 10));
58
+ if (code === 'f') return String(parseFloat(value));
59
+ return format(value);
60
+ });
61
+ rest = args.slice(next);
62
+ }
63
+ const text = [...(typeof args[0] === 'string' ? [head] : []), ...rest.map(format)].join(' ');
64
+ return text.length > MAX_TEXT ? `${text.slice(0, MAX_TEXT)}…` : text;
65
+ }
66
+
67
+ /**
68
+ * @param {*} error - An error thrown.
69
+ * @returns {string|undefined} The first lines of its stack.
70
+ */
71
+ function stackOf(error) {
72
+ const stack = error?.stack;
73
+ return typeof stack === 'string' ? stack.split('\n').slice(0, MAX_STACK_LINES).join('\n') : undefined;
74
+ }
75
+
76
+ /**
77
+ * Keeps the messages the page logs to the console, and the errors nothing caught, while started:
78
+ * the engine's warnings and errors in a debug build, shader compile errors, and the app's own
79
+ * messages. The console methods are wrapped while it runs, and still log as before; the console
80
+ * then names the wrapper as where a message came from, which is why it only runs while asked.
81
+ *
82
+ * @ignore
83
+ */
84
+ class LogCapture {
85
+ /**
86
+ * The messages kept, oldest first.
87
+ *
88
+ * @type {LogEntry[]}
89
+ */
90
+ entries = [];
91
+
92
+ /**
93
+ * The number of the last message.
94
+ *
95
+ * @type {number}
96
+ */
97
+ seq = 0;
98
+
99
+ /**
100
+ * @type {() => number}
101
+ * @private
102
+ */
103
+ _frame;
104
+
105
+ /**
106
+ * The console methods replaced, by level, while started.
107
+ *
108
+ * @type {Map<string, Function>|null}
109
+ * @private
110
+ */
111
+ _originals = null;
112
+
113
+ /**
114
+ * @type {Map<string, Function>}
115
+ * @private
116
+ */
117
+ _wrappers = new Map();
118
+
119
+ /**
120
+ * @type {number}
121
+ * @private
122
+ */
123
+ _start = 0;
124
+
125
+ /**
126
+ * @param {() => number} frame - The app frame now.
127
+ */
128
+ constructor(frame) {
129
+ this._frame = frame;
130
+ }
131
+
132
+ /**
133
+ * Whether messages are being kept.
134
+ *
135
+ * @type {boolean}
136
+ */
137
+ get capturing() {
138
+ return !!this._originals;
139
+ }
140
+
141
+ /**
142
+ * Starts keeping messages.
143
+ */
144
+ start() {
145
+ if (this._originals) return;
146
+ this._start = performance.now();
147
+ this._originals = new Map();
148
+ for (const level of LEVELS) {
149
+ const original = console[level];
150
+ this._originals.set(level, original);
151
+ const wrapper = (...args) => {
152
+ this.add(level, messageOf(args));
153
+ return original.apply(console, args);
154
+ };
155
+ this._wrappers.set(level, wrapper);
156
+ console[level] = wrapper;
157
+ }
158
+ window.addEventListener('error', this._onError);
159
+ window.addEventListener('unhandledrejection', this._onRejection);
160
+ }
161
+
162
+ /**
163
+ * Stops keeping messages, and puts the console back. A console method something else replaced
164
+ * after the capture started is left as it is.
165
+ */
166
+ stop() {
167
+ if (!this._originals) return;
168
+ for (const [level, original] of this._originals) {
169
+ if (console[level] === this._wrappers.get(level)) console[level] = original;
170
+ }
171
+ this._originals = null;
172
+ this._wrappers.clear();
173
+ window.removeEventListener('error', this._onError);
174
+ window.removeEventListener('unhandledrejection', this._onRejection);
175
+ }
176
+
177
+ /**
178
+ * Keeps a message. A message logged again right after itself counts up rather than repeating.
179
+ *
180
+ * @param {string} level - Its level.
181
+ * @param {string} text - The message.
182
+ * @param {string} [stack] - Where it was thrown.
183
+ */
184
+ add(level, text, stack) {
185
+ const time = Math.round(performance.now() - this._start);
186
+ const frame = this._frame();
187
+ const last = this.entries[this.entries.length - 1];
188
+ if (last && last.level === level && last.text === text) {
189
+ last.count++;
190
+ last.time = time;
191
+ last.frame = frame;
192
+ return;
193
+ }
194
+ /** @type {LogEntry} */
195
+ const entry = { seq: ++this.seq, time, frame, level, text, count: 1 };
196
+ if (stack) entry.stack = stack;
197
+ this.entries.push(entry);
198
+ if (this.entries.length > CAPACITY) this.entries.splice(0, this.entries.length - CAPACITY);
199
+ }
200
+
201
+ /**
202
+ * Forgets every message kept.
203
+ */
204
+ clear() {
205
+ this.entries.length = 0;
206
+ }
207
+
208
+ /**
209
+ * @param {ErrorEvent} e - An error nothing caught.
210
+ * @private
211
+ */
212
+ _onError = (e) => {
213
+ this.add('error', `Uncaught ${e.error instanceof Error ? `${e.error.name}: ${e.error.message}` : e.message}`, stackOf(e.error));
214
+ };
215
+
216
+ /**
217
+ * @param {PromiseRejectionEvent} e - A rejection nothing handled.
218
+ * @private
219
+ */
220
+ _onRejection = (e) => {
221
+ this.add('error', `Unhandled rejection: ${format(e.reason)}`, stackOf(e.reason));
222
+ };
223
+ }
224
+
225
+ export { LEVELS, LogCapture };
@@ -100,7 +100,7 @@ function materialListRows(survey) {
100
100
  const counts = `${instances} instance${instances === 1 ? '' : 's'} · ${textures} texture${textures === 1 ? '' : 's'} · ` +
101
101
  `${variants} variant${variants === 1 ? '' : 's'}`;
102
102
  cells.push({ text: counts, cls: 'pci-cell-info' });
103
- cells.push({ text: `#${material.id}`, cls: 'pci-cell-info pci-cell-right' });
103
+ cells.push({ text: `#${material.id}`, cls: 'pci-cell-info pci-cell-right', field: 'id' });
104
104
  const title = `${typeOf(material)} "${name}" #${material.id}\n` +
105
105
  `${instances} mesh instance${instances === 1 ? '' : 's'}, ${textures} texture${textures === 1 ? '' : 's'}, ` +
106
106
  `${variants} compiled variant${variants === 1 ? '' : 's'}` +