@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,387 @@
1
+ import {
2
+ drawQuadWithShader, FILTER_NEAREST, FILTER_NEAREST_MIPMAP_LINEAR, FILTER_NEAREST_MIPMAP_NEAREST, isIntegerPixelFormat,
3
+ isSrgbPixelFormat, PIXELFORMAT_DEPTH, PIXELFORMAT_DEPTH16, PIXELFORMAT_DEPTHSTENCIL, PIXELFORMAT_R16F, PIXELFORMAT_R32F,
4
+ PIXELFORMAT_R8, PIXELFORMAT_RG32F, PIXELFORMAT_RGB32F, PIXELFORMAT_RGBA32F, PIXELFORMAT_RGBA8, PIXELFORMAT_SRGBA8,
5
+ RenderTarget, SEMANTIC_POSITION, ShaderUtils, Texture
6
+ } from 'playcanvas';
7
+
8
+ import { storedBottomUp } from './render-target-view.js';
9
+ import { createTextureShaderDesc } from './renderers/texture-renderer-shaders.js';
10
+
11
+ /** @import { AppBase, GraphicsDevice, Shader } from 'playcanvas' */
12
+
13
+ /**
14
+ * An image captured from the app, ready to hand to an agent.
15
+ *
16
+ * @typedef {object} CapturedImage
17
+ * @ignore
18
+ * @property {number} width - The width of the image in pixels.
19
+ * @property {number} height - The height of the image in pixels.
20
+ * @property {string} png - The image as a PNG file, base64 encoded.
21
+ */
22
+
23
+ /**
24
+ * @typedef {object} CaptureJob
25
+ * @ignore
26
+ * @property {'texture'|'canvas'} kind - What is captured.
27
+ * @property {Texture|null} texture - The texture, for a texture.
28
+ * @property {number} maxSize - The longest side of the image, at most.
29
+ * @property {string} channels - Three of r, g, b and a, or 'rgb' to decode the texture.
30
+ * @property {boolean} flip - Whether the texture holds its rows bottom-up.
31
+ * @property {(image: CapturedImage) => void} resolve - Called with the image.
32
+ * @property {(error: Error) => void} reject - Called when it cannot be captured.
33
+ * @property {ReturnType<typeof setTimeout>} timer - Gives up when no frame renders.
34
+ */
35
+
36
+ // how long a capture waits for the app to render a frame
37
+ const FRAME_TIMEOUT = 5000;
38
+
39
+ // the red channel replicated, for a single channel and for the default selection
40
+ const SINGLE_CHANNEL_INDICES = new Int32Array([0, 0, 0]);
41
+
42
+ // the full-screen quad of the device, whose positions run from -1 to 1, with its texture coordinate
43
+ const QUAD_GLSL = /* glsl */ `
44
+ attribute vec2 vertex_position;
45
+ varying vec2 uv0;
46
+
47
+ void main(void) {
48
+ gl_Position = vec4(vertex_position, 0.5, 1.0);
49
+ uv0 = vertex_position * 0.5 + 0.5;
50
+ }
51
+ `;
52
+
53
+ const QUAD_WGSL = /* wgsl */ `
54
+ attribute vertex_position: vec2f;
55
+ varying uv0: vec2f;
56
+
57
+ @vertex fn vertexMain(input: VertexInput) -> VertexOutput {
58
+ var output: VertexOutput;
59
+ output.position = vec4f(input.vertex_position, 0.5, 1.0);
60
+ output.uv0 = input.vertex_position * 0.5 + vec2f(0.5);
61
+ return output;
62
+ }
63
+ `;
64
+
65
+ /**
66
+ * How a texture is sampled to show it, the way the texture previews choose, see
67
+ * TextureRenderer#draw, which this follows so a capture looks like the preview.
68
+ *
69
+ * @param {Texture} texture - The texture.
70
+ * @param {GraphicsDevice} device - The device.
71
+ * @param {string} channels - Three of r, g, b and a; 'rgb' decodes the texture's encoding.
72
+ * @returns {{ mode: string, encoding: string, channelIndices: Int32Array }|string} How to sample
73
+ * it, or why it cannot be captured.
74
+ */
75
+ function textureSampling(texture, device, channels) {
76
+ if (texture.device !== device || texture.cubemap || texture.volume || texture.arrayLength ||
77
+ texture.samples > 1 || isIntegerPixelFormat(texture.format)) {
78
+ return 'Only 2D color and depth textures can be captured, not cube, volume, array, multisampled or integer ones';
79
+ }
80
+ const format = texture.format;
81
+ const depth = format === PIXELFORMAT_DEPTH || format === PIXELFORMAT_DEPTH16 || format === PIXELFORMAT_DEPTHSTENCIL;
82
+ if (depth && device.isWebGL2 && texture.compareOnRead) {
83
+ return 'A comparison depth texture, such as a shadow map, cannot be captured on WebGL2';
84
+ }
85
+ const unfilterable = !device.textureFloatFilterable &&
86
+ (format === PIXELFORMAT_R32F || format === PIXELFORMAT_RG32F || format === PIXELFORMAT_RGB32F || format === PIXELFORMAT_RGBA32F);
87
+ if (device.isWebGL2 && (depth || unfilterable)) {
88
+ const minFilter = texture.minFilter;
89
+ const nearestMin = minFilter === FILTER_NEAREST || minFilter === FILTER_NEAREST_MIPMAP_NEAREST ||
90
+ (!texture.mipmaps && minFilter === FILTER_NEAREST_MIPMAP_LINEAR);
91
+ if (!nearestMin || texture.magFilter !== FILTER_NEAREST) {
92
+ return 'A depth or unfilterable float texture needs nearest filtering to be captured on WebGL2';
93
+ }
94
+ }
95
+ const singleChannel = format === PIXELFORMAT_R8 || format === PIXELFORMAT_R16F || format === PIXELFORMAT_R32F;
96
+ const decoded = channels === 'rgb' && !singleChannel;
97
+ const encoding = depth ? 'linear' : decoded ? texture.encoding : isSrgbPixelFormat(format) ? 'raw-srgb' : 'raw';
98
+ const channelIndices = channels === 'rgb' ? SINGLE_CHANNEL_INDICES : Int32Array.from(channels, c => 'rgba'.indexOf(c));
99
+ return { mode: depth ? 'depth' : unfilterable ? 'unfilterable' : 'filtered', encoding, channelIndices };
100
+ }
101
+
102
+ /**
103
+ * @param {number} width - The width of the source.
104
+ * @param {number} height - The height of the source.
105
+ * @param {number} maxSize - The longest side wanted, at most.
106
+ * @returns {{ width: number, height: number }} The size of the image: the source's, scaled down to
107
+ * fit, never up.
108
+ */
109
+ function fitSize(width, height, maxSize) {
110
+ const scale = Math.min(1, maxSize / Math.max(width, height));
111
+ return { width: Math.max(1, Math.round(width * scale)), height: Math.max(1, Math.round(height * scale)) };
112
+ }
113
+
114
+ /**
115
+ * @param {HTMLCanvasElement} canvas - A canvas.
116
+ * @returns {string} Its content as a PNG file, base64 encoded.
117
+ */
118
+ function canvasPng(canvas) {
119
+ const url = canvas.toDataURL('image/png');
120
+ return url.slice(url.indexOf(',') + 1);
121
+ }
122
+
123
+ /**
124
+ * @param {Uint8Array} pixels - RGBA pixels, row after row.
125
+ * @param {number} width - The width.
126
+ * @param {number} height - The height.
127
+ * @param {boolean} flip - Whether the rows run bottom-up, to turn them the right way up.
128
+ * @returns {string} The pixels as a PNG file, base64 encoded.
129
+ */
130
+ function pixelsPng(pixels, width, height, flip) {
131
+ const canvas = document.createElement('canvas');
132
+ canvas.width = width;
133
+ canvas.height = height;
134
+ const image = new ImageData(width, height);
135
+ const stride = width * 4;
136
+ for (let y = 0; y < height; y++) {
137
+ const from = (flip ? height - 1 - y : y) * stride;
138
+ image.data.set(pixels.subarray(from, from + stride), y * stride);
139
+ }
140
+ /** @type {CanvasRenderingContext2D} */ (canvas.getContext('2d')).putImageData(image, 0, 0);
141
+ return canvasPng(canvas);
142
+ }
143
+
144
+ /**
145
+ * Captures textures, render target attachments and the canvas into PNG images. A texture is drawn
146
+ * with the shaders of the texture previews into an 8-bit render target the size of the image, and
147
+ * read back, so an encoded or HDR texture, a depth buffer or a float target comes out as the
148
+ * preview shows it. Each capture waits for the next frame: a texture is drawn once the app has
149
+ * rendered it, inside the frame, and the canvas read once the frame is done.
150
+ *
151
+ * @ignore
152
+ */
153
+ class ImageCapture {
154
+ /**
155
+ * @type {AppBase|null}
156
+ * @private
157
+ */
158
+ _app;
159
+
160
+ /**
161
+ * @type {CaptureJob[]}
162
+ * @private
163
+ */
164
+ _jobs = [];
165
+
166
+ /**
167
+ * The capture shaders, by mode and encoding.
168
+ *
169
+ * @type {Map<string, Shader>}
170
+ * @private
171
+ */
172
+ _shaders = new Map();
173
+
174
+ /**
175
+ * @param {AppBase} app - The app.
176
+ */
177
+ constructor(app) {
178
+ this._app = app;
179
+ // a texture is drawn inside the frame, as the device takes render passes between its start
180
+ // and end, and the canvas read once the frame is done, when it holds the frame on WebGPU too
181
+ app.on('postrender', this._onPostRender, this);
182
+ app.on('frameend', this._onFrameEnd, this);
183
+ }
184
+
185
+ destroy() {
186
+ const app = this._app;
187
+ if (!app) return;
188
+ app.off('postrender', this._onPostRender, this);
189
+ app.off('frameend', this._onFrameEnd, this);
190
+ for (const job of this._jobs.splice(0)) this._fail(job, new Error('The inspector was destroyed'));
191
+ for (const shader of this._shaders.values()) shader.destroy();
192
+ this._shaders.clear();
193
+ this._app = null;
194
+ }
195
+
196
+ /**
197
+ * Captures a texture as its preview shows it.
198
+ *
199
+ * @param {Texture} texture - The texture.
200
+ * @param {object} [options] - The options.
201
+ * @param {number} [options.maxSize] - The longest side of the image, at most. Defaults to 512.
202
+ * @param {string} [options.channels] - Three of r, g, b and a, to show stored channels; 'rgb'
203
+ * decodes the texture's encoding. Defaults to 'rgb'.
204
+ * @returns {Promise<CapturedImage>} The image.
205
+ */
206
+ texture(texture, { maxSize = 512, channels = 'rgb' } = {}) {
207
+ const app = /** @type {AppBase} */ (this._app);
208
+ const sampling = textureSampling(texture, app.graphicsDevice, channels);
209
+ if (typeof sampling === 'string') return Promise.reject(new Error(sampling));
210
+ return this._queue('texture', texture, maxSize, channels);
211
+ }
212
+
213
+ /**
214
+ * Captures what the canvas shows at the end of the next frame.
215
+ *
216
+ * @param {object} [options] - The options.
217
+ * @param {number} [options.maxSize] - The longest side of the image, at most. Defaults to 1024.
218
+ * @returns {Promise<CapturedImage>} The image.
219
+ */
220
+ canvas({ maxSize = 1024 } = {}) {
221
+ return this._queue('canvas', null, maxSize, 'rgb');
222
+ }
223
+
224
+ /**
225
+ * @param {'texture'|'canvas'} kind - What is captured.
226
+ * @param {Texture|null} texture - The texture, for a texture.
227
+ * @param {number} maxSize - The longest side of the image.
228
+ * @param {string} channels - The channels shown.
229
+ * @returns {Promise<CapturedImage>} The image.
230
+ * @private
231
+ */
232
+ _queue(kind, texture, maxSize, channels) {
233
+ if (!this._app) return Promise.reject(new Error('The inspector was destroyed'));
234
+ const device = this._app.graphicsDevice;
235
+ return new Promise((resolve, reject) => {
236
+ /** @type {CaptureJob} */
237
+ const job = {
238
+ kind,
239
+ texture,
240
+ maxSize,
241
+ channels,
242
+ resolve,
243
+ reject,
244
+ flip: !!texture && storedBottomUp(texture, device),
245
+ timer: setTimeout(() => {
246
+ const index = this._jobs.indexOf(job);
247
+ if (index >= 0) this._jobs.splice(index, 1);
248
+ reject(new Error(`No frame rendered in ${FRAME_TIMEOUT / 1000} s, so nothing could be captured. Is the page hidden?`));
249
+ }, FRAME_TIMEOUT)
250
+ };
251
+ this._jobs.push(job);
252
+ });
253
+ }
254
+
255
+ /**
256
+ * @param {CaptureJob} job - A job.
257
+ * @param {Error} error - Why it failed.
258
+ * @private
259
+ */
260
+ _fail(job, error) {
261
+ clearTimeout(job.timer);
262
+ job.reject(error);
263
+ }
264
+
265
+ /**
266
+ * @param {CaptureJob} job - A job.
267
+ * @param {CapturedImage} image - The image.
268
+ * @private
269
+ */
270
+ _done(job, image) {
271
+ clearTimeout(job.timer);
272
+ job.resolve(image);
273
+ }
274
+
275
+ /**
276
+ * @param {string} mode - The sampling mode.
277
+ * @param {string} encoding - The encoding.
278
+ * @returns {Shader} The shader drawing a texture with them over the full-screen quad.
279
+ * @private
280
+ */
281
+ _shader(mode, encoding) {
282
+ const key = `${mode}-${encoding}`;
283
+ let shader = this._shaders.get(key);
284
+ if (!shader) {
285
+ const desc = createTextureShaderDesc(mode, encoding);
286
+ shader = ShaderUtils.createShader(/** @type {AppBase} */ (this._app).graphicsDevice, {
287
+ uniqueName: `InspectorCapture-${key}`,
288
+ attributes: { vertex_position: SEMANTIC_POSITION },
289
+ vertexGLSL: QUAD_GLSL,
290
+ fragmentGLSL: desc.fragmentGLSL,
291
+ vertexWGSL: QUAD_WGSL,
292
+ fragmentWGSL: desc.fragmentWGSL
293
+ });
294
+ this._shaders.set(key, shader);
295
+ }
296
+ return shader;
297
+ }
298
+
299
+ /**
300
+ * Draws the textures waiting to be captured, once the app has rendered them.
301
+ *
302
+ * @private
303
+ */
304
+ _onPostRender() {
305
+ const jobs = this._jobs.filter(job => job.kind === 'texture');
306
+ if (!jobs.length) return;
307
+ this._jobs = this._jobs.filter(job => job.kind !== 'texture');
308
+ for (const job of jobs) {
309
+ try {
310
+ this._captureTexture(job);
311
+ } catch (e) {
312
+ this._fail(job, e instanceof Error ? e : new Error(String(e)));
313
+ }
314
+ }
315
+ }
316
+
317
+ /**
318
+ * @param {CaptureJob} job - A texture job.
319
+ * @private
320
+ */
321
+ _captureTexture(job) {
322
+ const app = /** @type {AppBase} */ (this._app);
323
+ const device = app.graphicsDevice;
324
+ const texture = /** @type {Texture} */ (job.texture);
325
+ if (!texture.impl || /** @type {any} */ (texture)._destroyed) throw new Error('The texture was destroyed');
326
+ const sampling = textureSampling(texture, device, job.channels);
327
+ if (typeof sampling === 'string') throw new Error(sampling);
328
+
329
+ const { width, height } = fitSize(texture.width, texture.height, job.maxSize);
330
+ // decoded color is linear, and the sRGB target encodes it the way the screen shows it;
331
+ // stored channels and depth are written as they are
332
+ const raw = sampling.mode === 'depth' || sampling.encoding === 'raw' || sampling.encoding === 'raw-srgb';
333
+ const target = new Texture(device, {
334
+ name: 'InspectorCapture',
335
+ width,
336
+ height,
337
+ format: raw ? PIXELFORMAT_RGBA8 : PIXELFORMAT_SRGBA8,
338
+ mipmaps: false,
339
+ minFilter: FILTER_NEAREST,
340
+ magFilter: FILTER_NEAREST
341
+ });
342
+ const rt = new RenderTarget({ name: 'InspectorCapture', colorBuffer: target, depth: false });
343
+ device.scope.resolve('colorMap').setValue(texture);
344
+ if (sampling.encoding === 'raw' || sampling.encoding === 'raw-srgb') {
345
+ device.scope.resolve('textureChannels').setValue(sampling.channelIndices);
346
+ }
347
+ drawQuadWithShader(device, rt, this._shader(sampling.mode, sampling.encoding), undefined, undefined, 'InspectorCapture');
348
+
349
+ // the quad puts the texture's first row at the bottom of the target, which WebGL reads
350
+ // back first and WebGPU last
351
+ const flip = device.isWebGPU !== job.flip;
352
+ target.read(0, 0, width, height, { renderTarget: rt, immediate: true }).then((pixels) => {
353
+ this._done(job, { width, height, png: pixelsPng(/** @type {Uint8Array} */ (pixels), width, height, flip) });
354
+ }, (e) => {
355
+ this._fail(job, e instanceof Error ? e : new Error(String(e)));
356
+ }).finally(() => {
357
+ rt.destroy();
358
+ target.destroy();
359
+ });
360
+ }
361
+
362
+ /**
363
+ * Reads the canvas for the captures waiting for it, now that the frame is done.
364
+ *
365
+ * @private
366
+ */
367
+ _onFrameEnd() {
368
+ const jobs = this._jobs.filter(job => job.kind === 'canvas');
369
+ if (!jobs.length) return;
370
+ this._jobs = this._jobs.filter(job => job.kind !== 'canvas');
371
+ const source = /** @type {AppBase} */ (this._app).graphicsDevice.canvas;
372
+ for (const job of jobs) {
373
+ try {
374
+ const { width, height } = fitSize(source.width, source.height, job.maxSize);
375
+ const canvas = document.createElement('canvas');
376
+ canvas.width = width;
377
+ canvas.height = height;
378
+ /** @type {CanvasRenderingContext2D} */ (canvas.getContext('2d')).drawImage(source, 0, 0, width, height);
379
+ this._done(job, { width, height, png: canvasPng(canvas) });
380
+ } catch (e) {
381
+ this._fail(job, e instanceof Error ? e : new Error(String(e)));
382
+ }
383
+ }
384
+ }
385
+ }
386
+
387
+ export { ImageCapture, fitSize, textureSampling };