All files / engine/Source/Scene I3SLayer.js

93.58% Statements 146/156
84.93% Branches 62/73
92% Functions 23/25
93.42% Lines 142/152

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 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461                                              117x 117x   117x   1x     117x   117x 117x 19x     98x         117x 117x 117x 117x   117x 117x     117x 117x 117x 117x 117x 117x 117x 117x 117x 117x   117x 117x     1x                 269x                       10x                     14x                     26x                       118x                       235x                       118x                       117x     117x       74x   43x                     1x 117x 1x         116x 21x   116x 116x 116x   116x 116x 116x 74x             1x         117x   117x 4x 4x       4x   4x   4x 16x 16x 16x   16x   8x 8x 8x 32x       8x 60x 52x         16x               4x 16x   16x 8x   8x   4x               1x               12x   12x 12x 24x 24x 24x 24x 48x 12x 12x     24x 12x                                         1x 116x 42x 42x 9x   42x   74x     116x           1x 83x 83x 83x 83x             1x 1x           1x 1x     1x 1x     1x   1x       1x 1x       1x     1x           1x 117x 57x           60x 6x                       1x 116x               116x       116x 116x 116x 2x     2x       116x       116x 116x 116x           116x                   1x 4x 3x                 1x   9x     9x 9x 8x   1x        
import Cartesian4 from "../Core/Cartesian4.js";
import clone from "../Core/clone.js";
import Color from "../Core/Color.js";
import defined from "../Core/defined.js";
import Rectangle from "../Core/Rectangle.js";
import Resource from "../Core/Resource.js";
import RuntimeError from "../Core/RuntimeError.js";
import Cesium3DTileset from "./Cesium3DTileset.js";
import I3SNode from "./I3SNode.js";
import I3SSymbology from "./I3SSymbology.js";
 
/**
 * This class implements an I3S layer. In CesiumJS each I3SLayer creates a Cesium3DTileset.
 * <p>
 * Do not construct this directly, instead access layers through {@link I3SDataProvider}.
 * </p>
 * @alias I3SLayer
 * @internalConstructor
 * @privateParam {I3SDataProvider} dataProvider The i3s data provider
 * @privateParam {object} layerData The layer data that is loaded from the scene layer
 * @privateParam {I3SDataProvider|I3SSublayer} parent The parent of that layer
 */
function I3SLayer(dataProvider, layerData, parent) {
  this._dataProvider = dataProvider;
  this._parent = parent;
 
  if (!defined(layerData.href) && defined(layerData.id)) {
    // assign a default layer
    layerData.href = `layers/${layerData.id}`;
  }
 
  const parentUrl = this._parent.resource.getUrlComponent();
 
  let tilesetUrl = "";
  if (parentUrl.match(/layers\/\d/)) {
    tilesetUrl = `${parentUrl}`.replace(/\/+$/, "");
  } else {
    // Add '/' to url if needed + `${layerData.href}` if tilesetUrl not already in ../layers/[id] format
    tilesetUrl = `${parentUrl}`
      .replace(/\/?$/, "/")
      .concat(`${layerData.href}`);
  }
 
  this._version = layerData.store.version;
  const splitVersion = this._version.split(".");
  this._majorVersion = parseInt(splitVersion[0]);
  this._minorVersion = splitVersion.length > 1 ? parseInt(splitVersion[1]) : 0;
 
  this._resource = new Resource({ url: tilesetUrl });
  this._resource.setQueryParameters(
    this._dataProvider.resource.queryParameters,
  );
  this._resource.appendForwardSlash();
  this._data = layerData;
  this._rootNode = undefined;
  this._nodePages = {};
  this._nodePageFetches = {};
  this._extent = undefined;
  this._tileset = undefined;
  this._geometryDefinitions = undefined;
  this._filters = [];
  this._symbology = undefined;
 
  this._computeGeometryDefinitions(true);
  this._computeExtent();
}
 
Object.defineProperties(I3SLayer.prototype, {
  /**
   * Gets the resource for the layer.
   * @memberof I3SLayer.prototype
   * @type {Resource}
   * @readonly
   */
  resource: {
    get: function () {
      return this._resource;
    },
  },
 
  /**
   * Gets the root node of this layer.
   * @memberof I3SLayer.prototype
   * @type {I3SNode}
   * @readonly
   */
  rootNode: {
    get: function () {
      return this._rootNode;
    },
  },
  /**
   * Gets the Cesium3DTileset for this layer.
   * @memberof I3SLayer.prototype
   * @type {Cesium3DTileset|undefined}
   * @readonly
   */
  tileset: {
    get: function () {
      return this._tileset;
    },
  },
  /**
   * Gets the I3S data for this object.
   * @memberof I3SLayer.prototype
   * @type {object}
   * @readonly
   */
  data: {
    get: function () {
      return this._data;
    },
  },
 
  /**
   * The version string of the loaded I3S dataset
   * @memberof I3SLayer.prototype
   * @type {string}
   * @readonly
   */
  version: {
    get: function () {
      return this._version;
    },
  },
 
  /**
   * The major version number of the loaded I3S dataset
   * @memberof I3SLayer.prototype
   * @type {number}
   * @readonly
   */
  majorVersion: {
    get: function () {
      return this._majorVersion;
    },
  },
 
  /**
   * The minor version number of the loaded I3S dataset
   * @memberof I3SLayer.prototype
   * @type {number}
   * @readonly
   */
  minorVersion: {
    get: function () {
      return this._minorVersion;
    },
  },
 
  /**
   * When <code>true</code>, when the loaded I3S version is 1.6 or older
   * @memberof I3SLayer.prototype
   * @type {boolean}
   * @readonly
   */
  legacyVersion16: {
    get: function () {
      Iif (!defined(this.version)) {
        return undefined;
      }
      if (
        this.majorVersion < 1 ||
        (this.majorVersion === 1 && this.minorVersion <= 6)
      ) {
        return true;
      }
      return false;
    },
  },
});
 
/**
 * Loads the content, including the root node definition and its children
 * @param {Cesium3DTileset.ConstructorOptions} [cesium3dTilesetOptions] options for Cesium3dTileset constructor
 * @returns {Promise<void>} A promise that is resolved when the layer data is loaded
 * @private
 */
I3SLayer.prototype.load = async function (cesium3dTilesetOptions) {
  if (this._data.spatialReference.wkid !== 4326) {
    throw new RuntimeError(
      `Unsupported spatial reference: ${this._data.spatialReference.wkid}`,
    );
  }
 
  if (this._dataProvider.applySymbology) {
    this._symbology = new I3SSymbology(this);
  }
  await this._dataProvider.loadGeoidData();
  await this._loadRootNode(cesium3dTilesetOptions);
  await this._create3DTileset(cesium3dTilesetOptions);
 
  this._rootNode._tile = this._tileset._root;
  this._tileset._root._i3sNode = this._rootNode;
  if (this.legacyVersion16) {
    return this._rootNode._loadChildren();
  }
};
 
/**
 * @private
 */
I3SLayer.prototype._computeGeometryDefinitions = function (useCompression) {
  // create a table of all geometry buffers based on
  // the number of attributes and whether they are
  // compressed or not, sort them by priority
 
  this._geometryDefinitions = [];
 
  if (defined(this._data.geometryDefinitions)) {
    for (
      let defIndex = 0;
      defIndex < this._data.geometryDefinitions.length;
      defIndex++
    ) {
      const geometryBuffersInfo = [];
      const geometryBuffers =
        this._data.geometryDefinitions[defIndex].geometryBuffers;
 
      for (let bufIndex = 0; bufIndex < geometryBuffers.length; bufIndex++) {
        const geometryBuffer = geometryBuffers[bufIndex];
        const collectedAttributes = [];
        let compressed = false;
 
        if (defined(geometryBuffer.compressedAttributes) && useCompression) {
          // check if compressed
          compressed = true;
          const attributes = geometryBuffer.compressedAttributes.attributes;
          for (let i = 0; i < attributes.length; i++) {
            collectedAttributes.push(attributes[i]);
          }
        } else {
          // uncompressed attributes
          for (const attribute in geometryBuffer) {
            if (attribute !== "offset") {
              collectedAttributes.push(attribute);
            }
          }
        }
 
        geometryBuffersInfo.push({
          compressed: compressed,
          attributes: collectedAttributes,
          index: geometryBuffers.indexOf(geometryBuffer),
        });
      }
 
      // rank the buffer info
      geometryBuffersInfo.sort(function (a, b) {
        Iif (a.compressed && !b.compressed) {
          return -1;
        } else if (!a.compressed && b.compressed) {
          return 1;
        }
        return a.attributes.length - b.attributes.length;
      });
      this._geometryDefinitions.push(geometryBuffersInfo);
    }
  }
};
 
/**
 * @private
 */
I3SLayer.prototype._findBestGeometryBuffers = function (
  definition,
  attributes,
) {
  // find the most appropriate geometry definition
  // based on the required attributes, and by favouring
  // compression to improve bandwidth requirements
 
  const geometryDefinition = this._geometryDefinitions[definition];
 
  Eif (defined(geometryDefinition)) {
    for (let index = 0; index < geometryDefinition.length; ++index) {
      const geometryBufferInfo = geometryDefinition[index];
      let missed = false;
      const geometryAttributes = geometryBufferInfo.attributes;
      for (let attrIndex = 0; attrIndex < attributes.length; attrIndex++) {
        if (!geometryAttributes.includes(attributes[attrIndex])) {
          missed = true;
          break;
        }
      }
      if (!missed) {
        return {
          bufferIndex: geometryBufferInfo.index,
          definition: geometryDefinition,
          geometryBufferInfo: geometryBufferInfo,
        };
      }
    }
    // If no match found return first geometryBuffer
    if (defined(geometryDefinition[0])) {
      return {
        bufferIndex: 0,
        definition: geometryDefinition,
        geometryBufferInfo: geometryDefinition[0],
      };
    }
  }
};
 
/**
 * @private
 */
I3SLayer.prototype._loadRootNode = function (cesium3dTilesetOptions) {
  if (defined(this._data.nodePages)) {
    let rootIndex = 0;
    if (defined(this._data.nodePages.rootIndex)) {
      rootIndex = this._data.nodePages.rootIndex;
    }
    this._rootNode = new I3SNode(this, rootIndex, true);
  } else {
    this._rootNode = new I3SNode(this, this._data.store.rootNode, true);
  }
 
  return this._rootNode.load(cesium3dTilesetOptions);
};
 
/**
 * @private
 */
I3SLayer.prototype._getNodeInNodePages = function (nodeIndex) {
  const index = Math.floor(nodeIndex / this._data.nodePages.nodesPerPage);
  const offsetInPage = nodeIndex % this._data.nodePages.nodesPerPage;
  return this._loadNodePage(index).then(function (data) {
    return data.nodes[offsetInPage];
  });
};
 
/**
 * @private
 */
I3SLayer._fetchJson = function (resource) {
  return resource.fetchJson();
};
 
/**
 * @private
 */
I3SLayer.prototype._loadNodePage = function (page) {
  const that = this;
 
  // If node page was already requested return the same promise
  Eif (!defined(this._nodePageFetches[page])) {
    const nodePageResource = this.resource.getDerivedResource({
      url: `nodepages/${page}/`,
    });
    const fetchPromise = I3SLayer._fetchJson(nodePageResource).then(
      function (data) {
        Iif (defined(data.error) && data.error.code !== 200) {
          return Promise.reject(data.error);
        }
 
        that._nodePages[page] = data.nodes;
        return data;
      },
    );
 
    this._nodePageFetches[page] = fetchPromise;
  }
 
  return this._nodePageFetches[page];
};
 
/**
 * @private
 */
I3SLayer.prototype._computeExtent = function () {
  if (defined(this._data.fullExtent)) {
    this._extent = Rectangle.fromDegrees(
      this._data.fullExtent.xmin,
      this._data.fullExtent.ymin,
      this._data.fullExtent.xmax,
      this._data.fullExtent.ymax,
    );
  } else if (defined(this._data.store.extent)) {
    this._extent = Rectangle.fromDegrees(
      this._data.store.extent[0],
      this._data.store.extent[1],
      this._data.store.extent[2],
      this._data.store.extent[3],
    );
  }
};
 
/**
 * @private
 */
I3SLayer.prototype._create3DTileset = async function (cesium3dTilesetOptions) {
  const inPlaceTileset = {
    asset: {
      version: "1.0",
    },
    geometricError: Number.MAX_VALUE,
    root: this._rootNode._create3DTileDefinition(),
  };
 
  const tilesetBlob = new Blob([JSON.stringify(inPlaceTileset)], {
    type: "application/json",
  });
 
  const tilesetUrl = URL.createObjectURL(tilesetBlob);
  const outlineColor = this._symbology?.defaultSymbology?.edges?.color;
  if (defined(outlineColor) && !defined(cesium3dTilesetOptions?.outlineColor)) {
    cesium3dTilesetOptions = defined(cesium3dTilesetOptions)
      ? clone(cesium3dTilesetOptions)
      : {};
    cesium3dTilesetOptions.outlineColor = Color.fromCartesian4(
      Cartesian4.fromArray(outlineColor),
    );
  }
  this._tileset = await Cesium3DTileset.fromUrl(
    tilesetUrl,
    cesium3dTilesetOptions,
  );
  this._tileset.show = this._parent.show;
  this._tileset._isI3STileSet = true;
  this._tileset.tileUnload.addEventListener(function (tile) {
    tile._i3sNode._clearGeometryData();
    URL.revokeObjectURL(tile._contentResource._url);
    tile._contentResource = tile._i3sNode.resource;
  });
 
  this._tileset.tileVisible.addEventListener(function (tile) {
    if (defined(tile._i3sNode)) {
      tile._i3sNode._loadChildren();
    }
  });
};
 
/**
 * @private
 */
I3SLayer.prototype._updateVisibility = function () {
  if (defined(this._tileset)) {
    this._tileset.show = this._parent.show;
  }
};
 
/**
 * Filters the drawn elements of a layer to specific attribute names and values
 * @param {I3SNode.AttributeFilter[]} [filters=[]] The collection of attribute filters
 * @returns {Promise<void>} A promise that is resolved when the filter is applied
 */
I3SLayer.prototype.filterByAttributes = function (filters) {
  // Filters are applied for each node in the layer when the node model is loaded
  this._filters = defined(filters) ? clone(filters, true) : [];
 
  // Forced filtering is required for loaded nodes only
  const rootNode = this._rootNode;
  if (defined(rootNode)) {
    return rootNode._filterFeatures();
  }
  return Promise.resolve();
};
 
export default I3SLayer;