MCPcopy
hub / github.com/tensorflow/tfjs / draw

Function draw

tfjs-backend-webgpu/src/kernels/Draw.ts:24–79  ·  view source on GitHub ↗
(
    args: {inputs: DrawInputs, backend: WebGPUBackend, attrs: DrawAttrs})

Source from the content-addressed store, hash-verified

22import {DrawProgram} from '../draw_webgpu';
23
24export 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
81export const drawConfig: KernelConfig = {

Callers

nothing calls this directly

Calls 7

hasMethod · 0.80
runWebGPUProgramMethod · 0.80
sliceMethod · 0.65
disposeDataMethod · 0.65
getContextMethod · 0.45
makeTensorInfoMethod · 0.45
getMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…