diff --git a/src/components/VolumeRendering.vue b/src/components/VolumeRendering.vue index 76b33c615..77e549b97 100644 --- a/src/components/VolumeRendering.vue +++ b/src/components/VolumeRendering.vue @@ -20,8 +20,10 @@ import { useVolumeColoringInitializer } from '@/src/composables/useVolumeColorin import { useResizeObserver } from '@/src/composables/useResizeObserver'; import { useCurrentImage } from '@/src/composables/useCurrentImage'; import useVolumeColoringStore from '@/src/store/view-configs/volume-coloring'; +import { piecewiseHistogram } from '@/src/utils/histogram'; import { getColorFunctionRangeFromPreset, + getScalarSample, getShiftedOpacityFromPreset, } from '@/src/utils/vtk-helpers'; @@ -183,19 +185,26 @@ export default defineComponent({ colorTransferFunc.delete(); }); - watch( - currentImageData, - (image) => { - if (image) { - const scalars = image.getPointData().getScalars(); - // TODO(fli): setDataArray() re-computes the data range unnecessarily - pwfWidget.setDataArray(scalars.getData()); - pwfWidget.render(); - } - }, - { immediate: true } + const opacityMappingRange = computed( + () => opacityFunction.value?.mappingRange ); + watchEffect(() => { + const image = currentImageData.value; + const range = opacityMappingRange.value; + if (!image || !range) return; + pwfWidget.setHistogram( + piecewiseHistogram( + getScalarSample(image), + range, + pwfWidget.getNumberOfBins(), + !image.getPointData().getScalars().getDataType().includes('Float') + ), + range + ); + pwfWidget.render(); + }); + // update pwf widget when lut changes watch( colorTransferFunctionRef, diff --git a/src/utils/__tests__/histogram.spec.ts b/src/utils/__tests__/histogram.spec.ts index f7a1abdc0..a580840a5 100644 --- a/src/utils/__tests__/histogram.spec.ts +++ b/src/utils/__tests__/histogram.spec.ts @@ -1,5 +1,9 @@ import { describe, expect, it } from 'vitest'; -import { histogram, histogramWindowRanges } from '@/src/utils/histogram'; +import { + histogram, + histogramWindowRanges, + piecewiseHistogram, +} from '@/src/utils/histogram'; describe('scalar image histograms', () => { it('keeps inclusive integer source bins', () => { @@ -40,3 +44,33 @@ describe('scalar image histograms', () => { expect(() => histogram([1, -Infinity], [0, 1], 512)).toThrow(/finite/); }); }); + +describe('piecewiseHistogram', () => { + it('uses one bin per level for integers narrower than the bin count', () => { + const levels = Array.from({ length: 161 }, (_, index) => 20 + index); + const counts = piecewiseHistogram(levels, [20, 180], 256, true); + expect(counts).toHaveLength(161); + expect(counts.every((count) => count > 0)).toBe(true); + expect(piecewiseHistogram(levels, [20, 180], 256)).toHaveLength(256); + }); + + it('draws the two levels of a binary mask as separate peaks', () => { + const mask = [...Array(9).fill(0), 1]; + expect(Array.from(piecewiseHistogram(mask, [0, 1], 256, true))).toEqual([ + 9, 0, 1, + ]); + }); + + it('bins only the given range and scales by the second-largest bin', () => { + const values = [-5, 0, 0, 0, 0, 1, 1, 2, 3, 3, 4, 1e6, NaN]; + expect(Array.from(piecewiseHistogram(values, [0, 4], 5))).toEqual([ + 2, 1, 0.5, 1, 0.5, + ]); + }); + + it('is empty for a zero-width range', () => { + expect(Array.from(piecewiseHistogram([3, 3], [3, 3], 4))).toEqual([ + 0, 0, 0, 0, + ]); + }); +}); diff --git a/src/utils/histogram.ts b/src/utils/histogram.ts index 18a7cc0f8..000247c26 100644 --- a/src/utils/histogram.ts +++ b/src/utils/histogram.ts @@ -64,3 +64,25 @@ export function histogramWindowRanges( HighContrast: percentileRange(WLAutoRanges.HighContrast), }; } + +/** Bins and scaling as vtkPiecewiseGaussianWidget draws them: bin i at min + i * span / (bins - 1). */ +export function piecewiseHistogram( + values: ArrayLike, + [min, max]: readonly number[], + maxBins: number, + integer = false +) { + const span = max - min; + // One bin per integer level, as extra bins leave gaps; three at least so two levels draw as two peaks. + const numberOfBins = integer + ? Math.max(3, Math.min(maxBins, Math.floor(span) + 1)) + : maxBins; + const counts = new Float32Array(numberOfBins); + if (!(span > 0)) return counts; + for (let index = 0; index < values.length; index += 1) { + const bin = Math.floor(((numberOfBins - 1) * (values[index] - min)) / span); + if (bin >= 0 && bin < numberOfBins) counts[bin] += 1; + } + const scale = counts.slice().sort()[numberOfBins - 2] || 1; + return counts.map((count) => count / scale); +} diff --git a/src/vtk/PiecewiseWidget/index.js b/src/vtk/PiecewiseWidget/index.js index 88d513eff..2e43efd00 100644 --- a/src/vtk/PiecewiseWidget/index.js +++ b/src/vtk/PiecewiseWidget/index.js @@ -77,6 +77,14 @@ function vtkPiecewiseWidget(publicAPI, model) { model.opacityPointShift = 0; model.opacityValueShift = 0; + publicAPI.setHistogram = (histogram, dataRange) => { + model.histogram = histogram; + model.dataRange = [...dataRange]; + // The color bar is cached per transfer function mtime, not per range. + model.colorCanvasMTime = 0; + publicAPI.modified(); + }; + publicAPI.setGaussiansMode = () => { model.pwMode = Mode.Gaussians; }; diff --git a/tests/specs/volume-coloring-reset.e2e.ts b/tests/specs/volume-coloring-reset.e2e.ts index 0860aec7a..095a6431a 100644 --- a/tests/specs/volume-coloring-reset.e2e.ts +++ b/tests/specs/volume-coloring-reset.e2e.ts @@ -6,6 +6,7 @@ import { nrrd, showColorPresets, openWith3DLayout, + radialRamp, selectedPreset, writeNrrd, } from './volumeTestUtils'; @@ -77,14 +78,7 @@ async function dragOpacityCurve(steps: number) { describe('3D rendering color and opacity reset', () => { it('restores Shift, Width, and the opacity curve while keeping lighting', async () => { const name = 'volume-coloring-reset'; - const voxels = floatVoxels(SIZE, (index) => { - const offsets = [ - index % SIZE, - Math.floor(index / SIZE) % SIZE, - Math.floor(index / SIZE ** 2), - ].map((c) => c - SIZE / 2); - return Math.max(0, 1000 * (1 - Math.hypot(...offsets) / (SIZE / 2))); - }); + const voxels = floatVoxels(SIZE, radialRamp(SIZE)); await openWith3DLayout( writeNrrd(name, nrrd(['modality:=MR'], 'float', SIZE), voxels), name diff --git a/tests/specs/volume-opacity-histogram.e2e.ts b/tests/specs/volume-opacity-histogram.e2e.ts new file mode 100644 index 000000000..dd80fb814 --- /dev/null +++ b/tests/specs/volume-opacity-histogram.e2e.ts @@ -0,0 +1,62 @@ +import { volViewPage } from '../pageobjects/volview.page'; +import { captureViewPixels, waitForModuleTransitions } from './utils'; +import { + differingFraction, + floatVoxels, + nrrd, + openWith3DLayout, + radialRamp, + writeNrrd, +} from './volumeTestUtils'; + +const SIZE = 16; +const EDITOR = '[data-testid="volume-opacity-editor"]'; + +const ramp = radialRamp(SIZE); +const voxels = (corner: number) => + floatVoxels(SIZE, (index) => (index === 0 ? corner : ramp(index))); + +async function capture() { + const [{ data }] = await captureViewPixels( + EDITOR, + 0, + 'volume-opacity-histogram.png' + ); + return data; +} + +async function stableEditorPixels(name: string, data: Buffer) { + await openWith3DLayout(writeNrrd(name, nrrd([], 'float', SIZE), data), name); + await volViewPage.renderingModuleTab.waitForClickable(); + await volViewPage.renderingModuleTab.click(); + await waitForModuleTransitions(); + await $(EDITOR).scrollIntoView({ block: 'center', behavior: 'instant' }); + let previous = await capture(); + await browser.waitUntil(async () => { + const next = await capture(); + const same = next.equals(previous); + previous = next; + return same; + }); + return previous; +} + +describe('3D rendering opacity editor histogram', () => { + it('spans the fitted opacity range rather than a far outlier', async () => { + const plain = await stableEditorPixels( + 'opacity-histogram-plain', + voxels(0) + ); + const outlier = await stableEditorPixels( + 'opacity-histogram-outlier', + voxels(1e6) + ); + expect(differingFraction(plain, outlier)).toBeLessThan(0.01); + // A relative preset draws the same curve and color bar over any range, so only the histogram differs. + const squared = await stableEditorPixels( + 'opacity-histogram-squared', + floatVoxels(SIZE, (index) => ramp(index) ** 2 / 1000) + ); + expect(differingFraction(plain, squared)).toBeGreaterThan(0.05); + }); +}); diff --git a/tests/specs/volumeTestUtils.ts b/tests/specs/volumeTestUtils.ts index 554d391fc..a99898fbb 100644 --- a/tests/specs/volumeTestUtils.ts +++ b/tests/specs/volumeTestUtils.ts @@ -35,6 +35,16 @@ export function floatVoxels(size: number, valueAt: (index: number) => number) { return buffer; } +/** 1000 at the cube center, falling linearly to 0 at half the edge length. */ +export const radialRamp = (size: number) => (index: number) => { + const offsets = [ + index % size, + Math.floor(index / size) % size, + Math.floor(index / size ** 2), + ].map((c) => c - size / 2); + return Math.max(0, 1000 * (1 - Math.hypot(...offsets) / (size / 2))); +}; + export function writeNrrd(name: string, header: string, voxels: Buffer) { const directory = makeTempDir(name); fs.writeFileSync(