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

89.7% Statements 122/136
81.48% Branches 44/54
66.66% Functions 8/12
89.47% Lines 119/133

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                                      1x               1x                                                             958x   958x 958x 958x 958x 958x 958x 958x 958x 958x   958x 958x 958x 958x 958x 958x     958x 958x     958x   958x 958x 958x 958x 958x 958x 958x 958x 958x 958x 958x 958x 958x 958x 958x   958x   958x   958x     958x 958x     958x 958x 958x     1x 1x 1x     1x                                                                                 957x                   1x 958x       958x   955x 955x 955x 955x 955x   955x       955x   955x   955x         955x 899x     955x         955x                                 955x 955x   955x 955x     955x       955x 955x                   955x                     1x   1916x     1916x       1916x       1916x 1916x 961x     955x           955x         955x 955x     955x   955x 955x       955x 955x   955x 15x       940x   929x             11x       11x             940x 940x 940x 940x   940x         941x 941x 1x     941x 941x 969x 969x       969x 969x 969x 969x 969x 969x 969x         1x 949x 946x     949x 949x        
import Axis from "../Axis.js";
import B3dmParser from "../B3dmParser.js";
import Cartesian3 from "../../Core/Cartesian3.js";
import Cesium3DTileFeatureTable from "../Cesium3DTileFeatureTable.js";
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 StructuralMetadata from "../StructuralMetadata.js";
import GltfLoader from "../GltfLoader.js";
import Matrix4 from "../../Core/Matrix4.js";
import MetadataClass from "../MetadataClass.js";
import ModelComponents from "../ModelComponents.js";
import ModelUtility from "./ModelUtility.js";
import parseBatchTable from "../parseBatchTable.js";
import PropertyTable from "../PropertyTable.js";
import ResourceLoader from "../ResourceLoader.js";
import VertexAttributeSemantic from "../VertexAttributeSemantic.js";
 
const B3dmLoaderState = {
  UNLOADED: 0,
  LOADING: 1,
  PROCESSING: 2,
  READY: 3,
  FAILED: 4,
};
 
const FeatureIdAttribute = ModelComponents.FeatureIdAttribute;
 
/**
 * Loads a Batched 3D Model.
 * <p>
 * Implements the {@link ResourceLoader} interface.
 * </p>
 *
 * @alias B3dmLoader
 * @constructor
 * @augments ResourceLoader
 * @private
 *
 * @param {object} options Object with the following properties:
 * @param {Resource} options.b3dmResource The {@link Resource} containing the b3dm.
 * @param {ArrayBuffer} options.arrayBuffer The array buffer of the b3dm contents.
 * @param {number} [options.byteOffset] The byte offset to the beginning of the b3dm contents in the array buffer.
 * @param {Resource} [options.baseResource] The {@link Resource} that paths in the glTF JSON are relative to.
 * @param {boolean} [options.releaseGltfJson=false] When true, the glTF JSON is released once the glTF is loaded. This is especially useful for cases like 3D Tiles, where each .gltf model is unique and caching the glTF JSON is not effective.
 * @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.incrementallyLoadTextures=true] Determine if textures may continue to stream in after the glTF is loaded.
 * @param {Axis} [options.upAxis=Axis.Y] The up-axis of the glTF model.
 * @param {Axis} [options.forwardAxis=Axis.X] The forward-axis of the glTF model.
 * @param {boolean} [options.loadAttributesAsTypedArray=false] If <code>true</code>, load all attributes as typed arrays instead of GPU buffers. If the attributes are interleaved in the glTF they will be de-interleaved in the typed array.
 * @param {boolean} [options.loadAttributesFor2D=false] If <code>true</code>, load the positions buffer and any instanced attribute buffers as typed arrays for accurately projecting models to 2D.
 * @param {boolean} [options.enablePick=false]  If <code>true</code>, load the positions buffer, any instanced attribute buffers, and index buffer as typed arrays for CPU-enabled picking in WebGL1.
 * @param {boolean} [options.loadIndicesForWireframe=false] If <code>true</code>, load the index buffer as a typed array. This is useful for creating wireframe indices in WebGL1.
 * @param {boolean} [options.loadPrimitiveOutline=true] If <code>true</code>, load outlines from the {@link https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/CESIUM_primitive_outline|CESIUM_primitive_outline} extension. This can be set false to avoid post-processing geometry at load time.
 * @param {boolean} [options.loadForClassification=false] If <code>true</code> and if the model has feature IDs, load the feature IDs and indices as typed arrays. This is useful for batching features for classification.
 * */
function B3dmLoader(options) {
  options = options ?? Frozen.EMPTY_OBJECT;
 
  const b3dmResource = options.b3dmResource;
  let baseResource = options.baseResource;
  const arrayBuffer = options.arrayBuffer;
  const byteOffset = options.byteOffset ?? 0;
  const releaseGltfJson = options.releaseGltfJson ?? false;
  const asynchronous = options.asynchronous ?? true;
  const incrementallyLoadTextures = options.incrementallyLoadTextures ?? true;
  const upAxis = options.upAxis ?? Axis.Y;
  const forwardAxis = options.forwardAxis ?? Axis.X;
  const loadAttributesAsTypedArray =
    options.loadAttributesAsTypedArray ?? false;
  const loadAttributesFor2D = options.loadAttributesFor2D ?? false;
  const enablePick = options.enablePick ?? false;
  const loadIndicesForWireframe = options.loadIndicesForWireframe ?? false;
  const loadPrimitiveOutline = options.loadPrimitiveOutline ?? true;
  const loadForClassification = options.loadForClassification ?? false;
 
  //>>includeStart('debug', pragmas.debug);
  Check.typeOf.object("options.b3dmResource", b3dmResource);
  Check.typeOf.object("options.arrayBuffer", arrayBuffer);
  //>>includeEnd('debug');
 
  baseResource = defined(baseResource) ? baseResource : b3dmResource.clone();
 
  this._b3dmResource = b3dmResource;
  this._baseResource = baseResource;
  this._arrayBuffer = arrayBuffer;
  this._byteOffset = byteOffset;
  this._releaseGltfJson = releaseGltfJson;
  this._asynchronous = asynchronous;
  this._incrementallyLoadTextures = incrementallyLoadTextures;
  this._upAxis = upAxis;
  this._forwardAxis = forwardAxis;
  this._loadAttributesAsTypedArray = loadAttributesAsTypedArray;
  this._loadAttributesFor2D = loadAttributesFor2D;
  this._enablePick = enablePick;
  this._loadIndicesForWireframe = loadIndicesForWireframe;
  this._loadPrimitiveOutline = loadPrimitiveOutline;
  this._loadForClassification = loadForClassification;
 
  this._state = B3dmLoaderState.UNLOADED;
 
  this._promise = undefined;
 
  this._gltfLoader = undefined;
 
  // Loaded results.
  this._batchLength = 0;
  this._propertyTable = undefined;
 
  // The batch table object contains a json and a binary component access using keys of the same name.
  this._batchTable = undefined;
  this._components = undefined;
  this._transform = Matrix4.IDENTITY;
}
 
Eif (defined(Object.create)) {
  B3dmLoader.prototype = Object.create(ResourceLoader.prototype);
  B3dmLoader.prototype.constructor = B3dmLoader;
}
 
Object.defineProperties(B3dmLoader.prototype, {
  /**
   * true if textures are loaded, useful when incrementallyLoadTextures is true
   *
   * @memberof B3dmLoader.prototype
   *
   * @type {boolean}
   * @readonly
   * @private
   */
  texturesLoaded: {
    get: function () {
      return this._gltfLoader?.texturesLoaded;
    },
  },
  /**
   * The cache key of the resource
   *
   * @memberof B3dmLoader.prototype
   *
   * @type {string}
   * @readonly
   * @private
   */
  cacheKey: {
    get: function () {
      return undefined;
    },
  },
 
  /**
   * The loaded components.
   *
   * @memberof B3dmLoader.prototype
   *
   * @type {ModelComponents.Components}
   * @readonly
   * @private
   */
  components: {
    get: function () {
      return this._components;
    },
  },
});
 
/**
 * Loads the resource.
 * @returns {Promise<B3dmLoader>} A promise which resolves to the loader when the resource loading is completed.
 * @private
 */
B3dmLoader.prototype.load = function () {
  Iif (defined(this._promise)) {
    return this._promise;
  }
 
  const b3dm = B3dmParser.parse(this._arrayBuffer, this._byteOffset);
 
  let batchLength = b3dm.batchLength;
  const featureTableJson = b3dm.featureTableJson;
  const featureTableBinary = b3dm.featureTableBinary;
  const batchTableJson = b3dm.batchTableJson;
  const batchTableBinary = b3dm.batchTableBinary;
 
  const featureTable = new Cesium3DTileFeatureTable(
    featureTableJson,
    featureTableBinary,
  );
  batchLength = featureTable.getGlobalProperty("BATCH_LENGTH");
  // Set batch length.
  this._batchLength = batchLength;
  // Set the RTC Center transform, if present.
  const rtcCenter = featureTable.getGlobalProperty(
    "RTC_CENTER",
    ComponentDatatype.FLOAT,
    3,
  );
  if (defined(rtcCenter)) {
    this._transform = Matrix4.fromTranslation(Cartesian3.fromArray(rtcCenter));
  }
 
  this._batchTable = {
    json: batchTableJson,
    binary: batchTableBinary,
  };
 
  const gltfLoader = new GltfLoader({
    typedArray: b3dm.gltf,
    upAxis: this._upAxis,
    forwardAxis: this._forwardAxis,
    gltfResource: this._b3dmResource,
    baseResource: this._baseResource,
    releaseGltfJson: this._releaseGltfJson,
    incrementallyLoadTextures: this._incrementallyLoadTextures,
    loadAttributesAsTypedArray: this._loadAttributesAsTypedArray,
    loadAttributesFor2D: this._loadAttributesFor2D,
    enablePick: this._enablePick,
    loadIndicesForWireframe: this._loadIndicesForWireframe,
    loadPrimitiveOutline: this._loadPrimitiveOutline,
    loadForClassification: this._loadForClassification,
    renameBatchIdSemantic: true,
  });
 
  this._gltfLoader = gltfLoader;
  this._state = B3dmLoaderState.LOADING;
 
  const that = this;
  this._promise = gltfLoader
    .load()
    .then(function () {
      Iif (that.isDestroyed()) {
        return;
      }
 
      that._state = B3dmLoaderState.PROCESSING;
      return that;
    })
    .catch(function (error) {
      if (that.isDestroyed()) {
        return;
      }
 
      return handleError(that, error);
    });
 
  return this._promise;
};
 
function handleError(b3dmLoader, error) {
  b3dmLoader.unload();
  b3dmLoader._state = B3dmLoaderState.FAILED;
  const errorMessage = "Failed to load b3dm";
  error = b3dmLoader.getError(errorMessage, error);
  return Promise.reject(error);
}
 
B3dmLoader.prototype.process = function (frameState) {
  //>>includeStart('debug', pragmas.debug);
  Check.typeOf.object("frameState", frameState);
  //>>includeEnd('debug');
 
  Iif (this._state === B3dmLoaderState.READY) {
    return true;
  }
 
  Iif (this._state !== B3dmLoaderState.PROCESSING) {
    return false;
  }
 
  const ready = this._gltfLoader.process(frameState);
  if (!ready) {
    return false;
  }
 
  const components = this._gltfLoader.components;
 
  // Combine the RTC_CENTER transform from the b3dm and the CESIUM_RTC
  // transform from the glTF. In practice usually only one or the
  // other is supplied. If they don't exist the transforms will
  // be identity matrices.
  components.transform = Matrix4.multiplyTransformation(
    this._transform,
    components.transform,
    components.transform,
  );
  createStructuralMetadata(this, components);
  this._components = components;
 
  // Now that we have the parsed components, we can release the array buffer
  this._arrayBuffer = undefined;
 
  this._state = B3dmLoaderState.READY;
  return true;
};
 
function createStructuralMetadata(loader, components) {
  const batchTable = loader._batchTable;
  const batchLength = loader._batchLength;
 
  if (batchLength === 0) {
    return;
  }
 
  let structuralMetadata;
  if (defined(batchTable.json)) {
    // Add the structural metadata from the batch table to the model components.
    structuralMetadata = parseBatchTable({
      count: batchLength,
      batchTable: batchTable.json,
      binaryBody: batchTable.binary,
    });
  } else {
    // If batch table is not defined, create a property table without any properties.
    const emptyPropertyTable = new PropertyTable({
      name: MetadataClass.BATCH_TABLE_CLASS_NAME,
      count: batchLength,
    });
    structuralMetadata = new StructuralMetadata({
      schema: {},
      propertyTables: [emptyPropertyTable],
    });
  }
 
  // Add the feature ID attribute to the primitives.
  const nodes = components.scene.nodes;
  const length = nodes.length;
  for (let i = 0; i < length; i++) {
    processNode(nodes[i]);
  }
  components.structuralMetadata = structuralMetadata;
}
 
// Recursive function to add the feature ID attribute to all primitives that have a feature ID vertex attribute.
function processNode(node) {
  const childrenLength = node.children.length;
  for (let i = 0; i < childrenLength; i++) {
    processNode(node.children[i]);
  }
 
  const primitivesLength = node.primitives.length;
  for (let i = 0; i < primitivesLength; i++) {
    const primitive = node.primitives[i];
    const featureIdVertexAttribute = ModelUtility.getAttributeBySemantic(
      primitive,
      VertexAttributeSemantic.FEATURE_ID,
    );
    Eif (defined(featureIdVertexAttribute)) {
      featureIdVertexAttribute.setIndex = 0;
      const featureIdAttribute = new FeatureIdAttribute();
      featureIdAttribute.propertyTableId = 0;
      featureIdAttribute.setIndex = 0;
      featureIdAttribute.positionalLabel = "featureId_0";
      primitive.featureIds.push(featureIdAttribute);
    }
  }
}
 
B3dmLoader.prototype.unload = function () {
  if (defined(this._gltfLoader) && !this._gltfLoader.isDestroyed()) {
    this._gltfLoader.unload();
  }
 
  this._components = undefined;
  this._arrayBuffer = undefined;
};
 
export default B3dmLoader;