Skip to content

Commit e90c4d9

Browse files
committed
fix(WebGPU): use filterable textures for 16-bit image scalars
1 parent 3c78fbb commit e90c4d9

3 files changed

Lines changed: 117 additions & 71 deletions

File tree

‎Sources/Rendering/WebGPU/TextureManager/index.js‎

Lines changed: 2 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,6 @@ const { VtkDataTypes } = vtkDataArray;
1515

1616
const HALF_FLOAT_EXACT_INTEGER_LIMIT = 2048;
1717

18-
// This feature adds the r16unorm and r16snorm formats (and their rg and rgba
19-
// forms), which store 16 bit integers in 2 bytes.
20-
const NORMALIZED_16_BIT_FEATURE = 'texture-formats-tier1';
21-
2218
// ----------------------------------------------------------------------------
2319

2420
function vtkWebGPUTextureManager(publicAPI, model) {
@@ -36,22 +32,6 @@ function vtkWebGPUTextureManager(publicAPI, model) {
3632
}
3733
}
3834

39-
// The normalized 16 bit format for this data type, or null.
40-
// r16snorm samples max(v / 32767, -1). All values are exact, but -32768
41-
// reads as -32767.
42-
function _normalized16BitSuffix(dataType) {
43-
if (!model.device.hasFeature(NORMALIZED_16_BIT_FEATURE)) {
44-
return null;
45-
}
46-
if (dataType === VtkDataTypes.SHORT) {
47-
return '16snorm';
48-
}
49-
if (dataType === VtkDataTypes.UNSIGNED_SHORT) {
50-
return '16unorm';
51-
}
52-
return null;
53-
}
54-
5535
// The state has two parts. The first part is valid for one scalar mtime.
5636
// The second part stays for the life of the data array:
5737
// - promotedFormat is the 32 bit float format that an accurate texture of
@@ -150,10 +130,6 @@ function vtkWebGPUTextureManager(publicAPI, model) {
150130
if (uses8BitNormalizedFormat) {
151131
return format.endsWith('8unorm');
152132
}
153-
const normalized16BitSuffix = _normalized16BitSuffix(dataType);
154-
if (normalized16BitSuffix) {
155-
return format.endsWith(normalized16BitSuffix);
156-
}
157133
return format.endsWith('16float') || format.endsWith('32float');
158134
}
159135

@@ -207,11 +183,8 @@ function vtkWebGPUTextureManager(publicAPI, model) {
207183
return '8unorm';
208184
}
209185

210-
const normalized16BitSuffix = _normalized16BitSuffix(dataType);
211-
if (normalized16BitSuffix) {
212-
return normalized16BitSuffix;
213-
}
214-
186+
// Image mappers require filterable textures. texture-formats-tier1
187+
// enables 16 bit normalized formats, but does not make them filterable.
215188
if (req.forceFloat32) {
216189
return '32float';
217190
}
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
import { expect, it, onTestFinished } from 'vitest';
2+
3+
import vtkDataArray from 'vtk.js/Sources/Common/Core/DataArray';
4+
import vtkImageData from 'vtk.js/Sources/Common/DataModel/ImageData';
5+
import vtkWebGPUDevice from 'vtk.js/Sources/Rendering/WebGPU/Device';
6+
7+
/* eslint-disable no-undef, no-bitwise */
8+
it.skipIf(!__VTK_TEST_WEBGPU__).for([false, true])(
9+
'linearly samples 16 bit image scalars with tier1 enabled %s',
10+
async (enableTier1, { skip }) => {
11+
const adapter = await navigator.gpu.requestAdapter();
12+
expect(adapter).not.toBeNull();
13+
skip(
14+
enableTier1 && !adapter.features.has('texture-formats-tier1'),
15+
'texture-formats-tier1 unavailable'
16+
);
17+
const handle = await adapter.requestDevice({
18+
requiredFeatures: enableTier1 ? ['texture-formats-tier1'] : [],
19+
});
20+
onTestFinished(() => handle.destroy());
21+
const device = vtkWebGPUDevice.newInstance();
22+
device.initialize(handle);
23+
24+
const image = vtkImageData.newInstance();
25+
image.setDimensions(1, 1, 2);
26+
image.getPointData().setScalars(
27+
vtkDataArray.newInstance({
28+
values: new Int16Array([-2048, 1024, 1024, -512]),
29+
numberOfComponents: 2,
30+
})
31+
);
32+
const texture = device.getTextureManager().getTextureForImageData(image);
33+
const view = texture.createView('scalars', { dimension: '3d' });
34+
const sampler = handle.createSampler({
35+
minFilter: 'linear',
36+
magFilter: 'linear',
37+
});
38+
39+
const pipeline = await handle.createComputePipelineAsync({
40+
layout: 'auto',
41+
compute: {
42+
module: handle.createShaderModule({
43+
code: `
44+
@group(0) @binding(0) var image: texture_3d<f32>;
45+
@group(0) @binding(1) var linearSampler: sampler;
46+
@group(0) @binding(2) var<storage, read_write> result: vec2f;
47+
@compute @workgroup_size(1) fn main() {
48+
result = textureSampleLevel(image, linearSampler, vec3f(0.5), 0).rg;
49+
}`,
50+
}),
51+
entryPoint: 'main',
52+
},
53+
});
54+
const output = handle.createBuffer({
55+
size: 8,
56+
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC,
57+
});
58+
const readback = handle.createBuffer({
59+
size: 8,
60+
usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
61+
});
62+
handle.pushErrorScope('validation');
63+
const bindings = handle.createBindGroup({
64+
layout: pipeline.getBindGroupLayout(0),
65+
entries: [
66+
{ binding: 0, resource: view.getHandle() },
67+
{ binding: 1, resource: sampler },
68+
{ binding: 2, resource: { buffer: output } },
69+
],
70+
});
71+
const encoder = handle.createCommandEncoder();
72+
const pass = encoder.beginComputePass();
73+
pass.setPipeline(pipeline);
74+
pass.setBindGroup(0, bindings);
75+
pass.dispatchWorkgroups(1);
76+
pass.end();
77+
encoder.copyBufferToBuffer(output, 0, readback, 0, 8);
78+
handle.queue.submit([encoder.finish()]);
79+
expect(await handle.popErrorScope()).toBeNull();
80+
81+
await readback.mapAsync(GPUMapMode.READ);
82+
const samples = new Float32Array(readback.getMappedRange());
83+
expect(Array.from(samples, (value) => value * texture.getScale())).toEqual([
84+
-512, 256,
85+
]);
86+
}
87+
);

‎Sources/Rendering/WebGPU/TextureManager/test/testTextureOwnership.js‎

Lines changed: 28 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,10 @@ describe('vtkWebGPUTextureManager texture ownership', () => {
124124
});
125125

126126
it('shares one float32 texture after the values stop fitting half float', () => {
127-
const { device, textureManager } = createDevice(['float32-filterable']);
127+
const { device, textureManager } = createDevice([
128+
'float32-filterable',
129+
'texture-formats-tier1',
130+
]);
128131
const imageData = createImageData(new Int16Array([0, 1, 2, 3]));
129132
const scalars = imageData.getPointData().getScalars();
130133
const values = scalars.getData();
@@ -182,45 +185,28 @@ describe('vtkWebGPUTextureManager texture ownership', () => {
182185
});
183186
});
184187

185-
describe('vtkWebGPUTextureManager normalized 16 bit formats', () => {
186-
it.each([
187-
[new Int16Array([-30000, 30000]), 'r16snorm'],
188-
[new Uint16Array([0, 60000]), 'r16unorm'],
189-
])('stores %o in 2 bytes as %s', (values, format) => {
190-
const { textureManager } = createDevice([
191-
'float32-filterable',
192-
'texture-formats-tier1',
193-
]);
194-
const imageData = createImageData(values);
195-
196-
expect(textureManager.getTextureForImageData(imageData).getFormat()).toBe(
197-
format
198-
);
199-
expect(
200-
textureManager
201-
.getTextureForImageData(imageData, { preferSizeOverAccuracy: true })
202-
.getFormat()
203-
).toBe(format);
204-
});
205-
206-
it('keeps r16snorm for a partial update', () => {
207-
const { device, textureManager } = createDevice([
208-
'float32-filterable',
209-
'texture-formats-tier1',
210-
]);
211-
const imageData = createImageData(new Int16Array([0, 1, 2, 3]));
212-
const scalars = imageData.getPointData().getScalars();
213-
const texture = textureManager.getTextureForImageData(imageData);
214-
215-
scalars.getData()[2] = -32000;
216-
scalars.modified();
217-
const patched = textureManager.getTextureForImageData(imageData, {
218-
existingTexture: texture,
219-
updatedExtents: [[2, 2, 0, 0, 0, 0]],
220-
});
221-
222-
expect(patched).toBe(texture);
223-
expect(texture.writeSubImageData).toHaveBeenCalledOnce();
224-
expect(device.created).toHaveLength(1);
225-
});
188+
describe('vtkWebGPUTextureManager 16 bit formats on tier1 devices', () => {
189+
it.each([false, true])(
190+
'selects compact and accurate formats with float32 filtering %s',
191+
(float32Filterable) => {
192+
const features = ['texture-formats-tier1'];
193+
if (float32Filterable) features.push('float32-filterable');
194+
const { textureManager } = createDevice(features);
195+
for (const values of [
196+
new Int16Array([-30000, 30000]),
197+
new Uint16Array([0, 60000]),
198+
]) {
199+
const image = createImageData(values);
200+
const accurate = textureManager.getTextureForImageData(image);
201+
const compact = textureManager.getTextureForImageData(image, {
202+
preferSizeOverAccuracy: true,
203+
});
204+
205+
expect(accurate.getFormat()).toBe(
206+
float32Filterable ? 'r32float' : 'r16float'
207+
);
208+
expect(compact.getFormat()).toBe('r16float');
209+
}
210+
}
211+
);
226212
});

0 commit comments

Comments
 (0)