summaryrefslogtreecommitdiffstats
path: root/dom/webgpu/tests/cts/checkout/src/webgpu/web_platform/canvas/configure.spec.ts
blob: 3a29f55e72c64274d3be7a18b2fbb980d04c550d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
export const description = `
Tests for GPUCanvasContext.configure.

TODO:
- Test colorSpace
- Test viewFormats
`;

import { makeTestGroup } from '../../../common/framework/test_group.js';
import { assert } from '../../../common/util/util.js';
import {
  kAllTextureFormats,
  kCanvasTextureFormats,
  kTextureUsages,
  filterFormatsByFeature,
  kFeaturesForFormats,
  kTextureFormats,
  viewCompatible,
} from '../../capability_info.js';
import { GPUConst } from '../../constants.js';
import { GPUTest } from '../../gpu_test.js';
import { kAllCanvasTypes, createCanvas } from '../../util/create_elements.js';

export const g = makeTestGroup(GPUTest);

g.test('defaults')
  .desc(
    `
    Ensure that the defaults for GPUCanvasConfiguration are correct.
    `
  )
  .params(u =>
    u //
      .combine('canvasType', kAllCanvasTypes)
  )
  .fn(async t => {
    const { canvasType } = t.params;
    const canvas = createCanvas(t, canvasType, 2, 2);
    const ctx = canvas.getContext('webgpu');
    assert(ctx instanceof GPUCanvasContext, 'Failed to get WebGPU context from canvas');

    ctx.configure({
      device: t.device,
      format: 'rgba8unorm',
    });

    const currentTexture = ctx.getCurrentTexture();
    t.expect(currentTexture.format === 'rgba8unorm');
    t.expect(currentTexture.usage === GPUTextureUsage.RENDER_ATTACHMENT);
    t.expect(currentTexture.dimension === '2d');
    t.expect(currentTexture.width === canvas.width);
    t.expect(currentTexture.height === canvas.height);
    t.expect(currentTexture.depthOrArrayLayers === 1);
    t.expect(currentTexture.mipLevelCount === 1);
    t.expect(currentTexture.sampleCount === 1);
  });

g.test('device')
  .desc(
    `
    Ensure that configure reacts appropriately to various device states.
    `
  )
  .params(u =>
    u //
      .combine('canvasType', kAllCanvasTypes)
  )
  .fn(async t => {
    const { canvasType } = t.params;
    const canvas = createCanvas(t, canvasType, 2, 2);
    const ctx = canvas.getContext('webgpu');
    assert(ctx instanceof GPUCanvasContext, 'Failed to get WebGPU context from canvas');

    // Calling configure without a device should throw.
    t.shouldThrow(true, () => {
      ctx.configure({
        format: 'rgba8unorm',
      } as GPUCanvasConfiguration);
    });

    // Device is not configured, so getCurrentTexture will throw.
    t.shouldThrow(true, () => {
      ctx.getCurrentTexture();
    });

    // Calling configure with a device should succeed.
    ctx.configure({
      device: t.device,
      format: 'rgba8unorm',
    });

    // getCurrentTexture will succeed with a valid device.
    ctx.getCurrentTexture();

    // Unconfiguring should cause the device to be cleared.
    ctx.unconfigure();
    t.shouldThrow(true, () => {
      ctx.getCurrentTexture();
    });

    // Should be able to successfully configure again after unconfiguring.
    ctx.configure({
      device: t.device,
      format: 'rgba8unorm',
    });
    ctx.getCurrentTexture();
  });

g.test('format')
  .desc(
    `
    Ensure that only valid texture formats are allowed when calling configure.
    `
  )
  .params(u =>
    u //
      .combine('canvasType', kAllCanvasTypes)
      .combine('format', kAllTextureFormats)
  )
  .beforeAllSubcases(t => {
    t.selectDeviceForTextureFormatOrSkipTestCase(t.params.format);
  })
  .fn(async t => {
    const { canvasType, format } = t.params;
    const canvas = createCanvas(t, canvasType, 2, 2);
    const ctx = canvas.getContext('webgpu');
    assert(ctx instanceof GPUCanvasContext, 'Failed to get WebGPU context from canvas');

    // Would prefer to use kCanvasTextureFormats.includes(format), but that's giving TS errors.
    let validFormat = false;
    for (const canvasFormat of kCanvasTextureFormats) {
      if (format === canvasFormat) {
        validFormat = true;
        break;
      }
    }

    t.expectValidationError(() => {
      ctx.configure({
        device: t.device,
        format,
      });
    }, !validFormat);

    t.expectValidationError(() => {
      // Should always return a texture, whether the configured format was valid or not.
      const currentTexture = ctx.getCurrentTexture();
      t.expect(currentTexture instanceof GPUTexture);
    }, !validFormat);
  });

g.test('usage')
  .desc(
    `
    Ensure that getCurrentTexture returns a texture with the configured usages.
    `
  )
  .params(u =>
    u //
      .combine('canvasType', kAllCanvasTypes)
      .beginSubcases()
      .expand('usage', p => {
        const usageSet = new Set<number>();
        for (const usage0 of kTextureUsages) {
          for (const usage1 of kTextureUsages) {
            usageSet.add(usage0 | usage1);
          }
        }
        return usageSet;
      })
  )
  .fn(async t => {
    const { canvasType, usage } = t.params;
    const canvas = createCanvas(t, canvasType, 2, 2);
    const ctx = canvas.getContext('webgpu');
    assert(ctx instanceof GPUCanvasContext, 'Failed to get WebGPU context from canvas');

    ctx.configure({
      device: t.device,
      format: 'rgba8unorm',
      usage,
    });

    const currentTexture = ctx.getCurrentTexture();
    t.expect(currentTexture instanceof GPUTexture);
    t.expect(currentTexture.usage === usage);

    // Try to use the texture with the given usage

    if (usage & GPUConst.TextureUsage.RENDER_ATTACHMENT) {
      const encoder = t.device.createCommandEncoder();
      const pass = encoder.beginRenderPass({
        colorAttachments: [
          {
            view: currentTexture.createView(),
            clearValue: [1.0, 0.0, 0.0, 1.0],
            loadOp: 'clear',
            storeOp: 'store',
          },
        ],
      });
      pass.end();
      t.device.queue.submit([encoder.finish()]);
    }

    if (usage & GPUConst.TextureUsage.TEXTURE_BINDING) {
      const bgl = t.device.createBindGroupLayout({
        entries: [
          {
            binding: 0,
            visibility: GPUShaderStage.FRAGMENT,
            texture: {},
          },
        ],
      });

      t.device.createBindGroup({
        layout: bgl,
        entries: [
          {
            binding: 0,
            resource: currentTexture.createView(),
          },
        ],
      });
    }

    if (usage & GPUConst.TextureUsage.STORAGE_BINDING) {
      const bgl = t.device.createBindGroupLayout({
        entries: [
          {
            binding: 0,
            visibility: GPUShaderStage.FRAGMENT,
            storageTexture: { access: 'write-only', format: currentTexture.format },
          },
        ],
      });

      t.device.createBindGroup({
        layout: bgl,
        entries: [
          {
            binding: 0,
            resource: currentTexture.createView(),
          },
        ],
      });
    }

    if (usage & GPUConst.TextureUsage.COPY_DST) {
      const rgbaData = new Uint8Array([255, 0, 0, 255]);

      t.device.queue.writeTexture({ texture: currentTexture }, rgbaData, {}, [1, 1, 1]);
    }

    if (usage & GPUConst.TextureUsage.COPY_SRC) {
      const size = [currentTexture.width, currentTexture.height, 1];
      const dstTexture = t.device.createTexture({
        format: currentTexture.format,
        usage: GPUTextureUsage.COPY_DST,
        size,
      });

      const encoder = t.device.createCommandEncoder();
      encoder.copyTextureToTexture({ texture: currentTexture }, { texture: dstTexture }, size);
      t.device.queue.submit([encoder.finish()]);
    }
  });

g.test('alpha_mode')
  .desc(
    `
    Ensure that all valid alphaMode values are allowed when calling configure.
    `
  )
  .params(u =>
    u //
      .combine('canvasType', kAllCanvasTypes)
      .beginSubcases()
      .combine('alphaMode', ['opaque', 'premultiplied'] as const)
  )
  .fn(async t => {
    const { canvasType, alphaMode } = t.params;
    const canvas = createCanvas(t, canvasType, 2, 2);
    const ctx = canvas.getContext('webgpu');
    assert(ctx instanceof GPUCanvasContext, 'Failed to get WebGPU context from canvas');

    ctx.configure({
      device: t.device,
      format: 'rgba8unorm',
      alphaMode,
    });

    const currentTexture = ctx.getCurrentTexture();
    t.expect(currentTexture instanceof GPUTexture);
  });

g.test('size_zero_before_configure')
  .desc(`Ensure a validation error is raised in configure() if the size of the canvas is zero.`)
  .params(u =>
    u //
      .combine('canvasType', kAllCanvasTypes)
      .combine('zeroDimension', ['width', 'height'] as const)
  )
  .fn(t => {
    const { canvasType, zeroDimension } = t.params;
    const canvas = createCanvas(t, canvasType, 1, 1);
    canvas[zeroDimension] = 0;
    const ctx = canvas.getContext('webgpu');
    assert(ctx instanceof GPUCanvasContext, 'Failed to get WebGPU context from canvas');

    // Validation error, the canvas size is 0 which doesn't make a valid GPUTextureDescriptor.
    t.expectValidationError(() => {
      ctx.configure({
        device: t.device,
        format: 'bgra8unorm',
        usage: GPUTextureUsage.RENDER_ATTACHMENT,
      });
    });

    canvas[zeroDimension] = 1;

    // The size being incorrect doesn't make for an invalid configuration. Now that it is fixed
    // getting textures from the canvas should work.
    const currentTexture = ctx.getCurrentTexture();

    // Try rendering to it even!
    const encoder = t.device.createCommandEncoder();
    const pass = encoder.beginRenderPass({
      colorAttachments: [
        {
          view: currentTexture.createView(),
          clearValue: [1.0, 0.0, 0.0, 1.0],
          loadOp: 'clear',
          storeOp: 'store',
        },
      ],
    });
    pass.end();
    t.device.queue.submit([encoder.finish()]);
  });

g.test('size_zero_after_configure')
  .desc(
    `Ensure a validation error is raised after configure() if the size of the canvas becomes zero.`
  )
  .params(u =>
    u //
      .combine('canvasType', kAllCanvasTypes)
      .combine('zeroDimension', ['width', 'height'] as const)
  )
  .fn(t => {
    const { canvasType, zeroDimension } = t.params;
    const canvas = createCanvas(t, canvasType, 1, 1);
    const ctx = canvas.getContext('webgpu');
    assert(ctx instanceof GPUCanvasContext, 'Failed to get WebGPU context from canvas');

    ctx.configure({
      device: t.device,
      format: 'bgra8unorm',
      usage: GPUTextureUsage.RENDER_ATTACHMENT,
    });

    canvas[zeroDimension] = 0;

    // The size is incorrect, we should be getting an error texture and a validation error.
    let currentTexture: GPUTexture;
    t.expectValidationError(() => {
      currentTexture = ctx.getCurrentTexture();
    });

    t.expect(currentTexture![zeroDimension] === 0);

    // Using the texture should produce a validation error.
    t.expectValidationError(() => {
      currentTexture.createView();
    });
  });

g.test('viewFormats')
  .desc(
    `Test the validation that viewFormats are compatible with the format (for all canvas format / view formats)`
  )
  .params(u =>
    u
      .combine('canvasType', kAllCanvasTypes)
      .combine('format', kCanvasTextureFormats)
      .combine('viewFormatFeature', kFeaturesForFormats)
      .beginSubcases()
      .expand('viewFormat', ({ viewFormatFeature }) =>
        filterFormatsByFeature(viewFormatFeature, kTextureFormats)
      )
  )
  .beforeAllSubcases(t => {
    t.selectDeviceOrSkipTestCase([t.params.viewFormatFeature]);
  })
  .fn(t => {
    const { canvasType, format, viewFormat } = t.params;
    const canvas = createCanvas(t, canvasType, 1, 1);
    const ctx = canvas.getContext('webgpu');
    assert(ctx instanceof GPUCanvasContext, 'Failed to get WebGPU context from canvas');

    const compatible = viewCompatible(format, viewFormat);

    // Test configure() produces an error if the formats aren't compatible.
    t.expectValidationError(() => {
      ctx.configure({
        device: t.device,
        format,
        viewFormats: [viewFormat],
      });
    }, !compatible);

    // Likewise for getCurrentTexture().
    let currentTexture: GPUTexture;
    t.expectValidationError(() => {
      currentTexture = ctx.getCurrentTexture();
    }, !compatible);

    // The returned texture is an error texture.
    t.expectValidationError(() => {
      currentTexture.createView();
    }, !compatible);
  });