All files / engine/Source/Scene/Model TextureManager.js

91.66% Statements 66/72
70.73% Branches 29/41
100% Functions 14/14
91.54% Lines 65/71

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                                        87x 87x 87x       87x               1x 59x       11x     10x             1x 1x       1x                         1x 13x 2x         11x         12x       12x           12x 12x 2x   12x       12x   12x       12x 3x     12x       12x     12x     12x         12x 12x 12x   12x 10x 2x 1x 1x 1x 1x 1x 1x                                 24x                               1x   1x                   1x   155x 22x   133x   133x 133x       133x 133x 12x 12x   133x                           1x 10x                                     1x 13x 13x 11x 11x 11x 10x       13x        
import defined from "../../Core/defined.js";
import destroyObject from "../../Core/destroyObject.js";
import getImageFromTypedArray from "../../Core/getImageFromTypedArray.js";
import CesiumMath from "../../Core/Math.js";
import resizeImageToNextPowerOfTwo from "../../Core/resizeImageToNextPowerOfTwo.js";
import PixelDatatype from "../../Renderer/PixelDatatype.js";
import Texture from "../../Renderer/Texture.js";
import TextureMinificationFilter from "../../Renderer/TextureMinificationFilter.js";
import TextureWrap from "../../Renderer/TextureWrap.js";
 
/**
 * An object to manage loading textures
 *
 * @alias TextureManager
 * @constructor
 *
 * @private
 * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
 */
function TextureManager() {
  this._defaultTexture = undefined;
  this._textures = {};
  this._loadedImages = [];
 
  // Keep track of the last time update() was called to avoid
  // calling update() twice.
  this._lastUpdatedFrame = -1;
}
 
/**
 * Get one of the loaded textures
 * @param {string} textureId The unique ID of the texture loaded by {@link TextureManager#loadTexture2D}
 * @return {Texture} The texture or <code>undefined</code> if no texture exists
 */
TextureManager.prototype.getTexture = function (textureId) {
  return this._textures[textureId];
};
 
function fetchTexture2D(textureManager, textureId, textureUniform) {
  textureUniform.resource
    .fetchImage()
    .then(function (image) {
      textureManager._loadedImages.push({
        id: textureId,
        image: image,
        textureUniform: textureUniform,
      });
    })
    .catch(function () {
      const texture = textureManager._textures[textureId];
      Iif (defined(texture) && texture !== textureManager._defaultTexture) {
        texture.destroy();
      }
 
      textureManager._textures[textureId] = textureManager._defaultTexture;
    });
}
 
/**
 * Load a texture 2D asynchronously. Note that {@link TextureManager#update}
 * must be called in the render loop to finish processing the textures.
 *
 * @param {string} textureId A unique ID to identify this texture.
 * @param {TextureUniform} textureUniform A description of the texture
 *
 * @private
 */
TextureManager.prototype.loadTexture2D = function (textureId, textureUniform) {
  if (defined(textureUniform.typedArray)) {
    this._loadedImages.push({
      id: textureId,
      textureUniform: textureUniform,
    });
  } else {
    fetchTexture2D(this, textureId, textureUniform);
  }
};
 
function createTexture(textureManager, loadedImage, context) {
  const { id, textureUniform, image } = loadedImage;
 
  // If the context is WebGL1, and the sampler needs mipmaps or repeating
  // boundary conditions, the image may need to be resized first
  const texture = context.webgl2
    ? getTextureAndMips(textureUniform, image, context)
    : getWebGL1Texture(textureUniform, image, context);
 
  // Destroy the old texture once the new one is loaded for more seamless
  // transitions between values
  const oldTexture = textureManager._textures[id];
  if (defined(oldTexture) && oldTexture !== context.defaultTexture) {
    oldTexture.destroy();
  }
  textureManager._textures[id] = texture;
}
 
function getTextureAndMips(textureUniform, image, context) {
  const { typedArray, sampler } = textureUniform;
 
  const texture = defined(typedArray)
    ? getTextureFromTypedArray(textureUniform, context)
    : new Texture({ context, source: image, sampler });
 
  if (samplerRequiresMipmap(sampler)) {
    texture.generateMipmap();
  }
 
  return texture;
}
 
function getWebGL1Texture(textureUniform, image, context) {
  const { typedArray, sampler } = textureUniform;
 
  // WebGL1 requires power-of-two texture dimensions for mipmapping and REPEAT wrap modes
  const needMipmap = samplerRequiresMipmap(sampler);
 
  const samplerRepeats =
    sampler.wrapS === TextureWrap.REPEAT ||
    sampler.wrapS === TextureWrap.MIRRORED_REPEAT ||
    sampler.wrapT === TextureWrap.REPEAT ||
    sampler.wrapT === TextureWrap.MIRRORED_REPEAT;
 
  const { width, height } = defined(typedArray) ? textureUniform : image;
  const isPowerOfTwo = [width, height].every(CesiumMath.isPowerOfTwo);
  const requiresResize = (needMipmap || samplerRepeats) && !isPowerOfTwo;
 
  if (!requiresResize) {
    return getTextureAndMips(textureUniform, image, context);
  } else if (!defined(typedArray)) {
    const resizedImage = resizeImageToNextPowerOfTwo(image);
    return getTextureAndMips(textureUniform, resizedImage, context);
  } else Eif (textureUniform.pixelDatatype === PixelDatatype.UNSIGNED_BYTE) {
    const imageFromArray = getImageFromTypedArray(typedArray, width, height);
    const resizedImage = resizeImageToNextPowerOfTwo(imageFromArray);
    return getTextureAndMips({ sampler }, resizedImage, context);
  }
 
  // typedArray is non-power-of-two but can't be resized. Warn and return raw texture (no mipmaps)
  if (needMipmap) {
    console.warn(
      "Texture requires resizing for mipmaps but pixelDataType cannot be resized. The texture may be rendered incorrectly.",
    );
  } else if (samplerRepeats) {
    console.warn(
      "Texture requires resizing for wrapping but pixelDataType cannot be resized. The texture may be rendered incorrectly.",
    );
  }
  return getTextureFromTypedArray(textureUniform, context);
}
 
function samplerRequiresMipmap(sampler) {
  return [
    TextureMinificationFilter.NEAREST_MIPMAP_NEAREST,
    TextureMinificationFilter.NEAREST_MIPMAP_LINEAR,
    TextureMinificationFilter.LINEAR_MIPMAP_NEAREST,
    TextureMinificationFilter.LINEAR_MIPMAP_LINEAR,
  ].includes(sampler.minificationFilter);
}
 
function getTextureFromTypedArray(textureUniform, context) {
  const {
    pixelFormat,
    pixelDatatype,
    width,
    height,
    typedArray: arrayBufferView,
    sampler,
  } = textureUniform;
 
  return new Texture({
    context,
    pixelFormat,
    pixelDatatype,
    source: { arrayBufferView, width, height },
    sampler,
    flipY: false,
  });
}
 
TextureManager.prototype.update = function (frameState) {
  // update only needs to be called once a frame.
  if (frameState.frameNumber === this._lastUpdatedFrame) {
    return;
  }
  this._lastUpdatedFrame = frameState.frameNumber;
 
  const context = frameState.context;
  this._defaultTexture = context.defaultTexture;
 
  // If any images were loaded since the last frame, create Textures
  // for them and store in the uniform dictionary
  const loadedImages = this._loadedImages;
  for (let i = 0; i < loadedImages.length; i++) {
    const loadedImage = loadedImages[i];
    createTexture(this, loadedImage, context);
  }
  loadedImages.length = 0;
};
 
/**
 * Returns true if this object was destroyed; otherwise, false.
 * <br /><br />
 * If this object was destroyed, it should not be used; calling any function other than
 * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
 *
 * @returns {boolean} True if this object was destroyed; otherwise, false.
 *
 * @see TextureManager#destroy
 * @private
 */
TextureManager.prototype.isDestroyed = function () {
  return false;
};
 
/**
 * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
 * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
 * <br /><br />
 * Once an object is destroyed, it should not be used; calling any function other than
 * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
 * assign the return value (<code>undefined</code>) to the object as done in the example.
 *
 * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
 *
 * @example
 * textureManager = textureManager && textureManager.destroy();
 *
 * @see TextureManager#isDestroyed
 * @private
 */
TextureManager.prototype.destroy = function () {
  const textures = this._textures;
  for (const texture in textures) {
    Eif (textures.hasOwnProperty(texture)) {
      const instance = textures[texture];
      if (instance !== this._defaultTexture) {
        instance.destroy();
      }
    }
  }
  return destroyObject(this);
};
 
export default TextureManager;