All files / engine/Source/Scene GltfIndexBufferLoader.js

92.57% Statements 162/175
84.37% Branches 54/64
100% Functions 16/16
92.57% Lines 162/175

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                                                                            1771x 1771x 1771x 1771x 1771x 1771x 1771x 1771x 1771x 1771x 1771x 1771x     1771x 1770x 1769x 1768x 1767x 1766x 1x           1765x   1765x 1765x 1765x 1765x 1765x 1765x 1765x 1765x 1765x 1765x 1765x 1765x 1765x 1765x 1765x 1765x 1765x 1765x     1x 1x 1x     1x                       7031x                           3559x                           3542x                             1786x         1x             1x 1804x 43x     1761x 32x 32x     1729x 1729x       32x 32x   32x 32x             32x 32x   32x         32x 32x                     1729x 1729x 1729x 1729x   1729x 1729x 1729x 1729x           1729x   1729x 1727x 3x     1724x 1724x       1724x 1724x   2x       2x         1724x 1724x 1724x 1724x 1724x 1724x   1724x 1724x   1724x                         1724x 92x 1632x 1632x         1724x       3x 3x 3x 3x       1x 1x 1x 1x     1x         1745x 1745x 1745x     1x 1742x               1745x           1745x 1745x                 1x   3958x     3958x 113x     3845x       1993x     1852x 1852x   1852x 125x 125x 124x 28x 28x 28x   28x 28x     1x       1851x   96x       1755x 1745x 1745x 1745x 1745x   3x   1742x 10x 3x       1752x   1752x 1752x 1752x   1752x 1752x             1x 3510x 1738x     3510x   3510x       1729x     3510x 32x     3510x 3510x 3510x 3510x 3510x 3510x        
import Check from "../Core/Check.js";
import ComponentDatatype from "../Core/ComponentDatatype.js";
import Frozen from "../Core/Frozen.js";
import defined from "../Core/defined.js";
import deprecationWarning from "../Core/deprecationWarning.js";
import DeveloperError from "../Core/DeveloperError.js";
import IndexDatatype from "../Core/IndexDatatype.js";
import Buffer from "../Renderer/Buffer.js";
import BufferUsage from "../Renderer/BufferUsage.js";
import JobType from "./JobType.js";
import ResourceLoader from "./ResourceLoader.js";
import ResourceLoaderState from "./ResourceLoaderState.js";
 
/**
 * Loads an index buffer from a glTF accessor.
 * <p>
 * Implements the {@link ResourceLoader} interface.
 * </p>
 *
 * @alias GltfIndexBufferLoader
 * @constructor
 * @augments ResourceLoader
 *
 * @param {object} options Object with the following properties:
 * @param {ResourceCache} options.resourceCache The {@link ResourceCache} (to avoid circular dependencies).
 * @param {object} options.gltf The glTF JSON.
 * @param {number} options.accessorId The accessor ID corresponding to the index buffer.
 * @param {Resource} options.gltfResource The {@link Resource} containing the glTF.
 * @param {Resource} options.baseResource The {@link Resource} that paths in the glTF JSON are relative to.
 * @param {object} [options.primitive] The primitive containing the Draco extension.
 * @param {object} [options.draco] The Draco extension object.
 * @param {string} [options.cacheKey] The cache key of the resource.
 * @param {boolean} [options.asynchronous=true] Determines if WebGL resource creation will be spread out over several frames or block until all WebGL resources are created.
 * @param {boolean} [options.loadBuffer=false] Load the index buffer as a GPU index buffer.
 * @param {boolean} [options.loadTypedArray=false] Load the index buffer as a typed array.
 * @private
 */
function GltfIndexBufferLoader(options) {
  options = options ?? Frozen.EMPTY_OBJECT;
  const resourceCache = options.resourceCache;
  const gltf = options.gltf;
  const accessorId = options.accessorId;
  const gltfResource = options.gltfResource;
  const baseResource = options.baseResource;
  const primitive = options.primitive;
  const draco = options.draco;
  const cacheKey = options.cacheKey;
  const asynchronous = options.asynchronous ?? true;
  const loadBuffer = options.loadBuffer ?? false;
  const loadTypedArray = options.loadTypedArray ?? false;
 
  //>>includeStart('debug', pragmas.debug);
  Check.typeOf.func("options.resourceCache", resourceCache);
  Check.typeOf.object("options.gltf", gltf);
  Check.typeOf.number("options.accessorId", accessorId);
  Check.typeOf.object("options.gltfResource", gltfResource);
  Check.typeOf.object("options.baseResource", baseResource);
  if (!loadBuffer && !loadTypedArray) {
    throw new DeveloperError(
      "At least one of loadBuffer and loadTypedArray must be true.",
    );
  }
  //>>includeEnd('debug');
 
  const indexDatatype = gltf.accessors[accessorId].componentType;
 
  this._resourceCache = resourceCache;
  this._gltfResource = gltfResource;
  this._baseResource = baseResource;
  this._gltf = gltf;
  this._accessorId = accessorId;
  this._indexDatatype = indexDatatype;
  this._primitive = primitive;
  this._draco = draco;
  this._cacheKey = cacheKey;
  this._asynchronous = asynchronous;
  this._loadBuffer = loadBuffer;
  this._loadTypedArray = loadTypedArray;
  this._bufferViewLoader = undefined;
  this._dracoLoader = undefined;
  this._typedArray = undefined;
  this._buffer = undefined;
  this._state = ResourceLoaderState.UNLOADED;
  this._promise = undefined;
}
 
Eif (defined(Object.create)) {
  GltfIndexBufferLoader.prototype = Object.create(ResourceLoader.prototype);
  GltfIndexBufferLoader.prototype.constructor = GltfIndexBufferLoader;
}
 
Object.defineProperties(GltfIndexBufferLoader.prototype, {
  /**
   * The cache key of the resource.
   *
   * @memberof GltfIndexBufferLoader.prototype
   *
   * @type {string}
   * @readonly
   * @private
   */
  cacheKey: {
    get: function () {
      return this._cacheKey;
    },
  },
  /**
   * The index buffer. This is only defined when <code>loadBuffer</code> is true.
   *
   * @memberof GltfIndexBufferLoader.prototype
   *
   * @type {Buffer}
   * @readonly
   * @private
   */
  buffer: {
    get: function () {
      return this._buffer;
    },
  },
  /**
   * The typed array containing indices. This is only defined when <code>loadTypedArray</code> is true.
   *
   * @memberof GltfIndexBufferLoader.prototype
   *
   * @type {Uint8Array|Uint16Array|Uint32Array}
   * @readonly
   * @private
   */
  typedArray: {
    get: function () {
      return this._typedArray;
    },
  },
 
  /**
   * The index datatype after decode.
   *
   * @memberof GltfIndexBufferLoader.prototype
   *
   * @type {IndexDatatype}
   * @readonly
   * @private
   */
  indexDatatype: {
    get: function () {
      return this._indexDatatype;
    },
  },
});
 
const scratchIndexBufferJob = new CreateIndexBufferJob();
 
/**
 * Loads the resource.
 * @returns {Promise<GltfIndexBufferLoader>} A promise which resolves to the loader when the resource loading is completed.
 * @private
 */
GltfIndexBufferLoader.prototype.load = async function () {
  if (defined(this._promise)) {
    return this._promise;
  }
 
  if (defined(this._draco)) {
    this._promise = loadFromDraco(this);
    return this._promise;
  }
 
  this._promise = loadFromBufferView(this);
  return this._promise;
};
 
async function loadFromDraco(indexBufferLoader) {
  indexBufferLoader._state = ResourceLoaderState.LOADING;
  const resourceCache = indexBufferLoader._resourceCache;
 
  try {
    const dracoLoader = resourceCache.getDracoLoader({
      gltf: indexBufferLoader._gltf,
      primitive: indexBufferLoader._primitive,
      draco: indexBufferLoader._draco,
      gltfResource: indexBufferLoader._gltfResource,
      baseResource: indexBufferLoader._baseResource,
    });
    indexBufferLoader._dracoLoader = dracoLoader;
    await dracoLoader.load();
 
    Iif (indexBufferLoader.isDestroyed()) {
      return;
    }
 
    // Now wait for process() to run to finish loading
    indexBufferLoader._state = ResourceLoaderState.LOADED;
    return indexBufferLoader;
  } catch (error) {
    if (indexBufferLoader.isDestroyed()) {
      return;
    }
 
    handleError(indexBufferLoader, error);
  }
}
 
async function loadFromBufferView(indexBufferLoader) {
  const gltf = indexBufferLoader._gltf;
  const accessorId = indexBufferLoader._accessorId;
  const accessor = gltf.accessors[accessorId];
  const bufferViewId = accessor.bufferView;
 
  indexBufferLoader._state = ResourceLoaderState.LOADING;
  const resourceCache = indexBufferLoader._resourceCache;
  try {
    const bufferViewLoader = resourceCache.getBufferViewLoader({
      gltf: gltf,
      bufferViewId: bufferViewId,
      gltfResource: indexBufferLoader._gltfResource,
      baseResource: indexBufferLoader._baseResource,
    });
    indexBufferLoader._bufferViewLoader = bufferViewLoader;
 
    await bufferViewLoader.load();
    if (indexBufferLoader.isDestroyed()) {
      return;
    }
 
    const bufferViewTypedArray = bufferViewLoader.typedArray;
    indexBufferLoader._typedArray = createIndicesTypedArray(
      indexBufferLoader,
      bufferViewTypedArray,
    );
    indexBufferLoader._state = ResourceLoaderState.PROCESSING;
    return indexBufferLoader;
  } catch (error) {
    Iif (indexBufferLoader.isDestroyed()) {
      return;
    }
 
    handleError(indexBufferLoader, error);
  }
}
 
function createIndicesTypedArray(indexBufferLoader, bufferViewTypedArray) {
  const gltf = indexBufferLoader._gltf;
  const accessorId = indexBufferLoader._accessorId;
  const accessor = gltf.accessors[accessorId];
  const count = accessor.count;
  const indexDatatype = accessor.componentType;
  const indexSize = IndexDatatype.getSizeInBytes(indexDatatype);
 
  let arrayBuffer = bufferViewTypedArray.buffer;
  let byteOffset = bufferViewTypedArray.byteOffset + accessor.byteOffset;
 
  Iif (byteOffset % indexSize !== 0) {
    const byteLength = count * indexSize;
    const view = new Uint8Array(arrayBuffer, byteOffset, byteLength);
    const copy = new Uint8Array(view);
    arrayBuffer = copy.buffer;
    byteOffset = 0;
    deprecationWarning(
      "index-buffer-unaligned",
      `The index array is not aligned to a ${indexSize}-byte boundary.`,
    );
  }
 
  let typedArray;
  if (indexDatatype === IndexDatatype.UNSIGNED_BYTE) {
    typedArray = new Uint8Array(arrayBuffer, byteOffset, count);
  } else if (indexDatatype === IndexDatatype.UNSIGNED_SHORT) {
    typedArray = new Uint16Array(arrayBuffer, byteOffset, count);
  } else Eif (indexDatatype === IndexDatatype.UNSIGNED_INT) {
    typedArray = new Uint32Array(arrayBuffer, byteOffset, count);
  }
 
  return typedArray;
}
 
function handleError(indexBufferLoader, error) {
  indexBufferLoader.unload();
  indexBufferLoader._state = ResourceLoaderState.FAILED;
  const errorMessage = "Failed to load index buffer";
  throw indexBufferLoader.getError(errorMessage, error);
}
 
function CreateIndexBufferJob() {
  this.typedArray = undefined;
  this.indexDatatype = undefined;
  this.context = undefined;
  this.buffer = undefined;
}
 
CreateIndexBufferJob.prototype.set = function (
  typedArray,
  indexDatatype,
  context,
) {
  this.typedArray = typedArray;
  this.indexDatatype = indexDatatype;
  this.context = context;
};
 
CreateIndexBufferJob.prototype.execute = function () {
  this.buffer = createIndexBuffer(
    this.typedArray,
    this.indexDatatype,
    this.context,
  );
};
 
function createIndexBuffer(typedArray, indexDatatype, context) {
  const buffer = Buffer.createIndexBuffer({
    typedArray: typedArray,
    context: context,
    usage: BufferUsage.STATIC_DRAW,
    indexDatatype: indexDatatype,
  });
  buffer.vertexArrayDestroyable = false;
  return buffer;
}
 
/**
 * Processes the resource until it becomes ready.
 *
 * @param {FrameState} frameState The frame state.
 * @private
 */
GltfIndexBufferLoader.prototype.process = function (frameState) {
  //>>includeStart('debug', pragmas.debug);
  Check.typeOf.object("frameState", frameState);
  //>>includeEnd('debug');
 
  if (this._state === ResourceLoaderState.READY) {
    return true;
  }
 
  if (
    this._state !== ResourceLoaderState.LOADED &&
    this._state !== ResourceLoaderState.PROCESSING
  ) {
    return false;
  }
 
  let typedArray = this._typedArray;
  let indexDatatype = this._indexDatatype;
 
  if (defined(this._dracoLoader)) {
    try {
      const ready = this._dracoLoader.process(frameState);
      if (ready) {
        const dracoLoader = this._dracoLoader;
        typedArray = dracoLoader.decodedData.indices.typedArray;
        this._typedArray = typedArray;
        // The index datatype may be a smaller datatype after draco decode
        indexDatatype = ComponentDatatype.fromTypedArray(typedArray);
        this._indexDatatype = indexDatatype;
      }
    } catch (error) {
      handleError(this, error);
    }
  }
 
  if (!defined(typedArray)) {
    // Buffer view hasn't been loaded yet
    return false;
  }
 
  let buffer;
  if (this._loadBuffer && this._asynchronous) {
    const indexBufferJob = scratchIndexBufferJob;
    indexBufferJob.set(typedArray, indexDatatype, frameState.context);
    const jobScheduler = frameState.jobScheduler;
    if (!jobScheduler.execute(indexBufferJob, JobType.BUFFER)) {
      // Job scheduler is full. Try again next frame.
      return false;
    }
    buffer = indexBufferJob.buffer;
  } else if (this._loadBuffer) {
    buffer = createIndexBuffer(typedArray, indexDatatype, frameState.context);
  }
 
  // Unload everything except the index buffer and/or typed array.
  this.unload();
 
  this._buffer = buffer;
  this._typedArray = this._loadTypedArray ? typedArray : undefined;
  this._state = ResourceLoaderState.READY;
 
  this._resourceCache.statistics.addGeometryLoader(this);
  return true;
};
 
/**
 * Unloads the resource.
 * @private
 */
GltfIndexBufferLoader.prototype.unload = function () {
  if (defined(this._buffer)) {
    this._buffer.destroy();
  }
 
  const resourceCache = this._resourceCache;
 
  if (
    defined(this._bufferViewLoader) &&
    !this._bufferViewLoader.isDestroyed()
  ) {
    resourceCache.unload(this._bufferViewLoader);
  }
 
  if (defined(this._dracoLoader)) {
    resourceCache.unload(this._dracoLoader);
  }
 
  this._bufferViewLoader = undefined;
  this._dracoLoader = undefined;
  this._typedArray = undefined;
  this._buffer = undefined;
  this._gltf = undefined;
  this._primitive = undefined;
};
 
export default GltfIndexBufferLoader;