All files / Sources/IO/Geometry/GLTFImporter Utils.js

1.44% Statements 1/69
0% Branches 0/50
0% Functions 0/9
1.51% Lines 1/66

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                      1x                                                                                                                                                                                                                                                                                                                                                                                
import WebworkerPromise from 'webworker-promise';
import macro from 'vtk.js/Sources/macros';
import vtkTexture from 'vtk.js/Sources/Rendering/Core/Texture';
import Worker from 'vtk.js/Sources/IO/Geometry/GLTFImporter/ORMTexture.worker';
import {
  BYTES,
  COMPONENTS,
  ARRAY_TYPES,
  GL_SAMPLER,
} from 'vtk.js/Sources/IO/Geometry/GLTFImporter/Constants';
 
const { vtkWarningMacro, vtkErrorMacro } = macro;
 
/**
 * Get GL enum from sampler parameter
 * @param {*} parameter The sampler parameter
 * @returns The GL enum
 */
export function getGLEnumFromSamplerParameter(parameter) {
  const GL_TEXTURE_MAG_FILTER = 0x2800;
  const GL_TEXTURE_MIN_FILTER = 0x2801;
  const GL_TEXTURE_WRAP_S = 0x2802;
  const GL_TEXTURE_WRAP_T = 0x2803;
 
  const Mapping = {
    magFilter: GL_TEXTURE_MAG_FILTER,
    minFilter: GL_TEXTURE_MIN_FILTER,
    wrapS: GL_TEXTURE_WRAP_S,
    wrapT: GL_TEXTURE_WRAP_T,
  };
 
  return Mapping[parameter];
}
 
export function getAccessorArrayTypeAndLength(accessor, bufferView) {
  const ArrayType = ARRAY_TYPES[accessor.componentType];
  const components = COMPONENTS[accessor.type];
  const bytesPerComponent = BYTES[accessor.componentType];
  const length = accessor.count * components;
  const byteLength = accessor.count * components * bytesPerComponent;
  return { ArrayType, length, byteLength };
}
 
/**
 * Resolves a URL based on the original path
 * @param {*} url The URL to resolve
 * @param {*} originalPath The original path to resolve the URL against
 * @returns The resolved URL or an empty string if the URL is invalid
 */
export function resolveUrl(url, originalPath) {
  // Invalid URL
  if (typeof url !== 'string' || url === '') return '';
 
  try {
    // Data URI
    if (url.startsWith('data:')) return url;
 
    // Blob URL
    if (url.startsWith('blob:')) return url;
 
    // Create URL object from the original path
    const baseUrl = new URL(originalPath);
    if (!baseUrl.pathname.includes('.') && !baseUrl.pathname.endsWith('/')) {
      baseUrl.pathname += '/';
    }
 
    // Absolute URL (http://, https://, //)
    if (
      url.startsWith('http:') ||
      url.startsWith('https:') ||
      url.startsWith('//')
    ) {
      return new URL(url, baseUrl).href;
    }
 
    // Host Relative URL
    if (url.startsWith('/')) {
      return new URL(url, baseUrl).href;
    }
 
    // Relative URL
    return new URL(url, baseUrl).href;
  } catch (error) {
    vtkErrorMacro('Error resolving URL:', error);
    return '';
  }
}
 
/**
 * Loads image from buffer or URI
 * @param {*} image
 * @param {*} channel
 * @returns
 */
export async function loadImage(image, channel, forceReLoad = false) {
  // Initialize cache if it doesn't exist
  if (!image.cache) {
    image.cache = {};
  }
 
  // Return cached result for the channel if available and not forced to reload
  if (!forceReLoad && image.cache[channel]) {
    return image.cache[channel];
  }
 
  const worker = new WebworkerPromise(new Worker());
 
  if (image.bufferView) {
    return worker
      .postMessage({
        imageBuffer: image.bufferView.data,
        mimeType: image.mimeType,
        channel,
      })
      .then((result) => {
        // Cache the bitmap based on the channel
        image.cache[channel] = result.bitmap;
        return result.bitmap;
      })
      .finally(() => {
        worker.terminate();
      });
  }
 
  if (image.uri) {
    vtkWarningMacro('Falling back to image uri', image.uri);
    return new Promise((resolve, reject) => {
      const img = new Image();
      img.crossOrigin = 'Anonymous';
      img.onload = () => {
        image.cache[channel] = img; // Cache the loaded image based on the channel
        resolve(img);
      };
      img.onerror = reject;
      img.src = image.uri;
    });
  }
 
  return null;
}
 
/**
 *
 * @param {*} image
 * @param {*} sampler
 * @param {*} extensions
 * @returns
 */
export function createVTKTextureFromGLTFTexture(image, sampler, extensions) {
  const texture = vtkTexture.newInstance();
  // Apply sampler settings
  if (sampler) {
    if (
      ('wrapS' in sampler && 'wrapT' in sampler) ||
      ('minFilter' in sampler && 'magFilter' in sampler)
    ) {
      if (
        sampler.wrapS === GL_SAMPLER.CLAMP_TO_EDGE ||
        sampler.wrapT === GL_SAMPLER.CLAMP_TO_EDGE
      ) {
        texture.setRepeat(false);
        texture.setEdgeClamp(true);
      } else if (
        sampler.wrapS === GL_SAMPLER.REPEAT ||
        sampler.wrapT === GL_SAMPLER.REPEAT
      ) {
        texture.setRepeat(true);
        texture.setEdgeClamp(false);
      } else {
        vtkWarningMacro('Mirrored texture wrapping is not supported!');
      }
 
      const linearFilters = [
        GL_SAMPLER.LINEAR,
        GL_SAMPLER.LINEAR_MIPMAP_NEAREST,
        GL_SAMPLER.NEAREST_MIPMAP_LINEAR,
        GL_SAMPLER.LINEAR_MIPMAP_LINEAR,
      ];
 
      if (
        linearFilters.includes(sampler.minFilter) ||
        linearFilters.includes(sampler.magFilter)
      ) {
        texture.setInterpolate(true);
      }
    } else {
      texture.MipmapOn();
      texture.setInterpolate(true);
      texture.setEdgeClamp(true);
    }
  }
 
  texture.setJsImageData(image);
  return texture;
}