All files / Sources/IO/Misc/SkyboxReader index.js

18.68% Statements 17/91
0% Branches 0/35
11.76% Functions 2/17
19.31% Lines 17/88

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                        1x                       1x               1x     1x                                                                                                                                                                                                   1x       1x             1x                             1x             1x                                   1x     1x 1x 1x 1x 1x     1x         1x          
import macro from 'vtk.js/Sources/macros';
import ImageHelper from 'vtk.js/Sources/Common/Core/ImageHelper';
import vtkTexture from 'vtk.js/Sources/Rendering/Core/Texture';
 
import { strFromU8, unzipSync } from 'fflate';
 
// ----------------------------------------------------------------------------
// vtkSkyboxReader methods
// ----------------------------------------------------------------------------
 
function vtkSkyboxReader(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkSkyboxReader');
 
  // Internal method to fetch Array
  function fetchData(url, option = {}) {
    const { compression, progressCallback } = model;
    return model.dataAccessHelper.fetchBinary(url, {
      compression,
      progressCallback,
    });
  }
 
  // Set DataSet url
  publicAPI.setUrl = (url, option = {}) => {
    model.url = url;
 
    // Fetch metadata
    return publicAPI.loadData(option);
  };
 
  // Fetch the actual data arrays
  publicAPI.loadData = (option = {}) =>
    fetchData(model.url, option).then(publicAPI.parseAsArrayBuffer);
 
  publicAPI.parseAsArrayBuffer = (content) => {
    if (!content) {
      return false;
    }
    model.textures = {};
    model.busy = true;
    publicAPI.invokeBusy(model.busy);
    model.dataMapping = {};
    const imageReady = [];
 
    // Finish data processing
    function workDone() {
      for (let i = 0; i < model.positions.length; i++) {
        const key = model.positions[i];
        const images = model.dataMapping[key];
        if (!model.textures[key]) {
          model.textures[key] = vtkTexture.newInstance({ interpolate: true });
        }
        if (images) {
          const texture = model.textures[key];
 
          for (let idx = 0; idx < 6; idx++) {
            const { fileName, transform } = model.faceMapping[idx];
            const readyIndex = imageReady.indexOf(`${key}/${fileName}`);
 
            if (readyIndex !== -1) {
              texture.setInputData(
                ImageHelper.imageToImageData(images[fileName], transform),
                idx
              );
 
              // Free image
              URL.revokeObjectURL(images[fileName].src);
              delete images[fileName];
 
              // Don't process again
              imageReady.splice(readyIndex, 1);
            }
          }
        }
      }
 
      model.busy = false;
      publicAPI.modified();
      publicAPI.invokeBusy(model.busy);
    }
 
    const decompressedFiles = unzipSync(new Uint8Array(content));
    const pending = [];
    // Find root index.json
    Object.entries(decompressedFiles).forEach(([relativePath, fileData]) => {
      if (relativePath.match(/index.json$/)) {
        const txt = strFromU8(fileData);
        const config = JSON.parse(txt);
        if (config.skybox && config.skybox.faceMapping) {
          model.faceMapping = config.skybox.faceMapping;
        }
        if (
          config.metadata &&
          config.metadata.skybox &&
          config.metadata.skybox.faceMapping
        ) {
          model.faceMapping = config.metadata.skybox.faceMapping;
        }
      }
      if (relativePath.match(/\.jpg$/)) {
        const pathTokens = relativePath.split('/');
        const fileName = pathTokens.pop();
        const key = pathTokens.pop();
        if (!model.dataMapping[key]) {
          model.dataMapping[key] = {};
        }
        const blob = new Blob([fileData.buffer]);
        const img = new Image();
        const readyKey = `${key}/${fileName}`;
        model.dataMapping[key][fileName] = img;
        pending.push(
          new Promise((resolve) => {
            img.onload = () => {
              imageReady.push(readyKey);
              resolve();
            };
          })
        );
        img.src = URL.createObjectURL(blob);
      }
    });
 
    model.positions = Object.keys(model.dataMapping);
    model.position = model.positions[0];
 
    Promise.all(pending).then(() => {
      workDone();
    });
 
    return publicAPI.getReadyPromise();
  };
 
  publicAPI.requestData = (inData, outData) => {
    outData[0] = model.textures[model.position];
  };
 
  publicAPI.setPosition = (name) => {
    if (model.positions.indexOf(name) !== -1 && name !== model.position) {
      model.position = name;
      publicAPI.modified();
    }
  };
 
  publicAPI.getReadyPromise = () => {
    if (!model.busy) {
      return Promise.resolve(publicAPI);
    }
    return new Promise((resolve, reject) => {
      const subscription = publicAPI.onBusy((isBusy) => {
        if (!isBusy) {
          subscription.unsubscribe();
          resolve(publicAPI);
        }
      });
    });
  };
 
  // return Busy state
  publicAPI.isBusy = () => model.busy;
}
 
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
 
const DEFAULT_VALUES = {
  // url: null,
  busy: false,
  // everything must be flipped in Y due to canvas
  // versus vtk ordering
  faceMapping: [
    { fileName: 'right.jpg', transform: { flipY: true } },
    { fileName: 'left.jpg', transform: { flipY: true } },
    { fileName: 'up.jpg', transform: { flipY: true } },
    { fileName: 'down.jpg', transform: { flipY: true } },
    { fileName: 'back.jpg', transform: { flipY: true } },
    { fileName: 'front.jpg', transform: { flipY: true } },
  ],
};
 
// ----------------------------------------------------------------------------
 
export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);
 
  // Build VTK API
  macro.obj(publicAPI, model);
  macro.get(publicAPI, model, ['url', 'positions', 'position']);
  macro.setGet(publicAPI, model, ['faceMapping']);
  macro.event(publicAPI, model, 'busy');
  macro.algo(publicAPI, model, 0, 6);
 
  // Object methods
  vtkSkyboxReader(publicAPI, model);
}
 
// ----------------------------------------------------------------------------
 
export const newInstance = macro.newInstance(extend, 'vtkSkyboxReader');
 
// ----------------------------------------------------------------------------
 
export default { newInstance, extend };