All files / Sources/Filters/General/PaintFilter index.js

50.49% Statements 103/204
30.18% Branches 16/53
57.14% Functions 12/21
52.08% Lines 100/192

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 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417                    1x               2x   2x 2x 2x         3x 3x 3x         1x 1x 1x 1x     1x 1x 1x         2x 1x 1x 1x 1x     1x                   2x     1x 1x   1x 1x 1x 1x 1x     1x     2x 1x 1x 1x   1x 1x   132651x           1x 1x   1x 1x                           1x 132651x 669x 669x 669x         1x   1x 1x 1x 1x         2x                                   2x                                         2x 1x 1x 1x 1x 1x 1x 1x 1x 3x 1x                 2x       2x                                                                   2x                                       2x                                                   2x       2x                                                       2x 2x 1x 1x 1x 1x             2x 2x         2x         2x   1x     1x 1x     1x 1x       1x   1x     2x       2x   2x         2x   2x             2x             1x                         2x     2x     2x   2x                     2x         1x          
import { vec3 } from 'gl-matrix';
import WebworkerPromise from 'webworker-promise';
 
import macro from 'vtk.js/Sources/macros';
import vtkImageData from 'vtk.js/Sources/Common/DataModel/ImageData';
import vtkDataArray from 'vtk.js/Sources/Common/Core/DataArray';
import vtkPolygon from 'vtk.js/Sources/Common/DataModel/Polygon';
 
import PaintFilterWorker from 'vtk.js/Sources/Filters/General/PaintFilter/PaintFilter.worker';
 
const { vtkErrorMacro } = macro;
 
// ----------------------------------------------------------------------------
// vtkPaintFilter methods
// ----------------------------------------------------------------------------
 
function vtkPaintFilter(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkPaintFilter');
 
  let worker = null;
  let workerPromise = null;
  const history = {};
 
  // --------------------------------------------------------------------------
 
  function resetHistory() {
    history.index = -1;
    history.snapshots = [];
    history.labels = [];
  }
 
  function pushToHistory(snapshot, label) {
    // Clear any "redo" info
    const spliceIndex = history.index + 1;
    const spliceLength = history.snapshots.length - history.index;
    history.snapshots.splice(spliceIndex, spliceLength);
    history.labels.splice(spliceIndex, spliceLength);
 
    // Push new snapshot
    history.snapshots.push(snapshot);
    history.labels.push(label);
    history.index++;
  }
 
  // --------------------------------------------------------------------------
 
  publicAPI.startStroke = () => {
    if (model.labelMap) {
      if (!workerPromise) {
        worker = new PaintFilterWorker();
        workerPromise = new WebworkerPromise(worker);
      }
 
      workerPromise.exec('start', {
        bufferType: 'Uint8Array',
        dimensions: model.labelMap.getDimensions(),
        slicingMode: model.slicingMode,
      });
    }
  };
 
  // --------------------------------------------------------------------------
 
  publicAPI.endStroke = () => {
    let endStrokePromise;
 
    if (workerPromise) {
      endStrokePromise = workerPromise.exec('end');
 
      endStrokePromise.then((strokeBuffer) => {
        publicAPI.applyBinaryMask(strokeBuffer);
        worker.terminate();
        worker = null;
        workerPromise = null;
      });
    }
    return endStrokePromise;
  };
 
  publicAPI.applyBinaryMask = (maskBuffer) => {
    const scalars = model.labelMap.getPointData().getScalars();
    const data = scalars.getData();
    const maskLabelMap = new Uint8Array(maskBuffer);
 
    let diffCount = 0;
    for (let i = 0; i < maskLabelMap.length; i++) {
      // maskLabelMap is a binary mask
      diffCount += maskLabelMap[i];
    }
 
    // Format: [ [index, oldLabel], ...]
    // I could use an ArrayBuffer, which would place limits
    // on the values of index/old, but will be more efficient.
    const snapshot = new Array(diffCount);
    const label = model.label;
 
    let diffIdx = 0;
    Iif (model.voxelFunc) {
      const bgScalars = model.backgroundImage.getPointData().getScalars();
      const voxel = [];
      for (let i = 0; i < maskLabelMap.length; i++) {
        if (maskLabelMap[i]) {
          bgScalars.getTuple(i, voxel);
          // might not fill up snapshot
          if (model.voxelFunc(voxel, i, label)) {
            snapshot[diffIdx++] = [i, data[i]];
            data[i] = label;
          }
        }
      }
    } else {
      for (let i = 0; i < maskLabelMap.length; i++) {
        if (maskLabelMap[i]) {
          if (data[i] !== label) {
            snapshot[diffIdx++] = [i, data[i]];
            data[i] = label;
          }
        }
      }
    }
    pushToHistory(snapshot, label);
 
    scalars.setData(data);
    scalars.modified();
    model.labelMap.modified();
    publicAPI.modified();
  };
 
  // --------------------------------------------------------------------------
 
  publicAPI.addPoint = (point) => {
    if (workerPromise) {
      const worldPt = [point[0], point[1], point[2]];
      const indexPt = [0, 0, 0];
      vec3.transformMat4(indexPt, worldPt, model.maskWorldToIndex);
      indexPt[0] = Math.round(indexPt[0]);
      indexPt[1] = Math.round(indexPt[1]);
      indexPt[2] = Math.round(indexPt[2]);
 
      const spacing = model.labelMap.getSpacing();
      const radius = spacing.map((s) => model.radius / s);
 
      workerPromise.exec('paint', { point: indexPt, radius });
    }
  };
 
  // --------------------------------------------------------------------------
 
  publicAPI.paintRectangle = (point1, point2) => {
    if (workerPromise) {
      const index1 = [0, 0, 0];
      const index2 = [0, 0, 0];
      vec3.transformMat4(index1, point1, model.maskWorldToIndex);
      vec3.transformMat4(index2, point2, model.maskWorldToIndex);
      index1[0] = Math.round(index1[0]);
      index1[1] = Math.round(index1[1]);
      index1[2] = Math.round(index1[2]);
      index2[0] = Math.round(index2[0]);
      index2[1] = Math.round(index2[1]);
      index2[2] = Math.round(index2[2]);
      workerPromise.exec('paintRectangle', {
        point1: index1,
        point2: index2,
      });
    }
  };
 
  // --------------------------------------------------------------------------
 
  publicAPI.paintEllipse = (center, scale3) => {
    if (workerPromise) {
      const realCenter = [0, 0, 0];
      const origin = [0, 0, 0];
      let realScale3 = [0, 0, 0];
      vec3.transformMat4(realCenter, center, model.maskWorldToIndex);
      vec3.transformMat4(origin, origin, model.maskWorldToIndex);
      vec3.transformMat4(realScale3, scale3, model.maskWorldToIndex);
      vec3.subtract(realScale3, realScale3, origin);
      realScale3 = realScale3.map((s) => (s === 0 ? 0.25 : Math.abs(s)));
      workerPromise.exec('paintEllipse', {
        center: realCenter,
        scale3: realScale3,
      });
    }
  };
 
  // --------------------------------------------------------------------------
 
  publicAPI.canUndo = () => history.index > -1;
 
  // --------------------------------------------------------------------------
 
  publicAPI.paintPolygon = (pointList) => {
    if (workerPromise && pointList.length > 0) {
      const polygon = vtkPolygon.newInstance();
      const poly = [];
      for (let i = 0; i < pointList.length / 3; i++) {
        poly.push([
          pointList[3 * i + 0],
          pointList[3 * i + 1],
          pointList[3 * i + 2],
        ]);
      }
      polygon.setPoints(poly);
 
      if (!polygon.triangulate()) {
        console.log('triangulation failed!');
      }
 
      const points = polygon.getPointArray();
      const triangleList = new Float32Array(points.length);
      const numPoints = Math.floor(triangleList.length / 3);
      for (let i = 0; i < numPoints; i++) {
        const point = points.slice(3 * i, 3 * i + 3);
        const voxel = triangleList.subarray(3 * i, 3 * i + 3);
        vec3.transformMat4(voxel, point, model.maskWorldToIndex);
      }
 
      workerPromise.exec('paintTriangles', {
        triangleList,
      });
    }
  };
 
  // --------------------------------------------------------------------------
 
  publicAPI.applyLabelMap = (labelMap) => {
    const currentMapData = model.labelMap.getPointData().getScalars().getData();
 
    const newMapData = labelMap.getPointData().getScalars().getData();
 
    // Compute snapshot
    const snapshot = [];
    for (let i = 0; i < newMapData.length; ++i) {
      if (currentMapData[i] !== newMapData[i]) {
        snapshot.push([i, currentMapData[i]]);
      }
    }
 
    pushToHistory(snapshot, model.label);
    model.labelMap = labelMap;
    publicAPI.modified();
  };
 
  // --------------------------------------------------------------------------
 
  publicAPI.undo = () => {
    if (history.index > -1) {
      const scalars = model.labelMap.getPointData().getScalars();
      const data = scalars.getData();
 
      const snapshot = history.snapshots[history.index];
      for (let i = 0; i < snapshot.length; i++) {
        if (!snapshot[i]) {
          break;
        }
 
        const [index, oldLabel] = snapshot[i];
        data[index] = oldLabel;
      }
 
      history.index--;
 
      scalars.setData(data);
      scalars.modified();
      model.labelMap.modified();
      publicAPI.modified();
    }
  };
 
  // --------------------------------------------------------------------------
 
  publicAPI.canRedo = () => history.index < history.labels.length - 1;
 
  // --------------------------------------------------------------------------
 
  publicAPI.redo = () => {
    if (history.index < history.labels.length - 1) {
      const scalars = model.labelMap.getPointData().getScalars();
      const data = scalars.getData();
 
      const redoLabel = history.labels[history.index + 1];
      const snapshot = history.snapshots[history.index + 1];
 
      for (let i = 0; i < snapshot.length; i++) {
        if (!snapshot[i]) {
          break;
        }
 
        const [index] = snapshot[i];
        data[index] = redoLabel;
      }
 
      history.index++;
 
      scalars.setData(data);
      scalars.modified();
      model.labelMap.modified();
      publicAPI.modified();
    }
  };
 
  // --------------------------------------------------------------------------
 
  const superSetLabelMap = publicAPI.setLabelMap;
  publicAPI.setLabelMap = (lm) => {
    if (superSetLabelMap(lm)) {
      model.maskWorldToIndex = model.labelMap.getWorldToIndex();
      resetHistory();
      return true;
    }
    return false;
  };
 
  // --------------------------------------------------------------------------
 
  publicAPI.requestData = (inData, outData) => {
    Iif (!model.backgroundImage) {
      vtkErrorMacro('No background image');
      return;
    }
 
    Iif (!model.backgroundImage.getPointData().getScalars()) {
      vtkErrorMacro('Background image has no scalars');
      return;
    }
 
    if (!model.labelMap) {
      // clone background image properties
      const labelMap = vtkImageData.newInstance(
        model.backgroundImage.get('spacing', 'origin', 'direction')
      );
      labelMap.setDimensions(model.backgroundImage.getDimensions());
      labelMap.computeTransforms();
 
      // right now only support 256 labels
      const values = new Uint8Array(model.backgroundImage.getNumberOfPoints());
      const dataArray = vtkDataArray.newInstance({
        numberOfComponents: 1, // labelmap with single component
        values,
      });
      labelMap.getPointData().setScalars(dataArray);
 
      publicAPI.setLabelMap(labelMap);
    }
 
    Iif (!model.maskWorldToIndex) {
      model.maskWorldToIndex = model.labelMap.getWorldToIndex();
    }
 
    const scalars = model.labelMap.getPointData().getScalars();
 
    Iif (!scalars) {
      vtkErrorMacro('Mask image has no scalars');
      return;
    }
 
    model.labelMap.modified();
 
    outData[0] = model.labelMap;
  };
 
  // --------------------------------------------------------------------------
  // Initialization
  // --------------------------------------------------------------------------
 
  resetHistory();
}
 
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
 
const DEFAULT_VALUES = {
  backgroundImage: null,
  labelMap: null,
  maskWorldToIndex: null,
  voxelFunc: null,
  radius: 1,
  label: 0,
  slicingMode: null,
};
 
// ----------------------------------------------------------------------------
 
export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);
 
  // Make this a VTK object
  macro.obj(publicAPI, model);
 
  // Also make it an algorithm with no input and one output
  macro.algo(publicAPI, model, 0, 1);
 
  macro.setGet(publicAPI, model, [
    'backgroundImage',
    'labelMap',
    'maskWorldToIndex',
    'voxelFunc',
    'label',
    'radius',
    'slicingMode',
  ]);
 
  // Object specific methods
  vtkPaintFilter(publicAPI, model);
}
 
// ----------------------------------------------------------------------------
 
export const newInstance = macro.newInstance(extend, 'vtkPaintFilter');
 
// ----------------------------------------------------------------------------
 
export default { newInstance, extend };