(
args: {inputs: DrawInputs, backend: WebGPUBackend, attrs: DrawAttrs})
| 22 | import {DrawProgram} from '../draw_webgpu'; |
| 23 | |
| 24 | export function draw( |
| 25 | args: {inputs: DrawInputs, backend: WebGPUBackend, attrs: DrawAttrs}): |
| 26 | TensorInfo { |
| 27 | const {inputs, backend, attrs} = args; |
| 28 | const {image} = inputs; |
| 29 | const {canvas, options} = attrs; |
| 30 | const [height, width] = image.shape.slice(0, 2); |
| 31 | const {imageOptions} = options || {}; |
| 32 | const alpha = imageOptions ?.alpha || 1; |
| 33 | |
| 34 | // 'rgba8unorm' should work on macOS according to |
| 35 | // https://bugs.chromium.org/p/chromium/issues/detail?id=1298618. But |
| 36 | // failed on macOS/M2. So use 'bgra8unorm' first when available. |
| 37 | const format = backend.device.features.has('bgra8unorm-storage') ? |
| 38 | 'bgra8unorm' : |
| 39 | 'rgba8unorm'; |
| 40 | const outShape = [height, width]; |
| 41 | const program = new DrawProgram(outShape, image.dtype, format); |
| 42 | canvas.width = width; |
| 43 | canvas.height = height; |
| 44 | const backendName = 'webgpu'; |
| 45 | let gpuContext = canvas.getContext(backendName); |
| 46 | let canvasWebGPU; |
| 47 | if (!gpuContext) { |
| 48 | canvasWebGPU = new OffscreenCanvas(width, height); |
| 49 | gpuContext = canvasWebGPU.getContext(backendName); |
| 50 | } |
| 51 | const numChannels = image.shape.length === 3 ? image.shape[2] : 1; |
| 52 | gpuContext.configure({ |
| 53 | device: backend.device, |
| 54 | format, |
| 55 | usage: GPUTextureUsage.STORAGE_BINDING, |
| 56 | alphaMode: 'premultiplied' |
| 57 | }); |
| 58 | |
| 59 | const outputDtype = 'int32'; |
| 60 | const output = backend.makeTensorInfo(outShape, outputDtype); |
| 61 | const info = backend.tensorMap.get(output.dataId); |
| 62 | info.resource = gpuContext.getCurrentTexture(); |
| 63 | info.external = true; |
| 64 | |
| 65 | const uniformData = |
| 66 | [{type: 'uint32', data: [numChannels]}, {type: 'float32', data: [alpha]}]; |
| 67 | backend.runWebGPUProgram(program, [image], outputDtype, uniformData, output); |
| 68 | |
| 69 | if (canvasWebGPU) { |
| 70 | const canvas2dContext = canvas.getContext('2d'); |
| 71 | if (!canvas2dContext) { |
| 72 | throw new Error( |
| 73 | `Please make sure this canvas has only been used for 2d or webgpu context!`); |
| 74 | } |
| 75 | canvas2dContext.drawImage(canvasWebGPU, 0, 0); |
| 76 | } |
| 77 | backend.disposeData(output.dataId); |
| 78 | return image; |
| 79 | } |
| 80 | |
| 81 | export const drawConfig: KernelConfig = { |
nothing calls this directly
no test coverage detected
searching dependent graphs…