All files / core/src/utilities generateVolumePropsFromImageIds.ts

83.67% Statements 41/49
58.62% Branches 17/29
100% Functions 9/9
83.33% Lines 40/48

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192                              428x                                 116x     116x   116x         116x           116x 116x   116x         116x     116x 116x 348x   116x           116x                                                       116x 116x     116x 116x 2x       114x           114x 342x       114x 342x       114x 326x     114x   114x           114x 8x   106x 106x                                                     116x 348x     116x 114x       2x     2x   6x       2x              
import { vec3 } from 'gl-matrix';
import makeVolumeMetadata from './makeVolumeMetadata';
import sortImageIdsAndGetSpacing from './sortImageIdsAndGetSpacing';
import type {
  ImageVolumeProps,
  Mat3,
  PixelDataTypedArrayString,
  Point3,
} from '../types';
import getScalingParameters from './getScalingParameters';
import { hasFloatScalingParameters } from './hasFloatScalingParameters';
import { canRenderFloatTextures } from '../init';
import cache from '../cache/cache';
 
// Map constructor names to PixelDataTypedArrayString
const constructorToTypedArray: Record<string, PixelDataTypedArrayString> = {
  Uint8Array: 'Uint8Array',
  Int16Array: 'Int16Array',
  Uint16Array: 'Uint16Array',
  Float32Array: 'Float32Array',
};
/**
 * Generates volume properties from a list of image IDs.
 *
 * @param imageIds - An array of image IDs.
 * @param volumeId - The ID of the volume.
 * @returns The generated ImageVolumeProps object.
 */
function generateVolumePropsFromImageIds(
  imageIds: string[],
  volumeId: string
): ImageVolumeProps {
  const volumeMetadata = makeVolumeMetadata(imageIds);
 
  const { ImageOrientationPatient, PixelSpacing, Columns, Rows } =
    volumeMetadata;
 
  const rowCosineVec = vec3.fromValues(
    ImageOrientationPatient[0],
    ImageOrientationPatient[1],
    ImageOrientationPatient[2]
  );
  const colCosineVec = vec3.fromValues(
    ImageOrientationPatient[3],
    ImageOrientationPatient[4],
    ImageOrientationPatient[5]
  );
 
  const scanAxisNormal = vec3.create();
  vec3.cross(scanAxisNormal, rowCosineVec, colCosineVec);
 
  const { zSpacing, origin, sortedImageIds } = sortImageIdsAndGetSpacing(
    imageIds,
    scanAxisNormal
  );
 
  const numFrames = imageIds.length;
 
  // Spacing goes [1] then [0], as [1] is column spacing (x) and [0] is row spacing (y)
  const spacing = [PixelSpacing[1], PixelSpacing[0], zSpacing] as Point3;
  const dimensions = [Columns, Rows, numFrames].map((it) =>
    Math.floor(it)
  ) as Point3;
  const direction = [
    ...rowCosineVec,
    ...colCosineVec,
    ...scanAxisNormal,
  ] as Mat3;
 
  return {
    dimensions,
    spacing,
    origin,
    dataType: _determineDataType(sortedImageIds, volumeMetadata),
    direction,
    metadata: volumeMetadata,
    imageIds: sortedImageIds,
    volumeId,
    voxelManager: null,
    numberOfComponents:
      volumeMetadata.PhotometricInterpretation === 'RGB' ? 3 : 1,
  };
}
 
/**
 * Determines the appropriate data type based on bits allocated and other parameters.
 * @param BitsAllocated - The number of bits allocated for each pixel.
 * @param signed - Whether the data is signed.
 * @param canRenderFloat - Whether float rendering is supported.
 * @param floatAfterScale - Whether to use float after scaling.
 * @param hasNegativeRescale - Whether there's a negative rescale.
 * @returns The determined data type.
 */
function _determineDataType(
  imageIds: string[],
  volumeMetadata
): PixelDataTypedArrayString {
  const { BitsAllocated, PixelRepresentation } = volumeMetadata;
  const signed = PixelRepresentation === 1;
 
  // First try to get data type from cache if images are loaded
  const cachedDataType = _getDataTypeFromCache(imageIds);
  if (cachedDataType) {
    return cachedDataType;
  }
 
  // Check scaling parameters for first, middle, and last images
  const [firstIndex, middleIndex, lastIndex] = [
    0,
    Math.floor(imageIds.length / 2),
    imageIds.length - 1,
  ];
 
  const scalingParameters = [firstIndex, middleIndex, lastIndex].map((index) =>
    getScalingParameters(imageIds[index])
  );
 
  // Check if any image has negative rescale values
  const hasNegativeRescale = scalingParameters.some(
    (params) => params.rescaleIntercept < 0 || params.rescaleSlope < 0
  );
 
  // Check if any image has float scaling parameters
  const floatAfterScale = scalingParameters.some((params) =>
    hasFloatScalingParameters(params)
  );
 
  const canRenderFloat = canRenderFloatTextures();
 
  switch (BitsAllocated) {
    case 8:
      return 'Uint8Array';
 
    case 16:
      // Temporary fix for 16 bit images to use Float32
      if (canRenderFloat && floatAfterScale) {
        return 'Float32Array';
      }
      Eif (signed || hasNegativeRescale) {
        return 'Int16Array';
      }
      if (!signed && !hasNegativeRescale) {
        return 'Uint16Array';
      }
      return 'Float32Array';
 
    case 24:
      return 'Uint8Array';
 
    case 32:
      return 'Float32Array';
 
    default:
      throw new Error(
        `Bits allocated of ${BitsAllocated} is not defined to generate scalarData for the volume.`
      );
  }
}
 
/**
 * Attempts to determine data type from cached images
 */
function _getDataTypeFromCache(
  imageIds: string[]
): PixelDataTypedArrayString | null {
  // Check first, middle and last images
  const indices = [0, Math.floor(imageIds.length / 2), imageIds.length - 1];
  const images = indices.map((i) => cache.getImage(imageIds[i]));
 
  // Return null if any images are missing
  if (!images.every(Boolean)) {
    return null;
  }
 
  // Get constructor name from first image's pixel data
  const constructorName = images[0].getPixelData().constructor.name;
 
  // Check if all images have same constructor and it's a valid type
  Eif (
    images.every(
      (img) => img.getPixelData().constructor.name === constructorName
    ) &&
    constructorName in constructorToTypedArray
  ) {
    return constructorToTypedArray[constructorName];
  }
 
  return null;
}
 
export { generateVolumePropsFromImageIds };