All files / Sources/Common/Core/DataArray index.js

75.89% Statements 211/278
68.33% Branches 82/120
73.33% Functions 33/45
75.95% Lines 199/262

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 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576        1x 1x         1x         2680x 2680x 2680x         2680x 2681x 2672x 2672x 2672x       2680x 54506040x 54506040x 8513x 54497527x 10126x     2680x                                                                 2680x   1x 1x 1x 1x 256x 768x   256x   1x     2679x               986x   986x 3881x   986x         10210x                                         1x                           8249x               149x       149x 149x 149x 111x     38x       32x 32x       32x 32x       6x 1x 1x     6x     8249x 2054x 2054x     8249x 127x 127x 127x 20x 20x 20x   107x       8249x 107x     8249x         8249x 8x               8249x             8249x           8249x           8249x 15685x       8249x 6169x 6169x     4x     6169x   6169x 986x   6169x   6169x 3489x 3489x 3489x       2680x         2680x 2680x 2680x 2680x     8249x                         8249x 3977x 3977x 11022x       8249x 30x 30x 30x 115x       8249x 626x 4x 4x   626x 626x     8249x 30x 30x 18x 18x   30x 30x     8249x 4x 4x     8249x 18x 18x     8249x 7x 21x 13x 13x 22x 6x 6x     13x 7x             8249x 61755x 61755x     61755x         61245x     61245x     61707x 61707x   48x 432x     61755x     8249x 19x   19x 19x 19x     8249x 8249x 8249x 8249x 8249x   8249x 17x               8249x 5684x 8x 8x   5684x     8249x 1961x 1961x 1961x 1961x 1820x   1961x     1961x       8249x 446x 6x   440x     440x 440x     440x 4597x 729x         440x 440x     3868x       440x 440x     440x     8249x   106x 106x 106x       106x               106x       8249x                                                                                                       1x                         8249x   8249x           8249x 5697x 2552x 427x     8249x   8249x 8249x       8249x 8249x   8249x             8249x         1x          
import Constants from 'vtk.js/Sources/Common/Core/DataArray/Constants';
import * as macro from 'vtk.js/Sources/macros';
import * as vtkMath from 'vtk.js/Sources/Common/Core/Math';
 
const { vtkErrorMacro } = macro;
const { DefaultDataType } = Constants;
 
// ----------------------------------------------------------------------------
// Global methods
// ----------------------------------------------------------------------------
const EPSILON = 1e-6;
 
// Original source from https://www.npmjs.com/package/compute-range
// Modified to accept type arrays
function fastComputeRange(arr, offset, numberOfComponents) {
  const len = arr.length;
  let min = Number.MAX_VALUE;
  let max = -Number.MAX_VALUE;
  let x;
  let i;
 
  // find first non-NaN value
  for (i = offset; i < len; i += numberOfComponents) {
    if (!Number.isNaN(arr[i])) {
      min = arr[i];
      max = min;
      break;
    }
  }
 
  for (; i < len; i += numberOfComponents) {
    x = arr[i];
    if (x < min) {
      min = x;
    } else if (x > max) {
      max = x;
    }
  }
  return { min, max };
}
 
/**
 * @deprecated please use fastComputeRange instead
 */
function createRangeHelper() {
  let min = Number.MAX_VALUE;
  let max = -Number.MAX_VALUE;
  let count = 0;
  let sum = 0;
 
  return {
    add(value) {
      if (min > value) {
        min = value;
      }
      if (max < value) {
        max = value;
      }
      count++;
      sum += value;
    },
    get() {
      return { min, max, count, sum, mean: sum / count };
    },
    getRange() {
      return { min, max };
    },
  };
}
 
function computeRange(values, component = 0, numberOfComponents = 1) {
  if (component < 0 && numberOfComponents > 1) {
    // Compute magnitude
    const size = values.length;
    const numberOfValues = size / numberOfComponents;
    const data = new Float64Array(numberOfValues);
    for (let i = 0, j = 0; i < numberOfValues; ++i) {
      for (let nextJ = j + numberOfComponents; j < nextJ; ++j) {
        data[i] += values[j] * values[j];
      }
      data[i] **= 0.5;
    }
    return fastComputeRange(data, 0, 1);
  }
 
  return fastComputeRange(
    values,
    component < 0 ? 0 : component,
    numberOfComponents
  );
}
 
function ensureRangeSize(rangeArray, size = 0) {
  const ranges = rangeArray || [];
  // Pad ranges with null value to get the
  while (ranges.length <= size) {
    ranges.push(null);
  }
  return ranges;
}
 
function getDataType(typedArray) {
  // Expects toString() to return "[object ...Array]"
  return Object.prototype.toString.call(typedArray).slice(8, -1);
}
 
function getMaxNorm(normArray) {
  const numComps = normArray.getNumberOfComponents();
  let maxNorm = 0.0;
  const tuple = new Array(numComps);
  for (let i = 0; i < normArray.getNumberOfTuples(); ++i) {
    normArray.getTuple(i, tuple);
    const norm = vtkMath.norm(tuple, numComps);
    if (norm > maxNorm) {
      maxNorm = norm;
    }
  }
  return maxNorm;
}
 
// ----------------------------------------------------------------------------
// Static API
// ----------------------------------------------------------------------------
 
export const STATIC = {
  computeRange,
  createRangeHelper,
  fastComputeRange,
  getDataType,
  getMaxNorm,
};
 
// ----------------------------------------------------------------------------
// vtkDataArray methods
// ----------------------------------------------------------------------------
 
function vtkDataArray(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkDataArray');
 
  /**
   * Resize model.values and copy the old values to the new array.
   * @param {Number} requestedNumTuples Final expected number of tuples; must be >= 0
   * @returns {Boolean} True if a resize occured, false otherwise
   */
  function resize(requestedNumTuples) {
    Iif (requestedNumTuples < 0) {
      return false;
    }
 
    const numComps = publicAPI.getNumberOfComponents();
    const curNumTuples = model.values.length / (numComps > 0 ? numComps : 1);
    if (requestedNumTuples === curNumTuples) {
      return true;
    }
 
    if (requestedNumTuples > curNumTuples) {
      // Requested size is bigger than current size.  Allocate enough
      // memory to fit the requested size and be more than double the
      // currently allocated memory.
      const oldValues = model.values;
      model.values = macro.newTypedArray(
        model.dataType,
        (requestedNumTuples + curNumTuples) * numComps
      );
      model.values.set(oldValues);
      return true;
    }
 
    // Requested size is smaller than currently allocated size
    if (model.size > requestedNumTuples * numComps) {
      model.size = requestedNumTuples * numComps;
      publicAPI.dataChange();
    }
 
    return true;
  }
 
  publicAPI.dataChange = () => {
    model.ranges = null;
    publicAPI.modified();
  };
 
  publicAPI.resize = (requestedNumTuples) => {
    resize(requestedNumTuples);
    const newSize = requestedNumTuples * publicAPI.getNumberOfComponents();
    if (model.size !== newSize) {
      model.size = newSize;
      publicAPI.dataChange();
      return true;
    }
    return false;
  };
 
  // FIXME, to rename into "clear()" or "reset()"
  publicAPI.initialize = () => {
    publicAPI.resize(0);
  };
 
  publicAPI.getElementComponentSize = () => model.values.BYTES_PER_ELEMENT;
 
  // Description:
  // Return the data component at the location specified by tupleIdx and
  // compIdx.
  publicAPI.getComponent = (tupleIdx, compIdx = 0) =>
    model.values[tupleIdx * model.numberOfComponents + compIdx];
 
  // Description:
  // Set the data component at the location specified by tupleIdx and compIdx
  // to value.
  // Note that i is less than NumberOfTuples and j is less than
  //  NumberOfComponents. Make sure enough memory has been allocated
  // (use SetNumberOfTuples() and SetNumberOfComponents()).
  publicAPI.setComponent = (tupleIdx, compIdx, value) => {
    if (value !== model.values[tupleIdx * model.numberOfComponents + compIdx]) {
      model.values[tupleIdx * model.numberOfComponents + compIdx] = value;
      publicAPI.dataChange();
    }
  };
 
  publicAPI.getValue = (valueIdx) => {
    const idx = valueIdx / model.numberOfComponents;
    const comp = valueIdx % model.numberOfComponents;
    return publicAPI.getComponent(idx, comp);
  };
 
  publicAPI.setValue = (valueIdx, value) => {
    const idx = valueIdx / model.numberOfComponents;
    const comp = valueIdx % model.numberOfComponents;
    publicAPI.setComponent(idx, comp, value);
  };
 
  publicAPI.getData = () =>
    model.size === model.values.length
      ? model.values
      : model.values.subarray(0, model.size);
 
  publicAPI.getRange = (componentIndex = -1) => {
    let rangeIdx = componentIndex;
    if (rangeIdx < 0) {
      // If scalar data, then store in slot 0 (same as componentIndex = 0).
      // If vector data, then store in last slot.
      rangeIdx = model.numberOfComponents === 1 ? 0 : model.numberOfComponents;
    }
 
    let range = null;
 
    if (!model.ranges) {
      model.ranges = ensureRangeSize(model.ranges, model.numberOfComponents);
    }
    range = model.ranges[rangeIdx];
 
    if (range) {
      model.rangeTuple[0] = range.min;
      model.rangeTuple[1] = range.max;
      return model.rangeTuple;
    }
 
    // Need to compute ranges...
    range = computeRange(
      publicAPI.getData(),
      componentIndex,
      model.numberOfComponents
    );
    model.ranges[rangeIdx] = range;
    model.rangeTuple[0] = range.min;
    model.rangeTuple[1] = range.max;
    return model.rangeTuple;
  };
 
  publicAPI.setRange = (rangeValue, componentIndex) => {
    if (!model.ranges) {
      model.ranges = ensureRangeSize(model.ranges, model.numberOfComponents);
    }
    const range = { min: rangeValue.min, max: rangeValue.max };
 
    model.ranges[componentIndex] = range;
    model.rangeTuple[0] = range.min;
    model.rangeTuple[1] = range.max;
 
    return model.rangeTuple;
  };
 
  publicAPI.setTuple = (idx, tuple) => {
    const offset = idx * model.numberOfComponents;
    for (let i = 0; i < model.numberOfComponents; i++) {
      model.values[offset + i] = tuple[i];
    }
  };
 
  publicAPI.setTuples = (idx, tuples) => {
    let i = idx * model.numberOfComponents;
    const last = Math.min(tuples.length, model.size - i);
    for (let j = 0; j < last; ) {
      model.values[i++] = tuples[j++];
    }
  };
 
  publicAPI.insertTuple = (idx, tuple) => {
    if (model.size <= idx * model.numberOfComponents) {
      model.size = (idx + 1) * model.numberOfComponents;
      resize(idx + 1);
    }
    publicAPI.setTuple(idx, tuple);
    return idx;
  };
 
  publicAPI.insertTuples = (idx, tuples) => {
    const end = idx + tuples.length / model.numberOfComponents;
    if (model.size < end * model.numberOfComponents) {
      model.size = end * model.numberOfComponents;
      resize(end);
    }
    publicAPI.setTuples(idx, tuples);
    return end;
  };
 
  publicAPI.insertNextTuple = (tuple) => {
    const idx = model.size / model.numberOfComponents;
    return publicAPI.insertTuple(idx, tuple);
  };
 
  publicAPI.insertNextTuples = (tuples) => {
    const idx = model.size / model.numberOfComponents;
    return publicAPI.insertTuples(idx, tuples);
  };
 
  publicAPI.findTuple = (tuple, precision = EPSILON) => {
    for (let i = 0; i < model.size; i += model.numberOfComponents) {
      if (Math.abs(tuple[0] - model.values[i]) <= precision) {
        let match = true;
        for (let j = 1; j < model.numberOfComponents; ++j) {
          if (Math.abs(tuple[j] - model.values[i + j]) > precision) {
            match = false;
            break;
          }
        }
        if (match) {
          return i / model.numberOfComponents;
        }
      }
    }
    return -1;
  };
 
  publicAPI.getTuple = (idx, tupleToFill = []) => {
    const numberOfComponents = model.numberOfComponents || 1;
    const offset = idx * numberOfComponents;
    // Check most common component sizes first
    // to avoid doing a for loop if possible
    switch (numberOfComponents) {
      case 4:
        tupleToFill[3] = model.values[offset + 3];
      // eslint-disable-next-line no-fallthrough
      case 3:
        tupleToFill[2] = model.values[offset + 2];
      // eslint-disable-next-line no-fallthrough
      case 2:
        tupleToFill[1] = model.values[offset + 1];
      // eslint-disable-next-line no-fallthrough
      case 1:
        tupleToFill[0] = model.values[offset];
        break;
      default:
        for (let i = numberOfComponents - 1; i >= 0; --i) {
          tupleToFill[i] = model.values[offset + i];
        }
    }
    return tupleToFill;
  };
 
  publicAPI.getTuples = (fromId, toId) => {
    const from = (fromId ?? 0) * model.numberOfComponents;
    const to =
      (toId ?? publicAPI.getNumberOfTuples()) * model.numberOfComponents;
    const arr = publicAPI.getData().subarray(from, to);
    return arr.length > 0 ? arr : null;
  };
 
  publicAPI.getTupleLocation = (idx = 1) => idx * model.numberOfComponents;
  publicAPI.getNumberOfComponents = () => model.numberOfComponents;
  publicAPI.getNumberOfValues = () => model.size;
  publicAPI.getNumberOfTuples = () => model.size / model.numberOfComponents;
  publicAPI.getDataType = () => model.dataType;
  /* eslint-disable no-use-before-define */
  publicAPI.newClone = () =>
    newInstance({
      empty: true,
      name: model.name,
      dataType: model.dataType,
      numberOfComponents: model.numberOfComponents,
    });
  /* eslint-enable no-use-before-define */
 
  publicAPI.getName = () => {
    if (!model.name) {
      publicAPI.modified();
      model.name = `vtkDataArray${publicAPI.getMTime()}`;
    }
    return model.name;
  };
 
  publicAPI.setData = (typedArray, numberOfComponents) => {
    model.values = typedArray;
    model.size = typedArray.length;
    model.dataType = getDataType(typedArray);
    if (numberOfComponents) {
      model.numberOfComponents = numberOfComponents;
    }
    Iif (model.size % model.numberOfComponents !== 0) {
      model.numberOfComponents = 1;
    }
    publicAPI.dataChange();
  };
 
  // Override serialization support
  publicAPI.getState = () => {
    if (model.deleted) {
      return null;
    }
    const jsonArchive = { ...model, vtkClass: publicAPI.getClassName() };
 
    // Convert typed array to regular array
    jsonArchive.values = Array.from(jsonArchive.values);
    delete jsonArchive.buffer;
 
    // Clean any empty data
    Object.keys(jsonArchive).forEach((keyName) => {
      if (!jsonArchive[keyName]) {
        delete jsonArchive[keyName];
      }
    });
 
    // Sort resulting object by key name
    const sortedObj = {};
    Object.keys(jsonArchive)
      .sort()
      .forEach((name) => {
        sortedObj[name] = jsonArchive[name];
      });
 
    // Remove mtime
    if (sortedObj.mtime) {
      delete sortedObj.mtime;
    }
 
    return sortedObj;
  };
 
  publicAPI.deepCopy = (other) => {
    // Retain current dataType and array reference before shallowCopy call.
    const currentType = publicAPI.getDataType();
    const currentArray = model.values;
    publicAPI.shallowCopy(other);
 
    // Avoid array reallocation if size already sufficient
    // and dataTypes match.
    Iif (
      currentArray?.length >= other.getNumberOfValues() &&
      currentType === other.getDataType()
    ) {
      currentArray.set(other.getData());
      model.values = currentArray;
      publicAPI.dataChange();
    } else {
      publicAPI.setData(other.getData().slice());
    }
  };
 
  publicAPI.interpolateTuple = (
    idx,
    source1,
    source1Idx,
    source2,
    source2Idx,
    t
  ) => {
    const numberOfComponents = model.numberOfComponents || 1;
    if (
      numberOfComponents !== source1.getNumberOfComponents() ||
      numberOfComponents !== source2.getNumberOfComponents()
    ) {
      vtkErrorMacro('numberOfComponents must match');
    }
 
    const tuple1 = source1.getTuple(source1Idx);
    const tuple2 = source2.getTuple(source2Idx);
    const out = [];
    out.length = numberOfComponents;
 
    // Check most common component sizes first
    // to avoid doing a for loop if possible
    switch (numberOfComponents) {
      case 4:
        out[3] = tuple1[3] + (tuple2[3] - tuple1[3]) * t;
      // eslint-disable-next-line no-fallthrough
      case 3:
        out[2] = tuple1[2] + (tuple2[2] - tuple1[2]) * t;
      // eslint-disable-next-line no-fallthrough
      case 2:
        out[1] = tuple1[1] + (tuple2[1] - tuple1[1]) * t;
      // eslint-disable-next-line no-fallthrough
      case 1:
        out[0] = tuple1[0] + (tuple2[0] - tuple1[0]) * t;
        break;
      default:
        for (let i = 0; i < numberOfComponents; i++) {
          out[i] = tuple1[i] + (tuple2[i] - tuple1[i]) * t;
        }
    }
 
    return publicAPI.insertTuple(idx, out);
  };
}
 
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
 
// size: The current size of the dataArray.
// NOTE: The underlying typed array may be larger than 'size'.
const DEFAULT_VALUES = {
  name: '',
  numberOfComponents: 1,
  dataType: DefaultDataType,
  rangeTuple: [0, 0],
  // size: undefined,
  // values: null,
  // ranges: null,
};
 
// ----------------------------------------------------------------------------
 
export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);
 
  Iif (!model.empty && !model.values && !model.size) {
    throw new TypeError(
      'Cannot create vtkDataArray object without: size > 0, values'
    );
  }
 
  if (!model.values) {
    model.values = macro.newTypedArray(model.dataType, model.size);
  } else if (Array.isArray(model.values)) {
    model.values = macro.newTypedArrayFrom(model.dataType, model.values);
  }
 
  if (model.values) {
    // Takes the size if provided (can be lower than `model.values`) otherwise the actual length of `values`.
    model.size = model.size ?? model.values.length;
    model.dataType = getDataType(model.values);
  }
 
  // Object methods
  macro.obj(publicAPI, model);
  macro.set(publicAPI, model, ['name', 'numberOfComponents']);
 
  Iif (model.size % model.numberOfComponents !== 0) {
    throw new RangeError(
      'model.size is not a multiple of model.numberOfComponents'
    );
  }
 
  // Object specific methods
  vtkDataArray(publicAPI, model);
}
 
// ----------------------------------------------------------------------------
 
export const newInstance = macro.newInstance(extend, 'vtkDataArray');
 
// ----------------------------------------------------------------------------
 
export default { newInstance, extend, ...STATIC, ...Constants };