more shifting

This commit is contained in:
dannyrb committed 2019-07-04 16:19:28 -04:00
1 parent b73ea99971
commit e58ba39a60
432 files changed
+51231

No files matched your search

+14
View File
@@ -0,0 +1,14 @@
{
"presets": [
["@babel/preset-env", {
"targets": {
"ie": "11"
}
}],
"@babel/preset-react"
],
"plugins": [
"@babel/plugin-proposal-class-properties",
"@babel/plugin-transform-runtime"
]
}
+9
View File
@@ -0,0 +1,9 @@
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
+16
View File
@@ -0,0 +1,16 @@
{
"extends": [
"react-app",
"eslint:recommended",
"plugin:react/recommended"
],
"parser": "babel-eslint",
"env": {
"jest": true
},
"settings": {
"react": {
"version": "detect",
},
},
}
+26
View File
@@ -0,0 +1,26 @@
# See https://help.github.com/ignore-files/ for more about ignoring files.
# dependencies
node_modules
# builds
build
dist
.rpt2_cache
# misc
.DS_Store
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.idea
yalc.lock
.yalc
+9
View File
@@ -0,0 +1,9 @@
{
"trailingComma": "es5",
"printWidth": 80,
"proseWrap": "always",
"tabWidth": 2,
"semi": true,
"singleQuote": true,
"endOfLine": "lf"
}
+4
View File
@@ -0,0 +1,4 @@
language: node_js
node_js:
- 9
- 8
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 Open Health Imaging Foundation
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+55
View File
@@ -0,0 +1,55 @@
# @ohif/extension-vtk
![npm (scoped)](https://img.shields.io/npm/v/@ohif/extension-vtk.svg?style=flat-square)
<!-- TODO: Simple image or GIF? -->
#### Index
Extension Id: `vtk`
- [Commands Module](#commands-module)
- [Toolbar Module](#toolbar-module)
- [Viewport Module](#viewport-module)
## Commands Module
| Command Name | Description | Store Contexts |
| ---------------------- | ----------- | -------------- |
| `axial` | | viewports |
| `coronal` | | viewports |
| `sagittal` | | viewports |
| `enableRotateTool` | | viewports |
| `enableCrosshairsTool` | | viewports |
| `enableLevelTool` | | viewports |
| `mpr2d` | | viewports |
## Toolbar Module
Our toolbar module contains definitions for:
- `Crosshairs`
- `WWWC`
- `Rotate`
All use the `ACTIVE_VIEWPORT::VTK` context.
## Viewport Module
Our Viewport wraps [OHIF/react-vtkjs-viewport][react-viewport] and is connected
the redux store. This module is the most prone to change as we hammer out our
Viewport interface.
## Resources
### Repositories
- [OHIF/react-vtkjs-viewport][react-viewport]
<!--
Links
-->
<!-- prettier-ignore-start -->
[react-viewport]: https://github.com/OHIF/react-vtkjs-viewport
<!-- prettier-ignore-end -->
+109
View File
@@ -0,0 +1,109 @@
{
"name": "@ohif/extension-vtk",
"version": "0.1.3",
"description": "OHIF extension for VTK.js",
"author": "OHIF",
"license": "MIT",
"repository": "OHIF/Viewers",
"main": "dist/index.umd.js",
"engines": {
"node": ">=8",
"npm": ">=5"
},
"scripts": {
"build": "webpack --progress --colors --mode development",
"build:release": "webpack --progress --colors --mode production",
"start": "webpack --watch --progress --colors --mode development",
"prepare": "yarn run build:release",
"predeploy": "cd example && yarn install && yarn run build:release",
"prepublishOnly": "yarn install && yarn run build:release",
"lint": "eslint -c .eslintrc --fix src && prettier --single-quote --write src/**/*.{js,jsx,json,css}"
},
"peerDependencies": {
"@ohif/i18n": "0.2.2",
"cornerstone-core": "^2.2.8",
"cornerstone-wado-image-loader": "^2.2.3",
"dcmjs": "^0.4.7",
"dicom-parser": "^1.8.3",
"i18next": "^17.0.3",
"i18next-browser-languagedetector": "^3.0.1",
"ohif-core": "^0.6.0",
"prop-types": "^15.7.2",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-i18next": "^10.11.0",
"react-redux": "^7.1.0",
"react-resize-detector": "^4.2.0",
"react-viewerbase": "^0.15.1",
"redux": "^4.0.1"
},
"dependencies": {
"@babel/runtime": "^7.4.5",
"react-vtkjs-viewport": "0.0.9",
"vtk.js": "^8.11.0"
},
"devDependencies": {
"@babel/core": "^7.4.5",
"@babel/plugin-external-helpers": "^7.2.0",
"@babel/plugin-proposal-class-properties": "^7.4.4",
"@babel/plugin-transform-runtime": "^7.4.4",
"@babel/preset-env": "^7.4.5",
"@babel/preset-react": "^7.0.0",
"babel-eslint": "^10.0.1",
"babel-loader": "^8.0.6",
"cornerstone-tools": "^3.13.0",
"cornerstone-wado-image-loader": "^2.2.3",
"cross-env": "^5.2.0",
"dcmjs": "^0.4.7",
"dicom-parser": "^1.8.3",
"eslint": "5.16.0",
"eslint-plugin-import": "^2.17.3",
"eslint-plugin-node": "^9.1.0",
"eslint-plugin-promise": "^4.1.1",
"eslint-plugin-react": "^7.13.0",
"gh-pages": "^2.0.1",
"husky": "^2.4.1",
"i18next": "^17.0.3",
"i18next-browser-languagedetector": "^3.0.1",
"lint-staged": "^8.2.0",
"ohif-core": "^0.7.0",
"prettier": "^1.18.2",
"react": "^16.6.3",
"react-dom": "^16.6.3",
"react-i18next": "^10.11.0",
"react-redux": "^7.1.0",
"react-viewerbase": "^0.15.1",
"redux": "^4.0.1",
"shader-loader": "^1.3.1",
"stylelint": "^10.1.0",
"stylelint-config-recommended": "^2.2.0",
"stylus": "^0.54.5",
"webpack": "^4.33.0",
"webpack-cli": "^3.3.4",
"worker-loader": "^2.0.0"
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"src/**/*.{js,jsx,json,css}": [
"prettier --single-quote --write",
"git add"
]
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
],
"files": [
"dist",
"README.md"
],
"publishConfig": {
"access": "public"
}
}
+85
View File
@@ -0,0 +1,85 @@
import babel from 'rollup-plugin-babel';
import builtins from 'rollup-plugin-node-builtins';
import commonjs from 'rollup-plugin-commonjs';
import external from 'rollup-plugin-peer-deps-external';
import pkg from './package.json';
import postcss from 'rollup-plugin-postcss';
import resolve from 'rollup-plugin-node-resolve';
import url from 'rollup-plugin-url';
import copy from 'rollup-plugin-copy';
// Deal with https://github.com/rollup/rollup-plugin-commonjs/issues/297
const globals = {
react: 'React',
'react-dom': 'ReactDOM',
'react-redux': 'ReactRedux',
'react-resize-detector': 'ReactResizeDetector',
'react-viewerbase': 'reactViewerbase',
'prop-types': 'PropTypes',
'cornerstone-core': 'cornerstone',
'cornerstone-wado-image-loader': 'cornerstoneWADOImageLoader',
'cornerstone-math': 'cornerstoneMath',
'cornerstone-tools': 'cornerstoneTools',
dcmjs: 'dcmjs',
'dicom-parser': 'dicomParser',
'ohif-core': 'OHIF',
hammerjs: 'Hammer',
'@ohif/i18n': 'i18n'
};
export default {
input: 'src/index.js',
output: [
{
file: pkg.main,
format: 'umd',
name: 'ohif-vtk-extension',
sourcemap: true,
globals
},
{
file: pkg.module,
format: 'es',
sourcemap: true,
globals
}
],
plugins: [
builtins(),
external(),
postcss({
modules: false
}),
url(),
babel({
exclude: 'node_modules/**',
externalHelpers: true,
runtimeHelpers: true
}),
copy({
targets: ['src/locales'],
outputFolder: 'dist',
}),
resolve(),
commonjs({
include: ['node_modules/**', '.yalc/**'],
namedExports: {
'node_modules/react-vtkjs-viewport/dist/index.js': [
'getImageData',
'loadImageData',
'VTKViewport',
'VTKMPRViewport'
],
'.yalc/react-vtkjs-viewport/dist/index.js': [
'getImageData',
'loadImageData',
'VTKViewport',
'VTKMPRViewport'
]
}
})
],
external: Object.keys(pkg.peerDependencies || {})
};
@@ -0,0 +1,80 @@
import OHIF from 'ohif-core';
import { View2D } from 'react-vtkjs-viewport';
import { connect } from 'react-redux';
const { setViewportActive, setViewportSpecificData } = OHIF.redux.actions;
const mapStateToProps = (state, ownProps) => {
let dataFromStore;
if (state.extensions && state.extensions.vtk) {
dataFromStore = state.extensions.vtk;
}
// If this is the active viewport, enable prefetching.
const { viewportIndex } = ownProps;
const isActive = viewportIndex === state.viewports.activeViewportIndex;
const viewportLayout = state.viewports.layout.viewports[viewportIndex];
const pluginDetails = viewportLayout.vtk || {};
return {
layout: state.viewports.layout,
isActive,
...pluginDetails,
// Hopefully this doesn't break anything under the hood for this one
// activeTool: activeButton && activeButton.command,
...dataFromStore,
enableStackPrefetch: isActive,
};
};
const mapDispatchToProps = (dispatch, ownProps) => {
const { viewportIndex } = ownProps;
return {
setViewportActive: () => {
dispatch(setViewportActive(viewportIndex));
},
setViewportSpecificData: data => {
dispatch(setViewportSpecificData(viewportIndex, data));
},
};
};
const mergeProps = (propsFromState, propsFromDispatch, ownProps) => {
const { afterCreation } = propsFromState;
const props = {
...propsFromState,
...propsFromDispatch,
...ownProps,
/**
* Our component sets up the underlying dom element on "componentDidMount"
* for use with VTK.
*
* The onCreated prop passes back an Object containing many of the internal
* components of the VTK scene. We can grab a reference to these here, to
* make playing with VTK's native methods easier.
*
* A similar approach is taken with the Cornerstone extension.
*/
onCreated: api => {
// Store the API details for later
//setViewportSpecificData({ vtkApi: api });
if (afterCreation && typeof afterCreation === 'function') {
afterCreation(api);
}
},
};
return props;
};
const ConnectedVTKViewport = connect(
mapStateToProps,
mapDispatchToProps,
mergeProps
)(View2D);
export default ConnectedVTKViewport;
@@ -0,0 +1,17 @@
.imageViewerLoadingIndicator {
color: #91b9cd;
}
.loadingIndicator {
background-color: rgba(0, 0, 0, 0.75);
font-size: 18px;
height: 100%;
overflow: hidden;
position: absolute;
top: 0;
width: 100%;
z-index: 1;
/* Necessary for click-through to cornerstone element below */
pointer-events: none;
}
@@ -0,0 +1,49 @@
import './LoadingIndicator.css';
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
class LoadingIndicator extends PureComponent {
static propTypes = {
percentComplete: PropTypes.number.isRequired,
error: PropTypes.object,
};
static defaultProps = {
percentComplete: 0,
error: null,
};
render() {
let percComplete;
if (this.props.percentComplete && this.props.percentComplete !== 100) {
percComplete = `${this.props.percentComplete}%`;
}
return (
<React.Fragment>
{this.props.error ? (
<div className="imageViewerErrorLoadingIndicator loadingIndicator">
<div className="indicatorContents">
<h4>Error Loading Image</h4>
<p className="description">An error has occurred.</p>
<p className="details">{this.props.error.message}</p>
</div>
</div>
) : (
<div className="imageViewerLoadingIndicator loadingIndicator">
<div className="indicatorContents">
<p>
Loading... <i className="fa fa-spin fa-circle-o-notch fa-fw" />{' '}
{percComplete}
</p>
</div>
</div>
)}
</React.Fragment>
);
}
}
export default LoadingIndicator;
@@ -0,0 +1,294 @@
import React, { Component } from 'react';
import { getImageData, loadImageData } from 'react-vtkjs-viewport';
import ConnectedVTKViewport from './ConnectedVTKViewport';
import LoadingIndicator from './LoadingIndicator.js';
import OHIF from 'ohif-core';
import PropTypes from 'prop-types';
import cornerstone from 'cornerstone-core';
import handleSegmentationStorage from './handleSegmentationStorage.js';
import vtkDataArray from 'vtk.js/Sources/Common/Core/DataArray';
import vtkImageData from 'vtk.js/Sources/Common/DataModel/ImageData';
import vtkVolume from 'vtk.js/Sources/Rendering/Core/Volume';
import vtkVolumeMapper from 'vtk.js/Sources/Rendering/Core/VolumeMapper';
const { StackManager } = OHIF.utils;
// Metadata configuration
const metadataProvider = new OHIF.cornerstone.MetadataProvider();
cornerstone.metaData.addProvider(
metadataProvider.provider.bind(metadataProvider)
);
StackManager.setMetadataProvider(metadataProvider);
const SOP_CLASSES = {
SEGMENTATION_STORAGE: '1.2.840.10008.5.1.4.1.1.66.4',
};
const specialCaseHandlers = {};
specialCaseHandlers[
SOP_CLASSES.SEGMENTATION_STORAGE
] = handleSegmentationStorage;
// TODO: Figure out where we plan to put this long term
const volumeCache = {};
/**
* Create a labelmap image with the same dimensions as our background volume.
*
* @param backgroundImageData vtkImageData
*/
function createLabelMapImageData(backgroundImageData) {
const labelMapData = vtkImageData.newInstance(
backgroundImageData.get('spacing', 'origin', 'direction')
);
labelMapData.setDimensions(backgroundImageData.getDimensions());
labelMapData.computeTransforms();
const values = new Uint8Array(backgroundImageData.getNumberOfPoints());
const dataArray = vtkDataArray.newInstance({
numberOfComponents: 1, // labelmap with single component
values,
});
labelMapData.getPointData().setScalars(dataArray);
return labelMapData;
}
class OHIFVTKViewport extends Component {
state = {
volumes: null,
paintFilterLabelMapImageData: null,
paintFilterBackgroundImageData: null,
};
static propTypes = {
studies: PropTypes.object,
displaySet: PropTypes.object,
viewportIndex: PropTypes.number,
children: PropTypes.node,
};
static id = 'OHIFVTKViewport';
static init() {
console.log('OHIFVTKViewport init()');
}
static destroy() {
console.log('OHIFVTKViewport destroy()');
StackManager.clearStacks();
}
static getCornerstoneStack(
studies,
studyInstanceUid,
displaySetInstanceUid,
sopInstanceUid,
frameIndex
) {
// Create shortcut to displaySet
const study = studies.find(
study => study.studyInstanceUid === studyInstanceUid
);
const displaySet = study.displaySets.find(set => {
return set.displaySetInstanceUid === displaySetInstanceUid;
});
// Get stack from Stack Manager
const storedStack = StackManager.findOrCreateStack(study, displaySet);
// Clone the stack here so we don't mutate it
const stack = Object.assign({}, storedStack);
if (frameIndex !== undefined) {
stack.currentImageIdIndex = frameIndex;
} else if (sopInstanceUid) {
const index = stack.imageIds.findIndex(imageId => {
const sopCommonModule = cornerstone.metaData.get(
'sopCommonModule',
imageId
);
if (!sopCommonModule) {
return;
}
return sopCommonModule.sopInstanceUID === sopInstanceUid;
});
if (index > -1) {
stack.currentImageIdIndex = index;
}
} else {
stack.currentImageIdIndex = 0;
}
return stack;
}
getViewportData = (
studies,
studyInstanceUid,
displaySetInstanceUid,
sopClassUid,
sopInstanceUid,
frameIndex
) => {
const stack = OHIFVTKViewport.getCornerstoneStack(
studies,
studyInstanceUid,
displaySetInstanceUid,
sopClassUid,
sopInstanceUid,
frameIndex
);
let imageDataObject;
let labelmapDataObject;
switch (sopClassUid) {
case SOP_CLASSES.SEGMENTATION_STORAGE:
throw new Error('Not yet implemented');
const data = handleSegmentationStorage(
stack.imageIds,
displaySetInstanceUid
);
imageDataObject = data.referenceDataObject;
labelmapDataObject = data.labelmapDataObject;
return loadImageData(imageDataObject).then(() => {
return {
data: imageDataObject.vtkImageData,
labelmap: labelmapDataObject,
};
});
default:
imageDataObject = getImageData(stack.imageIds, displaySetInstanceUid);
return loadImageData(imageDataObject).then(() => {
return {
data: imageDataObject.vtkImageData,
};
});
}
};
getOrCreateVolume(data, displaySetInstanceUid) {
if (volumeCache[displaySetInstanceUid]) {
return volumeCache[displaySetInstanceUid];
}
const volumeActor = vtkVolume.newInstance();
const volumeMapper = vtkVolumeMapper.newInstance();
volumeActor.setMapper(volumeMapper);
volumeMapper.setInputData(data);
volumeCache[displaySetInstanceUid] = volumeActor;
return volumeActor;
}
async setStateFromProps() {
const { studies, displaySet } = this.props.viewportData;
const {
studyInstanceUid,
displaySetInstanceUid,
sopClassUids,
sopInstanceUid,
frameIndex,
} = displaySet;
if (sopClassUids.length > 1) {
console.warn(
'More than one SOPClassUid in the same series is not yet supported.'
);
}
const sopClassUid = sopClassUids[0];
let { data, labelmap } = await this.getViewportData(
studies,
studyInstanceUid,
displaySetInstanceUid,
sopClassUid,
sopInstanceUid,
frameIndex
);
if (!labelmap) {
labelmap = createLabelMapImageData(data);
}
const volumeActor = this.getOrCreateVolume(data, displaySetInstanceUid);
this.setState({
volumes: [volumeActor],
paintFilterBackgroundImageData: data,
paintFilterLabelMapImageData: labelmap,
});
}
componentDidMount() {
this.setStateFromProps();
}
componentDidUpdate(prevProps) {
const { studies, displaySet } = this.props.viewportData;
const prevDisplaySet = prevProps.viewportData.displaySet;
if (
displaySet.displaySetInstanceUid !==
prevDisplaySet.displaySetInstanceUid ||
displaySet.sopInstanceUid !== prevDisplaySet.sopInstanceUid ||
displaySet.frameIndex !== prevDisplaySet.frameIndex
) {
this.setStateFromProps();
}
}
render() {
let childrenWithProps = null;
// TODO: Does it make more sense to use Context?
if (this.props.children && this.props.children.length) {
childrenWithProps = this.props.children.map((child, index) => {
return React.cloneElement(child, {
viewportIndex: this.props.viewportIndex,
key: index,
});
});
}
const style = { width: '100%', height: '100%', position: 'relative' };
return (
<>
{this.state.volumes ? (
<ConnectedVTKViewport
volumes={this.state.volumes}
paintFilterLabelMapImageData={
this.state.paintFilterLabelMapImageData
}
paintFilterBackgroundImageData={
this.state.paintFilterBackgroundImageData
}
viewportIndex={this.props.viewportIndex}
/>
) : (
<div style={style}>
<LoadingIndicator />
</div>
)}
{childrenWithProps}
</>
);
}
}
export default OHIFVTKViewport;
@@ -0,0 +1,303 @@
import {
vtkInteractorStyleMPRCrosshairs,
vtkInteractorStyleMPRSlice,
vtkInteractorStyleMPRWindowLevel,
vtkSVGCrosshairsWidget,
vtkSVGWidgetManager,
} from 'react-vtkjs-viewport';
import setMPRLayout from './utils/setMPRLayout.js';
import setViewportToVTK from './utils/setViewportToVTK.js';
import vtkCoordinate from 'vtk.js/Sources/Rendering/Core/Coordinate';
import vtkMath from 'vtk.js/Sources/Common/Core/Math';
import vtkMatrixBuilder from 'vtk.js/Sources/Common/Core/MatrixBuilder';
// TODO: Put this somewhere else
let apis = {};
function getCrosshairCallbackForIndex(index) {
return ({ worldPos }) => {
// Set camera focal point to world coordinate for linked views
apis.forEach((api, viewportIndex) => {
if (viewportIndex !== index) {
// We are basically doing the same as getSlice but with the world coordinate
// that we want to jump to instead of the camera focal point.
// I would rather do the camera adjustment directly but I keep
// doing it wrong and so this is good enough for now.
const renderWindow = api.genericRenderWindow.getRenderWindow();
const istyle = renderWindow.getInteractor().getInteractorStyle();
const sliceNormal = istyle.getSliceNormal();
const transform = vtkMatrixBuilder
.buildFromDegree()
.identity()
.rotateFromDirections(sliceNormal, [1, 0, 0]);
const mutatedWorldPos = worldPos.slice();
transform.apply(mutatedWorldPos);
const slice = mutatedWorldPos[0];
istyle.setSlice(slice);
renderWindow.render();
}
const renderer = api.genericRenderWindow.getRenderer();
const wPos = vtkCoordinate.newInstance();
wPos.setCoordinateSystemToWorld();
wPos.setValue(worldPos);
const displayPosition = wPos.getComputedDisplayValue(renderer);
const { svgWidgetManager } = api;
api.svgWidgets.crosshairsWidget.setPoint(
displayPosition[0],
displayPosition[1]
);
svgWidgetManager.render();
});
};
}
async function _getActiveViewportVTKApi(viewports) {
const { layout, viewportSpecificData, activeViewportIndex } = viewports;
const currentData = layout.viewports[activeViewportIndex];
if (currentData && currentData.plugin === 'vtk') {
// TODO: I was storing/pulling this from Redux but ran into weird issues
if (apis[activeViewportIndex]) {
return apis[activeViewportIndex];
}
}
const displaySet = viewportSpecificData[activeViewportIndex];
let api;
if (!api) {
try {
api = await setViewportToVTK(
displaySet,
activeViewportIndex,
layout,
viewportSpecificData
);
} catch (error) {
throw new Error(error);
}
}
return api;
}
function _setView(api, sliceNormal, viewUp) {
const renderWindow = api.genericRenderWindow.getRenderWindow();
const renderer = api.genericRenderWindow.getRenderer();
const camera = renderer.getActiveCamera();
const istyle = renderWindow.getInteractor().getInteractorStyle();
istyle.setSliceNormal(...sliceNormal);
camera.setViewUp(...viewUp);
api.volumes[0].getMapper().setSampleDistance(5.0);
api.volumes[0].getMapper().setMaximumSamplesPerRay(2000);
renderWindow.render();
}
function switchMPRInteractors(api, istyle) {
const renderWindow = api.genericRenderWindow.getRenderWindow();
let currentNormal;
if (istyle.getSliceNormal) {
currentNormal = istyle.getSliceNormal();
}
// TODO: This is a hacky workaround because disabling the vtkInteractorStyleMPRSlice is currently
// broken. The camera.onModified is never removed. (https://github.com/Kitware/vtk-js/issues/1110)
renderWindow
.getInteractor()
.getInteractorStyle()
.setInteractor(null);
renderWindow.getInteractor().setInteractorStyle(istyle);
// TODO: Not sure why this is required the second time this function is called
istyle.setInteractor(renderWindow.getInteractor());
if (istyle.getVolumeMapper() !== api.volumes[0]) {
if (currentNormal) {
istyle.setSliceNormal(currentNormal);
}
istyle.setVolumeMapper(api.volumes[0]);
}
}
const actions = {
axial: async ({ viewports }) => {
const api = await _getActiveViewportVTKApi(viewports);
apis[viewports.activeViewportIndex] = api;
_setView(api, [0, 0, 1], [0, -1, 0]);
},
sagittal: async ({ viewports }) => {
const api = await _getActiveViewportVTKApi(viewports);
apis[viewports.activeViewportIndex] = api;
_setView(api, [1, 0, 0], [0, 0, 1]);
},
coronal: async ({ viewports }) => {
const api = await _getActiveViewportVTKApi(viewports);
apis[viewports.activeViewportIndex] = api;
_setView(api, [0, 1, 0], [0, 0, 1]);
},
enableRotateTool: async ({ viewports }) => {
apis.forEach(api => {
const istyle = vtkInteractorStyleMPRSlice.newInstance();
switchMPRInteractors(api, istyle);
});
},
enableCrosshairsTool: async ({ viewports }) => {
apis.forEach((api, index) => {
const istyle = vtkInteractorStyleMPRCrosshairs.newInstance();
switchMPRInteractors(api, istyle);
istyle.setCallback(getCrosshairCallbackForIndex(index));
});
},
enableLevelTool: async ({ viewports }) => {
apis.forEach(api => {
const istyle = vtkInteractorStyleMPRWindowLevel.newInstance();
switchMPRInteractors(api, istyle);
});
},
mpr2d: async ({ viewports }) => {
const displaySet =
viewports.viewportSpecificData[viewports.activeViewportIndex];
let apiByViewport;
try {
apiByViewport = await setMPRLayout(displaySet);
} catch (error) {
throw new Error(error);
}
apis = apiByViewport;
/*const rgbTransferFunction = apiByViewport[0].volumes[0]
.getProperty()
.getRGBTransferFunction(0);
rgbTransferFunction.onModified(() => {
apiByViewport.forEach(a => {
const renderWindow = a.genericRenderWindow.getRenderWindow();
renderWindow.render();
});
});*/
apis[0].volumes[0].getMapper().setSampleDistance(1.5);
apiByViewport.forEach((api, index) => {
const renderWindow = api.genericRenderWindow.getRenderWindow();
const renderer = api.genericRenderWindow.getRenderer();
const camera = renderer.getActiveCamera();
// TODO: This is a hacky workaround because disabling the vtkInteractorStyleMPRSlice is currently
// broken. The camera.onModified is never removed. (https://github.com/Kitware/vtk-js/issues/1110)
renderWindow
.getInteractor()
.getInteractorStyle()
.setInteractor(null);
const istyle = vtkInteractorStyleMPRCrosshairs.newInstance();
renderWindow.getInteractor().setInteractorStyle(istyle);
istyle.setVolumeMapper(api.volumes[0]);
istyle.setCallback(getCrosshairCallbackForIndex(index));
const svgWidgetManager = vtkSVGWidgetManager.newInstance();
svgWidgetManager.setRenderer(renderer);
svgWidgetManager.setScale(1);
const crosshairsWidget = vtkSVGCrosshairsWidget.newInstance();
svgWidgetManager.addWidget(crosshairsWidget);
svgWidgetManager.render();
api.svgWidgetManager = svgWidgetManager;
api.svgWidgets = {
crosshairsWidget,
};
switch (index) {
default:
case 0:
//Axial
istyle.setSliceNormal(0, 0, 1);
camera.setViewUp(0, -1, 0);
break;
case 1:
// sagittal
istyle.setSliceNormal(1, 0, 0);
camera.setViewUp(0, 0, 1);
break;
case 2:
// Coronal
istyle.setSliceNormal(0, 1, 0);
camera.setViewUp(0, 0, 1);
break;
}
renderWindow.render();
});
},
};
const definitions = {
axial: {
commandFn: actions.axial,
storeContexts: ['viewports'],
options: {},
},
coronal: {
commandFn: actions.coronal,
storeContexts: ['viewports'],
options: {},
},
sagittal: {
commandFn: actions.sagittal,
storeContexts: ['viewports'],
options: {},
},
enableRotateTool: {
commandFn: actions.enableRotateTool,
storeContexts: ['viewports'],
options: {},
},
enableCrosshairsTool: {
commandFn: actions.enableCrosshairsTool,
storeContexts: ['viewports'],
options: {},
},
enableLevelTool: {
commandFn: actions.enableLevelTool,
storeContexts: ['viewports'],
options: {},
},
mpr2d: {
commandFn: actions.mpr2d,
storeContexts: ['viewports'],
options: {},
context: 'VIEWER',
},
};
export default {
definitions,
defaultContext: 'ACTIVE_VIEWPORT::VTK',
};
@@ -0,0 +1,150 @@
import * as dcmjs from 'dcmjs';
import OHIF from 'ohif-core';
import { api } from 'dicomweb-client';
const { StackManager } = OHIF.utils;
function getDisplaySet(studies, studyInstanceUid, displaySetInstanceUid) {
const study = studies.find(
study => study.studyInstanceUid === studyInstanceUid
);
const displaySet = study.displaySets.find(set => {
return set.displaySetInstanceUid === displaySetInstanceUid;
});
return displaySet;
}
function getDisplaySetsBySeries(studies, studyInstanceUid, seriesInstanceUid) {
const study = studies.find(
study => study.studyInstanceUid === studyInstanceUid
);
return study.displaySets.filter(set => {
return set.seriesInstanceUid === seriesInstanceUid;
});
}
function getCornerstoneStack(studies, studyInstanceUid, displaySetInstanceUid) {
const study = studies.find(
study => study.studyInstanceUid === studyInstanceUid
);
// Create shortcut to displaySet
const displaySet = getDisplaySet(
studies,
studyInstanceUid,
displaySetInstanceUid
);
// Get stack from Stack Manager
const stack = StackManager.findOrCreateStack(study, displaySet);
// Clone the stack here so we don't mutate it later
const stackClone = Object.assign({}, stack);
stackClone.currentImageIdIndex = 0;
return stackClone;
}
function retrieveDicomData(
studyInstanceUID,
seriesInstanceUID,
sopInstanceUID,
wadoRoot
) {
const config = {
url: wadoRoot,
headers: DICOMWeb.getAuthorizationHeader(),
};
const dicomWeb = new api.DICOMwebClient(config);
const options = {
studyInstanceUID,
seriesInstanceUID,
sopInstanceUID,
};
return dicomWeb.retrieveInstance(options);
}
async function handleSegmentationStorage(
studies,
studyInstanceUid,
displaySetInstanceUid
) {
const study = studies.find(
study => study.studyInstanceUid === studyInstanceUid
);
const displaySet = getDisplaySet(
studies,
studyInstanceUid,
displaySetInstanceUid
);
// TODO: This is terrible but we need to use WADO-RS or we can't retrieve the SEG
// from google cloud
const wadoRoot = displaySet.images[0].getData().wadoRoot;
const StudyInstanceUID = displaySet.images[0].getStudyInstanceUID();
const SeriesInstanceUID = displaySet.images[0].getSeriesInstanceUID();
const SOPInstanceUID = displaySet.images[0].getSOPInstanceUID();
const arrayBuffer = await retrieveDicomData(
StudyInstanceUID,
SeriesInstanceUID,
SOPInstanceUID,
wadoRoot
);
const dicomData = dcmjs.data.DicomMessage.readFile(arrayBuffer);
const dataset = dcmjs.data.DicomMetaDictionary.naturalizeDataset(
dicomData.dict
);
const segments = dcmjs.adapters.VTKjs.Segmentation.generateSegments(dataset);
dataset._meta = dcmjs.data.DicomMetaDictionary.namifyDataset(dicomData.meta);
const seriesInstanceUid = dataset.ReferencedSeriesSequence.SeriesInstanceUID;
const displaySets = getDisplaySetsBySeries(
studies,
studyInstanceUid,
seriesInstanceUid
);
if (displaySets.length > 1) {
console.warn(
'More than one display set with the same seriesInstanceUid. This is not supported yet...'
);
}
const referenceDisplaySet = displaySets[0];
const imageIds = referenceDisplaySet.images.map(image => image.getImageId());
if (!results) {
throw new Error('Fractional segmentations are not supported');
}
const cachedStack = StackManager.findOrCreateStack(
study,
referenceDisplaySet
);
const stack = Object.assign({}, cachedStack);
stack.currentImageIdIndex = 0;
return {
referenceDataObject,
labelmapDataObject,
};
return {
studyInstanceUid,
displaySetInstanceUid,
stack,
};
}
export default handleSegmentationStorage;
+24
View File
@@ -0,0 +1,24 @@
import OHIFVTKViewport from './OHIFVTKViewport.js';
import commandsModule from './commandsModule.js';
// This feels weird
import loadLocales from './loadLocales';
import toolbarModule from './toolbarModule.js';
export default {
/**
* Only required property. Should be a unique value across all extensions.
*/
id: 'vtk',
getViewportModule() {
return OHIFVTKViewport;
},
getToolbarModule() {
return toolbarModule;
},
getCommandsModule() {
return commandsModule;
},
};
loadLocales();
+20
View File
@@ -0,0 +1,20 @@
import i18n from '@ohif/i18n';
import locales from './locales';
async function loadLocales() {
// Note: We should wait for the i18n initializing
// promise to complete before adding any new
// resources to i18next. If the resources are added
// to i18next before initialization is complete, the
// backend values (e.g. those from Locize) will not
// be loaded properly.
try {
await i18n.initializing;
} catch(error) {
throw new Error(error);
}
i18n.addLocales(locales);
}
export default loadLocales;
@@ -0,0 +1,3 @@
{
"Rotate": "Rotate"
}
@@ -0,0 +1,7 @@
import Buttons from './Buttons.json';
export default {
en: {
Buttons
}
};
@@ -0,0 +1,3 @@
{
"Rotate": "Rotacionar"
}
@@ -0,0 +1,7 @@
import Buttons from './Buttons.json';
export default {
es: {
Buttons
}
};
@@ -0,0 +1,7 @@
import en from './en';
import es from './es';
export default {
...en,
...es
};
@@ -0,0 +1,39 @@
const TOOLBAR_BUTTON_TYPES = {
COMMAND: 'command',
SET_TOOL_ACTIVE: 'setToolActive',
};
const definitions = [
{
id: 'Crosshairs',
label: 'Crosshairs',
icon: 'crosshairs',
//
type: TOOLBAR_BUTTON_TYPES.SET_TOOL_ACTIVE,
commandName: 'enableCrosshairsTool',
commandOptions: {},
},
{
id: 'WWWC',
label: 'WWWC',
icon: 'level',
//
type: TOOLBAR_BUTTON_TYPES.SET_TOOL_ACTIVE,
commandName: 'enableLevelTool',
commandOptions: {},
},
{
id: 'Rotate',
label: 'Rotate',
icon: '3d-rotate',
//
type: TOOLBAR_BUTTON_TYPES.SET_TOOL_ACTIVE,
commandName: 'enableRotateTool',
commandOptions: {},
},
];
export default {
definitions,
defaultContext: 'ACTIVE_VIEWPORT::VTK',
};
@@ -0,0 +1,10 @@
import { redux } from 'ohif-core';
const { setViewportLayoutAndData } = redux.actions;
// TODO: Should not be getting dispatch from the window, but I'm not sure how else to do it cleanly
export default function setLayoutAndViewportData(layout, viewportSpecificData) {
const action = setViewportLayoutAndData(layout, viewportSpecificData);
window.store.dispatch(action);
}
@@ -0,0 +1,61 @@
import setLayoutAndViewportData from './setLayoutAndViewportData.js';
import setSingleLayoutData from './setSingleLayoutData.js';
export default function setMPRLayout(displaySet) {
return new Promise((resolve, reject) => {
let viewports = [];
const rows = 1;
const columns = 3;
const numViewports = rows * columns;
const viewportSpecificData = {};
for (let i = 0; i < numViewports; i++) {
viewports.push({
height: `${100 / rows}%`,
width: `${100 / columns}%`,
});
viewportSpecificData[i] = displaySet;
viewportSpecificData[i].plugin = 'vtk';
}
const layout = {
viewports,
};
const viewportIndices = [0, 1, 2];
let updatedViewports = layout.viewports;
const apis = [];
viewportIndices.forEach(viewportIndex => {
apis[viewportIndex] = null;
/*const currentData = layout.viewports[viewportIndex];
if (currentData && currentData.plugin === 'vtk') {
reject(new Error('Should not have reached this point??'));
}*/
const data = {
// plugin: 'vtk',
vtk: {
mode: 'mpr', // TODO: not used
afterCreation: api => {
apis[viewportIndex] = api;
if (apis.every(a => !!a)) {
resolve(apis);
}
},
},
};
updatedViewports = setSingleLayoutData(
updatedViewports,
viewportIndex,
data
);
});
setLayoutAndViewportData(
{ viewports: updatedViewports },
viewportSpecificData
);
});
}
@@ -0,0 +1,12 @@
export default function setSingleLayoutData(
originalArray,
viewportIndex,
data
) {
const viewports = originalArray.slice();
const layoutData = Object.assign({}, viewports[viewportIndex], data);
viewports[viewportIndex] = layoutData;
return viewports;
}
@@ -0,0 +1,39 @@
import setLayoutAndViewportData from './setLayoutAndViewportData.js';
import setSingleLayoutData from './setSingleLayoutData.js';
export default function setViewportToVTK(
displaySet,
viewportIndex,
layout,
viewportSpecificData
) {
return new Promise((resolve, reject) => {
/*const currentData = layout.viewports[viewportIndex];
if (currentData && currentData.plugin === 'vtk') {
reject(new Error('Should not have reached this point??'));
}*/
const data = {
// plugin: 'vtk',
vtk: {
mode: 'mpr', // TODO: not used
afterCreation: api => {
resolve(api);
},
},
};
const updatedViewports = setSingleLayoutData(
layout.viewports,
viewportIndex,
data
);
const updatedViewportData = viewportSpecificData;
setLayoutAndViewportData(
{ viewports: updatedViewports },
updatedViewportData
);
});
}
+110
View File
@@ -0,0 +1,110 @@
var path = require('path');
var webpack = require('webpack');
const autoprefixer = require('autoprefixer');
const cssRules = [
{
test: /\.css$/,
exclude: /\.module\.css$/,
use: [
'style-loader',
'css-loader',
{
loader: 'postcss-loader',
options: {
plugins: () => [autoprefixer('last 2 version', 'ie >= 10')]
}
}
]
},
{
test: /\.glsl$/i,
include: /vtk\.js[\/\\]Sources/,
loader: 'shader-loader'
},
{
test: /\.worker\.js$/,
include: /vtk\.js[\/\\]Sources/,
use: [
{
loader: 'worker-loader',
options: { inline: true, fallback: false }
}
]
},
{
test: /\.css$/,
include: /\.module\.css$/,
use: [
{ loader: 'style-loader' },
{
loader: 'css-loader',
options: {
localIdentName: '[name]-[local]_[sha512:hash:base64:5]',
modules: true
}
},
{
loader: 'postcss-loader',
options: {
plugins: () => [autoprefixer('last 2 version', 'ie >= 10')]
}
}
]
}
];
var entry = path.join(__dirname, './src/index.js');
const sourcePath = path.join(__dirname, './src');
const outputPath = path.join(__dirname, './dist');
module.exports = {
entry,
output: {
path: outputPath,
filename: 'index.umd.js',
library: '@ohif/extension-vtk',
libraryTarget: 'umd',
globalObject: 'this'
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader']
}
].concat(cssRules)
},
resolve: {
modules: [path.resolve(__dirname, 'node_modules'), sourcePath]
},
externals: [
{
'cornerstone-core': {
commonjs: 'cornerstone-core',
commonjs2: 'cornerstone-core',
amd: 'cornerstone-core',
root: 'cornerstone'
},
'cornerstone-math': {
commonjs: 'cornerstone-math',
commonjs2: 'cornerstone-math',
amd: 'cornerstone-math',
root: 'cornerstoneMath'
}
},
'@ohif/i18n',
'ohif-core',
'dcmjs',
'react-viewerbase',
'react', //: 'React',
'react-dom', //: 'ReactDOM',
'react-redux', //: 'ReactRedux',
'react-resize-detector', //: 'ReactResizeDetector',
'react-viewerbase', //: 'reactViewerbase',
'prop-types' //: 'PropTypes'
/*/\b(vtk.js)/*/
]
};
File diff suppressed because it is too large. Load diff