From dfcb763f5644f348388fde4f005e377bea46e852 Mon Sep 17 00:00:00 2001 From: Paul Elliott Date: Fri, 27 Nov 2026 11:28:02 -0500 Subject: [PATCH 1/2] fix(dicom): mark every frame of a multi-frame file as loaded A single DICOM file with several frames fills one slice per frame, but its chunk load reported only the first slice as updated. The 3D view patches its volume texture with the reported slices, so it showed a single frame until something uploaded the whole volume again. --- src/core/streaming/dicomChunkImage.ts | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/core/streaming/dicomChunkImage.ts b/src/core/streaming/dicomChunkImage.ts index 566f5c1be..597ed7fe5 100644 --- a/src/core/streaming/dicomChunkImage.ts +++ b/src/core/streaming/dicomChunkImage.ts @@ -596,9 +596,18 @@ export default class DicomChunkImage chunk.setUserData(DATA_RANGE_KEY, chunkDataRange); this.chunkStatus[sliceIndex] = ChunkStatus.Loaded; + // A multi-frame file fills every slice from its offset on. + const frames = chunkData.length / (dims[0] * dims[1] * componentCount); this.events.emit('chunkLoad', { chunk, - updatedExtent: [0, dims[0] - 1, 0, dims[1] - 1, sliceIndex, sliceIndex], + updatedExtent: [ + 0, + dims[0] - 1, + 0, + dims[1] - 1, + sliceIndex, + sliceIndex + frames - 1, + ], }); this.onChunksUpdated(); From 4f1d240fce923ef30e89089347b12856ebbcf08e Mon Sep 17 00:00:00 2001 From: Paul Elliott Date: Fri, 27 Nov 2026 11:28:37 -0500 Subject: [PATCH 2/2] fix(volume-rendering): upload a streamed volume to the GPU once The vtk.js volume mapper keys its scalar texture on the scalars' modified time. Streamed DICOM chunks patch that texture through updated extents, but the cached hash kept the time of the first, empty upload. The first rebuild after loading, such as the preset fit once the image statistics arrive or the first 3D rotation, then reallocated and uploaded the whole volume while the old texture was still alive. Record the current hash after each partial update in the vtk.js patch. That full upload also hid partial uploads of multi-component scalars, which read and sized each extent in voxels instead of values, so the patch now strides them by the component count. --- patches/@kitware+vtk.js+38.0.4.patch | 58 +++++++ tests/specs/streamed-volume-texture.e2e.ts | 182 +++++++++++++++++++++ tests/specs/syntheticDicom.ts | 45 +++-- 3 files changed, 260 insertions(+), 25 deletions(-) create mode 100644 tests/specs/streamed-volume-texture.e2e.ts diff --git a/patches/@kitware+vtk.js+38.0.4.patch b/patches/@kitware+vtk.js+38.0.4.patch index c352c5755..3356f0fb7 100644 --- a/patches/@kitware+vtk.js+38.0.4.patch +++ b/patches/@kitware+vtk.js+38.0.4.patch @@ -111,6 +111,56 @@ diff --git a/node_modules/@kitware/vtk.js/Rendering/OpenGL/Renderer.js b/node_mo const background = model.renderable.getBackgroundByReference(); gl.clearColor(background[0], background[1], background[2], background[3]); clearMask |= gl.COLOR_BUFFER_BIT; +diff --git a/node_modules/@kitware/vtk.js/Rendering/OpenGL/Texture.js b/node_modules/@kitware/vtk.js/Rendering/OpenGL/Texture.js +--- a/node_modules/@kitware/vtk.js/Rendering/OpenGL/Texture.js ++++ b/node_modules/@kitware/vtk.js/Rendering/OpenGL/Texture.js +@@ -384,7 +384,7 @@ + * @param {number} outOffset + * @returns + */ +- function readExtentIntoArray(data, dataDims, extent, outArray, outOffset) { ++ function readExtentIntoArray(data, dataDims, numComps, extent, outArray, outOffset) { + const [xmin, xmax, ymin, ymax, zmin, zmax] = extent; + const [dx, dy] = dataDims; + const sxy = dx * dy; +@@ -393,7 +393,7 @@ + const zOffset = zi * sxy; + for (let yi = ymin; yi <= ymax; yi++) { + const zyOffset = zOffset + yi * dx; +- for (let readOffset = zyOffset + xmin, end = zyOffset + xmax; readOffset <= end; readOffset++, writeOffset++) outArray[writeOffset] = data[readOffset]; ++ for (let readOffset = (zyOffset + xmin) * numComps, end = (zyOffset + xmax + 1) * numComps; readOffset < end; readOffset++, writeOffset++) outArray[writeOffset] = data[readOffset]; + } + } + } +@@ -406,7 +406,7 @@ + * @returns + */ + function readExtents(data, extents, typedArrayConstructor = null) { +- const extentPixels = new (typedArrayConstructor || data.constructor)(extents.reduce((count, extent) => count + getExtentPixelCount(extent), 0)); ++ const extentPixels = new (typedArrayConstructor || data.constructor)(extents.reduce((count, extent) => count + getExtentPixelCount(extent), 0) * model.components); + const dataDims = [ + model.width, + model.height, +@@ -414,8 +414,8 @@ + ]; + let writeOffset = 0; + extents.forEach((extent) => { +- readExtentIntoArray(data, dataDims, extent, extentPixels, writeOffset); +- writeOffset += getExtentPixelCount(extent); ++ readExtentIntoArray(data, dataDims, model.components, extent, extentPixels, writeOffset); ++ writeOffset += getExtentPixelCount(extent) * model.components; + }); + return extentPixels; + } +@@ -797,7 +797,7 @@ + const extent = updatedExtents[i]; + const extentSize = getExtentSize(extent); + const extentPixelCount = getExtentPixelCount(extent); +- const textureData = new extentPixels.constructor(extentPixels.buffer, readOffset, extentPixelCount); ++ const textureData = new extentPixels.constructor(extentPixels.buffer, readOffset, extentPixelCount * model.components); + readOffset += textureData.byteLength; + model.context.texSubImage3D(model.target, 0, extent[0], extent[2], extent[4], extentSize[0], extentSize[1], extentSize[2], model.format, model.openGLDataType, textureData); + } diff --git a/node_modules/@kitware/vtk.js/Rendering/OpenGL/VolumeMapper.js b/node_modules/@kitware/vtk.js/Rendering/OpenGL/VolumeMapper.js --- a/node_modules/@kitware/vtk.js/Rendering/OpenGL/VolumeMapper.js +++ b/node_modules/@kitware/vtk.js/Rendering/OpenGL/VolumeMapper.js @@ -123,3 +173,11 @@ diff --git a/node_modules/@kitware/vtk.js/Rendering/OpenGL/VolumeMapper.js b/nod const newScalarTexture = Texture_default.newInstance(); newScalarTexture.setOpenGLRenderWindow(model._openGLRenderWindow); const dims = imageData.getDimensions(); +@@ -894,6 +894,7 @@ + dataArray: scalars, + updatedExtents + }); ++ model._openGLRenderWindow.getGraphicsResourceForObject(scalars).hash = scalarsHash; + } + replaceGraphicsResource(model._openGLRenderWindow, model._scalarTexturesCore[component], scalars); + model._scalarTexturesCore[component] = scalars; diff --git a/tests/specs/streamed-volume-texture.e2e.ts b/tests/specs/streamed-volume-texture.e2e.ts new file mode 100644 index 000000000..52a89034e --- /dev/null +++ b/tests/specs/streamed-volume-texture.e2e.ts @@ -0,0 +1,182 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import type { Page } from '@playwright/test'; +import { test, expect } from '../fixtures'; +import { CONTENT_VIEWPORT } from '../e2eRun'; +import type { VolViewPage } from '../pageobjects/volview.page'; +import { + buildSyntheticCineDicom, + buildSyntheticDicom, + newUid, +} from './syntheticDicom'; +import type { Utils } from './utils'; +import { displayedWindow, WINDOW_TOOL } from './octTestUtils'; +import { VIEW } from './volumeTestUtils'; + +const [COLS, ROWS, SLICES] = [24, 20, 32]; +const FULL_WIDTH = 4000; +const TWO_VIEW = 'div[data-testid="vtk-view vtk-two-view"]'; +const MULTIFRAME_GRAYSCALE_BYTE = '1.2.840.10008.5.1.4.1.1.7.2'; + +// The end slices each hold under 5% of the voxels, so High Contrast drops them. +const sliceValue = (index: number) => { + if (index === 0) return 0; + return index === SLICES - 1 ? FULL_WIDTH : 1000 + 10 * index; +}; + +const series = (modality: string) => { + const [studyUid, seriesUid] = [newUid(), newUid()]; + return Array.from({ length: SLICES }, (_, index): [string, Uint8Array] => [ + `slice-${index}.dcm`, + buildSyntheticDicom({ + studyUid, + seriesUid, + sopUid: newUid(), + modality, + instanceNumber: index + 1, + rows: ROWS, + cols: COLS, + imageOrientationPatient: [1, 0, 0, 0, 1, 0], + imagePositionPatient: [0, 0, index], + pixelValue: sliceValue(index), + }), + ]); +}; + +async function open( + page: Page, + volview: VolViewPage, + utils: Utils, + name: string, + files: [string, Uint8Array][] +) { + const directory = utils.makeTempDir(name); + const resources = files.map(([file, dicom]) => { + fs.writeFileSync(path.join(directory, file), dicom); + return { url: `tmp/${name}/${file}`, name: file }; + }); + await utils.writeManifestToFile({ resources }, `${name}.json`); + await utils.openVolViewPage(`${name}.json`); + await volview.waitForViewCounts(3, true); + await volview.waitForLoadingIndicator(page.locator(TWO_VIEW).first()); +} + +/** High Contrast narrows the window once the presets have their fit too. */ +async function waitForStatistics(page: Page, volview: VolViewPage) { + const view = page.locator(TWO_VIEW).first(); + await view.locator('canvas').click(); + const windowTool = page.locator(WINDOW_TOOL); + const menu = await volview.openMenu(windowTool); + await menu + .locator( + '.v-radio:has(input[value="HighContrast"]) .v-selection-control__input' + ) + .click(); + await volview.closeMenu(windowTool); + await expect + .poll(async () => (await displayedWindow(view)).width, { + message: 'Expected the image statistics to narrow the window', + }) + .toBeLessThan(FULL_WIDTH / 2); +} + +const canvasWidth = (page: Page) => + page + .locator(VIEW) + .locator('canvas') + .evaluate((canvas) => (canvas as HTMLCanvasElement).width); + +/** A resize redraws the 3D view at once, after every earlier change. */ +async function redraw3D(page: Page) { + const width = await canvasWidth(page); + await page.setViewportSize({ + ...CONTENT_VIEWPORT, + width: CONTENT_VIEWPORT.width - 100, + }); + await expect.poll(() => canvasWidth(page)).not.toBe(width); +} + +/** Share of the 3D view's rows that show any of the volume. */ +async function volumeHeight(utils: Utils) { + const [{ width, data }] = await utils.captureViewPixels( + VIEW, + 60, + 'volume.png' + ); + const rows = data.length / 4 / width; + const filled = Array.from({ length: rows }, (_, row) => + data + .subarray(row * width * 4, (row + 1) * width * 4) + .some((value, index) => index % 4 !== 3 && value > 40) + ); + return filled.filter(Boolean).length / rows; +} + +test.describe('streamed volume textures', () => { + test.beforeEach(async ({ page }) => { + await page.addInitScript((size) => { + const gl = WebGL2RenderingContext.prototype as unknown as Record< + string, + (...args: unknown[]) => unknown + >; + let count = 0; + Object.assign(window, { volumeAllocations: () => count }); + ['texImage3D', 'texStorage3D'].forEach((name) => { + const allocate = gl[name]; + gl[name] = function record(this: unknown, ...args: unknown[]) { + if (args.slice(3, 6).join('x') === size) count += 1; + return allocate.apply(this, args); + }; + }); + }, `${COLS}x${ROWS}x${SLICES}`); + }); + + ['CT', 'MR'].forEach((modality) => { + test(`uploads a ${modality} series once through loading and its preset fit`, async ({ + page, + volview, + utils, + }) => { + await open( + page, + volview, + utils, + `streamed-${modality}`, + series(modality) + ); + await waitForStatistics(page, volview); + await redraw3D(page); + const allocations = await page.evaluate(() => + ( + window as unknown as { volumeAllocations: () => number } + ).volumeAllocations() + ); + expect(allocations).toBe(1); + }); + }); + + test('shows every frame of a multi-frame file in 3D', async ({ + page, + volview, + utils, + }) => { + const dicom = buildSyntheticCineDicom({ + studyUid: newUid(), + seriesUid: newUid(), + sopUid: newUid(), + numberOfFrames: 16, + rows: ROWS, + cols: COLS, + sopClassUid: MULTIFRAME_GRAYSCALE_BYTE, + }); + await open(page, volview, utils, 'streamed-frames', [ + ['frames.dcm', dicom], + ]); + // One frame alone shows as a thin slab. + await expect + .poll(() => volumeHeight(utils), { + message: 'Expected the 3D view to show every frame', + }) + .toBeGreaterThan(0.5); + }); +}); diff --git a/tests/specs/syntheticDicom.ts b/tests/specs/syntheticDicom.ts index 810ec3df6..e3b0f87b4 100644 --- a/tests/specs/syntheticDicom.ts +++ b/tests/specs/syntheticDicom.ts @@ -122,6 +122,20 @@ const frameBytes16 = (sampleCount: number, value: number) => { return bytes; }; +const toPart10 = (sopClassUid: string, sopUid: string, dataset: Uint8Array) => { + const fileMetaBody = combine( + elemLong(0x0002, 0x0001, 'OB', new Uint8Array([0x00, 0x01])), + ui(0x0002, 0x0002, sopClassUid), + ui(0x0002, 0x0003, sopUid), + ui(0x0002, 0x0010, TS_EXPLICIT_VR_LE) + ); + const fileMeta = combine( + elemShort(0x0002, 0x0000, 'UL', writeLong(fileMetaBody.length)), + fileMetaBody + ); + return combine(new Uint8Array(128), enc.encode('DICM'), fileMeta, dataset); +}; + export type SyntheticSliceOptions = { studyUid: string; seriesUid: string; @@ -239,18 +253,7 @@ export function buildSyntheticDicom(opts: SyntheticSliceOptions): Uint8Array { : elemLong(0x7fe0, 0x0010, 'OW', frameBytes16(rows * cols, pixelValue)) ); - const fileMetaBody = combine( - elemLong(0x0002, 0x0001, 'OB', new Uint8Array([0x00, 0x01])), - ui(0x0002, 0x0002, SOP_CLASS_MR), - ui(0x0002, 0x0003, sopUid), - ui(0x0002, 0x0010, TS_EXPLICIT_VR_LE) - ); - const fileMeta = combine( - elemShort(0x0002, 0x0000, 'UL', writeLong(fileMetaBody.length)), - fileMetaBody - ); - - return combine(new Uint8Array(128), enc.encode('DICM'), fileMeta, dataset); + return toPart10(SOP_CLASS_MR, sopUid, dataset); } export type SyntheticCineOptions = { @@ -265,6 +268,8 @@ export type SyntheticCineOptions = { patientId?: string; seriesNumber?: number; studyDate?: string; + // Another multi-frame class loads the frames as a volume instead of a cine. + sopClassUid?: string; }; export function buildSyntheticCineDicom( @@ -282,13 +287,14 @@ export function buildSyntheticCineDicom( patientId = 'TEST001', seriesNumber = 1, studyDate = '20260101', + sopClassUid = SOP_CLASS_ULTRASOUND_MULTIFRAME, } = opts; const pixelData = new Uint8Array(numberOfFrames * rows * cols); for (let i = 0; i < pixelData.length; i++) pixelData[i] = i % 251; const dataset = combine( - ui(0x0008, 0x0016, SOP_CLASS_ULTRASOUND_MULTIFRAME), + ui(0x0008, 0x0016, sopClassUid), ui(0x0008, 0x0018, sopUid), da(0x0008, 0x0020, studyDate), da(0x0008, 0x0021, studyDate), @@ -315,18 +321,7 @@ export function buildSyntheticCineDicom( elemLong(0x7fe0, 0x0010, 'OB', pixelData) ); - const fileMetaBody = combine( - elemLong(0x0002, 0x0001, 'OB', new Uint8Array([0x00, 0x01])), - ui(0x0002, 0x0002, SOP_CLASS_ULTRASOUND_MULTIFRAME), - ui(0x0002, 0x0003, sopUid), - ui(0x0002, 0x0010, TS_EXPLICIT_VR_LE) - ); - const fileMeta = combine( - elemShort(0x0002, 0x0000, 'UL', writeLong(fileMetaBody.length)), - fileMetaBody - ); - - return combine(new Uint8Array(128), enc.encode('DICM'), fileMeta, dataset); + return toPart10(sopClassUid, sopUid, dataset); } // Pseudo-UID unique per call within a test process. All-numeric so it