All files / engine/Source/Scene TileMapServiceImageryProvider.js

98.13% Statements 105/107
93.24% Branches 69/74
100% Functions 7/7
98.09% Lines 103/105

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                                                                                                                                                        33x     1x             34x 34x 25x               11x 9x           2x                                                 1x   35x     34x 34x   34x 34x       34x 34x           32x     1x 1x     1x                 32x 1x   32x 1x   32x 1x   32x 1x   32x                     32x       32x         32x 32x 3x   29x                         1x             25x 25x 25x 25x   25x         25x 25x 351x 25x 326x 25x 25x   25x 183x   79x     301x 24x         25x 1x 1x                 1x       24x   24x   24x   24x   24x   24x 24x   24x 24x       14x     10x       9x       1x 1x                 1x         23x   23x               22x 22x 2x       2x         20x       20x                     22x 22x       21x 21x   1x 1x 1x     22x                 23x   23x           23x       23x                                         1x         9x 9x 9x 9x 9x       9x   9x     9x           9x       9x                            
import Cartesian2 from "../Core/Cartesian2.js";
import Cartographic from "../Core/Cartographic.js";
import Check from "../Core/Check.js";
import Frozen from "../Core/Frozen.js";
import defined from "../Core/defined.js";
import GeographicProjection from "../Core/GeographicProjection.js";
import GeographicTilingScheme from "../Core/GeographicTilingScheme.js";
import Rectangle from "../Core/Rectangle.js";
import RequestErrorEvent from "../Core/RequestErrorEvent.js";
import Resource from "../Core/Resource.js";
import RuntimeError from "../Core/RuntimeError.js";
import TileProviderError from "../Core/TileProviderError.js";
import WebMercatorTilingScheme from "../Core/WebMercatorTilingScheme.js";
import UrlTemplateImageryProvider from "./UrlTemplateImageryProvider.js";
 
/**
 * @typedef {object} TileMapServiceImageryProvider.ConstructorOptions
 *
 * Initialization options for the TileMapServiceImageryProvider constructor
 *
 * @property {string} [fileExtension='png'] The file extension for images on the server.
 * @property {Credit|string} [credit=''] A credit for the data source, which is displayed on the canvas.
 * @property {number} [minimumLevel=0] The minimum level-of-detail supported by the imagery provider.  Take care when specifying
 *                 this that the number of tiles at the minimum level is small, such as four or less.  A larger number is likely
 *                 to result in rendering problems.
 * @property {number} [maximumLevel] The maximum level-of-detail supported by the imagery provider, or undefined if there is no limit.
 * @property {Rectangle} [rectangle=Rectangle.MAX_VALUE] The rectangle, in radians, covered by the image.
 * @property {TilingScheme} [tilingScheme] The tiling scheme specifying how the ellipsoidal
 * surface is broken into tiles.  If this parameter is not provided, a {@link WebMercatorTilingScheme}
 * is used.
 * @property {Ellipsoid} [ellipsoid] The ellipsoid.  If the tilingScheme is specified,
 *                    this parameter is ignored and the tiling scheme's ellipsoid is used instead. If neither
 *                    parameter is specified, the WGS84 ellipsoid is used.
 * @property {number} [tileWidth=256] Pixel width of image tiles.
 * @property {number} [tileHeight=256] Pixel height of image tiles.
 * @property {boolean} [flipXY] Older versions of gdal2tiles.py flipped X and Y values in tilemapresource.xml.
 * @property {TileDiscardPolicy} [tileDiscardPolicy] A policy for discarding tile images according to some criteria
 * Specifying this option will do the same, allowing for loading of these incorrect tilesets.
 */
 
/**
 * <div class="notice">
 * To construct a TileMapServiceImageryProvider, call {@link TileMapServiceImageryProvider.fromUrl}. Do not call the constructor directly.
 * </div>
 *
 * An imagery provider that provides tiled imagery as generated by
 * {@link http://www.maptiler.org/|MapTiler}, {@link http://www.klokan.cz/projects/gdal2tiles/|GDAL2Tiles}, etc.
 *
 * @alias TileMapServiceImageryProvider
 * @constructor
 * @extends UrlTemplateImageryProvider
 *
 * @param {TileMapServiceImageryProvider.ConstructorOptions} [options] Object describing initialization options
 *
 * @see ArcGisMapServerImageryProvider
 * @see BingMapsImageryProvider
 * @see GoogleEarthEnterpriseMapsProvider
 * @see OpenStreetMapImageryProvider
 * @see SingleTileImageryProvider
 * @see WebMapServiceImageryProvider
 * @see WebMapTileServiceImageryProvider
 * @see UrlTemplateImageryProvider
 *
 * @example
 * const tms = await Cesium.TileMapServiceImageryProvider.fromUrl(
 *    "../images/cesium_maptiler/Cesium_Logo_Color", {
 *      fileExtension: 'png',
 *      maximumLevel: 4,
 *      rectangle: new Cesium.Rectangle(
 *        Cesium.Math.toRadians(-120.0),
 *        Cesium.Math.toRadians(20.0),
 *        Cesium.Math.toRadians(-60.0),
 *        Cesium.Math.toRadians(40.0))
 * });
 */
function TileMapServiceImageryProvider(options) {
  UrlTemplateImageryProvider.call(this, options);
}
 
TileMapServiceImageryProvider._requestMetadata = async function (
  options,
  tmsResource,
  xmlResource,
  provider,
) {
  // Try to load remaining parameters from XML
  try {
    const xml = await xmlResource.fetchXML();
    return TileMapServiceImageryProvider._metadataSuccess(
      xml,
      options,
      tmsResource,
      xmlResource,
      provider,
    );
  } catch (e) {
    if (e instanceof RequestErrorEvent) {
      return TileMapServiceImageryProvider._metadataFailure(
        options,
        tmsResource,
      );
    }
 
    throw e;
  }
};
/**
 * Creates a TileMapServiceImageryProvider from the specified url.
 *
 * @param {Resource|string} url Path to image tiles on server.
 * @param {TileMapServiceImageryProvider.ConstructorOptions} [options] Object describing initialization options.
 * @returns {Promise<TileMapServiceImageryProvider>} A promise that resolves to the created TileMapServiceImageryProvider.
 *
 * @example
 * const tms = await Cesium.TileMapServiceImageryProvider.fromUrl(
 *    '../images/cesium_maptiler/Cesium_Logo_Color', {
 *      fileExtension: 'png',
 *      maximumLevel: 4,
 *      rectangle: new Cesium.Rectangle(
 *        Cesium.Math.toRadians(-120.0),
 *        Cesium.Math.toRadians(20.0),
 *        Cesium.Math.toRadians(-60.0),
 *        Cesium.Math.toRadians(40.0))
 * });
 *
 * @exception {RuntimeError} Unable to find expected tilesets or bbox attributes in tilemapresource.xml
 * @exception {RuntimeError} tilemapresource.xml specifies an unsupported profile attribute
 */
TileMapServiceImageryProvider.fromUrl = async function (url, options) {
  //>>includeStart('debug', pragmas.debug);
  Check.defined("url", url);
  //>>includeEnd('debug');
 
  const resource = Resource.createIfNeeded(url);
  resource.appendForwardSlash();
 
  const tmsResource = resource;
  const xmlResource = resource.getDerivedResource({
    url: "tilemapresource.xml",
  });
 
  options = options ?? Frozen.EMPTY_OBJECT;
  const metadata = await TileMapServiceImageryProvider._requestMetadata(
    options,
    tmsResource,
    xmlResource,
  );
 
  return new TileMapServiceImageryProvider(metadata);
};
 
Eif (defined(Object.create)) {
  TileMapServiceImageryProvider.prototype = Object.create(
    UrlTemplateImageryProvider.prototype,
  );
  TileMapServiceImageryProvider.prototype.constructor =
    TileMapServiceImageryProvider;
}
 
/**
 * Mutates the properties of a given rectangle so it does not extend outside of the given tiling scheme's rectangle
 * @private
 */
function confineRectangleToTilingScheme(rectangle, tilingScheme) {
  if (rectangle.west < tilingScheme.rectangle.west) {
    rectangle.west = tilingScheme.rectangle.west;
  }
  if (rectangle.east > tilingScheme.rectangle.east) {
    rectangle.east = tilingScheme.rectangle.east;
  }
  if (rectangle.south < tilingScheme.rectangle.south) {
    rectangle.south = tilingScheme.rectangle.south;
  }
  if (rectangle.north > tilingScheme.rectangle.north) {
    rectangle.north = tilingScheme.rectangle.north;
  }
  return rectangle;
}
 
function calculateSafeMinimumDetailLevel(
  tilingScheme,
  rectangle,
  minimumLevel,
) {
  // Check the number of tiles at the minimum level.  If it's more than four,
  // try requesting the lower levels anyway, because starting at the higher minimum
  // level will cause too many tiles to be downloaded and rendered.
  const swTile = tilingScheme.positionToTileXY(
    Rectangle.southwest(rectangle),
    minimumLevel,
  );
  const neTile = tilingScheme.positionToTileXY(
    Rectangle.northeast(rectangle),
    minimumLevel,
  );
  const tileCount =
    (Math.abs(neTile.x - swTile.x) + 1) * (Math.abs(neTile.y - swTile.y) + 1);
  if (tileCount > 4) {
    return 0;
  }
  return minimumLevel;
}
 
/**
 * Parses the results of a successful xml request
 * @private
 *
 * @param {object} xml
 * @param {TileMapServiceImageryProvider.ConstructorOptions} options
 * @param {Resource} tmsResource
 * @param {Resource} xmlResource
 * @returns {UrlTemplateImageryProvider.ConstructorOptions}
 */
TileMapServiceImageryProvider._metadataSuccess = function (
  xml,
  options,
  tmsResource,
  xmlResource,
  provider,
) {
  const tileFormatRegex = /tileformat/i;
  const tileSetRegex = /tileset/i;
  const tileSetsRegex = /tilesets/i;
  const bboxRegex = /boundingbox/i;
  let format, bbox, tilesets;
  const tilesetsList = []; //list of TileSets
 
  // Allowing options properties (already copied to that) to override XML values
 
  // Iterate XML Document nodes for properties
  const nodeList = xml.childNodes[0].childNodes;
  for (let i = 0; i < nodeList.length; i++) {
    if (tileFormatRegex.test(nodeList.item(i).nodeName)) {
      format = nodeList.item(i);
    } else if (tileSetsRegex.test(nodeList.item(i).nodeName)) {
      tilesets = nodeList.item(i); // Node list of TileSets
      const tileSetNodes = nodeList.item(i).childNodes;
      // Iterate the nodes to find all TileSets
      for (let j = 0; j < tileSetNodes.length; j++) {
        if (tileSetRegex.test(tileSetNodes.item(j).nodeName)) {
          // Add them to tilesets list
          tilesetsList.push(tileSetNodes.item(j));
        }
      }
    } else if (bboxRegex.test(nodeList.item(i).nodeName)) {
      bbox = nodeList.item(i);
    }
  }
 
  let message;
  if (!defined(tilesets) || !defined(bbox)) {
    message = `Unable to find expected tilesets or bbox attributes in ${xmlResource.url}.`;
    Iif (defined(provider)) {
      TileProviderError.reportError(
        undefined,
        provider,
        provider.errorEvent,
        message,
      );
    }
 
    throw new RuntimeError(message);
  }
 
  const fileExtension =
    options.fileExtension ?? format.getAttribute("extension");
  const tileWidth =
    options.tileWidth ?? parseInt(format.getAttribute("width"), 10);
  const tileHeight =
    options.tileHeight ?? parseInt(format.getAttribute("height"), 10);
  let minimumLevel =
    options.minimumLevel ?? parseInt(tilesetsList[0].getAttribute("order"), 10);
  const maximumLevel =
    options.maximumLevel ??
    parseInt(tilesetsList[tilesetsList.length - 1].getAttribute("order"), 10);
  const tilingSchemeName = tilesets.getAttribute("profile");
  let tilingScheme = options.tilingScheme;
 
  Eif (!defined(tilingScheme)) {
    if (
      tilingSchemeName === "geodetic" ||
      tilingSchemeName === "global-geodetic"
    ) {
      tilingScheme = new GeographicTilingScheme({
        ellipsoid: options.ellipsoid,
      });
    } else if (
      tilingSchemeName === "mercator" ||
      tilingSchemeName === "global-mercator"
    ) {
      tilingScheme = new WebMercatorTilingScheme({
        ellipsoid: options.ellipsoid,
      });
    } else {
      message = `${xmlResource.url} specifies an unsupported profile attribute, ${tilingSchemeName}.`;
      Iif (defined(provider)) {
        TileProviderError.reportError(
          undefined,
          provider,
          provider.errorEvent,
          message,
        );
      }
 
      throw new RuntimeError(message);
    }
  }
 
  // rectangle handling
  let rectangle = Rectangle.clone(options.rectangle);
 
  if (!defined(rectangle)) {
    let sw;
    let ne;
    let swXY;
    let neXY;
 
    // In older versions of gdal x and y values were flipped, which is why we check for an option to flip
    // the values here as well. Unfortunately there is no way to autodetect whether flipping is needed.
    const flipXY = options.flipXY ?? false;
    if (flipXY) {
      swXY = new Cartesian2(
        parseFloat(bbox.getAttribute("miny")),
        parseFloat(bbox.getAttribute("minx")),
      );
      neXY = new Cartesian2(
        parseFloat(bbox.getAttribute("maxy")),
        parseFloat(bbox.getAttribute("maxx")),
      );
    } else {
      swXY = new Cartesian2(
        parseFloat(bbox.getAttribute("minx")),
        parseFloat(bbox.getAttribute("miny")),
      );
      neXY = new Cartesian2(
        parseFloat(bbox.getAttribute("maxx")),
        parseFloat(bbox.getAttribute("maxy")),
      );
    }
 
    // Determine based on the profile attribute if this tileset was generated by gdal2tiles.py, which
    // uses 'mercator' and 'geodetic' profiles, or by a tool compliant with the TMS standard, which is
    // 'global-mercator' and 'global-geodetic' profiles. In the gdal2Tiles case, X and Y are always in
    // geodetic degrees.
    const isGdal2tiles =
      tilingSchemeName === "geodetic" || tilingSchemeName === "mercator";
    if (
      tilingScheme.projection instanceof GeographicProjection ||
      isGdal2tiles
    ) {
      sw = Cartographic.fromDegrees(swXY.x, swXY.y);
      ne = Cartographic.fromDegrees(neXY.x, neXY.y);
    } else {
      const projection = tilingScheme.projection;
      sw = projection.unproject(swXY);
      ne = projection.unproject(neXY);
    }
 
    rectangle = new Rectangle(
      sw.longitude,
      sw.latitude,
      ne.longitude,
      ne.latitude,
    );
  }
 
  // The rectangle must not be outside the bounds allowed by the tiling scheme.
  rectangle = confineRectangleToTilingScheme(rectangle, tilingScheme);
  // clamp our minimum detail level to something that isn't going to request a ridiculous number of tiles
  minimumLevel = calculateSafeMinimumDetailLevel(
    tilingScheme,
    rectangle,
    minimumLevel,
  );
 
  const templateResource = tmsResource.getDerivedResource({
    url: `{z}/{x}/{reverseY}.${fileExtension}`,
  });
 
  return {
    url: templateResource,
    tilingScheme: tilingScheme,
    rectangle: rectangle,
    tileWidth: tileWidth,
    tileHeight: tileHeight,
    minimumLevel: minimumLevel,
    maximumLevel: maximumLevel,
    tileDiscardPolicy: options.tileDiscardPolicy,
    credit: options.credit,
  };
};
 
/**
 * Handle xml request failure by providing the default values
 * @private
 *
 * @param {TileMapServiceImageryProvider.ConstructorOptions} options
 * @param {Resource} tmsResource
 * @returns {UrlTemplateImageryProvider.ConstructorOptions}
 */
TileMapServiceImageryProvider._metadataFailure = function (
  options,
  tmsResource,
) {
  // Can't load XML, still allow options and defaults
  const fileExtension = options.fileExtension ?? "png";
  const tileWidth = options.tileWidth ?? 256;
  const tileHeight = options.tileHeight ?? 256;
  const maximumLevel = options.maximumLevel;
  const tilingScheme = defined(options.tilingScheme)
    ? options.tilingScheme
    : new WebMercatorTilingScheme({ ellipsoid: options.ellipsoid });
 
  let rectangle = options.rectangle ?? tilingScheme.rectangle;
  // The rectangle must not be outside the bounds allowed by the tiling scheme.
  rectangle = confineRectangleToTilingScheme(rectangle, tilingScheme);
 
  // make sure we use a safe minimum detail level, so we don't request a ridiculous number of tiles
  const minimumLevel = calculateSafeMinimumDetailLevel(
    tilingScheme,
    rectangle,
    options.minimumLevel,
  );
 
  const templateResource = tmsResource.getDerivedResource({
    url: `{z}/{x}/{reverseY}.${fileExtension}`,
  });
 
  return {
    url: templateResource,
    tilingScheme: tilingScheme,
    rectangle: rectangle,
    tileWidth: tileWidth,
    tileHeight: tileHeight,
    minimumLevel: minimumLevel,
    maximumLevel: maximumLevel,
    tileDiscardPolicy: options.tileDiscardPolicy,
    credit: options.credit,
  };
};
 
export default TileMapServiceImageryProvider;