All files / packages/core/src init.ts

34.44% Statements 31/90
20.4% Branches 10/49
66.66% Functions 14/21
34.44% Lines 31/90

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 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331      1x 1x 1x             1x                             1x                             1x           6x     6x       6x         6x     6x                                                                     47x     47x                                   2x 2x                                                                                                                               36x 36x 36x                           47x 47x                         6x 6x                   588x                                                                             75x                     146x                     557x                           42x 12x             5x 1x     5x                                    
import { getGPUTier } from 'detect-gpu';
import { SharedArrayBufferModes } from './enums';
import { getRenderingEngines } from './RenderingEngine/getRenderingEngine';
let csRenderInitialized = false;
let useSharedArrayBuffer = true;
let sharedArrayBufferMode = SharedArrayBufferModes.TRUE;
import { deepMerge } from './utilities';
import { Cornerstone3DConfig } from './types';
import CentralizedWebWorkerManager from './webWorkerManager/webWorkerManager';
 
// TODO: move sharedArrayBuffer into config.
// TODO: change config into a class with methods to better control get/set
const defaultConfig: Cornerstone3DConfig = {
  gpuTier: undefined,
  detectGPUConfig: {},
  isMobile: false, // is mobile device
  rendering: {
    useCPURendering: false,
    // GPU rendering options
    preferSizeOverAccuracy: false,
    useNorm16Texture: false,
    strictZSpacingForVolumeViewport: true,
  },
  // cache
  enableCacheOptimization: true,
};
 
let config: Cornerstone3DConfig = {
  gpuTier: undefined,
  detectGPUConfig: {},
  isMobile: false, // is mobile device
  rendering: {
    useCPURendering: false,
    // GPU rendering options
    preferSizeOverAccuracy: false,
    useNorm16Texture: false,
    strictZSpacingForVolumeViewport: true,
  },
  // cache
  enableCacheOptimization: true,
};
 
let webWorkerManager = null;
 
function _getGLContext(): RenderingContext {
  // Create canvas element. The canvas is not added to the
  // document itself, so it is never displayed in the
  // browser window.
  const canvas = document.createElement('canvas');
  // Get WebGLRenderingContext from canvas element.
  const gl =
    canvas.getContext('webgl2') ||
    canvas.getContext('webgl') ||
    canvas.getContext('experimental-webgl');
 
  return gl;
}
 
// https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/By_example/Detect_WebGL
function _hasActiveWebGLContext() {
  const gl = _getGLContext();
 
  // Check if the context is either WebGLRenderingContext or WebGL2RenderingContext
  return (
    gl instanceof WebGLRenderingContext || gl instanceof WebGL2RenderingContext
  );
}
 
function hasSharedArrayBuffer() {
  try {
    /*eslint-disable no-constant-condition */
    if (new SharedArrayBuffer(0)) {
      return true;
    } else {
      return false;
    }
  } catch {
    return false;
  }
}
 
function _hasNorm16TextureSupport() {
  const gl = _getGLContext();
 
  if (gl) {
    const ext = (gl as WebGL2RenderingContext).getExtension(
      'EXT_texture_norm16'
    );
 
    if (ext) {
      return true;
    }
  }
 
  return false;
}
 
function isIOS() {
  Iif (/iPad|iPhone|iPod/.test(navigator.platform)) {
    return true;
  } else {
    return (
      navigator.maxTouchPoints &&
      navigator.maxTouchPoints > 2 &&
      /MacIntel/.test(navigator.platform)
    );
  }
}
 
/**
 * Initialize the cornerstone-core. If the browser has a webgl context and
 * the detected gpu (by detect-gpu library) indicates the GPU is not low end we
 * will use webgl GPU rendering. Otherwise we will use cpu rendering.
 *
 * @param configuration - A configuration object
 * @returns A promise that resolves to true cornerstone has been initialized successfully.
 * @category Initialization
 */
async function init(configuration = config): Promise<boolean> {
  Eif (csRenderInitialized) {
    return csRenderInitialized;
  }
 
  // merge configs
  config = deepMerge(defaultConfig, configuration);
 
  if (isIOS()) {
    // iOS devices don't have support for OES_texture_float_linear
    // and thus we should use native data type if we are on iOS
    config.rendering.useNorm16Texture = _hasNorm16TextureSupport();
 
    if (!config.rendering.useNorm16Texture) {
      if (configuration.rendering?.preferSizeOverAccuracy) {
        config.rendering.preferSizeOverAccuracy = true;
      } else {
        console.log(
          'norm16 texture not supported, you can turn on the preferSizeOverAccuracy flag to use native data type, but be aware of the inaccuracy of the rendering in high bits'
        );
      }
    }
  }
 
  // gpuTier
  const hasWebGLContext = _hasActiveWebGLContext();
  if (!hasWebGLContext) {
    console.log('CornerstoneRender: GPU not detected, using CPU rendering');
    config.rendering.useCPURendering = true;
  } else {
    config.gpuTier =
      config.gpuTier || (await getGPUTier(config.detectGPUConfig));
    console.log(
      'CornerstoneRender: Using detect-gpu to get the GPU benchmark:',
      config.gpuTier
    );
    if (config.gpuTier?.tier < 1) {
      console.log(
        'CornerstoneRender: GPU is not powerful enough, using CPU rendering'
      );
      config.rendering.useCPURendering = true;
    } else {
      console.log('CornerstoneRender: using GPU rendering');
    }
  }
 
  setUseSharedArrayBuffer(sharedArrayBufferMode);
 
  csRenderInitialized = true;
 
  if (!webWorkerManager) {
    webWorkerManager = new CentralizedWebWorkerManager();
  }
 
  return csRenderInitialized;
}
 
/**
 * It sets the useCPURenderingOnlyForDebugOrTests variable to the status value.
 * This only should be used for debugging or tests. DO NOT USE IT IF YOU ARE NOT
 * SURE WHAT YOU ARE DOING.
 * @param status - boolean
 * @category Initialization
 *
 */
function setUseCPURendering(status: boolean): void {
  config.rendering.useCPURendering = status;
  csRenderInitialized = true;
  _updateRenderingPipelinesForAllViewports();
}
 
function setPreferSizeOverAccuracy(status: boolean): void {
  config.rendering.preferSizeOverAccuracy = status;
  csRenderInitialized = true;
  _updateRenderingPipelinesForAllViewports();
}
 
/**
 * Only IPhone IOS cannot render float textures right now due to the lack of support for OES_texture_float_linear.
 * So we should not use float textures on IOS devices.
 */
function canRenderFloatTextures(): boolean {
  Eif (!isIOS()) {
    return true;
  }
 
  return false;
}
 
/**
 * Resets the cornerstone-core init state if it has been manually
 * initialized to force use the cpu rendering (e.g., for tests)
 * @category Initialization
 *
 */
function resetUseCPURendering(): void {
  config.rendering.useCPURendering = !_hasActiveWebGLContext();
  _updateRenderingPipelinesForAllViewports();
}
 
/**
 * Returns whether or not we are using CPU rendering.
 * @returns true if we are using CPU rendering.
 * @category Initialization
 *
 */
function getShouldUseCPURendering(): boolean {
  return config.rendering.useCPURendering;
}
 
function setUseSharedArrayBuffer(mode: SharedArrayBufferModes | boolean): void {
  if (mode == SharedArrayBufferModes.AUTO) {
    sharedArrayBufferMode = SharedArrayBufferModes.AUTO;
    const hasSharedBuffer = hasSharedArrayBuffer();
    if (!hasSharedBuffer) {
      useSharedArrayBuffer = false;
      console.warn(
        `CornerstoneRender: SharedArray Buffer not allowed, performance may be slower.
        Try ensuring page is cross-origin isolated to enable SharedArrayBuffer.`
      );
    } else {
      useSharedArrayBuffer = true;
      // eslint-disable-next-line no-console
      console.log('CornerstoneRender: using SharedArrayBuffer');
    }
    return;
  }
 
  if (mode == SharedArrayBufferModes.TRUE || mode == true) {
    sharedArrayBufferMode = SharedArrayBufferModes.TRUE;
    useSharedArrayBuffer = true;
    return;
  }
 
  if (mode == SharedArrayBufferModes.FALSE || mode == false) {
    sharedArrayBufferMode = SharedArrayBufferModes.FALSE;
    useSharedArrayBuffer = false;
    return;
  }
}
 
function resetUseSharedArrayBuffer(): void {
  setUseSharedArrayBuffer(sharedArrayBufferMode);
}
 
function getShouldUseSharedArrayBuffer(): boolean {
  return useSharedArrayBuffer;
}
 
/**
 *
 * Returns whether or not cornerstone-core has been initialized.
 * @returns true if the cornerstone render has been initialized.
 * @category Initialization
 *
 */
function isCornerstoneInitialized(): boolean {
  return csRenderInitialized;
}
 
/**
 * This function returns a copy of the config object. This is used to prevent the
 * config object from being modified by other parts of the program.
 * @returns A copy of the config object.
 */
function getConfiguration(): Cornerstone3DConfig {
  // return a copy
  // return JSON.parse(JSON.stringify(config));
  return config;
}
 
function setConfiguration(c: Cornerstone3DConfig) {
  config = c;
  _updateRenderingPipelinesForAllViewports();
}
 
/**
 * Update rendering pipelines for all viewports in all rendering engines.
 * @returns {void}
 * @category Initialization
 */
function _updateRenderingPipelinesForAllViewports(): void {
  getRenderingEngines().forEach((engine) =>
    engine
      .getViewports()
      .forEach((viewport) => viewport.updateRenderingPipeline?.())
  );
}
 
function getWebWorkerManager() {
  if (!webWorkerManager) {
    webWorkerManager = new CentralizedWebWorkerManager();
  }
 
  return webWorkerManager;
}
 
export {
  init,
  getShouldUseCPURendering,
  getShouldUseSharedArrayBuffer,
  isCornerstoneInitialized,
  setUseCPURendering,
  setUseSharedArrayBuffer,
  setPreferSizeOverAccuracy,
  resetUseCPURendering,
  resetUseSharedArrayBuffer,
  getConfiguration,
  setConfiguration,
  getWebWorkerManager,
  canRenderFloatTextures,
};