/**
* @license
* Cesium - https://github.com/CesiumGS/cesium
* Version 1.105
*
* Copyright 2011-2022 Cesium Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Columbus View (Pat. Pend.)
*
* Portions licensed separately.
* See https://github.com/CesiumGS/cesium/blob/main/LICENSE.md for full licensing details.
*/
var Cesium = (() => {
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
get: (a3, b) => (typeof require !== "undefined" ? require : a3)[b]
}) : x)(function(x) {
if (typeof require !== "undefined")
return require.apply(this, arguments);
throw new Error('Dynamic require of "' + x + '" is not supported');
});
var __commonJS = (cb, mod2) => function __require2() {
return mod2 || (0, cb[__getOwnPropNames(cb)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports;
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target,
mod2
));
var __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2);
// node_modules/mersenne-twister/src/mersenne-twister.js
var require_mersenne_twister = __commonJS({
"node_modules/mersenne-twister/src/mersenne-twister.js"(exports2, module2) {
var MersenneTwister4 = function(seed) {
if (seed == void 0) {
seed = (/* @__PURE__ */ new Date()).getTime();
}
this.N = 624;
this.M = 397;
this.MATRIX_A = 2567483615;
this.UPPER_MASK = 2147483648;
this.LOWER_MASK = 2147483647;
this.mt = new Array(this.N);
this.mti = this.N + 1;
if (seed.constructor == Array) {
this.init_by_array(seed, seed.length);
} else {
this.init_seed(seed);
}
};
MersenneTwister4.prototype.init_seed = function(s) {
this.mt[0] = s >>> 0;
for (this.mti = 1; this.mti < this.N; this.mti++) {
var s = this.mt[this.mti - 1] ^ this.mt[this.mti - 1] >>> 30;
this.mt[this.mti] = (((s & 4294901760) >>> 16) * 1812433253 << 16) + (s & 65535) * 1812433253 + this.mti;
this.mt[this.mti] >>>= 0;
}
};
MersenneTwister4.prototype.init_by_array = function(init_key, key_length) {
var i, j, k;
this.init_seed(19650218);
i = 1;
j = 0;
k = this.N > key_length ? this.N : key_length;
for (; k; k--) {
var s = this.mt[i - 1] ^ this.mt[i - 1] >>> 30;
this.mt[i] = (this.mt[i] ^ (((s & 4294901760) >>> 16) * 1664525 << 16) + (s & 65535) * 1664525) + init_key[j] + j;
this.mt[i] >>>= 0;
i++;
j++;
if (i >= this.N) {
this.mt[0] = this.mt[this.N - 1];
i = 1;
}
if (j >= key_length)
j = 0;
}
for (k = this.N - 1; k; k--) {
var s = this.mt[i - 1] ^ this.mt[i - 1] >>> 30;
this.mt[i] = (this.mt[i] ^ (((s & 4294901760) >>> 16) * 1566083941 << 16) + (s & 65535) * 1566083941) - i;
this.mt[i] >>>= 0;
i++;
if (i >= this.N) {
this.mt[0] = this.mt[this.N - 1];
i = 1;
}
}
this.mt[0] = 2147483648;
};
MersenneTwister4.prototype.random_int = function() {
var y;
var mag01 = new Array(0, this.MATRIX_A);
if (this.mti >= this.N) {
var kk;
if (this.mti == this.N + 1)
this.init_seed(5489);
for (kk = 0; kk < this.N - this.M; kk++) {
y = this.mt[kk] & this.UPPER_MASK | this.mt[kk + 1] & this.LOWER_MASK;
this.mt[kk] = this.mt[kk + this.M] ^ y >>> 1 ^ mag01[y & 1];
}
for (; kk < this.N - 1; kk++) {
y = this.mt[kk] & this.UPPER_MASK | this.mt[kk + 1] & this.LOWER_MASK;
this.mt[kk] = this.mt[kk + (this.M - this.N)] ^ y >>> 1 ^ mag01[y & 1];
}
y = this.mt[this.N - 1] & this.UPPER_MASK | this.mt[0] & this.LOWER_MASK;
this.mt[this.N - 1] = this.mt[this.M - 1] ^ y >>> 1 ^ mag01[y & 1];
this.mti = 0;
}
y = this.mt[this.mti++];
y ^= y >>> 11;
y ^= y << 7 & 2636928640;
y ^= y << 15 & 4022730752;
y ^= y >>> 18;
return y >>> 0;
};
MersenneTwister4.prototype.random_int31 = function() {
return this.random_int() >>> 1;
};
MersenneTwister4.prototype.random_incl = function() {
return this.random_int() * (1 / 4294967295);
};
MersenneTwister4.prototype.random = function() {
return this.random_int() * (1 / 4294967296);
};
MersenneTwister4.prototype.random_excl = function() {
return (this.random_int() + 0.5) * (1 / 4294967296);
};
MersenneTwister4.prototype.random_long = function() {
var a3 = this.random_int() >>> 5, b = this.random_int() >>> 6;
return (a3 * 67108864 + b) * (1 / 9007199254740992);
};
module2.exports = MersenneTwister4;
}
});
// node_modules/urijs/src/punycode.js
var require_punycode = __commonJS({
"node_modules/urijs/src/punycode.js"(exports2, module2) {
/*! https://mths.be/punycode v1.4.0 by @mathias */
(function(root) {
var freeExports = typeof exports2 == "object" && exports2 && !exports2.nodeType && exports2;
var freeModule = typeof module2 == "object" && module2 && !module2.nodeType && module2;
var freeGlobal = typeof global == "object" && global;
if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal || freeGlobal.self === freeGlobal) {
root = freeGlobal;
}
var punycode, maxInt = 2147483647, base = 36, tMin = 1, tMax = 26, skew = 38, damp = 700, initialBias = 72, initialN = 128, delimiter = "-", regexPunycode = /^xn--/, regexNonASCII = /[^\x20-\x7E]/, regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, errors = {
"overflow": "Overflow: input needs wider integers to process",
"not-basic": "Illegal input >= 0x80 (not a basic code point)",
"invalid-input": "Invalid input"
}, baseMinusTMin = base - tMin, floor = Math.floor, stringFromCharCode = String.fromCharCode, key;
function error(type) {
throw new RangeError(errors[type]);
}
function map(array, fn) {
var length3 = array.length;
var result = [];
while (length3--) {
result[length3] = fn(array[length3]);
}
return result;
}
function mapDomain(string, fn) {
var parts = string.split("@");
var result = "";
if (parts.length > 1) {
result = parts[0] + "@";
string = parts[1];
}
string = string.replace(regexSeparators, ".");
var labels = string.split(".");
var encoded = map(labels, fn).join(".");
return result + encoded;
}
function ucs2decode(string) {
var output = [], counter = 0, length3 = string.length, value, extra;
while (counter < length3) {
value = string.charCodeAt(counter++);
if (value >= 55296 && value <= 56319 && counter < length3) {
extra = string.charCodeAt(counter++);
if ((extra & 64512) == 56320) {
output.push(((value & 1023) << 10) + (extra & 1023) + 65536);
} else {
output.push(value);
counter--;
}
} else {
output.push(value);
}
}
return output;
}
function ucs2encode(array) {
return map(array, function(value) {
var output = "";
if (value > 65535) {
value -= 65536;
output += stringFromCharCode(value >>> 10 & 1023 | 55296);
value = 56320 | value & 1023;
}
output += stringFromCharCode(value);
return output;
}).join("");
}
function basicToDigit(codePoint) {
if (codePoint - 48 < 10) {
return codePoint - 22;
}
if (codePoint - 65 < 26) {
return codePoint - 65;
}
if (codePoint - 97 < 26) {
return codePoint - 97;
}
return base;
}
function digitToBasic(digit, flag) {
return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
}
function adapt(delta, numPoints, firstTime) {
var k = 0;
delta = firstTime ? floor(delta / damp) : delta >> 1;
delta += floor(delta / numPoints);
for (; delta > baseMinusTMin * tMax >> 1; k += base) {
delta = floor(delta / baseMinusTMin);
}
return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
}
function decode(input) {
var output = [], inputLength = input.length, out, i = 0, n = initialN, bias = initialBias, basic, j, index, oldi, w, k, digit, t, baseMinusT;
basic = input.lastIndexOf(delimiter);
if (basic < 0) {
basic = 0;
}
for (j = 0; j < basic; ++j) {
if (input.charCodeAt(j) >= 128) {
error("not-basic");
}
output.push(input.charCodeAt(j));
}
for (index = basic > 0 ? basic + 1 : 0; index < inputLength; ) {
for (oldi = i, w = 1, k = base; ; k += base) {
if (index >= inputLength) {
error("invalid-input");
}
digit = basicToDigit(input.charCodeAt(index++));
if (digit >= base || digit > floor((maxInt - i) / w)) {
error("overflow");
}
i += digit * w;
t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
if (digit < t) {
break;
}
baseMinusT = base - t;
if (w > floor(maxInt / baseMinusT)) {
error("overflow");
}
w *= baseMinusT;
}
out = output.length + 1;
bias = adapt(i - oldi, out, oldi == 0);
if (floor(i / out) > maxInt - n) {
error("overflow");
}
n += floor(i / out);
i %= out;
output.splice(i++, 0, n);
}
return ucs2encode(output);
}
function encode(input) {
var n, delta, handledCPCount, basicLength, bias, j, m, q, k, t, currentValue, output = [], inputLength, handledCPCountPlusOne, baseMinusT, qMinusT;
input = ucs2decode(input);
inputLength = input.length;
n = initialN;
delta = 0;
bias = initialBias;
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < 128) {
output.push(stringFromCharCode(currentValue));
}
}
handledCPCount = basicLength = output.length;
if (basicLength) {
output.push(delimiter);
}
while (handledCPCount < inputLength) {
for (m = maxInt, j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue >= n && currentValue < m) {
m = currentValue;
}
}
handledCPCountPlusOne = handledCPCount + 1;
if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
error("overflow");
}
delta += (m - n) * handledCPCountPlusOne;
n = m;
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < n && ++delta > maxInt) {
error("overflow");
}
if (currentValue == n) {
for (q = delta, k = base; ; k += base) {
t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
if (q < t) {
break;
}
qMinusT = q - t;
baseMinusT = base - t;
output.push(
stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
);
q = floor(qMinusT / baseMinusT);
}
output.push(stringFromCharCode(digitToBasic(q, 0)));
bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
delta = 0;
++handledCPCount;
}
}
++delta;
++n;
}
return output.join("");
}
function toUnicode(input) {
return mapDomain(input, function(string) {
return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string;
});
}
function toASCII(input) {
return mapDomain(input, function(string) {
return regexNonASCII.test(string) ? "xn--" + encode(string) : string;
});
}
punycode = {
/**
* A string representing the current Punycode.js version number.
* @memberOf punycode
* @type String
*/
"version": "1.3.2",
/**
* An object of methods to convert from JavaScript's internal character
* representation (UCS-2) to Unicode code points, and back.
* @see
* For best rendering performance, use the tightest possible bounding volume. Although
*
* When
* Draws the {@link DrawCommand#boundingVolume} for this command, assuming it is a sphere, when the command executes.
*
* Requires that the texture has a mipmap. The mip level is chosen by the view angle and screen-space size of the texture.
*
* Requires that the texture has a mipmap. The mip level is chosen by the view angle and screen-space size of the texture.
*
* This option provides a good balance of visual quality and speed when sampling from a mipmapped texture.
*
* Requires that the texture has a mipmap. The mip level is chosen by the view angle and screen-space size of the texture.
*
* This option provides a good balance of visual quality and speed when sampling from a mipmapped texture.
*
* Requires that the texture has a mipmap. The mip level is chosen by the view angle and screen-space size of the texture.
* \n * All color values (diffuse, specular, emissive) are in linear color space.\n * The conversion is described in\n * {@link http://content.gpwiki.org/index.php/D3DBook:High-Dynamic_Range_Rendering#Luminance_Transform|Luminance Transform}\n * The conversion is described in\n * {@link http://content.gpwiki.org/index.php/D3DBook:High-Dynamic_Range_Rendering#Luminance_Transform|Luminance Transform}\n * \n * This uses standard position attributes, \n * Use this version when passing in a custom pixel ratio. For example, passing in 1.0 will return meters per native device pixel.\n * \n * Use this version when scaling by pixel ratio.\n * \n * This function only handles the lighting calculations. Metallic/roughness\n * and specular/glossy must be handled separately. See {@czm_pbrMetallicRoughnessMaterial}, {@czm_pbrSpecularGlossinessMaterial} and {@czm_defaultPbrMaterial}\n * \n * The order of the coefficients is [L00, L1_1, L10, L11, L2_2, L2_1, L20, L21, L22].\n * \n * This technique, called GPU RTE, eliminates jittering artifacts when using large coordinates as\n * described in {@link http://help.agi.com/AGIComponents/html/BlogPrecisionsPrecisions.htm|Precisions, Precisions}.\n * \n * There are also precision limitations in WebGL 1. highp int is still limited\n * to 24 bits. Above the value of 2^24 = 16777216, precision loss may occur.\n * \n * An example use case for this function would be moving the vertex in window coordinates\n * before converting back to clip coordinates. Use the original vertex clip coordinates.\n * \n * Use this when the vertex shader does not call {@link czm_vertexlogDepth}, for example, when\n * ray-casting geometry using a full screen quad.\n * \n * Use this when the vertex shader calls {@link czm_vertexlogDepth}.\n *
* x
, y
, width
,
* and height
properties in an vec4
's x
, y
, z
,
* and w
components, respectively.
*
* @example
* // GLSL declaration
* uniform vec4 czm_viewport;
*
* // Scale the window coordinate components to [0, 1] by dividing
* // by the viewport's width and height.
* vec2 v = gl_FragCoord.xy / czm_viewport.zw;
*
* @see Context#getViewport
*/
czm_viewport: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_VEC4,
getValue: function(uniformState) {
return uniformState.viewportCartesian4;
}
}),
/**
* An automatic GLSL uniform representing a 4x4 orthographic projection matrix that
* transforms window coordinates to clip coordinates. Clip coordinates is the
* coordinate system for a vertex shader's gl_Position
output.
*
* This transform is useful when a vertex shader inputs or manipulates window coordinates
* as done by {@link BillboardCollection}.
*
* Do not confuse {@link czm_viewportTransformation} with czm_viewportOrthographic
.
* The former transforms from normalized device coordinates to window coordinates; the later transforms
* from window coordinates to clip coordinates, and is often used to assign to gl_Position
.
*
* @example
* // GLSL declaration
* uniform mat4 czm_viewportOrthographic;
*
* // Example
* gl_Position = czm_viewportOrthographic * vec4(windowPosition, 0.0, 1.0);
*
* @see UniformState#viewportOrthographic
* @see czm_viewport
* @see czm_viewportTransformation
* @see BillboardCollection
*/
czm_viewportOrthographic: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_MAT4,
getValue: function(uniformState) {
return uniformState.viewportOrthographic;
}
}),
/**
* An automatic GLSL uniform representing a 4x4 transformation matrix that
* transforms normalized device coordinates to window coordinates. The context's
* full viewport is used, and the depth range is assumed to be near = 0
* and far = 1
.
*
* This transform is useful when there is a need to manipulate window coordinates
* in a vertex shader as done by {@link BillboardCollection}. In many cases,
* this matrix will not be used directly; instead, {@link czm_modelToWindowCoordinates}
* will be used to transform directly from model to window coordinates.
*
* Do not confuse czm_viewportTransformation
with {@link czm_viewportOrthographic}.
* The former transforms from normalized device coordinates to window coordinates; the later transforms
* from window coordinates to clip coordinates, and is often used to assign to gl_Position
.
*
* @example
* // GLSL declaration
* uniform mat4 czm_viewportTransformation;
*
* // Use czm_viewportTransformation as part of the
* // transform from model to window coordinates.
* vec4 q = czm_modelViewProjection * positionMC; // model to clip coordinates
* q.xyz /= q.w; // clip to normalized device coordinates (ndc)
* q.xyz = (czm_viewportTransformation * vec4(q.xyz, 1.0)).xyz; // ndc to window coordinates
*
* @see UniformState#viewportTransformation
* @see czm_viewport
* @see czm_viewportOrthographic
* @see czm_modelToWindowCoordinates
* @see BillboardCollection
*/
czm_viewportTransformation: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_MAT4,
getValue: function(uniformState) {
return uniformState.viewportTransformation;
}
}),
/**
* An automatic GLSL uniform representing the depth of the scene
* after the globe pass and then updated after the 3D Tiles pass.
* The depth is packed into an RGBA texture.
*
* @example
* // GLSL declaration
* uniform sampler2D czm_globeDepthTexture;
*
* // Get the depth at the current fragment
* vec2 coords = gl_FragCoord.xy / czm_viewport.zw;
* float depth = czm_unpackDepth(texture(czm_globeDepthTexture, coords));
*/
czm_globeDepthTexture: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.SAMPLER_2D,
getValue: function(uniformState) {
return uniformState.globeDepthTexture;
}
}),
/**
* An automatic GLSL uniform representing a 4x4 model transformation matrix that
* transforms model coordinates to world coordinates.
*
* @example
* // GLSL declaration
* uniform mat4 czm_model;
*
* // Example
* vec4 worldPosition = czm_model * modelPosition;
*
* @see UniformState#model
* @see czm_inverseModel
* @see czm_modelView
* @see czm_modelViewProjection
*/
czm_model: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_MAT4,
getValue: function(uniformState) {
return uniformState.model;
}
}),
/**
* An automatic GLSL uniform representing a 4x4 model transformation matrix that
* transforms world coordinates to model coordinates.
*
* @example
* // GLSL declaration
* uniform mat4 czm_inverseModel;
*
* // Example
* vec4 modelPosition = czm_inverseModel * worldPosition;
*
* @see UniformState#inverseModel
* @see czm_model
* @see czm_inverseModelView
*/
czm_inverseModel: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_MAT4,
getValue: function(uniformState) {
return uniformState.inverseModel;
}
}),
/**
* An automatic GLSL uniform representing a 4x4 view transformation matrix that
* transforms world coordinates to eye coordinates.
*
* @example
* // GLSL declaration
* uniform mat4 czm_view;
*
* // Example
* vec4 eyePosition = czm_view * worldPosition;
*
* @see UniformState#view
* @see czm_viewRotation
* @see czm_modelView
* @see czm_viewProjection
* @see czm_modelViewProjection
* @see czm_inverseView
*/
czm_view: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_MAT4,
getValue: function(uniformState) {
return uniformState.view;
}
}),
/**
* An automatic GLSL uniform representing a 4x4 view transformation matrix that
* transforms 3D world coordinates to eye coordinates. In 3D mode, this is identical to
* {@link czm_view}, but in 2D and Columbus View it represents the view matrix
* as if the camera were at an equivalent location in 3D mode. This is useful for lighting
* 2D and Columbus View in the same way that 3D is lit.
*
* @example
* // GLSL declaration
* uniform mat4 czm_view3D;
*
* // Example
* vec4 eyePosition3D = czm_view3D * worldPosition3D;
*
* @see UniformState#view3D
* @see czm_view
*/
czm_view3D: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_MAT4,
getValue: function(uniformState) {
return uniformState.view3D;
}
}),
/**
* An automatic GLSL uniform representing a 3x3 view rotation matrix that
* transforms vectors in world coordinates to eye coordinates.
*
* @example
* // GLSL declaration
* uniform mat3 czm_viewRotation;
*
* // Example
* vec3 eyeVector = czm_viewRotation * worldVector;
*
* @see UniformState#viewRotation
* @see czm_view
* @see czm_inverseView
* @see czm_inverseViewRotation
*/
czm_viewRotation: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_MAT3,
getValue: function(uniformState) {
return uniformState.viewRotation;
}
}),
/**
* An automatic GLSL uniform representing a 3x3 view rotation matrix that
* transforms vectors in 3D world coordinates to eye coordinates. In 3D mode, this is identical to
* {@link czm_viewRotation}, but in 2D and Columbus View it represents the view matrix
* as if the camera were at an equivalent location in 3D mode. This is useful for lighting
* 2D and Columbus View in the same way that 3D is lit.
*
* @example
* // GLSL declaration
* uniform mat3 czm_viewRotation3D;
*
* // Example
* vec3 eyeVector = czm_viewRotation3D * worldVector;
*
* @see UniformState#viewRotation3D
* @see czm_viewRotation
*/
czm_viewRotation3D: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_MAT3,
getValue: function(uniformState) {
return uniformState.viewRotation3D;
}
}),
/**
* An automatic GLSL uniform representing a 4x4 transformation matrix that
* transforms from eye coordinates to world coordinates.
*
* @example
* // GLSL declaration
* uniform mat4 czm_inverseView;
*
* // Example
* vec4 worldPosition = czm_inverseView * eyePosition;
*
* @see UniformState#inverseView
* @see czm_view
* @see czm_inverseNormal
*/
czm_inverseView: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_MAT4,
getValue: function(uniformState) {
return uniformState.inverseView;
}
}),
/**
* An automatic GLSL uniform representing a 4x4 transformation matrix that
* transforms from 3D eye coordinates to world coordinates. In 3D mode, this is identical to
* {@link czm_inverseView}, but in 2D and Columbus View it represents the inverse view matrix
* as if the camera were at an equivalent location in 3D mode. This is useful for lighting
* 2D and Columbus View in the same way that 3D is lit.
*
* @example
* // GLSL declaration
* uniform mat4 czm_inverseView3D;
*
* // Example
* vec4 worldPosition = czm_inverseView3D * eyePosition;
*
* @see UniformState#inverseView3D
* @see czm_inverseView
*/
czm_inverseView3D: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_MAT4,
getValue: function(uniformState) {
return uniformState.inverseView3D;
}
}),
/**
* An automatic GLSL uniform representing a 3x3 rotation matrix that
* transforms vectors from eye coordinates to world coordinates.
*
* @example
* // GLSL declaration
* uniform mat3 czm_inverseViewRotation;
*
* // Example
* vec4 worldVector = czm_inverseViewRotation * eyeVector;
*
* @see UniformState#inverseView
* @see czm_view
* @see czm_viewRotation
* @see czm_inverseViewRotation
*/
czm_inverseViewRotation: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_MAT3,
getValue: function(uniformState) {
return uniformState.inverseViewRotation;
}
}),
/**
* An automatic GLSL uniform representing a 3x3 rotation matrix that
* transforms vectors from 3D eye coordinates to world coordinates. In 3D mode, this is identical to
* {@link czm_inverseViewRotation}, but in 2D and Columbus View it represents the inverse view matrix
* as if the camera were at an equivalent location in 3D mode. This is useful for lighting
* 2D and Columbus View in the same way that 3D is lit.
*
* @example
* // GLSL declaration
* uniform mat3 czm_inverseViewRotation3D;
*
* // Example
* vec4 worldVector = czm_inverseViewRotation3D * eyeVector;
*
* @see UniformState#inverseView3D
* @see czm_inverseViewRotation
*/
czm_inverseViewRotation3D: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_MAT3,
getValue: function(uniformState) {
return uniformState.inverseViewRotation3D;
}
}),
/**
* An automatic GLSL uniform representing a 4x4 projection transformation matrix that
* transforms eye coordinates to clip coordinates. Clip coordinates is the
* coordinate system for a vertex shader's gl_Position
output.
*
* @example
* // GLSL declaration
* uniform mat4 czm_projection;
*
* // Example
* gl_Position = czm_projection * eyePosition;
*
* @see UniformState#projection
* @see czm_viewProjection
* @see czm_modelViewProjection
* @see czm_infiniteProjection
*/
czm_projection: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_MAT4,
getValue: function(uniformState) {
return uniformState.projection;
}
}),
/**
* An automatic GLSL uniform representing a 4x4 inverse projection transformation matrix that
* transforms from clip coordinates to eye coordinates. Clip coordinates is the
* coordinate system for a vertex shader's gl_Position
output.
*
* @example
* // GLSL declaration
* uniform mat4 czm_inverseProjection;
*
* // Example
* vec4 eyePosition = czm_inverseProjection * clipPosition;
*
* @see UniformState#inverseProjection
* @see czm_projection
*/
czm_inverseProjection: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_MAT4,
getValue: function(uniformState) {
return uniformState.inverseProjection;
}
}),
/**
* An automatic GLSL uniform representing a 4x4 projection transformation matrix with the far plane at infinity,
* that transforms eye coordinates to clip coordinates. Clip coordinates is the
* coordinate system for a vertex shader's gl_Position
output. An infinite far plane is used
* in algorithms like shadow volumes and GPU ray casting with proxy geometry to ensure that triangles
* are not clipped by the far plane.
*
* @example
* // GLSL declaration
* uniform mat4 czm_infiniteProjection;
*
* // Example
* gl_Position = czm_infiniteProjection * eyePosition;
*
* @see UniformState#infiniteProjection
* @see czm_projection
* @see czm_modelViewInfiniteProjection
*/
czm_infiniteProjection: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_MAT4,
getValue: function(uniformState) {
return uniformState.infiniteProjection;
}
}),
/**
* An automatic GLSL uniform representing a 4x4 model-view transformation matrix that
* transforms model coordinates to eye coordinates.
*
* Positions should be transformed to eye coordinates using czm_modelView
and
* normals should be transformed using {@link czm_normal}.
*
* @example
* // GLSL declaration
* uniform mat4 czm_modelView;
*
* // Example
* vec4 eyePosition = czm_modelView * modelPosition;
*
* // The above is equivalent to, but more efficient than:
* vec4 eyePosition = czm_view * czm_model * modelPosition;
*
* @see UniformState#modelView
* @see czm_model
* @see czm_view
* @see czm_modelViewProjection
* @see czm_normal
*/
czm_modelView: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_MAT4,
getValue: function(uniformState) {
return uniformState.modelView;
}
}),
/**
* An automatic GLSL uniform representing a 4x4 model-view transformation matrix that
* transforms 3D model coordinates to eye coordinates. In 3D mode, this is identical to
* {@link czm_modelView}, but in 2D and Columbus View it represents the model-view matrix
* as if the camera were at an equivalent location in 3D mode. This is useful for lighting
* 2D and Columbus View in the same way that 3D is lit.
*
* Positions should be transformed to eye coordinates using czm_modelView3D
and
* normals should be transformed using {@link czm_normal3D}.
*
* @example
* // GLSL declaration
* uniform mat4 czm_modelView3D;
*
* // Example
* vec4 eyePosition = czm_modelView3D * modelPosition;
*
* // The above is equivalent to, but more efficient than:
* vec4 eyePosition = czm_view3D * czm_model * modelPosition;
*
* @see UniformState#modelView3D
* @see czm_modelView
*/
czm_modelView3D: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_MAT4,
getValue: function(uniformState) {
return uniformState.modelView3D;
}
}),
/**
* An automatic GLSL uniform representing a 4x4 model-view transformation matrix that
* transforms model coordinates, relative to the eye, to eye coordinates. This is used
* in conjunction with {@link czm_translateRelativeToEye}.
*
* @example
* // GLSL declaration
* uniform mat4 czm_modelViewRelativeToEye;
*
* // Example
* attribute vec3 positionHigh;
* attribute vec3 positionLow;
*
* void main()
* {
* vec4 p = czm_translateRelativeToEye(positionHigh, positionLow);
* gl_Position = czm_projection * (czm_modelViewRelativeToEye * p);
* }
*
* @see czm_modelViewProjectionRelativeToEye
* @see czm_translateRelativeToEye
* @see EncodedCartesian3
*/
czm_modelViewRelativeToEye: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_MAT4,
getValue: function(uniformState) {
return uniformState.modelViewRelativeToEye;
}
}),
/**
* An automatic GLSL uniform representing a 4x4 transformation matrix that
* transforms from eye coordinates to model coordinates.
*
* @example
* // GLSL declaration
* uniform mat4 czm_inverseModelView;
*
* // Example
* vec4 modelPosition = czm_inverseModelView * eyePosition;
*
* @see UniformState#inverseModelView
* @see czm_modelView
*/
czm_inverseModelView: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_MAT4,
getValue: function(uniformState) {
return uniformState.inverseModelView;
}
}),
/**
* An automatic GLSL uniform representing a 4x4 transformation matrix that
* transforms from eye coordinates to 3D model coordinates. In 3D mode, this is identical to
* {@link czm_inverseModelView}, but in 2D and Columbus View it represents the inverse model-view matrix
* as if the camera were at an equivalent location in 3D mode. This is useful for lighting
* 2D and Columbus View in the same way that 3D is lit.
*
* @example
* // GLSL declaration
* uniform mat4 czm_inverseModelView3D;
*
* // Example
* vec4 modelPosition = czm_inverseModelView3D * eyePosition;
*
* @see UniformState#inverseModelView
* @see czm_inverseModelView
* @see czm_modelView3D
*/
czm_inverseModelView3D: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_MAT4,
getValue: function(uniformState) {
return uniformState.inverseModelView3D;
}
}),
/**
* An automatic GLSL uniform representing a 4x4 view-projection transformation matrix that
* transforms world coordinates to clip coordinates. Clip coordinates is the
* coordinate system for a vertex shader's gl_Position
output.
*
* @example
* // GLSL declaration
* uniform mat4 czm_viewProjection;
*
* // Example
* vec4 gl_Position = czm_viewProjection * czm_model * modelPosition;
*
* // The above is equivalent to, but more efficient than:
* gl_Position = czm_projection * czm_view * czm_model * modelPosition;
*
* @see UniformState#viewProjection
* @see czm_view
* @see czm_projection
* @see czm_modelViewProjection
* @see czm_inverseViewProjection
*/
czm_viewProjection: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_MAT4,
getValue: function(uniformState) {
return uniformState.viewProjection;
}
}),
/**
* An automatic GLSL uniform representing a 4x4 view-projection transformation matrix that
* transforms clip coordinates to world coordinates. Clip coordinates is the
* coordinate system for a vertex shader's gl_Position
output.
*
* @example
* // GLSL declaration
* uniform mat4 czm_inverseViewProjection;
*
* // Example
* vec4 worldPosition = czm_inverseViewProjection * clipPosition;
*
* @see UniformState#inverseViewProjection
* @see czm_viewProjection
*/
czm_inverseViewProjection: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_MAT4,
getValue: function(uniformState) {
return uniformState.inverseViewProjection;
}
}),
/**
* An automatic GLSL uniform representing a 4x4 model-view-projection transformation matrix that
* transforms model coordinates to clip coordinates. Clip coordinates is the
* coordinate system for a vertex shader's gl_Position
output.
*
* @example
* // GLSL declaration
* uniform mat4 czm_modelViewProjection;
*
* // Example
* vec4 gl_Position = czm_modelViewProjection * modelPosition;
*
* // The above is equivalent to, but more efficient than:
* gl_Position = czm_projection * czm_view * czm_model * modelPosition;
*
* @see UniformState#modelViewProjection
* @see czm_model
* @see czm_view
* @see czm_projection
* @see czm_modelView
* @see czm_viewProjection
* @see czm_modelViewInfiniteProjection
* @see czm_inverseModelViewProjection
*/
czm_modelViewProjection: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_MAT4,
getValue: function(uniformState) {
return uniformState.modelViewProjection;
}
}),
/**
* An automatic GLSL uniform representing a 4x4 inverse model-view-projection transformation matrix that
* transforms clip coordinates to model coordinates. Clip coordinates is the
* coordinate system for a vertex shader's gl_Position
output.
*
* @example
* // GLSL declaration
* uniform mat4 czm_inverseModelViewProjection;
*
* // Example
* vec4 modelPosition = czm_inverseModelViewProjection * clipPosition;
*
* @see UniformState#modelViewProjection
* @see czm_modelViewProjection
*/
czm_inverseModelViewProjection: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_MAT4,
getValue: function(uniformState) {
return uniformState.inverseModelViewProjection;
}
}),
/**
* An automatic GLSL uniform representing a 4x4 model-view-projection transformation matrix that
* transforms model coordinates, relative to the eye, to clip coordinates. Clip coordinates is the
* coordinate system for a vertex shader's gl_Position
output. This is used in
* conjunction with {@link czm_translateRelativeToEye}.
*
* @example
* // GLSL declaration
* uniform mat4 czm_modelViewProjectionRelativeToEye;
*
* // Example
* attribute vec3 positionHigh;
* attribute vec3 positionLow;
*
* void main()
* {
* vec4 p = czm_translateRelativeToEye(positionHigh, positionLow);
* gl_Position = czm_modelViewProjectionRelativeToEye * p;
* }
*
* @see czm_modelViewRelativeToEye
* @see czm_translateRelativeToEye
* @see EncodedCartesian3
*/
czm_modelViewProjectionRelativeToEye: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_MAT4,
getValue: function(uniformState) {
return uniformState.modelViewProjectionRelativeToEye;
}
}),
/**
* An automatic GLSL uniform representing a 4x4 model-view-projection transformation matrix that
* transforms model coordinates to clip coordinates. Clip coordinates is the
* coordinate system for a vertex shader's gl_Position
output. The projection matrix places
* the far plane at infinity. This is useful in algorithms like shadow volumes and GPU ray casting with
* proxy geometry to ensure that triangles are not clipped by the far plane.
*
* @example
* // GLSL declaration
* uniform mat4 czm_modelViewInfiniteProjection;
*
* // Example
* vec4 gl_Position = czm_modelViewInfiniteProjection * modelPosition;
*
* // The above is equivalent to, but more efficient than:
* gl_Position = czm_infiniteProjection * czm_view * czm_model * modelPosition;
*
* @see UniformState#modelViewInfiniteProjection
* @see czm_model
* @see czm_view
* @see czm_infiniteProjection
* @see czm_modelViewProjection
*/
czm_modelViewInfiniteProjection: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_MAT4,
getValue: function(uniformState) {
return uniformState.modelViewInfiniteProjection;
}
}),
/**
* An automatic GLSL uniform that indicates if the current camera is orthographic in 3D.
*
* @see UniformState#orthographicIn3D
*/
czm_orthographicIn3D: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT,
getValue: function(uniformState) {
return uniformState.orthographicIn3D ? 1 : 0;
}
}),
/**
* An automatic GLSL uniform representing a 3x3 normal transformation matrix that
* transforms normal vectors in model coordinates to eye coordinates.
*
* Positions should be transformed to eye coordinates using {@link czm_modelView} and
* normals should be transformed using czm_normal
.
*
* @example
* // GLSL declaration
* uniform mat3 czm_normal;
*
* // Example
* vec3 eyeNormal = czm_normal * normal;
*
* @see UniformState#normal
* @see czm_inverseNormal
* @see czm_modelView
*/
czm_normal: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_MAT3,
getValue: function(uniformState) {
return uniformState.normal;
}
}),
/**
* An automatic GLSL uniform representing a 3x3 normal transformation matrix that
* transforms normal vectors in 3D model coordinates to eye coordinates.
* In 3D mode, this is identical to
* {@link czm_normal}, but in 2D and Columbus View it represents the normal transformation
* matrix as if the camera were at an equivalent location in 3D mode. This is useful for lighting
* 2D and Columbus View in the same way that 3D is lit.
*
* Positions should be transformed to eye coordinates using {@link czm_modelView3D} and
* normals should be transformed using czm_normal3D
.
*
* @example
* // GLSL declaration
* uniform mat3 czm_normal3D;
*
* // Example
* vec3 eyeNormal = czm_normal3D * normal;
*
* @see UniformState#normal3D
* @see czm_normal
*/
czm_normal3D: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_MAT3,
getValue: function(uniformState) {
return uniformState.normal3D;
}
}),
/**
* An automatic GLSL uniform representing a 3x3 normal transformation matrix that
* transforms normal vectors in eye coordinates to model coordinates. This is
* the opposite of the transform provided by {@link czm_normal}.
*
* @example
* // GLSL declaration
* uniform mat3 czm_inverseNormal;
*
* // Example
* vec3 normalMC = czm_inverseNormal * normalEC;
*
* @see UniformState#inverseNormal
* @see czm_normal
* @see czm_modelView
* @see czm_inverseView
*/
czm_inverseNormal: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_MAT3,
getValue: function(uniformState) {
return uniformState.inverseNormal;
}
}),
/**
* An automatic GLSL uniform representing a 3x3 normal transformation matrix that
* transforms normal vectors in eye coordinates to 3D model coordinates. This is
* the opposite of the transform provided by {@link czm_normal}.
* In 3D mode, this is identical to
* {@link czm_inverseNormal}, but in 2D and Columbus View it represents the inverse normal transformation
* matrix as if the camera were at an equivalent location in 3D mode. This is useful for lighting
* 2D and Columbus View in the same way that 3D is lit.
*
* @example
* // GLSL declaration
* uniform mat3 czm_inverseNormal3D;
*
* // Example
* vec3 normalMC = czm_inverseNormal3D * normalEC;
*
* @see UniformState#inverseNormal3D
* @see czm_inverseNormal
*/
czm_inverseNormal3D: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_MAT3,
getValue: function(uniformState) {
return uniformState.inverseNormal3D;
}
}),
/**
* An automatic GLSL uniform containing the height in meters of the
* eye (camera) above or below the ellipsoid.
*
* @see UniformState#eyeHeight
*/
czm_eyeHeight: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT,
getValue: function(uniformState) {
return uniformState.eyeHeight;
}
}),
/**
* An automatic GLSL uniform containing height (x
) and height squared (y
)
* in meters of the eye (camera) above the 2D world plane. This uniform is only valid
* when the {@link SceneMode} is SCENE2D
.
*
* @see UniformState#eyeHeight2D
*/
czm_eyeHeight2D: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_VEC2,
getValue: function(uniformState) {
return uniformState.eyeHeight2D;
}
}),
/**
* An automatic GLSL uniform containing the near distance (x
) and the far distance (y
)
* of the frustum defined by the camera. This is the largest possible frustum, not an individual
* frustum used for multi-frustum rendering.
*
* @example
* // GLSL declaration
* uniform vec2 czm_entireFrustum;
*
* // Example
* float frustumLength = czm_entireFrustum.y - czm_entireFrustum.x;
*
* @see UniformState#entireFrustum
* @see czm_currentFrustum
*/
czm_entireFrustum: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_VEC2,
getValue: function(uniformState) {
return uniformState.entireFrustum;
}
}),
/**
* An automatic GLSL uniform containing the near distance (x
) and the far distance (y
)
* of the frustum defined by the camera. This is the individual
* frustum used for multi-frustum rendering.
*
* @example
* // GLSL declaration
* uniform vec2 czm_currentFrustum;
*
* // Example
* float frustumLength = czm_currentFrustum.y - czm_currentFrustum.x;
*
* @see UniformState#currentFrustum
* @see czm_entireFrustum
*/
czm_currentFrustum: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_VEC2,
getValue: function(uniformState) {
return uniformState.currentFrustum;
}
}),
/**
* The distances to the frustum planes. The top, bottom, left and right distances are
* the x, y, z, and w components, respectively.
*/
czm_frustumPlanes: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_VEC4,
getValue: function(uniformState) {
return uniformState.frustumPlanes;
}
}),
/**
* Gets the far plane's distance from the near plane, plus 1.0.
*/
czm_farDepthFromNearPlusOne: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT,
getValue: function(uniformState) {
return uniformState.farDepthFromNearPlusOne;
}
}),
/**
* Gets the log2 of {@link AutomaticUniforms#czm_farDepthFromNearPlusOne}.
*/
czm_log2FarDepthFromNearPlusOne: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT,
getValue: function(uniformState) {
return uniformState.log2FarDepthFromNearPlusOne;
}
}),
/**
* Gets 1.0 divided by {@link AutomaticUniforms#czm_log2FarDepthFromNearPlusOne}.
*/
czm_oneOverLog2FarDepthFromNearPlusOne: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT,
getValue: function(uniformState) {
return uniformState.oneOverLog2FarDepthFromNearPlusOne;
}
}),
/**
* An automatic GLSL uniform representing the sun position in world coordinates.
*
* @example
* // GLSL declaration
* uniform vec3 czm_sunPositionWC;
*
* @see UniformState#sunPositionWC
* @see czm_sunPositionColumbusView
* @see czm_sunDirectionWC
*/
czm_sunPositionWC: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_VEC3,
getValue: function(uniformState) {
return uniformState.sunPositionWC;
}
}),
/**
* An automatic GLSL uniform representing the sun position in Columbus view world coordinates.
*
* @example
* // GLSL declaration
* uniform vec3 czm_sunPositionColumbusView;
*
* @see UniformState#sunPositionColumbusView
* @see czm_sunPositionWC
*/
czm_sunPositionColumbusView: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_VEC3,
getValue: function(uniformState) {
return uniformState.sunPositionColumbusView;
}
}),
/**
* An automatic GLSL uniform representing the normalized direction to the sun in eye coordinates.
*
* @example
* // GLSL declaration
* uniform vec3 czm_sunDirectionEC;
*
* // Example
* float diffuse = max(dot(czm_sunDirectionEC, normalEC), 0.0);
*
* @see UniformState#sunDirectionEC
* @see czm_moonDirectionEC
* @see czm_sunDirectionWC
*/
czm_sunDirectionEC: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_VEC3,
getValue: function(uniformState) {
return uniformState.sunDirectionEC;
}
}),
/**
* An automatic GLSL uniform representing the normalized direction to the sun in world coordinates.
*
* @example
* // GLSL declaration
* uniform vec3 czm_sunDirectionWC;
*
* // Example
* float diffuse = max(dot(czm_sunDirectionWC, normalWC), 0.0);
*
* @see UniformState#sunDirectionWC
* @see czm_sunPositionWC
* @see czm_sunDirectionEC
*/
czm_sunDirectionWC: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_VEC3,
getValue: function(uniformState) {
return uniformState.sunDirectionWC;
}
}),
/**
* An automatic GLSL uniform representing the normalized direction to the moon in eye coordinates.
*
* @example
* // GLSL declaration
* uniform vec3 czm_moonDirectionEC;
*
* // Example
* float diffuse = max(dot(czm_moonDirectionEC, normalEC), 0.0);
*
* @see UniformState#moonDirectionEC
* @see czm_sunDirectionEC
*/
czm_moonDirectionEC: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_VEC3,
getValue: function(uniformState) {
return uniformState.moonDirectionEC;
}
}),
/**
* An automatic GLSL uniform representing the normalized direction to the scene's light source in eye coordinates.
* This is commonly used for directional lighting computations.
*
* @example
* // GLSL declaration
* uniform vec3 czm_lightDirectionEC;
*
* // Example
* float diffuse = max(dot(czm_lightDirectionEC, normalEC), 0.0);
*
* @see UniformState#lightDirectionEC
* @see czm_lightDirectionWC
*/
czm_lightDirectionEC: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_VEC3,
getValue: function(uniformState) {
return uniformState.lightDirectionEC;
}
}),
/**
* An automatic GLSL uniform representing the normalized direction to the scene's light source in world coordinates.
* This is commonly used for directional lighting computations.
*
* @example
* // GLSL declaration
* uniform vec3 czm_lightDirectionWC;
*
* // Example
* float diffuse = max(dot(czm_lightDirectionWC, normalWC), 0.0);
*
* @see UniformState#lightDirectionWC
* @see czm_lightDirectionEC
*/
czm_lightDirectionWC: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_VEC3,
getValue: function(uniformState) {
return uniformState.lightDirectionWC;
}
}),
/**
* An automatic GLSL uniform that represents the color of light emitted by the scene's light source. This
* is equivalent to the light color multiplied by the light intensity limited to a maximum luminance of 1.0
* suitable for non-HDR lighting.
*
* @example
* // GLSL declaration
* uniform vec3 czm_lightColor;
*
* // Example
* vec3 diffuseColor = czm_lightColor * max(dot(czm_lightDirectionWC, normalWC), 0.0);
*
* @see UniformState#lightColor
* @see czm_lightColorHdr
*/
czm_lightColor: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_VEC3,
getValue: function(uniformState) {
return uniformState.lightColor;
}
}),
/**
* An automatic GLSL uniform that represents the high dynamic range color of light emitted by the scene's light
* source. This is equivalent to the light color multiplied by the light intensity suitable for HDR lighting.
*
* @example
* // GLSL declaration
* uniform vec3 czm_lightColorHdr;
*
* // Example
* vec3 diffuseColor = czm_lightColorHdr * max(dot(czm_lightDirectionWC, normalWC), 0.0);
*
* @see UniformState#lightColorHdr
* @see czm_lightColor
*/
czm_lightColorHdr: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_VEC3,
getValue: function(uniformState) {
return uniformState.lightColorHdr;
}
}),
/**
* An automatic GLSL uniform representing the high bits of the camera position in model
* coordinates. This is used for GPU RTE to eliminate jittering artifacts when rendering
* as described in {@link http://help.agi.com/AGIComponents/html/BlogPrecisionsPrecisions.htm|Precisions, Precisions}.
*
* @example
* // GLSL declaration
* uniform vec3 czm_encodedCameraPositionMCHigh;
*
* @see czm_encodedCameraPositionMCLow
* @see czm_modelViewRelativeToEye
* @see czm_modelViewProjectionRelativeToEye
*/
czm_encodedCameraPositionMCHigh: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_VEC3,
getValue: function(uniformState) {
return uniformState.encodedCameraPositionMCHigh;
}
}),
/**
* An automatic GLSL uniform representing the low bits of the camera position in model
* coordinates. This is used for GPU RTE to eliminate jittering artifacts when rendering
* as described in {@linkhttp://help.agi.com/AGIComponents/html/BlogPrecisionsPrecisions.htm|Precisions, Precisions}.
*
* @example
* // GLSL declaration
* uniform vec3 czm_encodedCameraPositionMCLow;
*
* @see czm_encodedCameraPositionMCHigh
* @see czm_modelViewRelativeToEye
* @see czm_modelViewProjectionRelativeToEye
*/
czm_encodedCameraPositionMCLow: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_VEC3,
getValue: function(uniformState) {
return uniformState.encodedCameraPositionMCLow;
}
}),
/**
* An automatic GLSL uniform representing the position of the viewer (camera) in world coordinates.
*
* @example
* // GLSL declaration
* uniform vec3 czm_viewerPositionWC;
*/
czm_viewerPositionWC: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_VEC3,
getValue: function(uniformState) {
return Matrix4_default.getTranslation(
uniformState.inverseView,
viewerPositionWCScratch
);
}
}),
/**
* An automatic GLSL uniform representing the frame number. This uniform is automatically incremented
* every frame.
*
* @example
* // GLSL declaration
* uniform float czm_frameNumber;
*/
czm_frameNumber: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT,
getValue: function(uniformState) {
return uniformState.frameState.frameNumber;
}
}),
/**
* An automatic GLSL uniform representing the current morph transition time between
* 2D/Columbus View and 3D, with 0.0 being 2D or Columbus View and 1.0 being 3D.
*
* @example
* // GLSL declaration
* uniform float czm_morphTime;
*
* // Example
* vec4 p = czm_columbusViewMorph(position2D, position3D, czm_morphTime);
*/
czm_morphTime: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT,
getValue: function(uniformState) {
return uniformState.frameState.morphTime;
}
}),
/**
* An automatic GLSL uniform representing the current {@link SceneMode}, expressed
* as a float.
*
* @example
* // GLSL declaration
* uniform float czm_sceneMode;
*
* // Example
* if (czm_sceneMode == czm_sceneMode2D)
* {
* eyeHeightSq = czm_eyeHeight2D.y;
* }
*
* @see czm_sceneMode2D
* @see czm_sceneModeColumbusView
* @see czm_sceneMode3D
* @see czm_sceneModeMorphing
*/
czm_sceneMode: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT,
getValue: function(uniformState) {
return uniformState.frameState.mode;
}
}),
/**
* An automatic GLSL uniform representing the current rendering pass.
*
* @example
* // GLSL declaration
* uniform float czm_pass;
*
* // Example
* if ((czm_pass == czm_passTranslucent) && isOpaque())
* {
* gl_Position *= 0.0; // Cull opaque geometry in the translucent pass
* }
*/
czm_pass: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT,
getValue: function(uniformState) {
return uniformState.pass;
}
}),
/**
* An automatic GLSL uniform representing the current scene background color.
*
* @example
* // GLSL declaration
* uniform vec4 czm_backgroundColor;
*
* // Example: If the given color's RGB matches the background color, invert it.
* vec4 adjustColorForContrast(vec4 color)
* {
* if (czm_backgroundColor.rgb == color.rgb)
* {
* color.rgb = vec3(1.0) - color.rgb;
* }
*
* return color;
* }
*/
czm_backgroundColor: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_VEC4,
getValue: function(uniformState) {
return uniformState.backgroundColor;
}
}),
/**
* An automatic GLSL uniform containing the BRDF look up texture used for image-based lighting computations.
*
* @example
* // GLSL declaration
* uniform sampler2D czm_brdfLut;
*
* // Example: For a given roughness and NdotV value, find the material's BRDF information in the red and green channels
* float roughness = 0.5;
* float NdotV = dot(normal, view);
* vec2 brdfLut = texture(czm_brdfLut, vec2(NdotV, 1.0 - roughness)).rg;
*/
czm_brdfLut: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.SAMPLER_2D,
getValue: function(uniformState) {
return uniformState.brdfLut;
}
}),
/**
* An automatic GLSL uniform containing the environment map used within the scene.
*
* @example
* // GLSL declaration
* uniform samplerCube czm_environmentMap;
*
* // Example: Create a perfect reflection of the environment map on a model
* float reflected = reflect(view, normal);
* vec4 reflectedColor = texture(czm_environmentMap, reflected);
*/
czm_environmentMap: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.SAMPLER_CUBE,
getValue: function(uniformState) {
return uniformState.environmentMap;
}
}),
/**
* An automatic GLSL uniform containing the specular environment map atlas used within the scene.
*
* @example
* // GLSL declaration
* uniform sampler2D czm_specularEnvironmentMaps;
*/
czm_specularEnvironmentMaps: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.SAMPLER_2D,
getValue: function(uniformState) {
return uniformState.specularEnvironmentMaps;
}
}),
/**
* An automatic GLSL uniform containing the size of the specular environment map atlas used within the scene.
*
* @example
* // GLSL declaration
* uniform vec2 czm_specularEnvironmentMapSize;
*/
czm_specularEnvironmentMapSize: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_VEC2,
getValue: function(uniformState) {
return uniformState.specularEnvironmentMapsDimensions;
}
}),
/**
* An automatic GLSL uniform containing the maximum level-of-detail of the specular environment map atlas used within the scene.
*
* @example
* // GLSL declaration
* uniform float czm_specularEnvironmentMapsMaximumLOD;
*/
czm_specularEnvironmentMapsMaximumLOD: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT,
getValue: function(uniformState) {
return uniformState.specularEnvironmentMapsMaximumLOD;
}
}),
/**
* An automatic GLSL uniform containing the spherical harmonic coefficients used within the scene.
*
* @example
* // GLSL declaration
* uniform vec3[9] czm_sphericalHarmonicCoefficients;
*/
czm_sphericalHarmonicCoefficients: new AutomaticUniform({
size: 9,
datatype: WebGLConstants_default.FLOAT_VEC3,
getValue: function(uniformState) {
return uniformState.sphericalHarmonicCoefficients;
}
}),
/**
* An automatic GLSL uniform representing a 3x3 rotation matrix that transforms
* from True Equator Mean Equinox (TEME) axes to the pseudo-fixed axes at the current scene time.
*
* @example
* // GLSL declaration
* uniform mat3 czm_temeToPseudoFixed;
*
* // Example
* vec3 pseudoFixed = czm_temeToPseudoFixed * teme;
*
* @see UniformState#temeToPseudoFixedMatrix
* @see Transforms.computeTemeToPseudoFixedMatrix
*/
czm_temeToPseudoFixed: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_MAT3,
getValue: function(uniformState) {
return uniformState.temeToPseudoFixedMatrix;
}
}),
/**
* An automatic GLSL uniform representing the ratio of canvas coordinate space to canvas pixel space.
*
* @example
* uniform float czm_pixelRatio;
*/
czm_pixelRatio: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT,
getValue: function(uniformState) {
return uniformState.pixelRatio;
}
}),
/**
* An automatic GLSL uniform scalar used to mix a color with the fog color based on the distance to the camera.
*
* @see czm_fog
*/
czm_fogDensity: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT,
getValue: function(uniformState) {
return uniformState.fogDensity;
}
}),
/**
* An automatic GLSL uniform representing the splitter position to use when rendering with a splitter.
* This will be in pixel coordinates relative to the canvas.
*
* @example
* // GLSL declaration
* uniform float czm_splitPosition;
*/
czm_splitPosition: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT,
getValue: function(uniformState) {
return uniformState.splitPosition;
}
}),
/**
* An automatic GLSL uniform scalar representing the geometric tolerance per meter
*/
czm_geometricToleranceOverMeter: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT,
getValue: function(uniformState) {
return uniformState.geometricToleranceOverMeter;
}
}),
/**
* An automatic GLSL uniform representing the distance from the camera at which to disable the depth test of billboards, labels and points
* to, for example, prevent clipping against terrain. When set to zero, the depth test should always be applied. When less than zero,
* the depth test should never be applied.
*/
czm_minimumDisableDepthTestDistance: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT,
getValue: function(uniformState) {
return uniformState.minimumDisableDepthTestDistance;
}
}),
/**
* An automatic GLSL uniform that will be the highlight color of unclassified 3D Tiles.
*/
czm_invertClassificationColor: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_VEC4,
getValue: function(uniformState) {
return uniformState.invertClassificationColor;
}
}),
/**
* An automatic GLSL uniform that is used for gamma correction.
*/
czm_gamma: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT,
getValue: function(uniformState) {
return uniformState.gamma;
}
}),
/**
* An automatic GLSL uniform that stores the ellipsoid radii.
*/
czm_ellipsoidRadii: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_VEC3,
getValue: function(uniformState) {
return uniformState.ellipsoid.radii;
}
}),
/**
* An automatic GLSL uniform that stores the ellipsoid inverse radii.
*/
czm_ellipsoidInverseRadii: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_VEC3,
getValue: function(uniformState) {
return uniformState.ellipsoid.oneOverRadii;
}
})
};
var AutomaticUniforms_default = AutomaticUniforms;
// packages/engine/Source/Core/createGuid.js
function createGuid() {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
const r = Math.random() * 16 | 0;
const v7 = c === "x" ? r : r & 3 | 8;
return v7.toString(16);
});
}
var createGuid_default = createGuid;
// packages/engine/Source/Core/destroyObject.js
function returnTrue() {
return true;
}
function destroyObject(object2, message) {
message = defaultValue_default(
message,
"This object was destroyed, i.e., destroy() was called."
);
function throwOnDestroyed() {
throw new DeveloperError_default(message);
}
for (const key in object2) {
if (typeof object2[key] === "function") {
object2[key] = throwOnDestroyed;
}
}
object2.isDestroyed = returnTrue;
return void 0;
}
var destroyObject_default = destroyObject;
// packages/engine/Source/Core/IndexDatatype.js
var IndexDatatype = {
/**
* 8-bit unsigned byte corresponding to UNSIGNED_BYTE
and the type
* of an element in Uint8Array
.
*
* @type {number}
* @constant
*/
UNSIGNED_BYTE: WebGLConstants_default.UNSIGNED_BYTE,
/**
* 16-bit unsigned short corresponding to UNSIGNED_SHORT
and the type
* of an element in Uint16Array
.
*
* @type {number}
* @constant
*/
UNSIGNED_SHORT: WebGLConstants_default.UNSIGNED_SHORT,
/**
* 32-bit unsigned int corresponding to UNSIGNED_INT
and the type
* of an element in Uint32Array
.
*
* @type {number}
* @constant
*/
UNSIGNED_INT: WebGLConstants_default.UNSIGNED_INT
};
IndexDatatype.getSizeInBytes = function(indexDatatype) {
switch (indexDatatype) {
case IndexDatatype.UNSIGNED_BYTE:
return Uint8Array.BYTES_PER_ELEMENT;
case IndexDatatype.UNSIGNED_SHORT:
return Uint16Array.BYTES_PER_ELEMENT;
case IndexDatatype.UNSIGNED_INT:
return Uint32Array.BYTES_PER_ELEMENT;
}
throw new DeveloperError_default(
"indexDatatype is required and must be a valid IndexDatatype constant."
);
};
IndexDatatype.fromSizeInBytes = function(sizeInBytes) {
switch (sizeInBytes) {
case 2:
return IndexDatatype.UNSIGNED_SHORT;
case 4:
return IndexDatatype.UNSIGNED_INT;
case 1:
return IndexDatatype.UNSIGNED_BYTE;
default:
throw new DeveloperError_default(
"Size in bytes cannot be mapped to an IndexDatatype"
);
}
};
IndexDatatype.validate = function(indexDatatype) {
return defined_default(indexDatatype) && (indexDatatype === IndexDatatype.UNSIGNED_BYTE || indexDatatype === IndexDatatype.UNSIGNED_SHORT || indexDatatype === IndexDatatype.UNSIGNED_INT);
};
IndexDatatype.createTypedArray = function(numberOfVertices, indicesLengthOrArray) {
if (!defined_default(numberOfVertices)) {
throw new DeveloperError_default("numberOfVertices is required.");
}
if (numberOfVertices >= Math_default.SIXTY_FOUR_KILOBYTES) {
return new Uint32Array(indicesLengthOrArray);
}
return new Uint16Array(indicesLengthOrArray);
};
IndexDatatype.createTypedArrayFromArrayBuffer = function(numberOfVertices, sourceArray, byteOffset, length3) {
if (!defined_default(numberOfVertices)) {
throw new DeveloperError_default("numberOfVertices is required.");
}
if (!defined_default(sourceArray)) {
throw new DeveloperError_default("sourceArray is required.");
}
if (!defined_default(byteOffset)) {
throw new DeveloperError_default("byteOffset is required.");
}
if (numberOfVertices >= Math_default.SIXTY_FOUR_KILOBYTES) {
return new Uint32Array(sourceArray, byteOffset, length3);
}
return new Uint16Array(sourceArray, byteOffset, length3);
};
IndexDatatype.fromTypedArray = function(array) {
if (array instanceof Uint8Array) {
return IndexDatatype.UNSIGNED_BYTE;
}
if (array instanceof Uint16Array) {
return IndexDatatype.UNSIGNED_SHORT;
}
if (array instanceof Uint32Array) {
return IndexDatatype.UNSIGNED_INT;
}
throw new DeveloperError_default(
"array must be a Uint8Array, Uint16Array, or Uint32Array."
);
};
var IndexDatatype_default = Object.freeze(IndexDatatype);
// packages/engine/Source/Renderer/BufferUsage.js
var BufferUsage = {
STREAM_DRAW: WebGLConstants_default.STREAM_DRAW,
STATIC_DRAW: WebGLConstants_default.STATIC_DRAW,
DYNAMIC_DRAW: WebGLConstants_default.DYNAMIC_DRAW,
validate: function(bufferUsage) {
return bufferUsage === BufferUsage.STREAM_DRAW || bufferUsage === BufferUsage.STATIC_DRAW || bufferUsage === BufferUsage.DYNAMIC_DRAW;
}
};
var BufferUsage_default = Object.freeze(BufferUsage);
// packages/engine/Source/Renderer/Buffer.js
function Buffer2(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
Check_default.defined("options.context", options.context);
if (!defined_default(options.typedArray) && !defined_default(options.sizeInBytes)) {
throw new DeveloperError_default(
"Either options.sizeInBytes or options.typedArray is required."
);
}
if (defined_default(options.typedArray) && defined_default(options.sizeInBytes)) {
throw new DeveloperError_default(
"Cannot pass in both options.sizeInBytes and options.typedArray."
);
}
if (defined_default(options.typedArray)) {
Check_default.typeOf.object("options.typedArray", options.typedArray);
Check_default.typeOf.number(
"options.typedArray.byteLength",
options.typedArray.byteLength
);
}
if (!BufferUsage_default.validate(options.usage)) {
throw new DeveloperError_default("usage is invalid.");
}
const gl = options.context._gl;
const bufferTarget = options.bufferTarget;
const typedArray = options.typedArray;
let sizeInBytes = options.sizeInBytes;
const usage = options.usage;
const hasArray = defined_default(typedArray);
if (hasArray) {
sizeInBytes = typedArray.byteLength;
}
Check_default.typeOf.number.greaterThan("sizeInBytes", sizeInBytes, 0);
const buffer = gl.createBuffer();
gl.bindBuffer(bufferTarget, buffer);
gl.bufferData(bufferTarget, hasArray ? typedArray : sizeInBytes, usage);
gl.bindBuffer(bufferTarget, null);
this._id = createGuid_default();
this._gl = gl;
this._webgl2 = options.context._webgl2;
this._bufferTarget = bufferTarget;
this._sizeInBytes = sizeInBytes;
this._usage = usage;
this._buffer = buffer;
this.vertexArrayDestroyable = true;
}
Buffer2.createVertexBuffer = function(options) {
Check_default.defined("options.context", options.context);
return new Buffer2({
context: options.context,
bufferTarget: WebGLConstants_default.ARRAY_BUFFER,
typedArray: options.typedArray,
sizeInBytes: options.sizeInBytes,
usage: options.usage
});
};
Buffer2.createIndexBuffer = function(options) {
Check_default.defined("options.context", options.context);
if (!IndexDatatype_default.validate(options.indexDatatype)) {
throw new DeveloperError_default("Invalid indexDatatype.");
}
if (options.indexDatatype === IndexDatatype_default.UNSIGNED_INT && !options.context.elementIndexUint) {
throw new DeveloperError_default(
"IndexDatatype.UNSIGNED_INT requires OES_element_index_uint, which is not supported on this system. Check context.elementIndexUint."
);
}
const context = options.context;
const indexDatatype = options.indexDatatype;
const bytesPerIndex = IndexDatatype_default.getSizeInBytes(indexDatatype);
const buffer = new Buffer2({
context,
bufferTarget: WebGLConstants_default.ELEMENT_ARRAY_BUFFER,
typedArray: options.typedArray,
sizeInBytes: options.sizeInBytes,
usage: options.usage
});
const numberOfIndices = buffer.sizeInBytes / bytesPerIndex;
Object.defineProperties(buffer, {
indexDatatype: {
get: function() {
return indexDatatype;
}
},
bytesPerIndex: {
get: function() {
return bytesPerIndex;
}
},
numberOfIndices: {
get: function() {
return numberOfIndices;
}
}
});
return buffer;
};
Object.defineProperties(Buffer2.prototype, {
sizeInBytes: {
get: function() {
return this._sizeInBytes;
}
},
usage: {
get: function() {
return this._usage;
}
}
});
Buffer2.prototype._getBuffer = function() {
return this._buffer;
};
Buffer2.prototype.copyFromArrayView = function(arrayView, offsetInBytes) {
offsetInBytes = defaultValue_default(offsetInBytes, 0);
Check_default.defined("arrayView", arrayView);
Check_default.typeOf.number.lessThanOrEquals(
"offsetInBytes + arrayView.byteLength",
offsetInBytes + arrayView.byteLength,
this._sizeInBytes
);
const gl = this._gl;
const target = this._bufferTarget;
gl.bindBuffer(target, this._buffer);
gl.bufferSubData(target, offsetInBytes, arrayView);
gl.bindBuffer(target, null);
};
Buffer2.prototype.copyFromBuffer = function(readBuffer, readOffset, writeOffset, sizeInBytes) {
if (!this._webgl2) {
throw new DeveloperError_default("A WebGL 2 context is required.");
}
if (!defined_default(readBuffer)) {
throw new DeveloperError_default("readBuffer must be defined.");
}
if (!defined_default(sizeInBytes) || sizeInBytes <= 0) {
throw new DeveloperError_default(
"sizeInBytes must be defined and be greater than zero."
);
}
if (!defined_default(readOffset) || readOffset < 0 || readOffset + sizeInBytes > readBuffer._sizeInBytes) {
throw new DeveloperError_default(
"readOffset must be greater than or equal to zero and readOffset + sizeInBytes must be less than of equal to readBuffer.sizeInBytes."
);
}
if (!defined_default(writeOffset) || writeOffset < 0 || writeOffset + sizeInBytes > this._sizeInBytes) {
throw new DeveloperError_default(
"writeOffset must be greater than or equal to zero and writeOffset + sizeInBytes must be less than of equal to this.sizeInBytes."
);
}
if (this._buffer === readBuffer._buffer && (writeOffset >= readOffset && writeOffset < readOffset + sizeInBytes || readOffset > writeOffset && readOffset < writeOffset + sizeInBytes)) {
throw new DeveloperError_default(
"When readBuffer is equal to this, the ranges [readOffset + sizeInBytes) and [writeOffset, writeOffset + sizeInBytes) must not overlap."
);
}
if (this._bufferTarget === WebGLConstants_default.ELEMENT_ARRAY_BUFFER && readBuffer._bufferTarget !== WebGLConstants_default.ELEMENT_ARRAY_BUFFER || this._bufferTarget !== WebGLConstants_default.ELEMENT_ARRAY_BUFFER && readBuffer._bufferTarget === WebGLConstants_default.ELEMENT_ARRAY_BUFFER) {
throw new DeveloperError_default(
"Can not copy an index buffer into another buffer type."
);
}
const readTarget = WebGLConstants_default.COPY_READ_BUFFER;
const writeTarget = WebGLConstants_default.COPY_WRITE_BUFFER;
const gl = this._gl;
gl.bindBuffer(writeTarget, this._buffer);
gl.bindBuffer(readTarget, readBuffer._buffer);
gl.copyBufferSubData(
readTarget,
writeTarget,
readOffset,
writeOffset,
sizeInBytes
);
gl.bindBuffer(writeTarget, null);
gl.bindBuffer(readTarget, null);
};
Buffer2.prototype.getBufferData = function(arrayView, sourceOffset, destinationOffset, length3) {
sourceOffset = defaultValue_default(sourceOffset, 0);
destinationOffset = defaultValue_default(destinationOffset, 0);
if (!this._webgl2) {
throw new DeveloperError_default("A WebGL 2 context is required.");
}
if (!defined_default(arrayView)) {
throw new DeveloperError_default("arrayView is required.");
}
let copyLength;
let elementSize;
let arrayLength = arrayView.byteLength;
if (!defined_default(length3)) {
if (defined_default(arrayLength)) {
copyLength = arrayLength - destinationOffset;
elementSize = 1;
} else {
arrayLength = arrayView.length;
copyLength = arrayLength - destinationOffset;
elementSize = arrayView.BYTES_PER_ELEMENT;
}
} else {
copyLength = length3;
if (defined_default(arrayLength)) {
elementSize = 1;
} else {
arrayLength = arrayView.length;
elementSize = arrayView.BYTES_PER_ELEMENT;
}
}
if (destinationOffset < 0 || destinationOffset > arrayLength) {
throw new DeveloperError_default(
"destinationOffset must be greater than zero and less than the arrayView length."
);
}
if (destinationOffset + copyLength > arrayLength) {
throw new DeveloperError_default(
"destinationOffset + length must be less than or equal to the arrayViewLength."
);
}
if (sourceOffset < 0 || sourceOffset > this._sizeInBytes) {
throw new DeveloperError_default(
"sourceOffset must be greater than zero and less than the buffers size."
);
}
if (sourceOffset + copyLength * elementSize > this._sizeInBytes) {
throw new DeveloperError_default(
"sourceOffset + length must be less than the buffers size."
);
}
const gl = this._gl;
const target = WebGLConstants_default.COPY_READ_BUFFER;
gl.bindBuffer(target, this._buffer);
gl.getBufferSubData(
target,
sourceOffset,
arrayView,
destinationOffset,
length3
);
gl.bindBuffer(target, null);
};
Buffer2.prototype.isDestroyed = function() {
return false;
};
Buffer2.prototype.destroy = function() {
this._gl.deleteBuffer(this._buffer);
return destroyObject_default(this);
};
var Buffer_default = Buffer2;
// packages/engine/Source/Core/Fullscreen.js
var _supportsFullscreen;
var _names = {
requestFullscreen: void 0,
exitFullscreen: void 0,
fullscreenEnabled: void 0,
fullscreenElement: void 0,
fullscreenchange: void 0,
fullscreenerror: void 0
};
var Fullscreen = {};
Object.defineProperties(Fullscreen, {
/**
* The element that is currently fullscreen, if any. To simply check if the
* browser is in fullscreen mode or not, use {@link Fullscreen#fullscreen}.
* @memberof Fullscreen
* @type {object}
* @readonly
*/
element: {
get: function() {
if (!Fullscreen.supportsFullscreen()) {
return void 0;
}
return document[_names.fullscreenElement];
}
},
/**
* The name of the event on the document that is fired when fullscreen is
* entered or exited. This event name is intended for use with addEventListener.
* In your event handler, to determine if the browser is in fullscreen mode or not,
* use {@link Fullscreen#fullscreen}.
* @memberof Fullscreen
* @type {string}
* @readonly
*/
changeEventName: {
get: function() {
if (!Fullscreen.supportsFullscreen()) {
return void 0;
}
return _names.fullscreenchange;
}
},
/**
* The name of the event that is fired when a fullscreen error
* occurs. This event name is intended for use with addEventListener.
* @memberof Fullscreen
* @type {string}
* @readonly
*/
errorEventName: {
get: function() {
if (!Fullscreen.supportsFullscreen()) {
return void 0;
}
return _names.fullscreenerror;
}
},
/**
* Determine whether the browser will allow an element to be made fullscreen, or not.
* For example, by default, iframes cannot go fullscreen unless the containing page
* adds an "allowfullscreen" attribute (or prefixed equivalent).
* @memberof Fullscreen
* @type {boolean}
* @readonly
*/
enabled: {
get: function() {
if (!Fullscreen.supportsFullscreen()) {
return void 0;
}
return document[_names.fullscreenEnabled];
}
},
/**
* Determines if the browser is currently in fullscreen mode.
* @memberof Fullscreen
* @type {boolean}
* @readonly
*/
fullscreen: {
get: function() {
if (!Fullscreen.supportsFullscreen()) {
return void 0;
}
return Fullscreen.element !== null;
}
}
});
Fullscreen.supportsFullscreen = function() {
if (defined_default(_supportsFullscreen)) {
return _supportsFullscreen;
}
_supportsFullscreen = false;
const body = document.body;
if (typeof body.requestFullscreen === "function") {
_names.requestFullscreen = "requestFullscreen";
_names.exitFullscreen = "exitFullscreen";
_names.fullscreenEnabled = "fullscreenEnabled";
_names.fullscreenElement = "fullscreenElement";
_names.fullscreenchange = "fullscreenchange";
_names.fullscreenerror = "fullscreenerror";
_supportsFullscreen = true;
return _supportsFullscreen;
}
const prefixes = ["webkit", "moz", "o", "ms", "khtml"];
let name;
for (let i = 0, len = prefixes.length; i < len; ++i) {
const prefix = prefixes[i];
name = `${prefix}RequestFullscreen`;
if (typeof body[name] === "function") {
_names.requestFullscreen = name;
_supportsFullscreen = true;
} else {
name = `${prefix}RequestFullScreen`;
if (typeof body[name] === "function") {
_names.requestFullscreen = name;
_supportsFullscreen = true;
}
}
name = `${prefix}ExitFullscreen`;
if (typeof document[name] === "function") {
_names.exitFullscreen = name;
} else {
name = `${prefix}CancelFullScreen`;
if (typeof document[name] === "function") {
_names.exitFullscreen = name;
}
}
name = `${prefix}FullscreenEnabled`;
if (document[name] !== void 0) {
_names.fullscreenEnabled = name;
} else {
name = `${prefix}FullScreenEnabled`;
if (document[name] !== void 0) {
_names.fullscreenEnabled = name;
}
}
name = `${prefix}FullscreenElement`;
if (document[name] !== void 0) {
_names.fullscreenElement = name;
} else {
name = `${prefix}FullScreenElement`;
if (document[name] !== void 0) {
_names.fullscreenElement = name;
}
}
name = `${prefix}fullscreenchange`;
if (document[`on${name}`] !== void 0) {
if (prefix === "ms") {
name = "MSFullscreenChange";
}
_names.fullscreenchange = name;
}
name = `${prefix}fullscreenerror`;
if (document[`on${name}`] !== void 0) {
if (prefix === "ms") {
name = "MSFullscreenError";
}
_names.fullscreenerror = name;
}
}
return _supportsFullscreen;
};
Fullscreen.requestFullscreen = function(element, vrDevice) {
if (!Fullscreen.supportsFullscreen()) {
return;
}
element[_names.requestFullscreen]({ vrDisplay: vrDevice });
};
Fullscreen.exitFullscreen = function() {
if (!Fullscreen.supportsFullscreen()) {
return;
}
document[_names.exitFullscreen]();
};
Fullscreen._names = _names;
var Fullscreen_default = Fullscreen;
// packages/engine/Source/Core/FeatureDetection.js
var theNavigator;
if (typeof navigator !== "undefined") {
theNavigator = navigator;
} else {
theNavigator = {};
}
function extractVersion(versionString) {
const parts = versionString.split(".");
for (let i = 0, len = parts.length; i < len; ++i) {
parts[i] = parseInt(parts[i], 10);
}
return parts;
}
var isChromeResult;
var chromeVersionResult;
function isChrome() {
if (!defined_default(isChromeResult)) {
isChromeResult = false;
if (!isEdge()) {
const fields = / Chrome\/([\.0-9]+)/.exec(theNavigator.userAgent);
if (fields !== null) {
isChromeResult = true;
chromeVersionResult = extractVersion(fields[1]);
}
}
}
return isChromeResult;
}
function chromeVersion() {
return isChrome() && chromeVersionResult;
}
var isSafariResult;
var safariVersionResult;
function isSafari() {
if (!defined_default(isSafariResult)) {
isSafariResult = false;
if (!isChrome() && !isEdge() && / Safari\/[\.0-9]+/.test(theNavigator.userAgent)) {
const fields = / Version\/([\.0-9]+)/.exec(theNavigator.userAgent);
if (fields !== null) {
isSafariResult = true;
safariVersionResult = extractVersion(fields[1]);
}
}
}
return isSafariResult;
}
function safariVersion() {
return isSafari() && safariVersionResult;
}
var isWebkitResult;
var webkitVersionResult;
function isWebkit() {
if (!defined_default(isWebkitResult)) {
isWebkitResult = false;
const fields = / AppleWebKit\/([\.0-9]+)(\+?)/.exec(theNavigator.userAgent);
if (fields !== null) {
isWebkitResult = true;
webkitVersionResult = extractVersion(fields[1]);
webkitVersionResult.isNightly = !!fields[2];
}
}
return isWebkitResult;
}
function webkitVersion() {
return isWebkit() && webkitVersionResult;
}
var isInternetExplorerResult;
var internetExplorerVersionResult;
function isInternetExplorer() {
if (!defined_default(isInternetExplorerResult)) {
isInternetExplorerResult = false;
let fields;
if (theNavigator.appName === "Microsoft Internet Explorer") {
fields = /MSIE ([0-9]{1,}[\.0-9]{0,})/.exec(theNavigator.userAgent);
if (fields !== null) {
isInternetExplorerResult = true;
internetExplorerVersionResult = extractVersion(fields[1]);
}
} else if (theNavigator.appName === "Netscape") {
fields = /Trident\/.*rv:([0-9]{1,}[\.0-9]{0,})/.exec(
theNavigator.userAgent
);
if (fields !== null) {
isInternetExplorerResult = true;
internetExplorerVersionResult = extractVersion(fields[1]);
}
}
}
return isInternetExplorerResult;
}
function internetExplorerVersion() {
return isInternetExplorer() && internetExplorerVersionResult;
}
var isEdgeResult;
var edgeVersionResult;
function isEdge() {
if (!defined_default(isEdgeResult)) {
isEdgeResult = false;
const fields = / Edg\/([\.0-9]+)/.exec(theNavigator.userAgent);
if (fields !== null) {
isEdgeResult = true;
edgeVersionResult = extractVersion(fields[1]);
}
}
return isEdgeResult;
}
function edgeVersion() {
return isEdge() && edgeVersionResult;
}
var isFirefoxResult;
var firefoxVersionResult;
function isFirefox() {
if (!defined_default(isFirefoxResult)) {
isFirefoxResult = false;
const fields = /Firefox\/([\.0-9]+)/.exec(theNavigator.userAgent);
if (fields !== null) {
isFirefoxResult = true;
firefoxVersionResult = extractVersion(fields[1]);
}
}
return isFirefoxResult;
}
var isWindowsResult;
function isWindows() {
if (!defined_default(isWindowsResult)) {
isWindowsResult = /Windows/i.test(theNavigator.appVersion);
}
return isWindowsResult;
}
var isIPadOrIOSResult;
function isIPadOrIOS() {
if (!defined_default(isIPadOrIOSResult)) {
isIPadOrIOSResult = navigator.platform === "iPhone" || navigator.platform === "iPod" || navigator.platform === "iPad";
}
return isIPadOrIOSResult;
}
function firefoxVersion() {
return isFirefox() && firefoxVersionResult;
}
var hasPointerEvents;
function supportsPointerEvents() {
if (!defined_default(hasPointerEvents)) {
hasPointerEvents = !isFirefox() && typeof PointerEvent !== "undefined" && (!defined_default(theNavigator.pointerEnabled) || theNavigator.pointerEnabled);
}
return hasPointerEvents;
}
var imageRenderingValueResult;
var supportsImageRenderingPixelatedResult;
function supportsImageRenderingPixelated() {
if (!defined_default(supportsImageRenderingPixelatedResult)) {
const canvas = document.createElement("canvas");
canvas.setAttribute(
"style",
"image-rendering: -moz-crisp-edges;image-rendering: pixelated;"
);
const tmp2 = canvas.style.imageRendering;
supportsImageRenderingPixelatedResult = defined_default(tmp2) && tmp2 !== "";
if (supportsImageRenderingPixelatedResult) {
imageRenderingValueResult = tmp2;
}
}
return supportsImageRenderingPixelatedResult;
}
function imageRenderingValue() {
return supportsImageRenderingPixelated() ? imageRenderingValueResult : void 0;
}
function supportsWebP() {
if (!supportsWebP.initialized) {
throw new DeveloperError_default(
"You must call FeatureDetection.supportsWebP.initialize and wait for the promise to resolve before calling FeatureDetection.supportsWebP"
);
}
return supportsWebP._result;
}
supportsWebP._promise = void 0;
supportsWebP._result = void 0;
supportsWebP.initialize = function() {
if (defined_default(supportsWebP._promise)) {
return supportsWebP._promise;
}
supportsWebP._promise = new Promise((resolve2) => {
const image = new Image();
image.onload = function() {
supportsWebP._result = image.width > 0 && image.height > 0;
resolve2(supportsWebP._result);
};
image.onerror = function() {
supportsWebP._result = false;
resolve2(supportsWebP._result);
};
image.src = "data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA";
});
return supportsWebP._promise;
};
Object.defineProperties(supportsWebP, {
initialized: {
get: function() {
return defined_default(supportsWebP._result);
}
}
});
var typedArrayTypes = [];
if (typeof ArrayBuffer !== "undefined") {
typedArrayTypes.push(
Int8Array,
Uint8Array,
Int16Array,
Uint16Array,
Int32Array,
Uint32Array,
Float32Array,
Float64Array
);
if (typeof Uint8ClampedArray !== "undefined") {
typedArrayTypes.push(Uint8ClampedArray);
}
if (typeof Uint8ClampedArray !== "undefined") {
typedArrayTypes.push(Uint8ClampedArray);
}
if (typeof BigInt64Array !== "undefined") {
typedArrayTypes.push(BigInt64Array);
}
if (typeof BigUint64Array !== "undefined") {
typedArrayTypes.push(BigUint64Array);
}
}
var FeatureDetection = {
isChrome,
chromeVersion,
isSafari,
safariVersion,
isWebkit,
webkitVersion,
isInternetExplorer,
internetExplorerVersion,
isEdge,
edgeVersion,
isFirefox,
firefoxVersion,
isWindows,
isIPadOrIOS,
hardwareConcurrency: defaultValue_default(theNavigator.hardwareConcurrency, 3),
supportsPointerEvents,
supportsImageRenderingPixelated,
supportsWebP,
imageRenderingValue,
typedArrayTypes
};
FeatureDetection.supportsBasis = function(scene) {
return FeatureDetection.supportsWebAssembly() && scene.context.supportsBasis;
};
FeatureDetection.supportsFullscreen = function() {
return Fullscreen_default.supportsFullscreen();
};
FeatureDetection.supportsTypedArrays = function() {
return typeof ArrayBuffer !== "undefined";
};
FeatureDetection.supportsBigInt64Array = function() {
return typeof BigInt64Array !== "undefined";
};
FeatureDetection.supportsBigUint64Array = function() {
return typeof BigUint64Array !== "undefined";
};
FeatureDetection.supportsBigInt = function() {
return typeof BigInt !== "undefined";
};
FeatureDetection.supportsWebWorkers = function() {
return typeof Worker !== "undefined";
};
FeatureDetection.supportsWebAssembly = function() {
return typeof WebAssembly !== "undefined";
};
FeatureDetection.supportsWebgl2 = function(scene) {
Check_default.defined("scene", scene);
return scene.context.webgl2;
};
var FeatureDetection_default = FeatureDetection;
// packages/engine/Source/Core/Color.js
function hue2rgb(m1, m2, h) {
if (h < 0) {
h += 1;
}
if (h > 1) {
h -= 1;
}
if (h * 6 < 1) {
return m1 + (m2 - m1) * 6 * h;
}
if (h * 2 < 1) {
return m2;
}
if (h * 3 < 2) {
return m1 + (m2 - m1) * (2 / 3 - h) * 6;
}
return m1;
}
function Color(red, green, blue, alpha) {
this.red = defaultValue_default(red, 1);
this.green = defaultValue_default(green, 1);
this.blue = defaultValue_default(blue, 1);
this.alpha = defaultValue_default(alpha, 1);
}
Color.fromCartesian4 = function(cartesian11, result) {
Check_default.typeOf.object("cartesian", cartesian11);
if (!defined_default(result)) {
return new Color(cartesian11.x, cartesian11.y, cartesian11.z, cartesian11.w);
}
result.red = cartesian11.x;
result.green = cartesian11.y;
result.blue = cartesian11.z;
result.alpha = cartesian11.w;
return result;
};
Color.fromBytes = function(red, green, blue, alpha, result) {
red = Color.byteToFloat(defaultValue_default(red, 255));
green = Color.byteToFloat(defaultValue_default(green, 255));
blue = Color.byteToFloat(defaultValue_default(blue, 255));
alpha = Color.byteToFloat(defaultValue_default(alpha, 255));
if (!defined_default(result)) {
return new Color(red, green, blue, alpha);
}
result.red = red;
result.green = green;
result.blue = blue;
result.alpha = alpha;
return result;
};
Color.fromAlpha = function(color, alpha, result) {
Check_default.typeOf.object("color", color);
Check_default.typeOf.number("alpha", alpha);
if (!defined_default(result)) {
return new Color(color.red, color.green, color.blue, alpha);
}
result.red = color.red;
result.green = color.green;
result.blue = color.blue;
result.alpha = alpha;
return result;
};
var scratchArrayBuffer;
var scratchUint32Array;
var scratchUint8Array;
if (FeatureDetection_default.supportsTypedArrays()) {
scratchArrayBuffer = new ArrayBuffer(4);
scratchUint32Array = new Uint32Array(scratchArrayBuffer);
scratchUint8Array = new Uint8Array(scratchArrayBuffer);
}
Color.fromRgba = function(rgba, result) {
scratchUint32Array[0] = rgba;
return Color.fromBytes(
scratchUint8Array[0],
scratchUint8Array[1],
scratchUint8Array[2],
scratchUint8Array[3],
result
);
};
Color.fromHsl = function(hue, saturation, lightness, alpha, result) {
hue = defaultValue_default(hue, 0) % 1;
saturation = defaultValue_default(saturation, 0);
lightness = defaultValue_default(lightness, 0);
alpha = defaultValue_default(alpha, 1);
let red = lightness;
let green = lightness;
let blue = lightness;
if (saturation !== 0) {
let m2;
if (lightness < 0.5) {
m2 = lightness * (1 + saturation);
} else {
m2 = lightness + saturation - lightness * saturation;
}
const m1 = 2 * lightness - m2;
red = hue2rgb(m1, m2, hue + 1 / 3);
green = hue2rgb(m1, m2, hue);
blue = hue2rgb(m1, m2, hue - 1 / 3);
}
if (!defined_default(result)) {
return new Color(red, green, blue, alpha);
}
result.red = red;
result.green = green;
result.blue = blue;
result.alpha = alpha;
return result;
};
Color.fromRandom = function(options, result) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
let red = options.red;
if (!defined_default(red)) {
const minimumRed = defaultValue_default(options.minimumRed, 0);
const maximumRed = defaultValue_default(options.maximumRed, 1);
Check_default.typeOf.number.lessThanOrEquals("minimumRed", minimumRed, maximumRed);
red = minimumRed + Math_default.nextRandomNumber() * (maximumRed - minimumRed);
}
let green = options.green;
if (!defined_default(green)) {
const minimumGreen = defaultValue_default(options.minimumGreen, 0);
const maximumGreen = defaultValue_default(options.maximumGreen, 1);
Check_default.typeOf.number.lessThanOrEquals(
"minimumGreen",
minimumGreen,
maximumGreen
);
green = minimumGreen + Math_default.nextRandomNumber() * (maximumGreen - minimumGreen);
}
let blue = options.blue;
if (!defined_default(blue)) {
const minimumBlue = defaultValue_default(options.minimumBlue, 0);
const maximumBlue = defaultValue_default(options.maximumBlue, 1);
Check_default.typeOf.number.lessThanOrEquals(
"minimumBlue",
minimumBlue,
maximumBlue
);
blue = minimumBlue + Math_default.nextRandomNumber() * (maximumBlue - minimumBlue);
}
let alpha = options.alpha;
if (!defined_default(alpha)) {
const minimumAlpha = defaultValue_default(options.minimumAlpha, 0);
const maximumAlpha = defaultValue_default(options.maximumAlpha, 1);
Check_default.typeOf.number.lessThanOrEquals(
"minumumAlpha",
minimumAlpha,
maximumAlpha
);
alpha = minimumAlpha + Math_default.nextRandomNumber() * (maximumAlpha - minimumAlpha);
}
if (!defined_default(result)) {
return new Color(red, green, blue, alpha);
}
result.red = red;
result.green = green;
result.blue = blue;
result.alpha = alpha;
return result;
};
var rgbaMatcher = /^#([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])?$/i;
var rrggbbaaMatcher = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})?$/i;
var rgbParenthesesMatcher = /^rgba?\(\s*([0-9.]+%?)\s*,\s*([0-9.]+%?)\s*,\s*([0-9.]+%?)(?:\s*,\s*([0-9.]+))?\s*\)$/i;
var hslParenthesesMatcher = /^hsla?\(\s*([0-9.]+)\s*,\s*([0-9.]+%)\s*,\s*([0-9.]+%)(?:\s*,\s*([0-9.]+))?\s*\)$/i;
Color.fromCssColorString = function(color, result) {
Check_default.typeOf.string("color", color);
if (!defined_default(result)) {
result = new Color();
}
color = color.replace(/\s/g, "");
const namedColor = Color[color.toUpperCase()];
if (defined_default(namedColor)) {
Color.clone(namedColor, result);
return result;
}
let matches = rgbaMatcher.exec(color);
if (matches !== null) {
result.red = parseInt(matches[1], 16) / 15;
result.green = parseInt(matches[2], 16) / 15;
result.blue = parseInt(matches[3], 16) / 15;
result.alpha = parseInt(defaultValue_default(matches[4], "f"), 16) / 15;
return result;
}
matches = rrggbbaaMatcher.exec(color);
if (matches !== null) {
result.red = parseInt(matches[1], 16) / 255;
result.green = parseInt(matches[2], 16) / 255;
result.blue = parseInt(matches[3], 16) / 255;
result.alpha = parseInt(defaultValue_default(matches[4], "ff"), 16) / 255;
return result;
}
matches = rgbParenthesesMatcher.exec(color);
if (matches !== null) {
result.red = parseFloat(matches[1]) / ("%" === matches[1].substr(-1) ? 100 : 255);
result.green = parseFloat(matches[2]) / ("%" === matches[2].substr(-1) ? 100 : 255);
result.blue = parseFloat(matches[3]) / ("%" === matches[3].substr(-1) ? 100 : 255);
result.alpha = parseFloat(defaultValue_default(matches[4], "1.0"));
return result;
}
matches = hslParenthesesMatcher.exec(color);
if (matches !== null) {
return Color.fromHsl(
parseFloat(matches[1]) / 360,
parseFloat(matches[2]) / 100,
parseFloat(matches[3]) / 100,
parseFloat(defaultValue_default(matches[4], "1.0")),
result
);
}
result = void 0;
return result;
};
Color.packedLength = 4;
Color.pack = function(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
array[startingIndex++] = value.red;
array[startingIndex++] = value.green;
array[startingIndex++] = value.blue;
array[startingIndex] = value.alpha;
return array;
};
Color.unpack = function(array, startingIndex, result) {
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
if (!defined_default(result)) {
result = new Color();
}
result.red = array[startingIndex++];
result.green = array[startingIndex++];
result.blue = array[startingIndex++];
result.alpha = array[startingIndex];
return result;
};
Color.byteToFloat = function(number) {
return number / 255;
};
Color.floatToByte = function(number) {
return number === 1 ? 255 : number * 256 | 0;
};
Color.clone = function(color, result) {
if (!defined_default(color)) {
return void 0;
}
if (!defined_default(result)) {
return new Color(color.red, color.green, color.blue, color.alpha);
}
result.red = color.red;
result.green = color.green;
result.blue = color.blue;
result.alpha = color.alpha;
return result;
};
Color.equals = function(left, right) {
return left === right || //
defined_default(left) && //
defined_default(right) && //
left.red === right.red && //
left.green === right.green && //
left.blue === right.blue && //
left.alpha === right.alpha;
};
Color.equalsArray = function(color, array, offset2) {
return color.red === array[offset2] && color.green === array[offset2 + 1] && color.blue === array[offset2 + 2] && color.alpha === array[offset2 + 3];
};
Color.prototype.clone = function(result) {
return Color.clone(this, result);
};
Color.prototype.equals = function(other) {
return Color.equals(this, other);
};
Color.prototype.equalsEpsilon = function(other, epsilon) {
return this === other || //
defined_default(other) && //
Math.abs(this.red - other.red) <= epsilon && //
Math.abs(this.green - other.green) <= epsilon && //
Math.abs(this.blue - other.blue) <= epsilon && //
Math.abs(this.alpha - other.alpha) <= epsilon;
};
Color.prototype.toString = function() {
return `(${this.red}, ${this.green}, ${this.blue}, ${this.alpha})`;
};
Color.prototype.toCssColorString = function() {
const red = Color.floatToByte(this.red);
const green = Color.floatToByte(this.green);
const blue = Color.floatToByte(this.blue);
if (this.alpha === 1) {
return `rgb(${red},${green},${blue})`;
}
return `rgba(${red},${green},${blue},${this.alpha})`;
};
Color.prototype.toCssHexString = function() {
let r = Color.floatToByte(this.red).toString(16);
if (r.length < 2) {
r = `0${r}`;
}
let g = Color.floatToByte(this.green).toString(16);
if (g.length < 2) {
g = `0${g}`;
}
let b = Color.floatToByte(this.blue).toString(16);
if (b.length < 2) {
b = `0${b}`;
}
if (this.alpha < 1) {
let hexAlpha = Color.floatToByte(this.alpha).toString(16);
if (hexAlpha.length < 2) {
hexAlpha = `0${hexAlpha}`;
}
return `#${r}${g}${b}${hexAlpha}`;
}
return `#${r}${g}${b}`;
};
Color.prototype.toBytes = function(result) {
const red = Color.floatToByte(this.red);
const green = Color.floatToByte(this.green);
const blue = Color.floatToByte(this.blue);
const alpha = Color.floatToByte(this.alpha);
if (!defined_default(result)) {
return [red, green, blue, alpha];
}
result[0] = red;
result[1] = green;
result[2] = blue;
result[3] = alpha;
return result;
};
Color.prototype.toRgba = function() {
scratchUint8Array[0] = Color.floatToByte(this.red);
scratchUint8Array[1] = Color.floatToByte(this.green);
scratchUint8Array[2] = Color.floatToByte(this.blue);
scratchUint8Array[3] = Color.floatToByte(this.alpha);
return scratchUint32Array[0];
};
Color.prototype.brighten = function(magnitude, result) {
Check_default.typeOf.number("magnitude", magnitude);
Check_default.typeOf.number.greaterThanOrEquals("magnitude", magnitude, 0);
Check_default.typeOf.object("result", result);
magnitude = 1 - magnitude;
result.red = 1 - (1 - this.red) * magnitude;
result.green = 1 - (1 - this.green) * magnitude;
result.blue = 1 - (1 - this.blue) * magnitude;
result.alpha = this.alpha;
return result;
};
Color.prototype.darken = function(magnitude, result) {
Check_default.typeOf.number("magnitude", magnitude);
Check_default.typeOf.number.greaterThanOrEquals("magnitude", magnitude, 0);
Check_default.typeOf.object("result", result);
magnitude = 1 - magnitude;
result.red = this.red * magnitude;
result.green = this.green * magnitude;
result.blue = this.blue * magnitude;
result.alpha = this.alpha;
return result;
};
Color.prototype.withAlpha = function(alpha, result) {
return Color.fromAlpha(this, alpha, result);
};
Color.add = function(left, right, result) {
Check_default.typeOf.object("left", left);
Check_default.typeOf.object("right", right);
Check_default.typeOf.object("result", result);
result.red = left.red + right.red;
result.green = left.green + right.green;
result.blue = left.blue + right.blue;
result.alpha = left.alpha + right.alpha;
return result;
};
Color.subtract = function(left, right, result) {
Check_default.typeOf.object("left", left);
Check_default.typeOf.object("right", right);
Check_default.typeOf.object("result", result);
result.red = left.red - right.red;
result.green = left.green - right.green;
result.blue = left.blue - right.blue;
result.alpha = left.alpha - right.alpha;
return result;
};
Color.multiply = function(left, right, result) {
Check_default.typeOf.object("left", left);
Check_default.typeOf.object("right", right);
Check_default.typeOf.object("result", result);
result.red = left.red * right.red;
result.green = left.green * right.green;
result.blue = left.blue * right.blue;
result.alpha = left.alpha * right.alpha;
return result;
};
Color.divide = function(left, right, result) {
Check_default.typeOf.object("left", left);
Check_default.typeOf.object("right", right);
Check_default.typeOf.object("result", result);
result.red = left.red / right.red;
result.green = left.green / right.green;
result.blue = left.blue / right.blue;
result.alpha = left.alpha / right.alpha;
return result;
};
Color.mod = function(left, right, result) {
Check_default.typeOf.object("left", left);
Check_default.typeOf.object("right", right);
Check_default.typeOf.object("result", result);
result.red = left.red % right.red;
result.green = left.green % right.green;
result.blue = left.blue % right.blue;
result.alpha = left.alpha % right.alpha;
return result;
};
Color.lerp = function(start, end, t, result) {
Check_default.typeOf.object("start", start);
Check_default.typeOf.object("end", end);
Check_default.typeOf.number("t", t);
Check_default.typeOf.object("result", result);
result.red = Math_default.lerp(start.red, end.red, t);
result.green = Math_default.lerp(start.green, end.green, t);
result.blue = Math_default.lerp(start.blue, end.blue, t);
result.alpha = Math_default.lerp(start.alpha, end.alpha, t);
return result;
};
Color.multiplyByScalar = function(color, scalar, result) {
Check_default.typeOf.object("color", color);
Check_default.typeOf.number("scalar", scalar);
Check_default.typeOf.object("result", result);
result.red = color.red * scalar;
result.green = color.green * scalar;
result.blue = color.blue * scalar;
result.alpha = color.alpha * scalar;
return result;
};
Color.divideByScalar = function(color, scalar, result) {
Check_default.typeOf.object("color", color);
Check_default.typeOf.number("scalar", scalar);
Check_default.typeOf.object("result", result);
result.red = color.red / scalar;
result.green = color.green / scalar;
result.blue = color.blue / scalar;
result.alpha = color.alpha / scalar;
return result;
};
Color.ALICEBLUE = Object.freeze(Color.fromCssColorString("#F0F8FF"));
Color.ANTIQUEWHITE = Object.freeze(Color.fromCssColorString("#FAEBD7"));
Color.AQUA = Object.freeze(Color.fromCssColorString("#00FFFF"));
Color.AQUAMARINE = Object.freeze(Color.fromCssColorString("#7FFFD4"));
Color.AZURE = Object.freeze(Color.fromCssColorString("#F0FFFF"));
Color.BEIGE = Object.freeze(Color.fromCssColorString("#F5F5DC"));
Color.BISQUE = Object.freeze(Color.fromCssColorString("#FFE4C4"));
Color.BLACK = Object.freeze(Color.fromCssColorString("#000000"));
Color.BLANCHEDALMOND = Object.freeze(Color.fromCssColorString("#FFEBCD"));
Color.BLUE = Object.freeze(Color.fromCssColorString("#0000FF"));
Color.BLUEVIOLET = Object.freeze(Color.fromCssColorString("#8A2BE2"));
Color.BROWN = Object.freeze(Color.fromCssColorString("#A52A2A"));
Color.BURLYWOOD = Object.freeze(Color.fromCssColorString("#DEB887"));
Color.CADETBLUE = Object.freeze(Color.fromCssColorString("#5F9EA0"));
Color.CHARTREUSE = Object.freeze(Color.fromCssColorString("#7FFF00"));
Color.CHOCOLATE = Object.freeze(Color.fromCssColorString("#D2691E"));
Color.CORAL = Object.freeze(Color.fromCssColorString("#FF7F50"));
Color.CORNFLOWERBLUE = Object.freeze(Color.fromCssColorString("#6495ED"));
Color.CORNSILK = Object.freeze(Color.fromCssColorString("#FFF8DC"));
Color.CRIMSON = Object.freeze(Color.fromCssColorString("#DC143C"));
Color.CYAN = Object.freeze(Color.fromCssColorString("#00FFFF"));
Color.DARKBLUE = Object.freeze(Color.fromCssColorString("#00008B"));
Color.DARKCYAN = Object.freeze(Color.fromCssColorString("#008B8B"));
Color.DARKGOLDENROD = Object.freeze(Color.fromCssColorString("#B8860B"));
Color.DARKGRAY = Object.freeze(Color.fromCssColorString("#A9A9A9"));
Color.DARKGREEN = Object.freeze(Color.fromCssColorString("#006400"));
Color.DARKGREY = Color.DARKGRAY;
Color.DARKKHAKI = Object.freeze(Color.fromCssColorString("#BDB76B"));
Color.DARKMAGENTA = Object.freeze(Color.fromCssColorString("#8B008B"));
Color.DARKOLIVEGREEN = Object.freeze(Color.fromCssColorString("#556B2F"));
Color.DARKORANGE = Object.freeze(Color.fromCssColorString("#FF8C00"));
Color.DARKORCHID = Object.freeze(Color.fromCssColorString("#9932CC"));
Color.DARKRED = Object.freeze(Color.fromCssColorString("#8B0000"));
Color.DARKSALMON = Object.freeze(Color.fromCssColorString("#E9967A"));
Color.DARKSEAGREEN = Object.freeze(Color.fromCssColorString("#8FBC8F"));
Color.DARKSLATEBLUE = Object.freeze(Color.fromCssColorString("#483D8B"));
Color.DARKSLATEGRAY = Object.freeze(Color.fromCssColorString("#2F4F4F"));
Color.DARKSLATEGREY = Color.DARKSLATEGRAY;
Color.DARKTURQUOISE = Object.freeze(Color.fromCssColorString("#00CED1"));
Color.DARKVIOLET = Object.freeze(Color.fromCssColorString("#9400D3"));
Color.DEEPPINK = Object.freeze(Color.fromCssColorString("#FF1493"));
Color.DEEPSKYBLUE = Object.freeze(Color.fromCssColorString("#00BFFF"));
Color.DIMGRAY = Object.freeze(Color.fromCssColorString("#696969"));
Color.DIMGREY = Color.DIMGRAY;
Color.DODGERBLUE = Object.freeze(Color.fromCssColorString("#1E90FF"));
Color.FIREBRICK = Object.freeze(Color.fromCssColorString("#B22222"));
Color.FLORALWHITE = Object.freeze(Color.fromCssColorString("#FFFAF0"));
Color.FORESTGREEN = Object.freeze(Color.fromCssColorString("#228B22"));
Color.FUCHSIA = Object.freeze(Color.fromCssColorString("#FF00FF"));
Color.GAINSBORO = Object.freeze(Color.fromCssColorString("#DCDCDC"));
Color.GHOSTWHITE = Object.freeze(Color.fromCssColorString("#F8F8FF"));
Color.GOLD = Object.freeze(Color.fromCssColorString("#FFD700"));
Color.GOLDENROD = Object.freeze(Color.fromCssColorString("#DAA520"));
Color.GRAY = Object.freeze(Color.fromCssColorString("#808080"));
Color.GREEN = Object.freeze(Color.fromCssColorString("#008000"));
Color.GREENYELLOW = Object.freeze(Color.fromCssColorString("#ADFF2F"));
Color.GREY = Color.GRAY;
Color.HONEYDEW = Object.freeze(Color.fromCssColorString("#F0FFF0"));
Color.HOTPINK = Object.freeze(Color.fromCssColorString("#FF69B4"));
Color.INDIANRED = Object.freeze(Color.fromCssColorString("#CD5C5C"));
Color.INDIGO = Object.freeze(Color.fromCssColorString("#4B0082"));
Color.IVORY = Object.freeze(Color.fromCssColorString("#FFFFF0"));
Color.KHAKI = Object.freeze(Color.fromCssColorString("#F0E68C"));
Color.LAVENDER = Object.freeze(Color.fromCssColorString("#E6E6FA"));
Color.LAVENDAR_BLUSH = Object.freeze(Color.fromCssColorString("#FFF0F5"));
Color.LAWNGREEN = Object.freeze(Color.fromCssColorString("#7CFC00"));
Color.LEMONCHIFFON = Object.freeze(Color.fromCssColorString("#FFFACD"));
Color.LIGHTBLUE = Object.freeze(Color.fromCssColorString("#ADD8E6"));
Color.LIGHTCORAL = Object.freeze(Color.fromCssColorString("#F08080"));
Color.LIGHTCYAN = Object.freeze(Color.fromCssColorString("#E0FFFF"));
Color.LIGHTGOLDENRODYELLOW = Object.freeze(Color.fromCssColorString("#FAFAD2"));
Color.LIGHTGRAY = Object.freeze(Color.fromCssColorString("#D3D3D3"));
Color.LIGHTGREEN = Object.freeze(Color.fromCssColorString("#90EE90"));
Color.LIGHTGREY = Color.LIGHTGRAY;
Color.LIGHTPINK = Object.freeze(Color.fromCssColorString("#FFB6C1"));
Color.LIGHTSEAGREEN = Object.freeze(Color.fromCssColorString("#20B2AA"));
Color.LIGHTSKYBLUE = Object.freeze(Color.fromCssColorString("#87CEFA"));
Color.LIGHTSLATEGRAY = Object.freeze(Color.fromCssColorString("#778899"));
Color.LIGHTSLATEGREY = Color.LIGHTSLATEGRAY;
Color.LIGHTSTEELBLUE = Object.freeze(Color.fromCssColorString("#B0C4DE"));
Color.LIGHTYELLOW = Object.freeze(Color.fromCssColorString("#FFFFE0"));
Color.LIME = Object.freeze(Color.fromCssColorString("#00FF00"));
Color.LIMEGREEN = Object.freeze(Color.fromCssColorString("#32CD32"));
Color.LINEN = Object.freeze(Color.fromCssColorString("#FAF0E6"));
Color.MAGENTA = Object.freeze(Color.fromCssColorString("#FF00FF"));
Color.MAROON = Object.freeze(Color.fromCssColorString("#800000"));
Color.MEDIUMAQUAMARINE = Object.freeze(Color.fromCssColorString("#66CDAA"));
Color.MEDIUMBLUE = Object.freeze(Color.fromCssColorString("#0000CD"));
Color.MEDIUMORCHID = Object.freeze(Color.fromCssColorString("#BA55D3"));
Color.MEDIUMPURPLE = Object.freeze(Color.fromCssColorString("#9370DB"));
Color.MEDIUMSEAGREEN = Object.freeze(Color.fromCssColorString("#3CB371"));
Color.MEDIUMSLATEBLUE = Object.freeze(Color.fromCssColorString("#7B68EE"));
Color.MEDIUMSPRINGGREEN = Object.freeze(Color.fromCssColorString("#00FA9A"));
Color.MEDIUMTURQUOISE = Object.freeze(Color.fromCssColorString("#48D1CC"));
Color.MEDIUMVIOLETRED = Object.freeze(Color.fromCssColorString("#C71585"));
Color.MIDNIGHTBLUE = Object.freeze(Color.fromCssColorString("#191970"));
Color.MINTCREAM = Object.freeze(Color.fromCssColorString("#F5FFFA"));
Color.MISTYROSE = Object.freeze(Color.fromCssColorString("#FFE4E1"));
Color.MOCCASIN = Object.freeze(Color.fromCssColorString("#FFE4B5"));
Color.NAVAJOWHITE = Object.freeze(Color.fromCssColorString("#FFDEAD"));
Color.NAVY = Object.freeze(Color.fromCssColorString("#000080"));
Color.OLDLACE = Object.freeze(Color.fromCssColorString("#FDF5E6"));
Color.OLIVE = Object.freeze(Color.fromCssColorString("#808000"));
Color.OLIVEDRAB = Object.freeze(Color.fromCssColorString("#6B8E23"));
Color.ORANGE = Object.freeze(Color.fromCssColorString("#FFA500"));
Color.ORANGERED = Object.freeze(Color.fromCssColorString("#FF4500"));
Color.ORCHID = Object.freeze(Color.fromCssColorString("#DA70D6"));
Color.PALEGOLDENROD = Object.freeze(Color.fromCssColorString("#EEE8AA"));
Color.PALEGREEN = Object.freeze(Color.fromCssColorString("#98FB98"));
Color.PALETURQUOISE = Object.freeze(Color.fromCssColorString("#AFEEEE"));
Color.PALEVIOLETRED = Object.freeze(Color.fromCssColorString("#DB7093"));
Color.PAPAYAWHIP = Object.freeze(Color.fromCssColorString("#FFEFD5"));
Color.PEACHPUFF = Object.freeze(Color.fromCssColorString("#FFDAB9"));
Color.PERU = Object.freeze(Color.fromCssColorString("#CD853F"));
Color.PINK = Object.freeze(Color.fromCssColorString("#FFC0CB"));
Color.PLUM = Object.freeze(Color.fromCssColorString("#DDA0DD"));
Color.POWDERBLUE = Object.freeze(Color.fromCssColorString("#B0E0E6"));
Color.PURPLE = Object.freeze(Color.fromCssColorString("#800080"));
Color.RED = Object.freeze(Color.fromCssColorString("#FF0000"));
Color.ROSYBROWN = Object.freeze(Color.fromCssColorString("#BC8F8F"));
Color.ROYALBLUE = Object.freeze(Color.fromCssColorString("#4169E1"));
Color.SADDLEBROWN = Object.freeze(Color.fromCssColorString("#8B4513"));
Color.SALMON = Object.freeze(Color.fromCssColorString("#FA8072"));
Color.SANDYBROWN = Object.freeze(Color.fromCssColorString("#F4A460"));
Color.SEAGREEN = Object.freeze(Color.fromCssColorString("#2E8B57"));
Color.SEASHELL = Object.freeze(Color.fromCssColorString("#FFF5EE"));
Color.SIENNA = Object.freeze(Color.fromCssColorString("#A0522D"));
Color.SILVER = Object.freeze(Color.fromCssColorString("#C0C0C0"));
Color.SKYBLUE = Object.freeze(Color.fromCssColorString("#87CEEB"));
Color.SLATEBLUE = Object.freeze(Color.fromCssColorString("#6A5ACD"));
Color.SLATEGRAY = Object.freeze(Color.fromCssColorString("#708090"));
Color.SLATEGREY = Color.SLATEGRAY;
Color.SNOW = Object.freeze(Color.fromCssColorString("#FFFAFA"));
Color.SPRINGGREEN = Object.freeze(Color.fromCssColorString("#00FF7F"));
Color.STEELBLUE = Object.freeze(Color.fromCssColorString("#4682B4"));
Color.TAN = Object.freeze(Color.fromCssColorString("#D2B48C"));
Color.TEAL = Object.freeze(Color.fromCssColorString("#008080"));
Color.THISTLE = Object.freeze(Color.fromCssColorString("#D8BFD8"));
Color.TOMATO = Object.freeze(Color.fromCssColorString("#FF6347"));
Color.TURQUOISE = Object.freeze(Color.fromCssColorString("#40E0D0"));
Color.VIOLET = Object.freeze(Color.fromCssColorString("#EE82EE"));
Color.WHEAT = Object.freeze(Color.fromCssColorString("#F5DEB3"));
Color.WHITE = Object.freeze(Color.fromCssColorString("#FFFFFF"));
Color.WHITESMOKE = Object.freeze(Color.fromCssColorString("#F5F5F5"));
Color.YELLOW = Object.freeze(Color.fromCssColorString("#FFFF00"));
Color.YELLOWGREEN = Object.freeze(Color.fromCssColorString("#9ACD32"));
Color.TRANSPARENT = Object.freeze(new Color(0, 0, 0, 0));
var Color_default = Color;
// packages/engine/Source/Renderer/ClearCommand.js
function ClearCommand(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this.color = options.color;
this.depth = options.depth;
this.stencil = options.stencil;
this.renderState = options.renderState;
this.framebuffer = options.framebuffer;
this.owner = options.owner;
this.pass = options.pass;
}
ClearCommand.ALL = Object.freeze(
new ClearCommand({
color: new Color_default(0, 0, 0, 0),
depth: 1,
stencil: 0
})
);
ClearCommand.prototype.execute = function(context, passState) {
context.clear(this, passState);
};
var ClearCommand_default = ClearCommand;
// packages/engine/Source/Renderer/Pass.js
var Pass = {
// If you add/modify/remove Pass constants, also change the automatic GLSL constants
// that start with 'czm_pass'
//
// Commands are executed in order by pass up to the translucent pass.
// Translucent geometry needs special handling (sorting/OIT). The compute pass
// is executed first and the overlay pass is executed last. Both are not sorted
// by frustum.
ENVIRONMENT: 0,
COMPUTE: 1,
GLOBE: 2,
TERRAIN_CLASSIFICATION: 3,
CESIUM_3D_TILE: 4,
CESIUM_3D_TILE_CLASSIFICATION: 5,
CESIUM_3D_TILE_CLASSIFICATION_IGNORE_SHOW: 6,
OPAQUE: 7,
TRANSLUCENT: 8,
VOXELS: 9,
OVERLAY: 10,
NUMBER_OF_PASSES: 11
};
var Pass_default = Object.freeze(Pass);
// packages/engine/Source/Renderer/ComputeCommand.js
function ComputeCommand(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this.vertexArray = options.vertexArray;
this.fragmentShaderSource = options.fragmentShaderSource;
this.shaderProgram = options.shaderProgram;
this.uniformMap = options.uniformMap;
this.outputTexture = options.outputTexture;
this.preExecute = options.preExecute;
this.postExecute = options.postExecute;
this.canceled = options.canceled;
this.persists = defaultValue_default(options.persists, false);
this.pass = Pass_default.COMPUTE;
this.owner = options.owner;
}
ComputeCommand.prototype.execute = function(computeEngine) {
computeEngine.execute(this);
};
var ComputeCommand_default = ComputeCommand;
// packages/engine/Source/Core/Cartesian2.js
function Cartesian2(x, y) {
this.x = defaultValue_default(x, 0);
this.y = defaultValue_default(y, 0);
}
Cartesian2.fromElements = function(x, y, result) {
if (!defined_default(result)) {
return new Cartesian2(x, y);
}
result.x = x;
result.y = y;
return result;
};
Cartesian2.clone = function(cartesian11, result) {
if (!defined_default(cartesian11)) {
return void 0;
}
if (!defined_default(result)) {
return new Cartesian2(cartesian11.x, cartesian11.y);
}
result.x = cartesian11.x;
result.y = cartesian11.y;
return result;
};
Cartesian2.fromCartesian3 = Cartesian2.clone;
Cartesian2.fromCartesian4 = Cartesian2.clone;
Cartesian2.packedLength = 2;
Cartesian2.pack = function(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
array[startingIndex++] = value.x;
array[startingIndex] = value.y;
return array;
};
Cartesian2.unpack = function(array, startingIndex, result) {
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
if (!defined_default(result)) {
result = new Cartesian2();
}
result.x = array[startingIndex++];
result.y = array[startingIndex];
return result;
};
Cartesian2.packArray = function(array, result) {
Check_default.defined("array", array);
const length3 = array.length;
const resultLength = length3 * 2;
if (!defined_default(result)) {
result = new Array(resultLength);
} else if (!Array.isArray(result) && result.length !== resultLength) {
throw new DeveloperError_default(
"If result is a typed array, it must have exactly array.length * 2 elements"
);
} else if (result.length !== resultLength) {
result.length = resultLength;
}
for (let i = 0; i < length3; ++i) {
Cartesian2.pack(array[i], result, i * 2);
}
return result;
};
Cartesian2.unpackArray = function(array, result) {
Check_default.defined("array", array);
Check_default.typeOf.number.greaterThanOrEquals("array.length", array.length, 2);
if (array.length % 2 !== 0) {
throw new DeveloperError_default("array length must be a multiple of 2.");
}
const length3 = array.length;
if (!defined_default(result)) {
result = new Array(length3 / 2);
} else {
result.length = length3 / 2;
}
for (let i = 0; i < length3; i += 2) {
const index = i / 2;
result[index] = Cartesian2.unpack(array, i, result[index]);
}
return result;
};
Cartesian2.fromArray = Cartesian2.unpack;
Cartesian2.maximumComponent = function(cartesian11) {
Check_default.typeOf.object("cartesian", cartesian11);
return Math.max(cartesian11.x, cartesian11.y);
};
Cartesian2.minimumComponent = function(cartesian11) {
Check_default.typeOf.object("cartesian", cartesian11);
return Math.min(cartesian11.x, cartesian11.y);
};
Cartesian2.minimumByComponent = function(first, second, result) {
Check_default.typeOf.object("first", first);
Check_default.typeOf.object("second", second);
Check_default.typeOf.object("result", result);
result.x = Math.min(first.x, second.x);
result.y = Math.min(first.y, second.y);
return result;
};
Cartesian2.maximumByComponent = function(first, second, result) {
Check_default.typeOf.object("first", first);
Check_default.typeOf.object("second", second);
Check_default.typeOf.object("result", result);
result.x = Math.max(first.x, second.x);
result.y = Math.max(first.y, second.y);
return result;
};
Cartesian2.clamp = function(value, min3, max3, result) {
Check_default.typeOf.object("value", value);
Check_default.typeOf.object("min", min3);
Check_default.typeOf.object("max", max3);
Check_default.typeOf.object("result", result);
const x = Math_default.clamp(value.x, min3.x, max3.x);
const y = Math_default.clamp(value.y, min3.y, max3.y);
result.x = x;
result.y = y;
return result;
};
Cartesian2.magnitudeSquared = function(cartesian11) {
Check_default.typeOf.object("cartesian", cartesian11);
return cartesian11.x * cartesian11.x + cartesian11.y * cartesian11.y;
};
Cartesian2.magnitude = function(cartesian11) {
return Math.sqrt(Cartesian2.magnitudeSquared(cartesian11));
};
var distanceScratch3 = new Cartesian2();
Cartesian2.distance = function(left, right) {
Check_default.typeOf.object("left", left);
Check_default.typeOf.object("right", right);
Cartesian2.subtract(left, right, distanceScratch3);
return Cartesian2.magnitude(distanceScratch3);
};
Cartesian2.distanceSquared = function(left, right) {
Check_default.typeOf.object("left", left);
Check_default.typeOf.object("right", right);
Cartesian2.subtract(left, right, distanceScratch3);
return Cartesian2.magnitudeSquared(distanceScratch3);
};
Cartesian2.normalize = function(cartesian11, result) {
Check_default.typeOf.object("cartesian", cartesian11);
Check_default.typeOf.object("result", result);
const magnitude = Cartesian2.magnitude(cartesian11);
result.x = cartesian11.x / magnitude;
result.y = cartesian11.y / magnitude;
if (isNaN(result.x) || isNaN(result.y)) {
throw new DeveloperError_default("normalized result is not a number");
}
return result;
};
Cartesian2.dot = function(left, right) {
Check_default.typeOf.object("left", left);
Check_default.typeOf.object("right", right);
return left.x * right.x + left.y * right.y;
};
Cartesian2.cross = function(left, right) {
Check_default.typeOf.object("left", left);
Check_default.typeOf.object("right", right);
return left.x * right.y - left.y * right.x;
};
Cartesian2.multiplyComponents = function(left, right, result) {
Check_default.typeOf.object("left", left);
Check_default.typeOf.object("right", right);
Check_default.typeOf.object("result", result);
result.x = left.x * right.x;
result.y = left.y * right.y;
return result;
};
Cartesian2.divideComponents = function(left, right, result) {
Check_default.typeOf.object("left", left);
Check_default.typeOf.object("right", right);
Check_default.typeOf.object("result", result);
result.x = left.x / right.x;
result.y = left.y / right.y;
return result;
};
Cartesian2.add = function(left, right, result) {
Check_default.typeOf.object("left", left);
Check_default.typeOf.object("right", right);
Check_default.typeOf.object("result", result);
result.x = left.x + right.x;
result.y = left.y + right.y;
return result;
};
Cartesian2.subtract = function(left, right, result) {
Check_default.typeOf.object("left", left);
Check_default.typeOf.object("right", right);
Check_default.typeOf.object("result", result);
result.x = left.x - right.x;
result.y = left.y - right.y;
return result;
};
Cartesian2.multiplyByScalar = function(cartesian11, scalar, result) {
Check_default.typeOf.object("cartesian", cartesian11);
Check_default.typeOf.number("scalar", scalar);
Check_default.typeOf.object("result", result);
result.x = cartesian11.x * scalar;
result.y = cartesian11.y * scalar;
return result;
};
Cartesian2.divideByScalar = function(cartesian11, scalar, result) {
Check_default.typeOf.object("cartesian", cartesian11);
Check_default.typeOf.number("scalar", scalar);
Check_default.typeOf.object("result", result);
result.x = cartesian11.x / scalar;
result.y = cartesian11.y / scalar;
return result;
};
Cartesian2.negate = function(cartesian11, result) {
Check_default.typeOf.object("cartesian", cartesian11);
Check_default.typeOf.object("result", result);
result.x = -cartesian11.x;
result.y = -cartesian11.y;
return result;
};
Cartesian2.abs = function(cartesian11, result) {
Check_default.typeOf.object("cartesian", cartesian11);
Check_default.typeOf.object("result", result);
result.x = Math.abs(cartesian11.x);
result.y = Math.abs(cartesian11.y);
return result;
};
var lerpScratch3 = new Cartesian2();
Cartesian2.lerp = function(start, end, t, result) {
Check_default.typeOf.object("start", start);
Check_default.typeOf.object("end", end);
Check_default.typeOf.number("t", t);
Check_default.typeOf.object("result", result);
Cartesian2.multiplyByScalar(end, t, lerpScratch3);
result = Cartesian2.multiplyByScalar(start, 1 - t, result);
return Cartesian2.add(lerpScratch3, result, result);
};
var angleBetweenScratch3 = new Cartesian2();
var angleBetweenScratch22 = new Cartesian2();
Cartesian2.angleBetween = function(left, right) {
Check_default.typeOf.object("left", left);
Check_default.typeOf.object("right", right);
Cartesian2.normalize(left, angleBetweenScratch3);
Cartesian2.normalize(right, angleBetweenScratch22);
return Math_default.acosClamped(
Cartesian2.dot(angleBetweenScratch3, angleBetweenScratch22)
);
};
var mostOrthogonalAxisScratch3 = new Cartesian2();
Cartesian2.mostOrthogonalAxis = function(cartesian11, result) {
Check_default.typeOf.object("cartesian", cartesian11);
Check_default.typeOf.object("result", result);
const f = Cartesian2.normalize(cartesian11, mostOrthogonalAxisScratch3);
Cartesian2.abs(f, f);
if (f.x <= f.y) {
result = Cartesian2.clone(Cartesian2.UNIT_X, result);
} else {
result = Cartesian2.clone(Cartesian2.UNIT_Y, result);
}
return result;
};
Cartesian2.equals = function(left, right) {
return left === right || defined_default(left) && defined_default(right) && left.x === right.x && left.y === right.y;
};
Cartesian2.equalsArray = function(cartesian11, array, offset2) {
return cartesian11.x === array[offset2] && cartesian11.y === array[offset2 + 1];
};
Cartesian2.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
return left === right || defined_default(left) && defined_default(right) && Math_default.equalsEpsilon(
left.x,
right.x,
relativeEpsilon,
absoluteEpsilon
) && Math_default.equalsEpsilon(
left.y,
right.y,
relativeEpsilon,
absoluteEpsilon
);
};
Cartesian2.ZERO = Object.freeze(new Cartesian2(0, 0));
Cartesian2.ONE = Object.freeze(new Cartesian2(1, 1));
Cartesian2.UNIT_X = Object.freeze(new Cartesian2(1, 0));
Cartesian2.UNIT_Y = Object.freeze(new Cartesian2(0, 1));
Cartesian2.prototype.clone = function(result) {
return Cartesian2.clone(this, result);
};
Cartesian2.prototype.equals = function(right) {
return Cartesian2.equals(this, right);
};
Cartesian2.prototype.equalsEpsilon = function(right, relativeEpsilon, absoluteEpsilon) {
return Cartesian2.equalsEpsilon(
this,
right,
relativeEpsilon,
absoluteEpsilon
);
};
Cartesian2.prototype.toString = function() {
return `(${this.x}, ${this.y})`;
};
var Cartesian2_default = Cartesian2;
// packages/engine/Source/Core/scaleToGeodeticSurface.js
var scaleToGeodeticSurfaceIntersection = new Cartesian3_default();
var scaleToGeodeticSurfaceGradient = new Cartesian3_default();
function scaleToGeodeticSurface(cartesian11, oneOverRadii, oneOverRadiiSquared, centerToleranceSquared, result) {
if (!defined_default(cartesian11)) {
throw new DeveloperError_default("cartesian is required.");
}
if (!defined_default(oneOverRadii)) {
throw new DeveloperError_default("oneOverRadii is required.");
}
if (!defined_default(oneOverRadiiSquared)) {
throw new DeveloperError_default("oneOverRadiiSquared is required.");
}
if (!defined_default(centerToleranceSquared)) {
throw new DeveloperError_default("centerToleranceSquared is required.");
}
const positionX = cartesian11.x;
const positionY = cartesian11.y;
const positionZ = cartesian11.z;
const oneOverRadiiX = oneOverRadii.x;
const oneOverRadiiY = oneOverRadii.y;
const oneOverRadiiZ = oneOverRadii.z;
const x2 = positionX * positionX * oneOverRadiiX * oneOverRadiiX;
const y2 = positionY * positionY * oneOverRadiiY * oneOverRadiiY;
const z2 = positionZ * positionZ * oneOverRadiiZ * oneOverRadiiZ;
const squaredNorm = x2 + y2 + z2;
const ratio = Math.sqrt(1 / squaredNorm);
const intersection = Cartesian3_default.multiplyByScalar(
cartesian11,
ratio,
scaleToGeodeticSurfaceIntersection
);
if (squaredNorm < centerToleranceSquared) {
return !isFinite(ratio) ? void 0 : Cartesian3_default.clone(intersection, result);
}
const oneOverRadiiSquaredX = oneOverRadiiSquared.x;
const oneOverRadiiSquaredY = oneOverRadiiSquared.y;
const oneOverRadiiSquaredZ = oneOverRadiiSquared.z;
const gradient = scaleToGeodeticSurfaceGradient;
gradient.x = intersection.x * oneOverRadiiSquaredX * 2;
gradient.y = intersection.y * oneOverRadiiSquaredY * 2;
gradient.z = intersection.z * oneOverRadiiSquaredZ * 2;
let lambda = (1 - ratio) * Cartesian3_default.magnitude(cartesian11) / (0.5 * Cartesian3_default.magnitude(gradient));
let correction = 0;
let func;
let denominator;
let xMultiplier;
let yMultiplier;
let zMultiplier;
let xMultiplier2;
let yMultiplier2;
let zMultiplier2;
let xMultiplier3;
let yMultiplier3;
let zMultiplier3;
do {
lambda -= correction;
xMultiplier = 1 / (1 + lambda * oneOverRadiiSquaredX);
yMultiplier = 1 / (1 + lambda * oneOverRadiiSquaredY);
zMultiplier = 1 / (1 + lambda * oneOverRadiiSquaredZ);
xMultiplier2 = xMultiplier * xMultiplier;
yMultiplier2 = yMultiplier * yMultiplier;
zMultiplier2 = zMultiplier * zMultiplier;
xMultiplier3 = xMultiplier2 * xMultiplier;
yMultiplier3 = yMultiplier2 * yMultiplier;
zMultiplier3 = zMultiplier2 * zMultiplier;
func = x2 * xMultiplier2 + y2 * yMultiplier2 + z2 * zMultiplier2 - 1;
denominator = x2 * xMultiplier3 * oneOverRadiiSquaredX + y2 * yMultiplier3 * oneOverRadiiSquaredY + z2 * zMultiplier3 * oneOverRadiiSquaredZ;
const derivative = -2 * denominator;
correction = func / derivative;
} while (Math.abs(func) > Math_default.EPSILON12);
if (!defined_default(result)) {
return new Cartesian3_default(
positionX * xMultiplier,
positionY * yMultiplier,
positionZ * zMultiplier
);
}
result.x = positionX * xMultiplier;
result.y = positionY * yMultiplier;
result.z = positionZ * zMultiplier;
return result;
}
var scaleToGeodeticSurface_default = scaleToGeodeticSurface;
// packages/engine/Source/Core/Cartographic.js
function Cartographic(longitude, latitude, height) {
this.longitude = defaultValue_default(longitude, 0);
this.latitude = defaultValue_default(latitude, 0);
this.height = defaultValue_default(height, 0);
}
Cartographic.fromRadians = function(longitude, latitude, height, result) {
Check_default.typeOf.number("longitude", longitude);
Check_default.typeOf.number("latitude", latitude);
height = defaultValue_default(height, 0);
if (!defined_default(result)) {
return new Cartographic(longitude, latitude, height);
}
result.longitude = longitude;
result.latitude = latitude;
result.height = height;
return result;
};
Cartographic.fromDegrees = function(longitude, latitude, height, result) {
Check_default.typeOf.number("longitude", longitude);
Check_default.typeOf.number("latitude", latitude);
longitude = Math_default.toRadians(longitude);
latitude = Math_default.toRadians(latitude);
return Cartographic.fromRadians(longitude, latitude, height, result);
};
var cartesianToCartographicN = new Cartesian3_default();
var cartesianToCartographicP = new Cartesian3_default();
var cartesianToCartographicH = new Cartesian3_default();
var wgs84OneOverRadii = new Cartesian3_default(
1 / 6378137,
1 / 6378137,
1 / 6356752314245179e-9
);
var wgs84OneOverRadiiSquared = new Cartesian3_default(
1 / (6378137 * 6378137),
1 / (6378137 * 6378137),
1 / (6356752314245179e-9 * 6356752314245179e-9)
);
var wgs84CenterToleranceSquared = Math_default.EPSILON1;
Cartographic.fromCartesian = function(cartesian11, ellipsoid, result) {
const oneOverRadii = defined_default(ellipsoid) ? ellipsoid.oneOverRadii : wgs84OneOverRadii;
const oneOverRadiiSquared = defined_default(ellipsoid) ? ellipsoid.oneOverRadiiSquared : wgs84OneOverRadiiSquared;
const centerToleranceSquared = defined_default(ellipsoid) ? ellipsoid._centerToleranceSquared : wgs84CenterToleranceSquared;
const p = scaleToGeodeticSurface_default(
cartesian11,
oneOverRadii,
oneOverRadiiSquared,
centerToleranceSquared,
cartesianToCartographicP
);
if (!defined_default(p)) {
return void 0;
}
let n = Cartesian3_default.multiplyComponents(
p,
oneOverRadiiSquared,
cartesianToCartographicN
);
n = Cartesian3_default.normalize(n, n);
const h = Cartesian3_default.subtract(cartesian11, p, cartesianToCartographicH);
const longitude = Math.atan2(n.y, n.x);
const latitude = Math.asin(n.z);
const height = Math_default.sign(Cartesian3_default.dot(h, cartesian11)) * Cartesian3_default.magnitude(h);
if (!defined_default(result)) {
return new Cartographic(longitude, latitude, height);
}
result.longitude = longitude;
result.latitude = latitude;
result.height = height;
return result;
};
Cartographic.toCartesian = function(cartographic2, ellipsoid, result) {
Check_default.defined("cartographic", cartographic2);
return Cartesian3_default.fromRadians(
cartographic2.longitude,
cartographic2.latitude,
cartographic2.height,
ellipsoid,
result
);
};
Cartographic.clone = function(cartographic2, result) {
if (!defined_default(cartographic2)) {
return void 0;
}
if (!defined_default(result)) {
return new Cartographic(
cartographic2.longitude,
cartographic2.latitude,
cartographic2.height
);
}
result.longitude = cartographic2.longitude;
result.latitude = cartographic2.latitude;
result.height = cartographic2.height;
return result;
};
Cartographic.equals = function(left, right) {
return left === right || defined_default(left) && defined_default(right) && left.longitude === right.longitude && left.latitude === right.latitude && left.height === right.height;
};
Cartographic.equalsEpsilon = function(left, right, epsilon) {
epsilon = defaultValue_default(epsilon, 0);
return left === right || defined_default(left) && defined_default(right) && Math.abs(left.longitude - right.longitude) <= epsilon && Math.abs(left.latitude - right.latitude) <= epsilon && Math.abs(left.height - right.height) <= epsilon;
};
Cartographic.ZERO = Object.freeze(new Cartographic(0, 0, 0));
Cartographic.prototype.clone = function(result) {
return Cartographic.clone(this, result);
};
Cartographic.prototype.equals = function(right) {
return Cartographic.equals(this, right);
};
Cartographic.prototype.equalsEpsilon = function(right, epsilon) {
return Cartographic.equalsEpsilon(this, right, epsilon);
};
Cartographic.prototype.toString = function() {
return `(${this.longitude}, ${this.latitude}, ${this.height})`;
};
var Cartographic_default = Cartographic;
// packages/engine/Source/Core/Ellipsoid.js
function initialize(ellipsoid, x, y, z) {
x = defaultValue_default(x, 0);
y = defaultValue_default(y, 0);
z = defaultValue_default(z, 0);
Check_default.typeOf.number.greaterThanOrEquals("x", x, 0);
Check_default.typeOf.number.greaterThanOrEquals("y", y, 0);
Check_default.typeOf.number.greaterThanOrEquals("z", z, 0);
ellipsoid._radii = new Cartesian3_default(x, y, z);
ellipsoid._radiiSquared = new Cartesian3_default(x * x, y * y, z * z);
ellipsoid._radiiToTheFourth = new Cartesian3_default(
x * x * x * x,
y * y * y * y,
z * z * z * z
);
ellipsoid._oneOverRadii = new Cartesian3_default(
x === 0 ? 0 : 1 / x,
y === 0 ? 0 : 1 / y,
z === 0 ? 0 : 1 / z
);
ellipsoid._oneOverRadiiSquared = new Cartesian3_default(
x === 0 ? 0 : 1 / (x * x),
y === 0 ? 0 : 1 / (y * y),
z === 0 ? 0 : 1 / (z * z)
);
ellipsoid._minimumRadius = Math.min(x, y, z);
ellipsoid._maximumRadius = Math.max(x, y, z);
ellipsoid._centerToleranceSquared = Math_default.EPSILON1;
if (ellipsoid._radiiSquared.z !== 0) {
ellipsoid._squaredXOverSquaredZ = ellipsoid._radiiSquared.x / ellipsoid._radiiSquared.z;
}
}
function Ellipsoid(x, y, z) {
this._radii = void 0;
this._radiiSquared = void 0;
this._radiiToTheFourth = void 0;
this._oneOverRadii = void 0;
this._oneOverRadiiSquared = void 0;
this._minimumRadius = void 0;
this._maximumRadius = void 0;
this._centerToleranceSquared = void 0;
this._squaredXOverSquaredZ = void 0;
initialize(this, x, y, z);
}
Object.defineProperties(Ellipsoid.prototype, {
/**
* Gets the radii of the ellipsoid.
* @memberof Ellipsoid.prototype
* @type {Cartesian3}
* @readonly
*/
radii: {
get: function() {
return this._radii;
}
},
/**
* Gets the squared radii of the ellipsoid.
* @memberof Ellipsoid.prototype
* @type {Cartesian3}
* @readonly
*/
radiiSquared: {
get: function() {
return this._radiiSquared;
}
},
/**
* Gets the radii of the ellipsoid raise to the fourth power.
* @memberof Ellipsoid.prototype
* @type {Cartesian3}
* @readonly
*/
radiiToTheFourth: {
get: function() {
return this._radiiToTheFourth;
}
},
/**
* Gets one over the radii of the ellipsoid.
* @memberof Ellipsoid.prototype
* @type {Cartesian3}
* @readonly
*/
oneOverRadii: {
get: function() {
return this._oneOverRadii;
}
},
/**
* Gets one over the squared radii of the ellipsoid.
* @memberof Ellipsoid.prototype
* @type {Cartesian3}
* @readonly
*/
oneOverRadiiSquared: {
get: function() {
return this._oneOverRadiiSquared;
}
},
/**
* Gets the minimum radius of the ellipsoid.
* @memberof Ellipsoid.prototype
* @type {number}
* @readonly
*/
minimumRadius: {
get: function() {
return this._minimumRadius;
}
},
/**
* Gets the maximum radius of the ellipsoid.
* @memberof Ellipsoid.prototype
* @type {number}
* @readonly
*/
maximumRadius: {
get: function() {
return this._maximumRadius;
}
}
});
Ellipsoid.clone = function(ellipsoid, result) {
if (!defined_default(ellipsoid)) {
return void 0;
}
const radii = ellipsoid._radii;
if (!defined_default(result)) {
return new Ellipsoid(radii.x, radii.y, radii.z);
}
Cartesian3_default.clone(radii, result._radii);
Cartesian3_default.clone(ellipsoid._radiiSquared, result._radiiSquared);
Cartesian3_default.clone(ellipsoid._radiiToTheFourth, result._radiiToTheFourth);
Cartesian3_default.clone(ellipsoid._oneOverRadii, result._oneOverRadii);
Cartesian3_default.clone(ellipsoid._oneOverRadiiSquared, result._oneOverRadiiSquared);
result._minimumRadius = ellipsoid._minimumRadius;
result._maximumRadius = ellipsoid._maximumRadius;
result._centerToleranceSquared = ellipsoid._centerToleranceSquared;
return result;
};
Ellipsoid.fromCartesian3 = function(cartesian11, result) {
if (!defined_default(result)) {
result = new Ellipsoid();
}
if (!defined_default(cartesian11)) {
return result;
}
initialize(result, cartesian11.x, cartesian11.y, cartesian11.z);
return result;
};
Ellipsoid.WGS84 = Object.freeze(
new Ellipsoid(6378137, 6378137, 6356752314245179e-9)
);
Ellipsoid.UNIT_SPHERE = Object.freeze(new Ellipsoid(1, 1, 1));
Ellipsoid.MOON = Object.freeze(
new Ellipsoid(
Math_default.LUNAR_RADIUS,
Math_default.LUNAR_RADIUS,
Math_default.LUNAR_RADIUS
)
);
Ellipsoid.prototype.clone = function(result) {
return Ellipsoid.clone(this, result);
};
Ellipsoid.packedLength = Cartesian3_default.packedLength;
Ellipsoid.pack = function(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
Cartesian3_default.pack(value._radii, array, startingIndex);
return array;
};
Ellipsoid.unpack = function(array, startingIndex, result) {
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
const radii = Cartesian3_default.unpack(array, startingIndex);
return Ellipsoid.fromCartesian3(radii, result);
};
Ellipsoid.prototype.geocentricSurfaceNormal = Cartesian3_default.normalize;
Ellipsoid.prototype.geodeticSurfaceNormalCartographic = function(cartographic2, result) {
Check_default.typeOf.object("cartographic", cartographic2);
const longitude = cartographic2.longitude;
const latitude = cartographic2.latitude;
const cosLatitude = Math.cos(latitude);
const x = cosLatitude * Math.cos(longitude);
const y = cosLatitude * Math.sin(longitude);
const z = Math.sin(latitude);
if (!defined_default(result)) {
result = new Cartesian3_default();
}
result.x = x;
result.y = y;
result.z = z;
return Cartesian3_default.normalize(result, result);
};
Ellipsoid.prototype.geodeticSurfaceNormal = function(cartesian11, result) {
if (Cartesian3_default.equalsEpsilon(cartesian11, Cartesian3_default.ZERO, Math_default.EPSILON14)) {
return void 0;
}
if (!defined_default(result)) {
result = new Cartesian3_default();
}
result = Cartesian3_default.multiplyComponents(
cartesian11,
this._oneOverRadiiSquared,
result
);
return Cartesian3_default.normalize(result, result);
};
var cartographicToCartesianNormal = new Cartesian3_default();
var cartographicToCartesianK = new Cartesian3_default();
Ellipsoid.prototype.cartographicToCartesian = function(cartographic2, result) {
const n = cartographicToCartesianNormal;
const k = cartographicToCartesianK;
this.geodeticSurfaceNormalCartographic(cartographic2, n);
Cartesian3_default.multiplyComponents(this._radiiSquared, n, k);
const gamma = Math.sqrt(Cartesian3_default.dot(n, k));
Cartesian3_default.divideByScalar(k, gamma, k);
Cartesian3_default.multiplyByScalar(n, cartographic2.height, n);
if (!defined_default(result)) {
result = new Cartesian3_default();
}
return Cartesian3_default.add(k, n, result);
};
Ellipsoid.prototype.cartographicArrayToCartesianArray = function(cartographics, result) {
Check_default.defined("cartographics", cartographics);
const length3 = cartographics.length;
if (!defined_default(result)) {
result = new Array(length3);
} else {
result.length = length3;
}
for (let i = 0; i < length3; i++) {
result[i] = this.cartographicToCartesian(cartographics[i], result[i]);
}
return result;
};
var cartesianToCartographicN2 = new Cartesian3_default();
var cartesianToCartographicP2 = new Cartesian3_default();
var cartesianToCartographicH2 = new Cartesian3_default();
Ellipsoid.prototype.cartesianToCartographic = function(cartesian11, result) {
const p = this.scaleToGeodeticSurface(cartesian11, cartesianToCartographicP2);
if (!defined_default(p)) {
return void 0;
}
const n = this.geodeticSurfaceNormal(p, cartesianToCartographicN2);
const h = Cartesian3_default.subtract(cartesian11, p, cartesianToCartographicH2);
const longitude = Math.atan2(n.y, n.x);
const latitude = Math.asin(n.z);
const height = Math_default.sign(Cartesian3_default.dot(h, cartesian11)) * Cartesian3_default.magnitude(h);
if (!defined_default(result)) {
return new Cartographic_default(longitude, latitude, height);
}
result.longitude = longitude;
result.latitude = latitude;
result.height = height;
return result;
};
Ellipsoid.prototype.cartesianArrayToCartographicArray = function(cartesians, result) {
Check_default.defined("cartesians", cartesians);
const length3 = cartesians.length;
if (!defined_default(result)) {
result = new Array(length3);
} else {
result.length = length3;
}
for (let i = 0; i < length3; ++i) {
result[i] = this.cartesianToCartographic(cartesians[i], result[i]);
}
return result;
};
Ellipsoid.prototype.scaleToGeodeticSurface = function(cartesian11, result) {
return scaleToGeodeticSurface_default(
cartesian11,
this._oneOverRadii,
this._oneOverRadiiSquared,
this._centerToleranceSquared,
result
);
};
Ellipsoid.prototype.scaleToGeocentricSurface = function(cartesian11, result) {
Check_default.typeOf.object("cartesian", cartesian11);
if (!defined_default(result)) {
result = new Cartesian3_default();
}
const positionX = cartesian11.x;
const positionY = cartesian11.y;
const positionZ = cartesian11.z;
const oneOverRadiiSquared = this._oneOverRadiiSquared;
const beta = 1 / Math.sqrt(
positionX * positionX * oneOverRadiiSquared.x + positionY * positionY * oneOverRadiiSquared.y + positionZ * positionZ * oneOverRadiiSquared.z
);
return Cartesian3_default.multiplyByScalar(cartesian11, beta, result);
};
Ellipsoid.prototype.transformPositionToScaledSpace = function(position, result) {
if (!defined_default(result)) {
result = new Cartesian3_default();
}
return Cartesian3_default.multiplyComponents(position, this._oneOverRadii, result);
};
Ellipsoid.prototype.transformPositionFromScaledSpace = function(position, result) {
if (!defined_default(result)) {
result = new Cartesian3_default();
}
return Cartesian3_default.multiplyComponents(position, this._radii, result);
};
Ellipsoid.prototype.equals = function(right) {
return this === right || defined_default(right) && Cartesian3_default.equals(this._radii, right._radii);
};
Ellipsoid.prototype.toString = function() {
return this._radii.toString();
};
Ellipsoid.prototype.getSurfaceNormalIntersectionWithZAxis = function(position, buffer, result) {
Check_default.typeOf.object("position", position);
if (!Math_default.equalsEpsilon(
this._radii.x,
this._radii.y,
Math_default.EPSILON15
)) {
throw new DeveloperError_default(
"Ellipsoid must be an ellipsoid of revolution (radii.x == radii.y)"
);
}
Check_default.typeOf.number.greaterThan("Ellipsoid.radii.z", this._radii.z, 0);
buffer = defaultValue_default(buffer, 0);
const squaredXOverSquaredZ = this._squaredXOverSquaredZ;
if (!defined_default(result)) {
result = new Cartesian3_default();
}
result.x = 0;
result.y = 0;
result.z = position.z * (1 - squaredXOverSquaredZ);
if (Math.abs(result.z) >= this._radii.z - buffer) {
return void 0;
}
return result;
};
var abscissas = [
0.14887433898163,
0.43339539412925,
0.67940956829902,
0.86506336668898,
0.97390652851717,
0
];
var weights = [
0.29552422471475,
0.26926671930999,
0.21908636251598,
0.14945134915058,
0.066671344308684,
0
];
function gaussLegendreQuadrature(a3, b, func) {
Check_default.typeOf.number("a", a3);
Check_default.typeOf.number("b", b);
Check_default.typeOf.func("func", func);
const xMean = 0.5 * (b + a3);
const xRange = 0.5 * (b - a3);
let sum = 0;
for (let i = 0; i < 5; i++) {
const dx = xRange * abscissas[i];
sum += weights[i] * (func(xMean + dx) + func(xMean - dx));
}
sum *= xRange;
return sum;
}
Ellipsoid.prototype.surfaceArea = function(rectangle) {
Check_default.typeOf.object("rectangle", rectangle);
const minLongitude = rectangle.west;
let maxLongitude = rectangle.east;
const minLatitude = rectangle.south;
const maxLatitude = rectangle.north;
while (maxLongitude < minLongitude) {
maxLongitude += Math_default.TWO_PI;
}
const radiiSquared = this._radiiSquared;
const a22 = radiiSquared.x;
const b2 = radiiSquared.y;
const c22 = radiiSquared.z;
const a2b2 = a22 * b2;
return gaussLegendreQuadrature(minLatitude, maxLatitude, function(lat) {
const sinPhi = Math.cos(lat);
const cosPhi = Math.sin(lat);
return Math.cos(lat) * gaussLegendreQuadrature(minLongitude, maxLongitude, function(lon) {
const cosTheta = Math.cos(lon);
const sinTheta = Math.sin(lon);
return Math.sqrt(
a2b2 * cosPhi * cosPhi + c22 * (b2 * cosTheta * cosTheta + a22 * sinTheta * sinTheta) * sinPhi * sinPhi
);
});
});
};
var Ellipsoid_default = Ellipsoid;
// packages/engine/Source/Core/GeographicProjection.js
function GeographicProjection(ellipsoid) {
this._ellipsoid = defaultValue_default(ellipsoid, Ellipsoid_default.WGS84);
this._semimajorAxis = this._ellipsoid.maximumRadius;
this._oneOverSemimajorAxis = 1 / this._semimajorAxis;
}
Object.defineProperties(GeographicProjection.prototype, {
/**
* Gets the {@link Ellipsoid}.
*
* @memberof GeographicProjection.prototype
*
* @type {Ellipsoid}
* @readonly
*/
ellipsoid: {
get: function() {
return this._ellipsoid;
}
}
});
GeographicProjection.prototype.project = function(cartographic2, result) {
const semimajorAxis = this._semimajorAxis;
const x = cartographic2.longitude * semimajorAxis;
const y = cartographic2.latitude * semimajorAxis;
const z = cartographic2.height;
if (!defined_default(result)) {
return new Cartesian3_default(x, y, z);
}
result.x = x;
result.y = y;
result.z = z;
return result;
};
GeographicProjection.prototype.unproject = function(cartesian11, result) {
if (!defined_default(cartesian11)) {
throw new DeveloperError_default("cartesian is required");
}
const oneOverEarthSemimajorAxis = this._oneOverSemimajorAxis;
const longitude = cartesian11.x * oneOverEarthSemimajorAxis;
const latitude = cartesian11.y * oneOverEarthSemimajorAxis;
const height = cartesian11.z;
if (!defined_default(result)) {
return new Cartographic_default(longitude, latitude, height);
}
result.longitude = longitude;
result.latitude = latitude;
result.height = height;
return result;
};
var GeographicProjection_default = GeographicProjection;
// packages/engine/Source/Core/Intersect.js
var Intersect = {
/**
* Represents that an object is not contained within the frustum.
*
* @type {number}
* @constant
*/
OUTSIDE: -1,
/**
* Represents that an object intersects one of the frustum's planes.
*
* @type {number}
* @constant
*/
INTERSECTING: 0,
/**
* Represents that an object is fully within the frustum.
*
* @type {number}
* @constant
*/
INSIDE: 1
};
var Intersect_default = Object.freeze(Intersect);
// packages/engine/Source/Core/Rectangle.js
function Rectangle(west, south, east, north) {
this.west = defaultValue_default(west, 0);
this.south = defaultValue_default(south, 0);
this.east = defaultValue_default(east, 0);
this.north = defaultValue_default(north, 0);
}
Object.defineProperties(Rectangle.prototype, {
/**
* Gets the width of the rectangle in radians.
* @memberof Rectangle.prototype
* @type {number}
* @readonly
*/
width: {
get: function() {
return Rectangle.computeWidth(this);
}
},
/**
* Gets the height of the rectangle in radians.
* @memberof Rectangle.prototype
* @type {number}
* @readonly
*/
height: {
get: function() {
return Rectangle.computeHeight(this);
}
}
});
Rectangle.packedLength = 4;
Rectangle.pack = function(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
array[startingIndex++] = value.west;
array[startingIndex++] = value.south;
array[startingIndex++] = value.east;
array[startingIndex] = value.north;
return array;
};
Rectangle.unpack = function(array, startingIndex, result) {
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
if (!defined_default(result)) {
result = new Rectangle();
}
result.west = array[startingIndex++];
result.south = array[startingIndex++];
result.east = array[startingIndex++];
result.north = array[startingIndex];
return result;
};
Rectangle.computeWidth = function(rectangle) {
Check_default.typeOf.object("rectangle", rectangle);
let east = rectangle.east;
const west = rectangle.west;
if (east < west) {
east += Math_default.TWO_PI;
}
return east - west;
};
Rectangle.computeHeight = function(rectangle) {
Check_default.typeOf.object("rectangle", rectangle);
return rectangle.north - rectangle.south;
};
Rectangle.fromDegrees = function(west, south, east, north, result) {
west = Math_default.toRadians(defaultValue_default(west, 0));
south = Math_default.toRadians(defaultValue_default(south, 0));
east = Math_default.toRadians(defaultValue_default(east, 0));
north = Math_default.toRadians(defaultValue_default(north, 0));
if (!defined_default(result)) {
return new Rectangle(west, south, east, north);
}
result.west = west;
result.south = south;
result.east = east;
result.north = north;
return result;
};
Rectangle.fromRadians = function(west, south, east, north, result) {
if (!defined_default(result)) {
return new Rectangle(west, south, east, north);
}
result.west = defaultValue_default(west, 0);
result.south = defaultValue_default(south, 0);
result.east = defaultValue_default(east, 0);
result.north = defaultValue_default(north, 0);
return result;
};
Rectangle.fromCartographicArray = function(cartographics, result) {
Check_default.defined("cartographics", cartographics);
let west = Number.MAX_VALUE;
let east = -Number.MAX_VALUE;
let westOverIDL = Number.MAX_VALUE;
let eastOverIDL = -Number.MAX_VALUE;
let south = Number.MAX_VALUE;
let north = -Number.MAX_VALUE;
for (let i = 0, len = cartographics.length; i < len; i++) {
const position = cartographics[i];
west = Math.min(west, position.longitude);
east = Math.max(east, position.longitude);
south = Math.min(south, position.latitude);
north = Math.max(north, position.latitude);
const lonAdjusted = position.longitude >= 0 ? position.longitude : position.longitude + Math_default.TWO_PI;
westOverIDL = Math.min(westOverIDL, lonAdjusted);
eastOverIDL = Math.max(eastOverIDL, lonAdjusted);
}
if (east - west > eastOverIDL - westOverIDL) {
west = westOverIDL;
east = eastOverIDL;
if (east > Math_default.PI) {
east = east - Math_default.TWO_PI;
}
if (west > Math_default.PI) {
west = west - Math_default.TWO_PI;
}
}
if (!defined_default(result)) {
return new Rectangle(west, south, east, north);
}
result.west = west;
result.south = south;
result.east = east;
result.north = north;
return result;
};
Rectangle.fromCartesianArray = function(cartesians, ellipsoid, result) {
Check_default.defined("cartesians", cartesians);
ellipsoid = defaultValue_default(ellipsoid, Ellipsoid_default.WGS84);
let west = Number.MAX_VALUE;
let east = -Number.MAX_VALUE;
let westOverIDL = Number.MAX_VALUE;
let eastOverIDL = -Number.MAX_VALUE;
let south = Number.MAX_VALUE;
let north = -Number.MAX_VALUE;
for (let i = 0, len = cartesians.length; i < len; i++) {
const position = ellipsoid.cartesianToCartographic(cartesians[i]);
west = Math.min(west, position.longitude);
east = Math.max(east, position.longitude);
south = Math.min(south, position.latitude);
north = Math.max(north, position.latitude);
const lonAdjusted = position.longitude >= 0 ? position.longitude : position.longitude + Math_default.TWO_PI;
westOverIDL = Math.min(westOverIDL, lonAdjusted);
eastOverIDL = Math.max(eastOverIDL, lonAdjusted);
}
if (east - west > eastOverIDL - westOverIDL) {
west = westOverIDL;
east = eastOverIDL;
if (east > Math_default.PI) {
east = east - Math_default.TWO_PI;
}
if (west > Math_default.PI) {
west = west - Math_default.TWO_PI;
}
}
if (!defined_default(result)) {
return new Rectangle(west, south, east, north);
}
result.west = west;
result.south = south;
result.east = east;
result.north = north;
return result;
};
Rectangle.clone = function(rectangle, result) {
if (!defined_default(rectangle)) {
return void 0;
}
if (!defined_default(result)) {
return new Rectangle(
rectangle.west,
rectangle.south,
rectangle.east,
rectangle.north
);
}
result.west = rectangle.west;
result.south = rectangle.south;
result.east = rectangle.east;
result.north = rectangle.north;
return result;
};
Rectangle.equalsEpsilon = function(left, right, absoluteEpsilon) {
absoluteEpsilon = defaultValue_default(absoluteEpsilon, 0);
return left === right || defined_default(left) && defined_default(right) && Math.abs(left.west - right.west) <= absoluteEpsilon && Math.abs(left.south - right.south) <= absoluteEpsilon && Math.abs(left.east - right.east) <= absoluteEpsilon && Math.abs(left.north - right.north) <= absoluteEpsilon;
};
Rectangle.prototype.clone = function(result) {
return Rectangle.clone(this, result);
};
Rectangle.prototype.equals = function(other) {
return Rectangle.equals(this, other);
};
Rectangle.equals = function(left, right) {
return left === right || defined_default(left) && defined_default(right) && left.west === right.west && left.south === right.south && left.east === right.east && left.north === right.north;
};
Rectangle.prototype.equalsEpsilon = function(other, epsilon) {
return Rectangle.equalsEpsilon(this, other, epsilon);
};
Rectangle.validate = function(rectangle) {
Check_default.typeOf.object("rectangle", rectangle);
const north = rectangle.north;
Check_default.typeOf.number.greaterThanOrEquals(
"north",
north,
-Math_default.PI_OVER_TWO
);
Check_default.typeOf.number.lessThanOrEquals("north", north, Math_default.PI_OVER_TWO);
const south = rectangle.south;
Check_default.typeOf.number.greaterThanOrEquals(
"south",
south,
-Math_default.PI_OVER_TWO
);
Check_default.typeOf.number.lessThanOrEquals("south", south, Math_default.PI_OVER_TWO);
const west = rectangle.west;
Check_default.typeOf.number.greaterThanOrEquals("west", west, -Math.PI);
Check_default.typeOf.number.lessThanOrEquals("west", west, Math.PI);
const east = rectangle.east;
Check_default.typeOf.number.greaterThanOrEquals("east", east, -Math.PI);
Check_default.typeOf.number.lessThanOrEquals("east", east, Math.PI);
};
Rectangle.southwest = function(rectangle, result) {
Check_default.typeOf.object("rectangle", rectangle);
if (!defined_default(result)) {
return new Cartographic_default(rectangle.west, rectangle.south);
}
result.longitude = rectangle.west;
result.latitude = rectangle.south;
result.height = 0;
return result;
};
Rectangle.northwest = function(rectangle, result) {
Check_default.typeOf.object("rectangle", rectangle);
if (!defined_default(result)) {
return new Cartographic_default(rectangle.west, rectangle.north);
}
result.longitude = rectangle.west;
result.latitude = rectangle.north;
result.height = 0;
return result;
};
Rectangle.northeast = function(rectangle, result) {
Check_default.typeOf.object("rectangle", rectangle);
if (!defined_default(result)) {
return new Cartographic_default(rectangle.east, rectangle.north);
}
result.longitude = rectangle.east;
result.latitude = rectangle.north;
result.height = 0;
return result;
};
Rectangle.southeast = function(rectangle, result) {
Check_default.typeOf.object("rectangle", rectangle);
if (!defined_default(result)) {
return new Cartographic_default(rectangle.east, rectangle.south);
}
result.longitude = rectangle.east;
result.latitude = rectangle.south;
result.height = 0;
return result;
};
Rectangle.center = function(rectangle, result) {
Check_default.typeOf.object("rectangle", rectangle);
let east = rectangle.east;
const west = rectangle.west;
if (east < west) {
east += Math_default.TWO_PI;
}
const longitude = Math_default.negativePiToPi((west + east) * 0.5);
const latitude = (rectangle.south + rectangle.north) * 0.5;
if (!defined_default(result)) {
return new Cartographic_default(longitude, latitude);
}
result.longitude = longitude;
result.latitude = latitude;
result.height = 0;
return result;
};
Rectangle.intersection = function(rectangle, otherRectangle, result) {
Check_default.typeOf.object("rectangle", rectangle);
Check_default.typeOf.object("otherRectangle", otherRectangle);
let rectangleEast = rectangle.east;
let rectangleWest = rectangle.west;
let otherRectangleEast = otherRectangle.east;
let otherRectangleWest = otherRectangle.west;
if (rectangleEast < rectangleWest && otherRectangleEast > 0) {
rectangleEast += Math_default.TWO_PI;
} else if (otherRectangleEast < otherRectangleWest && rectangleEast > 0) {
otherRectangleEast += Math_default.TWO_PI;
}
if (rectangleEast < rectangleWest && otherRectangleWest < 0) {
otherRectangleWest += Math_default.TWO_PI;
} else if (otherRectangleEast < otherRectangleWest && rectangleWest < 0) {
rectangleWest += Math_default.TWO_PI;
}
const west = Math_default.negativePiToPi(
Math.max(rectangleWest, otherRectangleWest)
);
const east = Math_default.negativePiToPi(
Math.min(rectangleEast, otherRectangleEast)
);
if ((rectangle.west < rectangle.east || otherRectangle.west < otherRectangle.east) && east <= west) {
return void 0;
}
const south = Math.max(rectangle.south, otherRectangle.south);
const north = Math.min(rectangle.north, otherRectangle.north);
if (south >= north) {
return void 0;
}
if (!defined_default(result)) {
return new Rectangle(west, south, east, north);
}
result.west = west;
result.south = south;
result.east = east;
result.north = north;
return result;
};
Rectangle.simpleIntersection = function(rectangle, otherRectangle, result) {
Check_default.typeOf.object("rectangle", rectangle);
Check_default.typeOf.object("otherRectangle", otherRectangle);
const west = Math.max(rectangle.west, otherRectangle.west);
const south = Math.max(rectangle.south, otherRectangle.south);
const east = Math.min(rectangle.east, otherRectangle.east);
const north = Math.min(rectangle.north, otherRectangle.north);
if (south >= north || west >= east) {
return void 0;
}
if (!defined_default(result)) {
return new Rectangle(west, south, east, north);
}
result.west = west;
result.south = south;
result.east = east;
result.north = north;
return result;
};
Rectangle.union = function(rectangle, otherRectangle, result) {
Check_default.typeOf.object("rectangle", rectangle);
Check_default.typeOf.object("otherRectangle", otherRectangle);
if (!defined_default(result)) {
result = new Rectangle();
}
let rectangleEast = rectangle.east;
let rectangleWest = rectangle.west;
let otherRectangleEast = otherRectangle.east;
let otherRectangleWest = otherRectangle.west;
if (rectangleEast < rectangleWest && otherRectangleEast > 0) {
rectangleEast += Math_default.TWO_PI;
} else if (otherRectangleEast < otherRectangleWest && rectangleEast > 0) {
otherRectangleEast += Math_default.TWO_PI;
}
if (rectangleEast < rectangleWest && otherRectangleWest < 0) {
otherRectangleWest += Math_default.TWO_PI;
} else if (otherRectangleEast < otherRectangleWest && rectangleWest < 0) {
rectangleWest += Math_default.TWO_PI;
}
const west = Math_default.negativePiToPi(
Math.min(rectangleWest, otherRectangleWest)
);
const east = Math_default.negativePiToPi(
Math.max(rectangleEast, otherRectangleEast)
);
result.west = west;
result.south = Math.min(rectangle.south, otherRectangle.south);
result.east = east;
result.north = Math.max(rectangle.north, otherRectangle.north);
return result;
};
Rectangle.expand = function(rectangle, cartographic2, result) {
Check_default.typeOf.object("rectangle", rectangle);
Check_default.typeOf.object("cartographic", cartographic2);
if (!defined_default(result)) {
result = new Rectangle();
}
result.west = Math.min(rectangle.west, cartographic2.longitude);
result.south = Math.min(rectangle.south, cartographic2.latitude);
result.east = Math.max(rectangle.east, cartographic2.longitude);
result.north = Math.max(rectangle.north, cartographic2.latitude);
return result;
};
Rectangle.contains = function(rectangle, cartographic2) {
Check_default.typeOf.object("rectangle", rectangle);
Check_default.typeOf.object("cartographic", cartographic2);
let longitude = cartographic2.longitude;
const latitude = cartographic2.latitude;
const west = rectangle.west;
let east = rectangle.east;
if (east < west) {
east += Math_default.TWO_PI;
if (longitude < 0) {
longitude += Math_default.TWO_PI;
}
}
return (longitude > west || Math_default.equalsEpsilon(longitude, west, Math_default.EPSILON14)) && (longitude < east || Math_default.equalsEpsilon(longitude, east, Math_default.EPSILON14)) && latitude >= rectangle.south && latitude <= rectangle.north;
};
var subsampleLlaScratch = new Cartographic_default();
Rectangle.subsample = function(rectangle, ellipsoid, surfaceHeight, result) {
Check_default.typeOf.object("rectangle", rectangle);
ellipsoid = defaultValue_default(ellipsoid, Ellipsoid_default.WGS84);
surfaceHeight = defaultValue_default(surfaceHeight, 0);
if (!defined_default(result)) {
result = [];
}
let length3 = 0;
const north = rectangle.north;
const south = rectangle.south;
const east = rectangle.east;
const west = rectangle.west;
const lla = subsampleLlaScratch;
lla.height = surfaceHeight;
lla.longitude = west;
lla.latitude = north;
result[length3] = ellipsoid.cartographicToCartesian(lla, result[length3]);
length3++;
lla.longitude = east;
result[length3] = ellipsoid.cartographicToCartesian(lla, result[length3]);
length3++;
lla.latitude = south;
result[length3] = ellipsoid.cartographicToCartesian(lla, result[length3]);
length3++;
lla.longitude = west;
result[length3] = ellipsoid.cartographicToCartesian(lla, result[length3]);
length3++;
if (north < 0) {
lla.latitude = north;
} else if (south > 0) {
lla.latitude = south;
} else {
lla.latitude = 0;
}
for (let i = 1; i < 8; ++i) {
lla.longitude = -Math.PI + i * Math_default.PI_OVER_TWO;
if (Rectangle.contains(rectangle, lla)) {
result[length3] = ellipsoid.cartographicToCartesian(lla, result[length3]);
length3++;
}
}
if (lla.latitude === 0) {
lla.longitude = west;
result[length3] = ellipsoid.cartographicToCartesian(lla, result[length3]);
length3++;
lla.longitude = east;
result[length3] = ellipsoid.cartographicToCartesian(lla, result[length3]);
length3++;
}
result.length = length3;
return result;
};
Rectangle.subsection = function(rectangle, westLerp, southLerp, eastLerp, northLerp, result) {
Check_default.typeOf.object("rectangle", rectangle);
Check_default.typeOf.number.greaterThanOrEquals("westLerp", westLerp, 0);
Check_default.typeOf.number.lessThanOrEquals("westLerp", westLerp, 1);
Check_default.typeOf.number.greaterThanOrEquals("southLerp", southLerp, 0);
Check_default.typeOf.number.lessThanOrEquals("southLerp", southLerp, 1);
Check_default.typeOf.number.greaterThanOrEquals("eastLerp", eastLerp, 0);
Check_default.typeOf.number.lessThanOrEquals("eastLerp", eastLerp, 1);
Check_default.typeOf.number.greaterThanOrEquals("northLerp", northLerp, 0);
Check_default.typeOf.number.lessThanOrEquals("northLerp", northLerp, 1);
Check_default.typeOf.number.lessThanOrEquals("westLerp", westLerp, eastLerp);
Check_default.typeOf.number.lessThanOrEquals("southLerp", southLerp, northLerp);
if (!defined_default(result)) {
result = new Rectangle();
}
if (rectangle.west <= rectangle.east) {
const width = rectangle.east - rectangle.west;
result.west = rectangle.west + westLerp * width;
result.east = rectangle.west + eastLerp * width;
} else {
const width = Math_default.TWO_PI + rectangle.east - rectangle.west;
result.west = Math_default.negativePiToPi(rectangle.west + westLerp * width);
result.east = Math_default.negativePiToPi(rectangle.west + eastLerp * width);
}
const height = rectangle.north - rectangle.south;
result.south = rectangle.south + southLerp * height;
result.north = rectangle.south + northLerp * height;
if (westLerp === 1) {
result.west = rectangle.east;
}
if (eastLerp === 1) {
result.east = rectangle.east;
}
if (southLerp === 1) {
result.south = rectangle.north;
}
if (northLerp === 1) {
result.north = rectangle.north;
}
return result;
};
Rectangle.MAX_VALUE = Object.freeze(
new Rectangle(
-Math.PI,
-Math_default.PI_OVER_TWO,
Math.PI,
Math_default.PI_OVER_TWO
)
);
var Rectangle_default = Rectangle;
// packages/engine/Source/Core/BoundingRectangle.js
function BoundingRectangle(x, y, width, height) {
this.x = defaultValue_default(x, 0);
this.y = defaultValue_default(y, 0);
this.width = defaultValue_default(width, 0);
this.height = defaultValue_default(height, 0);
}
BoundingRectangle.packedLength = 4;
BoundingRectangle.pack = function(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
array[startingIndex++] = value.x;
array[startingIndex++] = value.y;
array[startingIndex++] = value.width;
array[startingIndex] = value.height;
return array;
};
BoundingRectangle.unpack = function(array, startingIndex, result) {
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
if (!defined_default(result)) {
result = new BoundingRectangle();
}
result.x = array[startingIndex++];
result.y = array[startingIndex++];
result.width = array[startingIndex++];
result.height = array[startingIndex];
return result;
};
BoundingRectangle.fromPoints = function(positions, result) {
if (!defined_default(result)) {
result = new BoundingRectangle();
}
if (!defined_default(positions) || positions.length === 0) {
result.x = 0;
result.y = 0;
result.width = 0;
result.height = 0;
return result;
}
const length3 = positions.length;
let minimumX = positions[0].x;
let minimumY = positions[0].y;
let maximumX = positions[0].x;
let maximumY = positions[0].y;
for (let i = 1; i < length3; i++) {
const p = positions[i];
const x = p.x;
const y = p.y;
minimumX = Math.min(x, minimumX);
maximumX = Math.max(x, maximumX);
minimumY = Math.min(y, minimumY);
maximumY = Math.max(y, maximumY);
}
result.x = minimumX;
result.y = minimumY;
result.width = maximumX - minimumX;
result.height = maximumY - minimumY;
return result;
};
var defaultProjection = new GeographicProjection_default();
var fromRectangleLowerLeft = new Cartographic_default();
var fromRectangleUpperRight = new Cartographic_default();
BoundingRectangle.fromRectangle = function(rectangle, projection, result) {
if (!defined_default(result)) {
result = new BoundingRectangle();
}
if (!defined_default(rectangle)) {
result.x = 0;
result.y = 0;
result.width = 0;
result.height = 0;
return result;
}
projection = defaultValue_default(projection, defaultProjection);
const lowerLeft = projection.project(
Rectangle_default.southwest(rectangle, fromRectangleLowerLeft)
);
const upperRight = projection.project(
Rectangle_default.northeast(rectangle, fromRectangleUpperRight)
);
Cartesian2_default.subtract(upperRight, lowerLeft, upperRight);
result.x = lowerLeft.x;
result.y = lowerLeft.y;
result.width = upperRight.x;
result.height = upperRight.y;
return result;
};
BoundingRectangle.clone = function(rectangle, result) {
if (!defined_default(rectangle)) {
return void 0;
}
if (!defined_default(result)) {
return new BoundingRectangle(
rectangle.x,
rectangle.y,
rectangle.width,
rectangle.height
);
}
result.x = rectangle.x;
result.y = rectangle.y;
result.width = rectangle.width;
result.height = rectangle.height;
return result;
};
BoundingRectangle.union = function(left, right, result) {
Check_default.typeOf.object("left", left);
Check_default.typeOf.object("right", right);
if (!defined_default(result)) {
result = new BoundingRectangle();
}
const lowerLeftX = Math.min(left.x, right.x);
const lowerLeftY = Math.min(left.y, right.y);
const upperRightX = Math.max(left.x + left.width, right.x + right.width);
const upperRightY = Math.max(left.y + left.height, right.y + right.height);
result.x = lowerLeftX;
result.y = lowerLeftY;
result.width = upperRightX - lowerLeftX;
result.height = upperRightY - lowerLeftY;
return result;
};
BoundingRectangle.expand = function(rectangle, point, result) {
Check_default.typeOf.object("rectangle", rectangle);
Check_default.typeOf.object("point", point);
result = BoundingRectangle.clone(rectangle, result);
const width = point.x - result.x;
const height = point.y - result.y;
if (width > result.width) {
result.width = width;
} else if (width < 0) {
result.width -= width;
result.x = point.x;
}
if (height > result.height) {
result.height = height;
} else if (height < 0) {
result.height -= height;
result.y = point.y;
}
return result;
};
BoundingRectangle.intersect = function(left, right) {
Check_default.typeOf.object("left", left);
Check_default.typeOf.object("right", right);
const leftX = left.x;
const leftY = left.y;
const rightX = right.x;
const rightY = right.y;
if (!(leftX > rightX + right.width || leftX + left.width < rightX || leftY + left.height < rightY || leftY > rightY + right.height)) {
return Intersect_default.INTERSECTING;
}
return Intersect_default.OUTSIDE;
};
BoundingRectangle.equals = function(left, right) {
return left === right || defined_default(left) && defined_default(right) && left.x === right.x && left.y === right.y && left.width === right.width && left.height === right.height;
};
BoundingRectangle.prototype.clone = function(result) {
return BoundingRectangle.clone(this, result);
};
BoundingRectangle.prototype.intersect = function(right) {
return BoundingRectangle.intersect(this, right);
};
BoundingRectangle.prototype.equals = function(right) {
return BoundingRectangle.equals(this, right);
};
var BoundingRectangle_default = BoundingRectangle;
// packages/engine/Source/Core/PrimitiveType.js
var PrimitiveType = {
/**
* Points primitive where each vertex (or index) is a separate point.
*
* @type {number}
* @constant
*/
POINTS: WebGLConstants_default.POINTS,
/**
* Lines primitive where each two vertices (or indices) is a line segment. Line segments are not necessarily connected.
*
* @type {number}
* @constant
*/
LINES: WebGLConstants_default.LINES,
/**
* Line loop primitive where each vertex (or index) after the first connects a line to
* the previous vertex, and the last vertex implicitly connects to the first.
*
* @type {number}
* @constant
*/
LINE_LOOP: WebGLConstants_default.LINE_LOOP,
/**
* Line strip primitive where each vertex (or index) after the first connects a line to the previous vertex.
*
* @type {number}
* @constant
*/
LINE_STRIP: WebGLConstants_default.LINE_STRIP,
/**
* Triangles primitive where each three vertices (or indices) is a triangle. Triangles do not necessarily share edges.
*
* @type {number}
* @constant
*/
TRIANGLES: WebGLConstants_default.TRIANGLES,
/**
* Triangle strip primitive where each vertex (or index) after the first two connect to
* the previous two vertices forming a triangle. For example, this can be used to model a wall.
*
* @type {number}
* @constant
*/
TRIANGLE_STRIP: WebGLConstants_default.TRIANGLE_STRIP,
/**
* Triangle fan primitive where each vertex (or index) after the first two connect to
* the previous vertex and the first vertex forming a triangle. For example, this can be used
* to model a cone or circle.
*
* @type {number}
* @constant
*/
TRIANGLE_FAN: WebGLConstants_default.TRIANGLE_FAN
};
PrimitiveType.isLines = function(primitiveType) {
return primitiveType === PrimitiveType.LINES || primitiveType === PrimitiveType.LINE_LOOP || primitiveType === PrimitiveType.LINE_STRIP;
};
PrimitiveType.isTriangles = function(primitiveType) {
return primitiveType === PrimitiveType.TRIANGLES || primitiveType === PrimitiveType.TRIANGLE_STRIP || primitiveType === PrimitiveType.TRIANGLE_FAN;
};
PrimitiveType.validate = function(primitiveType) {
return primitiveType === PrimitiveType.POINTS || primitiveType === PrimitiveType.LINES || primitiveType === PrimitiveType.LINE_LOOP || primitiveType === PrimitiveType.LINE_STRIP || primitiveType === PrimitiveType.TRIANGLES || primitiveType === PrimitiveType.TRIANGLE_STRIP || primitiveType === PrimitiveType.TRIANGLE_FAN;
};
var PrimitiveType_default = Object.freeze(PrimitiveType);
// packages/engine/Source/Shaders/ViewportQuadVS.js
var ViewportQuadVS_default = "in vec4 position;\nin vec2 textureCoordinates;\n\nout vec2 v_textureCoordinates;\n\nvoid main() \n{\n gl_Position = position;\n v_textureCoordinates = textureCoordinates;\n}\n";
// packages/engine/Source/Renderer/DrawCommand.js
var Flags = {
CULL: 1,
OCCLUDE: 2,
EXECUTE_IN_CLOSEST_FRUSTUM: 4,
DEBUG_SHOW_BOUNDING_VOLUME: 8,
CAST_SHADOWS: 16,
RECEIVE_SHADOWS: 32,
PICK_ONLY: 64,
DEPTH_FOR_TRANSLUCENT_CLASSIFICATION: 128
};
function DrawCommand(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this._boundingVolume = options.boundingVolume;
this._orientedBoundingBox = options.orientedBoundingBox;
this._modelMatrix = options.modelMatrix;
this._primitiveType = defaultValue_default(
options.primitiveType,
PrimitiveType_default.TRIANGLES
);
this._vertexArray = options.vertexArray;
this._count = options.count;
this._offset = defaultValue_default(options.offset, 0);
this._instanceCount = defaultValue_default(options.instanceCount, 0);
this._shaderProgram = options.shaderProgram;
this._uniformMap = options.uniformMap;
this._renderState = options.renderState;
this._framebuffer = options.framebuffer;
this._pass = options.pass;
this._owner = options.owner;
this._debugOverlappingFrustums = 0;
this._pickId = options.pickId;
this._flags = 0;
this.cull = defaultValue_default(options.cull, true);
this.occlude = defaultValue_default(options.occlude, true);
this.executeInClosestFrustum = defaultValue_default(
options.executeInClosestFrustum,
false
);
this.debugShowBoundingVolume = defaultValue_default(
options.debugShowBoundingVolume,
false
);
this.castShadows = defaultValue_default(options.castShadows, false);
this.receiveShadows = defaultValue_default(options.receiveShadows, false);
this.pickOnly = defaultValue_default(options.pickOnly, false);
this.depthForTranslucentClassification = defaultValue_default(
options.depthForTranslucentClassification,
false
);
this.dirty = true;
this.lastDirtyTime = 0;
this.derivedCommands = {};
}
function hasFlag(command, flag) {
return (command._flags & flag) === flag;
}
function setFlag(command, flag, value) {
if (value) {
command._flags |= flag;
} else {
command._flags &= ~flag;
}
}
Object.defineProperties(DrawCommand.prototype, {
/**
* The bounding volume of the geometry in world space. This is used for culling and frustum selection.
* undefined
is allowed, always try to provide a bounding volume to
* allow the tightest possible near and far planes to be computed for the scene, and
* minimize the number of frustums needed.
* true
, the renderer frustum and horizon culls the command based on its {@link DrawCommand#boundingVolume}.
* If the command was already culled, set this to false
for a performance improvement.
*
* @memberof DrawCommand.prototype
* @type {boolean}
* @default true
*/
cull: {
get: function() {
return hasFlag(this, Flags.CULL);
},
set: function(value) {
if (hasFlag(this, Flags.CULL) !== value) {
setFlag(this, Flags.CULL, value);
this.dirty = true;
}
}
},
/**
* When true
, the horizon culls the command based on its {@link DrawCommand#boundingVolume}.
* {@link DrawCommand#cull} must also be true
in order for the command to be culled.
*
* @memberof DrawCommand.prototype
* @type {boolean}
* @default true
*/
occlude: {
get: function() {
return hasFlag(this, Flags.OCCLUDE);
},
set: function(value) {
if (hasFlag(this, Flags.OCCLUDE) !== value) {
setFlag(this, Flags.OCCLUDE, value);
this.dirty = true;
}
}
},
/**
* The transformation from the geometry in model space to world space.
* undefined
, the geometry is assumed to be defined in world space.
* false
.
*
* @memberof DrawCommand.prototype
* @type {boolean}
* @default false
*/
executeInClosestFrustum: {
get: function() {
return hasFlag(this, Flags.EXECUTE_IN_CLOSEST_FRUSTUM);
},
set: function(value) {
if (hasFlag(this, Flags.EXECUTE_IN_CLOSEST_FRUSTUM) !== value) {
setFlag(this, Flags.EXECUTE_IN_CLOSEST_FRUSTUM, value);
this.dirty = true;
}
}
},
/**
* The object who created this command. This is useful for debugging command
* execution; it allows us to see who created a command when we only have a
* reference to the command, and can be used to selectively execute commands
* with {@link Scene#debugCommandFilter}.
*
* @memberof DrawCommand.prototype
* @type {object}
* @default undefined
*
* @see Scene#debugCommandFilter
*/
owner: {
get: function() {
return this._owner;
},
set: function(value) {
if (this._owner !== value) {
this._owner = value;
this.dirty = true;
}
}
},
/**
* This property is for debugging only; it is not for production use nor is it optimized.
* undefined
, the command will only draw depth
* during the pick pass.
*
* @memberof DrawCommand.prototype
* @type {string}
* @default undefined
*/
pickId: {
get: function() {
return this._pickId;
},
set: function(value) {
if (this._pickId !== value) {
this._pickId = value;
this.dirty = true;
}
}
},
/**
* Whether this command should be executed in the pick pass only.
*
* @memberof DrawCommand.prototype
* @type {boolean}
* @default false
*/
pickOnly: {
get: function() {
return hasFlag(this, Flags.PICK_ONLY);
},
set: function(value) {
if (hasFlag(this, Flags.PICK_ONLY) !== value) {
setFlag(this, Flags.PICK_ONLY, value);
this.dirty = true;
}
}
},
/**
* Whether this command should be derived to draw depth for classification of translucent primitives.
*
* @memberof DrawCommand.prototype
* @type {boolean}
* @default false
*/
depthForTranslucentClassification: {
get: function() {
return hasFlag(this, Flags.DEPTH_FOR_TRANSLUCENT_CLASSIFICATION);
},
set: function(value) {
if (hasFlag(this, Flags.DEPTH_FOR_TRANSLUCENT_CLASSIFICATION) !== value) {
setFlag(this, Flags.DEPTH_FOR_TRANSLUCENT_CLASSIFICATION, value);
this.dirty = true;
}
}
}
});
DrawCommand.shallowClone = function(command, result) {
if (!defined_default(command)) {
return void 0;
}
if (!defined_default(result)) {
result = new DrawCommand();
}
result._boundingVolume = command._boundingVolume;
result._orientedBoundingBox = command._orientedBoundingBox;
result._modelMatrix = command._modelMatrix;
result._primitiveType = command._primitiveType;
result._vertexArray = command._vertexArray;
result._count = command._count;
result._offset = command._offset;
result._instanceCount = command._instanceCount;
result._shaderProgram = command._shaderProgram;
result._uniformMap = command._uniformMap;
result._renderState = command._renderState;
result._framebuffer = command._framebuffer;
result._pass = command._pass;
result._owner = command._owner;
result._debugOverlappingFrustums = command._debugOverlappingFrustums;
result._pickId = command._pickId;
result._flags = command._flags;
result.dirty = true;
result.lastDirtyTime = 0;
return result;
};
DrawCommand.prototype.execute = function(context, passState) {
context.draw(this, passState);
};
var DrawCommand_default = DrawCommand;
// packages/engine/Source/Renderer/PixelDatatype.js
var PixelDatatype = {
UNSIGNED_BYTE: WebGLConstants_default.UNSIGNED_BYTE,
UNSIGNED_SHORT: WebGLConstants_default.UNSIGNED_SHORT,
UNSIGNED_INT: WebGLConstants_default.UNSIGNED_INT,
FLOAT: WebGLConstants_default.FLOAT,
HALF_FLOAT: WebGLConstants_default.HALF_FLOAT_OES,
UNSIGNED_INT_24_8: WebGLConstants_default.UNSIGNED_INT_24_8,
UNSIGNED_SHORT_4_4_4_4: WebGLConstants_default.UNSIGNED_SHORT_4_4_4_4,
UNSIGNED_SHORT_5_5_5_1: WebGLConstants_default.UNSIGNED_SHORT_5_5_5_1,
UNSIGNED_SHORT_5_6_5: WebGLConstants_default.UNSIGNED_SHORT_5_6_5
};
PixelDatatype.toWebGLConstant = function(pixelDatatype, context) {
switch (pixelDatatype) {
case PixelDatatype.UNSIGNED_BYTE:
return WebGLConstants_default.UNSIGNED_BYTE;
case PixelDatatype.UNSIGNED_SHORT:
return WebGLConstants_default.UNSIGNED_SHORT;
case PixelDatatype.UNSIGNED_INT:
return WebGLConstants_default.UNSIGNED_INT;
case PixelDatatype.FLOAT:
return WebGLConstants_default.FLOAT;
case PixelDatatype.HALF_FLOAT:
return context.webgl2 ? WebGLConstants_default.HALF_FLOAT : WebGLConstants_default.HALF_FLOAT_OES;
case PixelDatatype.UNSIGNED_INT_24_8:
return WebGLConstants_default.UNSIGNED_INT_24_8;
case PixelDatatype.UNSIGNED_SHORT_4_4_4_4:
return WebGLConstants_default.UNSIGNED_SHORT_4_4_4_4;
case PixelDatatype.UNSIGNED_SHORT_5_5_5_1:
return WebGLConstants_default.UNSIGNED_SHORT_5_5_5_1;
case PixelDatatype.UNSIGNED_SHORT_5_6_5:
return PixelDatatype.UNSIGNED_SHORT_5_6_5;
}
};
PixelDatatype.isPacked = function(pixelDatatype) {
return pixelDatatype === PixelDatatype.UNSIGNED_INT_24_8 || pixelDatatype === PixelDatatype.UNSIGNED_SHORT_4_4_4_4 || pixelDatatype === PixelDatatype.UNSIGNED_SHORT_5_5_5_1 || pixelDatatype === PixelDatatype.UNSIGNED_SHORT_5_6_5;
};
PixelDatatype.sizeInBytes = function(pixelDatatype) {
switch (pixelDatatype) {
case PixelDatatype.UNSIGNED_BYTE:
return 1;
case PixelDatatype.UNSIGNED_SHORT:
case PixelDatatype.UNSIGNED_SHORT_4_4_4_4:
case PixelDatatype.UNSIGNED_SHORT_5_5_5_1:
case PixelDatatype.UNSIGNED_SHORT_5_6_5:
case PixelDatatype.HALF_FLOAT:
return 2;
case PixelDatatype.UNSIGNED_INT:
case PixelDatatype.FLOAT:
case PixelDatatype.UNSIGNED_INT_24_8:
return 4;
}
};
PixelDatatype.validate = function(pixelDatatype) {
return pixelDatatype === PixelDatatype.UNSIGNED_BYTE || pixelDatatype === PixelDatatype.UNSIGNED_SHORT || pixelDatatype === PixelDatatype.UNSIGNED_INT || pixelDatatype === PixelDatatype.FLOAT || pixelDatatype === PixelDatatype.HALF_FLOAT || pixelDatatype === PixelDatatype.UNSIGNED_INT_24_8 || pixelDatatype === PixelDatatype.UNSIGNED_SHORT_4_4_4_4 || pixelDatatype === PixelDatatype.UNSIGNED_SHORT_5_5_5_1 || pixelDatatype === PixelDatatype.UNSIGNED_SHORT_5_6_5;
};
var PixelDatatype_default = Object.freeze(PixelDatatype);
// packages/engine/Source/Core/PixelFormat.js
var PixelFormat = {
/**
* A pixel format containing a depth value.
*
* @type {number}
* @constant
*/
DEPTH_COMPONENT: WebGLConstants_default.DEPTH_COMPONENT,
/**
* A pixel format containing a depth and stencil value, most often used with {@link PixelDatatype.UNSIGNED_INT_24_8}.
*
* @type {number}
* @constant
*/
DEPTH_STENCIL: WebGLConstants_default.DEPTH_STENCIL,
/**
* A pixel format containing an alpha channel.
*
* @type {number}
* @constant
*/
ALPHA: WebGLConstants_default.ALPHA,
/**
* A pixel format containing a red channel
*
* @type {number}
* @constant
*/
RED: WebGLConstants_default.RED,
/**
* A pixel format containing red and green channels.
*
* @type {number}
* @constant
*/
RG: WebGLConstants_default.RG,
/**
* A pixel format containing red, green, and blue channels.
*
* @type {number}
* @constant
*/
RGB: WebGLConstants_default.RGB,
/**
* A pixel format containing red, green, blue, and alpha channels.
*
* @type {number}
* @constant
*/
RGBA: WebGLConstants_default.RGBA,
/**
* A pixel format containing a luminance (intensity) channel.
*
* @type {number}
* @constant
*/
LUMINANCE: WebGLConstants_default.LUMINANCE,
/**
* A pixel format containing luminance (intensity) and alpha channels.
*
* @type {number}
* @constant
*/
LUMINANCE_ALPHA: WebGLConstants_default.LUMINANCE_ALPHA,
/**
* A pixel format containing red, green, and blue channels that is DXT1 compressed.
*
* @type {number}
* @constant
*/
RGB_DXT1: WebGLConstants_default.COMPRESSED_RGB_S3TC_DXT1_EXT,
/**
* A pixel format containing red, green, blue, and alpha channels that is DXT1 compressed.
*
* @type {number}
* @constant
*/
RGBA_DXT1: WebGLConstants_default.COMPRESSED_RGBA_S3TC_DXT1_EXT,
/**
* A pixel format containing red, green, blue, and alpha channels that is DXT3 compressed.
*
* @type {number}
* @constant
*/
RGBA_DXT3: WebGLConstants_default.COMPRESSED_RGBA_S3TC_DXT3_EXT,
/**
* A pixel format containing red, green, blue, and alpha channels that is DXT5 compressed.
*
* @type {number}
* @constant
*/
RGBA_DXT5: WebGLConstants_default.COMPRESSED_RGBA_S3TC_DXT5_EXT,
/**
* A pixel format containing red, green, and blue channels that is PVR 4bpp compressed.
*
* @type {number}
* @constant
*/
RGB_PVRTC_4BPPV1: WebGLConstants_default.COMPRESSED_RGB_PVRTC_4BPPV1_IMG,
/**
* A pixel format containing red, green, and blue channels that is PVR 2bpp compressed.
*
* @type {number}
* @constant
*/
RGB_PVRTC_2BPPV1: WebGLConstants_default.COMPRESSED_RGB_PVRTC_2BPPV1_IMG,
/**
* A pixel format containing red, green, blue, and alpha channels that is PVR 4bpp compressed.
*
* @type {number}
* @constant
*/
RGBA_PVRTC_4BPPV1: WebGLConstants_default.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG,
/**
* A pixel format containing red, green, blue, and alpha channels that is PVR 2bpp compressed.
*
* @type {number}
* @constant
*/
RGBA_PVRTC_2BPPV1: WebGLConstants_default.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG,
/**
* A pixel format containing red, green, blue, and alpha channels that is ASTC compressed.
*
* @type {number}
* @constant
*/
RGBA_ASTC: WebGLConstants_default.COMPRESSED_RGBA_ASTC_4x4_WEBGL,
/**
* A pixel format containing red, green, and blue channels that is ETC1 compressed.
*
* @type {number}
* @constant
*/
RGB_ETC1: WebGLConstants_default.COMPRESSED_RGB_ETC1_WEBGL,
/**
* A pixel format containing red, green, and blue channels that is ETC2 compressed.
*
* @type {number}
* @constant
*/
RGB8_ETC2: WebGLConstants_default.COMPRESSED_RGB8_ETC2,
/**
* A pixel format containing red, green, blue, and alpha channels that is ETC2 compressed.
*
* @type {number}
* @constant
*/
RGBA8_ETC2_EAC: WebGLConstants_default.COMPRESSED_RGBA8_ETC2_EAC,
/**
* A pixel format containing red, green, blue, and alpha channels that is BC7 compressed.
*
* @type {number}
* @constant
*/
RGBA_BC7: WebGLConstants_default.COMPRESSED_RGBA_BPTC_UNORM
};
PixelFormat.componentsLength = function(pixelFormat) {
switch (pixelFormat) {
case PixelFormat.RGB:
return 3;
case PixelFormat.RGBA:
return 4;
case PixelFormat.LUMINANCE_ALPHA:
case PixelFormat.RG:
return 2;
case PixelFormat.ALPHA:
case PixelFormat.RED:
case PixelFormat.LUMINANCE:
return 1;
default:
return 1;
}
};
PixelFormat.validate = function(pixelFormat) {
return pixelFormat === PixelFormat.DEPTH_COMPONENT || pixelFormat === PixelFormat.DEPTH_STENCIL || pixelFormat === PixelFormat.ALPHA || pixelFormat === PixelFormat.RED || pixelFormat === PixelFormat.RG || pixelFormat === PixelFormat.RGB || pixelFormat === PixelFormat.RGBA || pixelFormat === PixelFormat.LUMINANCE || pixelFormat === PixelFormat.LUMINANCE_ALPHA || pixelFormat === PixelFormat.RGB_DXT1 || pixelFormat === PixelFormat.RGBA_DXT1 || pixelFormat === PixelFormat.RGBA_DXT3 || pixelFormat === PixelFormat.RGBA_DXT5 || pixelFormat === PixelFormat.RGB_PVRTC_4BPPV1 || pixelFormat === PixelFormat.RGB_PVRTC_2BPPV1 || pixelFormat === PixelFormat.RGBA_PVRTC_4BPPV1 || pixelFormat === PixelFormat.RGBA_PVRTC_2BPPV1 || pixelFormat === PixelFormat.RGBA_ASTC || pixelFormat === PixelFormat.RGB_ETC1 || pixelFormat === PixelFormat.RGB8_ETC2 || pixelFormat === PixelFormat.RGBA8_ETC2_EAC || pixelFormat === PixelFormat.RGBA_BC7;
};
PixelFormat.isColorFormat = function(pixelFormat) {
return pixelFormat === PixelFormat.ALPHA || pixelFormat === PixelFormat.RGB || pixelFormat === PixelFormat.RGBA || pixelFormat === PixelFormat.LUMINANCE || pixelFormat === PixelFormat.LUMINANCE_ALPHA;
};
PixelFormat.isDepthFormat = function(pixelFormat) {
return pixelFormat === PixelFormat.DEPTH_COMPONENT || pixelFormat === PixelFormat.DEPTH_STENCIL;
};
PixelFormat.isCompressedFormat = function(pixelFormat) {
return pixelFormat === PixelFormat.RGB_DXT1 || pixelFormat === PixelFormat.RGBA_DXT1 || pixelFormat === PixelFormat.RGBA_DXT3 || pixelFormat === PixelFormat.RGBA_DXT5 || pixelFormat === PixelFormat.RGB_PVRTC_4BPPV1 || pixelFormat === PixelFormat.RGB_PVRTC_2BPPV1 || pixelFormat === PixelFormat.RGBA_PVRTC_4BPPV1 || pixelFormat === PixelFormat.RGBA_PVRTC_2BPPV1 || pixelFormat === PixelFormat.RGBA_ASTC || pixelFormat === PixelFormat.RGB_ETC1 || pixelFormat === PixelFormat.RGB8_ETC2 || pixelFormat === PixelFormat.RGBA8_ETC2_EAC || pixelFormat === PixelFormat.RGBA_BC7;
};
PixelFormat.isDXTFormat = function(pixelFormat) {
return pixelFormat === PixelFormat.RGB_DXT1 || pixelFormat === PixelFormat.RGBA_DXT1 || pixelFormat === PixelFormat.RGBA_DXT3 || pixelFormat === PixelFormat.RGBA_DXT5;
};
PixelFormat.isPVRTCFormat = function(pixelFormat) {
return pixelFormat === PixelFormat.RGB_PVRTC_4BPPV1 || pixelFormat === PixelFormat.RGB_PVRTC_2BPPV1 || pixelFormat === PixelFormat.RGBA_PVRTC_4BPPV1 || pixelFormat === PixelFormat.RGBA_PVRTC_2BPPV1;
};
PixelFormat.isASTCFormat = function(pixelFormat) {
return pixelFormat === PixelFormat.RGBA_ASTC;
};
PixelFormat.isETC1Format = function(pixelFormat) {
return pixelFormat === PixelFormat.RGB_ETC1;
};
PixelFormat.isETC2Format = function(pixelFormat) {
return pixelFormat === PixelFormat.RGB8_ETC2 || pixelFormat === PixelFormat.RGBA8_ETC2_EAC;
};
PixelFormat.isBC7Format = function(pixelFormat) {
return pixelFormat === PixelFormat.RGBA_BC7;
};
PixelFormat.compressedTextureSizeInBytes = function(pixelFormat, width, height) {
switch (pixelFormat) {
case PixelFormat.RGB_DXT1:
case PixelFormat.RGBA_DXT1:
case PixelFormat.RGB_ETC1:
case PixelFormat.RGB8_ETC2:
return Math.floor((width + 3) / 4) * Math.floor((height + 3) / 4) * 8;
case PixelFormat.RGBA_DXT3:
case PixelFormat.RGBA_DXT5:
case PixelFormat.RGBA_ASTC:
case PixelFormat.RGBA8_ETC2_EAC:
return Math.floor((width + 3) / 4) * Math.floor((height + 3) / 4) * 16;
case PixelFormat.RGB_PVRTC_4BPPV1:
case PixelFormat.RGBA_PVRTC_4BPPV1:
return Math.floor((Math.max(width, 8) * Math.max(height, 8) * 4 + 7) / 8);
case PixelFormat.RGB_PVRTC_2BPPV1:
case PixelFormat.RGBA_PVRTC_2BPPV1:
return Math.floor(
(Math.max(width, 16) * Math.max(height, 8) * 2 + 7) / 8
);
case PixelFormat.RGBA_BC7:
return Math.ceil(width / 4) * Math.ceil(height / 4) * 16;
default:
return 0;
}
};
PixelFormat.textureSizeInBytes = function(pixelFormat, pixelDatatype, width, height) {
let componentsLength = PixelFormat.componentsLength(pixelFormat);
if (PixelDatatype_default.isPacked(pixelDatatype)) {
componentsLength = 1;
}
return componentsLength * PixelDatatype_default.sizeInBytes(pixelDatatype) * width * height;
};
PixelFormat.alignmentInBytes = function(pixelFormat, pixelDatatype, width) {
const mod2 = PixelFormat.textureSizeInBytes(pixelFormat, pixelDatatype, width, 1) % 4;
return mod2 === 0 ? 4 : mod2 === 2 ? 2 : 1;
};
PixelFormat.createTypedArray = function(pixelFormat, pixelDatatype, width, height) {
let constructor;
const sizeInBytes = PixelDatatype_default.sizeInBytes(pixelDatatype);
if (sizeInBytes === Uint8Array.BYTES_PER_ELEMENT) {
constructor = Uint8Array;
} else if (sizeInBytes === Uint16Array.BYTES_PER_ELEMENT) {
constructor = Uint16Array;
} else if (sizeInBytes === Float32Array.BYTES_PER_ELEMENT && pixelDatatype === PixelDatatype_default.FLOAT) {
constructor = Float32Array;
} else {
constructor = Uint32Array;
}
const size = PixelFormat.componentsLength(pixelFormat) * width * height;
return new constructor(size);
};
PixelFormat.flipY = function(bufferView, pixelFormat, pixelDatatype, width, height) {
if (height === 1) {
return bufferView;
}
const flipped = PixelFormat.createTypedArray(
pixelFormat,
pixelDatatype,
width,
height
);
const numberOfComponents = PixelFormat.componentsLength(pixelFormat);
const textureWidth = width * numberOfComponents;
for (let i = 0; i < height; ++i) {
const row = i * width * numberOfComponents;
const flippedRow = (height - i - 1) * width * numberOfComponents;
for (let j = 0; j < textureWidth; ++j) {
flipped[flippedRow + j] = bufferView[row + j];
}
}
return flipped;
};
PixelFormat.toInternalFormat = function(pixelFormat, pixelDatatype, context) {
if (!context.webgl2) {
return pixelFormat;
}
if (pixelFormat === PixelFormat.DEPTH_STENCIL) {
return WebGLConstants_default.DEPTH24_STENCIL8;
}
if (pixelFormat === PixelFormat.DEPTH_COMPONENT) {
if (pixelDatatype === PixelDatatype_default.UNSIGNED_SHORT) {
return WebGLConstants_default.DEPTH_COMPONENT16;
} else if (pixelDatatype === PixelDatatype_default.UNSIGNED_INT) {
return WebGLConstants_default.DEPTH_COMPONENT24;
}
}
if (pixelDatatype === PixelDatatype_default.FLOAT) {
switch (pixelFormat) {
case PixelFormat.RGBA:
return WebGLConstants_default.RGBA32F;
case PixelFormat.RGB:
return WebGLConstants_default.RGB32F;
case PixelFormat.RG:
return WebGLConstants_default.RG32F;
case PixelFormat.RED:
return WebGLConstants_default.R32F;
}
}
if (pixelDatatype === PixelDatatype_default.HALF_FLOAT) {
switch (pixelFormat) {
case PixelFormat.RGBA:
return WebGLConstants_default.RGBA16F;
case PixelFormat.RGB:
return WebGLConstants_default.RGB16F;
case PixelFormat.RG:
return WebGLConstants_default.RG16F;
case PixelFormat.RED:
return WebGLConstants_default.R16F;
}
}
return pixelFormat;
};
var PixelFormat_default = Object.freeze(PixelFormat);
// packages/engine/Source/Renderer/ContextLimits.js
var ContextLimits = {
_maximumCombinedTextureImageUnits: 0,
_maximumCubeMapSize: 0,
_maximumFragmentUniformVectors: 0,
_maximumTextureImageUnits: 0,
_maximumRenderbufferSize: 0,
_maximumTextureSize: 0,
_maximumVaryingVectors: 0,
_maximumVertexAttributes: 0,
_maximumVertexTextureImageUnits: 0,
_maximumVertexUniformVectors: 0,
_minimumAliasedLineWidth: 0,
_maximumAliasedLineWidth: 0,
_minimumAliasedPointSize: 0,
_maximumAliasedPointSize: 0,
_maximumViewportWidth: 0,
_maximumViewportHeight: 0,
_maximumTextureFilterAnisotropy: 0,
_maximumDrawBuffers: 0,
_maximumColorAttachments: 0,
_maximumSamples: 0,
_highpFloatSupported: false,
_highpIntSupported: false
};
Object.defineProperties(ContextLimits, {
/**
* The maximum number of texture units that can be used from the vertex and fragment
* shader with this WebGL implementation. The minimum is eight. If both shaders access the
* same texture unit, this counts as two texture units.
* @memberof ContextLimits
* @type {number}
* @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with MAX_COMBINED_TEXTURE_IMAGE_UNITS
.
*/
maximumCombinedTextureImageUnits: {
get: function() {
return ContextLimits._maximumCombinedTextureImageUnits;
}
},
/**
* The approximate maximum cube mape width and height supported by this WebGL implementation.
* The minimum is 16, but most desktop and laptop implementations will support much larger sizes like 8,192.
* @memberof ContextLimits
* @type {number}
* @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with MAX_CUBE_MAP_TEXTURE_SIZE
.
*/
maximumCubeMapSize: {
get: function() {
return ContextLimits._maximumCubeMapSize;
}
},
/**
* The maximum number of vec4
, ivec4
, and bvec4
* uniforms that can be used by a fragment shader with this WebGL implementation. The minimum is 16.
* @memberof ContextLimits
* @type {number}
* @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with MAX_FRAGMENT_UNIFORM_VECTORS
.
*/
maximumFragmentUniformVectors: {
get: function() {
return ContextLimits._maximumFragmentUniformVectors;
}
},
/**
* The maximum number of texture units that can be used from the fragment shader with this WebGL implementation. The minimum is eight.
* @memberof ContextLimits
* @type {number}
* @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with MAX_TEXTURE_IMAGE_UNITS
.
*/
maximumTextureImageUnits: {
get: function() {
return ContextLimits._maximumTextureImageUnits;
}
},
/**
* The maximum renderbuffer width and height supported by this WebGL implementation.
* The minimum is 16, but most desktop and laptop implementations will support much larger sizes like 8,192.
* @memberof ContextLimits
* @type {number}
* @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with MAX_RENDERBUFFER_SIZE
.
*/
maximumRenderbufferSize: {
get: function() {
return ContextLimits._maximumRenderbufferSize;
}
},
/**
* The approximate maximum texture width and height supported by this WebGL implementation.
* The minimum is 64, but most desktop and laptop implementations will support much larger sizes like 8,192.
* @memberof ContextLimits
* @type {number}
* @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with MAX_TEXTURE_SIZE
.
*/
maximumTextureSize: {
get: function() {
return ContextLimits._maximumTextureSize;
}
},
/**
* The maximum number of vec4
varying variables supported by this WebGL implementation.
* The minimum is eight. Matrices and arrays count as multiple vec4
s.
* @memberof ContextLimits
* @type {number}
* @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with MAX_VARYING_VECTORS
.
*/
maximumVaryingVectors: {
get: function() {
return ContextLimits._maximumVaryingVectors;
}
},
/**
* The maximum number of vec4
vertex attributes supported by this WebGL implementation. The minimum is eight.
* @memberof ContextLimits
* @type {number}
* @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with MAX_VERTEX_ATTRIBS
.
*/
maximumVertexAttributes: {
get: function() {
return ContextLimits._maximumVertexAttributes;
}
},
/**
* The maximum number of texture units that can be used from the vertex shader with this WebGL implementation.
* The minimum is zero, which means the GL does not support vertex texture fetch.
* @memberof ContextLimits
* @type {number}
* @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with MAX_VERTEX_TEXTURE_IMAGE_UNITS
.
*/
maximumVertexTextureImageUnits: {
get: function() {
return ContextLimits._maximumVertexTextureImageUnits;
}
},
/**
* The maximum number of vec4
, ivec4
, and bvec4
* uniforms that can be used by a vertex shader with this WebGL implementation. The minimum is 16.
* @memberof ContextLimits
* @type {number}
* @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with MAX_VERTEX_UNIFORM_VECTORS
.
*/
maximumVertexUniformVectors: {
get: function() {
return ContextLimits._maximumVertexUniformVectors;
}
},
/**
* The minimum aliased line width, in pixels, supported by this WebGL implementation. It will be at most one.
* @memberof ContextLimits
* @type {number}
* @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with ALIASED_LINE_WIDTH_RANGE
.
*/
minimumAliasedLineWidth: {
get: function() {
return ContextLimits._minimumAliasedLineWidth;
}
},
/**
* The maximum aliased line width, in pixels, supported by this WebGL implementation. It will be at least one.
* @memberof ContextLimits
* @type {number}
* @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with ALIASED_LINE_WIDTH_RANGE
.
*/
maximumAliasedLineWidth: {
get: function() {
return ContextLimits._maximumAliasedLineWidth;
}
},
/**
* The minimum aliased point size, in pixels, supported by this WebGL implementation. It will be at most one.
* @memberof ContextLimits
* @type {number}
* @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with ALIASED_POINT_SIZE_RANGE
.
*/
minimumAliasedPointSize: {
get: function() {
return ContextLimits._minimumAliasedPointSize;
}
},
/**
* The maximum aliased point size, in pixels, supported by this WebGL implementation. It will be at least one.
* @memberof ContextLimits
* @type {number}
* @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with ALIASED_POINT_SIZE_RANGE
.
*/
maximumAliasedPointSize: {
get: function() {
return ContextLimits._maximumAliasedPointSize;
}
},
/**
* The maximum supported width of the viewport. It will be at least as large as the visible width of the associated canvas.
* @memberof ContextLimits
* @type {number}
* @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with MAX_VIEWPORT_DIMS
.
*/
maximumViewportWidth: {
get: function() {
return ContextLimits._maximumViewportWidth;
}
},
/**
* The maximum supported height of the viewport. It will be at least as large as the visible height of the associated canvas.
* @memberof ContextLimits
* @type {number}
* @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with MAX_VIEWPORT_DIMS
.
*/
maximumViewportHeight: {
get: function() {
return ContextLimits._maximumViewportHeight;
}
},
/**
* The maximum degree of anisotropy for texture filtering
* @memberof ContextLimits
* @type {number}
*/
maximumTextureFilterAnisotropy: {
get: function() {
return ContextLimits._maximumTextureFilterAnisotropy;
}
},
/**
* The maximum number of simultaneous outputs that may be written in a fragment shader.
* @memberof ContextLimits
* @type {number}
*/
maximumDrawBuffers: {
get: function() {
return ContextLimits._maximumDrawBuffers;
}
},
/**
* The maximum number of color attachments supported.
* @memberof ContextLimits
* @type {number}
*/
maximumColorAttachments: {
get: function() {
return ContextLimits._maximumColorAttachments;
}
},
/**
* The maximum number of samples supported for multisampling.
* @memberof ContextLimits
* @type {number}
*/
maximumSamples: {
get: function() {
return ContextLimits._maximumSamples;
}
},
/**
* High precision float supported (highp
) in fragment shaders.
* @memberof ContextLimits
* @type {boolean}
*/
highpFloatSupported: {
get: function() {
return ContextLimits._highpFloatSupported;
}
},
/**
* High precision int supported (highp
) in fragment shaders.
* @memberof ContextLimits
* @type {boolean}
*/
highpIntSupported: {
get: function() {
return ContextLimits._highpIntSupported;
}
}
});
var ContextLimits_default = ContextLimits;
// packages/engine/Source/Renderer/Framebuffer.js
function attachTexture(framebuffer, attachment, texture) {
const gl = framebuffer._gl;
gl.framebufferTexture2D(
gl.FRAMEBUFFER,
attachment,
texture._target,
texture._texture,
0
);
}
function attachRenderbuffer(framebuffer, attachment, renderbuffer) {
const gl = framebuffer._gl;
gl.framebufferRenderbuffer(
gl.FRAMEBUFFER,
attachment,
gl.RENDERBUFFER,
renderbuffer._getRenderbuffer()
);
}
function Framebuffer(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const context = options.context;
Check_default.defined("options.context", context);
const gl = context._gl;
const maximumColorAttachments = ContextLimits_default.maximumColorAttachments;
this._gl = gl;
this._framebuffer = gl.createFramebuffer();
this._colorTextures = [];
this._colorRenderbuffers = [];
this._activeColorAttachments = [];
this._depthTexture = void 0;
this._depthRenderbuffer = void 0;
this._stencilRenderbuffer = void 0;
this._depthStencilTexture = void 0;
this._depthStencilRenderbuffer = void 0;
this.destroyAttachments = defaultValue_default(options.destroyAttachments, true);
if (defined_default(options.colorTextures) && defined_default(options.colorRenderbuffers)) {
throw new DeveloperError_default(
"Cannot have both color texture and color renderbuffer attachments."
);
}
if (defined_default(options.depthTexture) && defined_default(options.depthRenderbuffer)) {
throw new DeveloperError_default(
"Cannot have both a depth texture and depth renderbuffer attachment."
);
}
if (defined_default(options.depthStencilTexture) && defined_default(options.depthStencilRenderbuffer)) {
throw new DeveloperError_default(
"Cannot have both a depth-stencil texture and depth-stencil renderbuffer attachment."
);
}
const depthAttachment = defined_default(options.depthTexture) || defined_default(options.depthRenderbuffer);
const depthStencilAttachment = defined_default(options.depthStencilTexture) || defined_default(options.depthStencilRenderbuffer);
if (depthAttachment && depthStencilAttachment) {
throw new DeveloperError_default(
"Cannot have both a depth and depth-stencil attachment."
);
}
if (defined_default(options.stencilRenderbuffer) && depthStencilAttachment) {
throw new DeveloperError_default(
"Cannot have both a stencil and depth-stencil attachment."
);
}
if (depthAttachment && defined_default(options.stencilRenderbuffer)) {
throw new DeveloperError_default(
"Cannot have both a depth and stencil attachment."
);
}
this._bind();
let texture;
let renderbuffer;
let i;
let length3;
let attachmentEnum;
if (defined_default(options.colorTextures)) {
const textures = options.colorTextures;
length3 = this._colorTextures.length = this._activeColorAttachments.length = textures.length;
if (length3 > maximumColorAttachments) {
throw new DeveloperError_default(
"The number of color attachments exceeds the number supported."
);
}
for (i = 0; i < length3; ++i) {
texture = textures[i];
if (!PixelFormat_default.isColorFormat(texture.pixelFormat)) {
throw new DeveloperError_default(
"The color-texture pixel-format must be a color format."
);
}
if (texture.pixelDatatype === PixelDatatype_default.FLOAT && !context.colorBufferFloat) {
throw new DeveloperError_default(
"The color texture pixel datatype is FLOAT and the WebGL implementation does not support the EXT_color_buffer_float or WEBGL_color_buffer_float extensions. See Context.colorBufferFloat."
);
}
if (texture.pixelDatatype === PixelDatatype_default.HALF_FLOAT && !context.colorBufferHalfFloat) {
throw new DeveloperError_default(
"The color texture pixel datatype is HALF_FLOAT and the WebGL implementation does not support the EXT_color_buffer_half_float extension. See Context.colorBufferHalfFloat."
);
}
attachmentEnum = this._gl.COLOR_ATTACHMENT0 + i;
attachTexture(this, attachmentEnum, texture);
this._activeColorAttachments[i] = attachmentEnum;
this._colorTextures[i] = texture;
}
}
if (defined_default(options.colorRenderbuffers)) {
const renderbuffers = options.colorRenderbuffers;
length3 = this._colorRenderbuffers.length = this._activeColorAttachments.length = renderbuffers.length;
if (length3 > maximumColorAttachments) {
throw new DeveloperError_default(
"The number of color attachments exceeds the number supported."
);
}
for (i = 0; i < length3; ++i) {
renderbuffer = renderbuffers[i];
attachmentEnum = this._gl.COLOR_ATTACHMENT0 + i;
attachRenderbuffer(this, attachmentEnum, renderbuffer);
this._activeColorAttachments[i] = attachmentEnum;
this._colorRenderbuffers[i] = renderbuffer;
}
}
if (defined_default(options.depthTexture)) {
texture = options.depthTexture;
if (texture.pixelFormat !== PixelFormat_default.DEPTH_COMPONENT) {
throw new DeveloperError_default(
"The depth-texture pixel-format must be DEPTH_COMPONENT."
);
}
attachTexture(this, this._gl.DEPTH_ATTACHMENT, texture);
this._depthTexture = texture;
}
if (defined_default(options.depthRenderbuffer)) {
renderbuffer = options.depthRenderbuffer;
attachRenderbuffer(this, this._gl.DEPTH_ATTACHMENT, renderbuffer);
this._depthRenderbuffer = renderbuffer;
}
if (defined_default(options.stencilRenderbuffer)) {
renderbuffer = options.stencilRenderbuffer;
attachRenderbuffer(this, this._gl.STENCIL_ATTACHMENT, renderbuffer);
this._stencilRenderbuffer = renderbuffer;
}
if (defined_default(options.depthStencilTexture)) {
texture = options.depthStencilTexture;
if (texture.pixelFormat !== PixelFormat_default.DEPTH_STENCIL) {
throw new DeveloperError_default(
"The depth-stencil pixel-format must be DEPTH_STENCIL."
);
}
attachTexture(this, this._gl.DEPTH_STENCIL_ATTACHMENT, texture);
this._depthStencilTexture = texture;
}
if (defined_default(options.depthStencilRenderbuffer)) {
renderbuffer = options.depthStencilRenderbuffer;
attachRenderbuffer(this, this._gl.DEPTH_STENCIL_ATTACHMENT, renderbuffer);
this._depthStencilRenderbuffer = renderbuffer;
}
this._unBind();
}
Object.defineProperties(Framebuffer.prototype, {
/**
* The status of the framebuffer. If the status is not WebGLConstants.FRAMEBUFFER_COMPLETE,
* a {@link DeveloperError} will be thrown when attempting to render to the framebuffer.
* @memberof Framebuffer.prototype
* @type {number}
*/
status: {
get: function() {
this._bind();
const status = this._gl.checkFramebufferStatus(this._gl.FRAMEBUFFER);
this._unBind();
return status;
}
},
numberOfColorAttachments: {
get: function() {
return this._activeColorAttachments.length;
}
},
depthTexture: {
get: function() {
return this._depthTexture;
}
},
depthRenderbuffer: {
get: function() {
return this._depthRenderbuffer;
}
},
stencilRenderbuffer: {
get: function() {
return this._stencilRenderbuffer;
}
},
depthStencilTexture: {
get: function() {
return this._depthStencilTexture;
}
},
depthStencilRenderbuffer: {
get: function() {
return this._depthStencilRenderbuffer;
}
},
/**
* True if the framebuffer has a depth attachment. Depth attachments include
* depth and depth-stencil textures, and depth and depth-stencil renderbuffers. When
* rendering to a framebuffer, a depth attachment is required for the depth test to have effect.
* @memberof Framebuffer.prototype
* @type {boolean}
*/
hasDepthAttachment: {
get: function() {
return !!(this.depthTexture || this.depthRenderbuffer || this.depthStencilTexture || this.depthStencilRenderbuffer);
}
}
});
Framebuffer.prototype._bind = function() {
const gl = this._gl;
gl.bindFramebuffer(gl.FRAMEBUFFER, this._framebuffer);
};
Framebuffer.prototype._unBind = function() {
const gl = this._gl;
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
};
Framebuffer.prototype.bindDraw = function() {
const gl = this._gl;
gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, this._framebuffer);
};
Framebuffer.prototype.bindRead = function() {
const gl = this._gl;
gl.bindFramebuffer(gl.READ_FRAMEBUFFER, this._framebuffer);
};
Framebuffer.prototype._getActiveColorAttachments = function() {
return this._activeColorAttachments;
};
Framebuffer.prototype.getColorTexture = function(index) {
if (!defined_default(index) || index < 0 || index >= this._colorTextures.length) {
throw new DeveloperError_default(
"index is required, must be greater than or equal to zero and must be less than the number of color attachments."
);
}
return this._colorTextures[index];
};
Framebuffer.prototype.getColorRenderbuffer = function(index) {
if (!defined_default(index) || index < 0 || index >= this._colorRenderbuffers.length) {
throw new DeveloperError_default(
"index is required, must be greater than or equal to zero and must be less than the number of color attachments."
);
}
return this._colorRenderbuffers[index];
};
Framebuffer.prototype.isDestroyed = function() {
return false;
};
Framebuffer.prototype.destroy = function() {
if (this.destroyAttachments) {
let i = 0;
const textures = this._colorTextures;
let length3 = textures.length;
for (; i < length3; ++i) {
const texture = textures[i];
if (defined_default(texture)) {
texture.destroy();
}
}
const renderbuffers = this._colorRenderbuffers;
length3 = renderbuffers.length;
for (i = 0; i < length3; ++i) {
const renderbuffer = renderbuffers[i];
if (defined_default(renderbuffer)) {
renderbuffer.destroy();
}
}
this._depthTexture = this._depthTexture && this._depthTexture.destroy();
this._depthRenderbuffer = this._depthRenderbuffer && this._depthRenderbuffer.destroy();
this._stencilRenderbuffer = this._stencilRenderbuffer && this._stencilRenderbuffer.destroy();
this._depthStencilTexture = this._depthStencilTexture && this._depthStencilTexture.destroy();
this._depthStencilRenderbuffer = this._depthStencilRenderbuffer && this._depthStencilRenderbuffer.destroy();
}
this._gl.deleteFramebuffer(this._framebuffer);
return destroyObject_default(this);
};
var Framebuffer_default = Framebuffer;
// packages/engine/Source/Core/WindingOrder.js
var WindingOrder = {
/**
* Vertices are in clockwise order.
*
* @type {number}
* @constant
*/
CLOCKWISE: WebGLConstants_default.CW,
/**
* Vertices are in counter-clockwise order.
*
* @type {number}
* @constant
*/
COUNTER_CLOCKWISE: WebGLConstants_default.CCW
};
WindingOrder.validate = function(windingOrder) {
return windingOrder === WindingOrder.CLOCKWISE || windingOrder === WindingOrder.COUNTER_CLOCKWISE;
};
var WindingOrder_default = Object.freeze(WindingOrder);
// packages/engine/Source/Renderer/freezeRenderState.js
function freezeRenderState(renderState) {
if (typeof renderState !== "object" || renderState === null) {
return renderState;
}
let propName;
const propNames = Object.keys(renderState);
for (let i = 0; i < propNames.length; i++) {
propName = propNames[i];
if (renderState.hasOwnProperty(propName) && propName !== "_applyFunctions") {
renderState[propName] = freezeRenderState(renderState[propName]);
}
}
return Object.freeze(renderState);
}
var freezeRenderState_default = freezeRenderState;
// packages/engine/Source/Renderer/RenderState.js
function validateBlendEquation(blendEquation) {
return blendEquation === WebGLConstants_default.FUNC_ADD || blendEquation === WebGLConstants_default.FUNC_SUBTRACT || blendEquation === WebGLConstants_default.FUNC_REVERSE_SUBTRACT || blendEquation === WebGLConstants_default.MIN || blendEquation === WebGLConstants_default.MAX;
}
function validateBlendFunction(blendFunction) {
return blendFunction === WebGLConstants_default.ZERO || blendFunction === WebGLConstants_default.ONE || blendFunction === WebGLConstants_default.SRC_COLOR || blendFunction === WebGLConstants_default.ONE_MINUS_SRC_COLOR || blendFunction === WebGLConstants_default.DST_COLOR || blendFunction === WebGLConstants_default.ONE_MINUS_DST_COLOR || blendFunction === WebGLConstants_default.SRC_ALPHA || blendFunction === WebGLConstants_default.ONE_MINUS_SRC_ALPHA || blendFunction === WebGLConstants_default.DST_ALPHA || blendFunction === WebGLConstants_default.ONE_MINUS_DST_ALPHA || blendFunction === WebGLConstants_default.CONSTANT_COLOR || blendFunction === WebGLConstants_default.ONE_MINUS_CONSTANT_COLOR || blendFunction === WebGLConstants_default.CONSTANT_ALPHA || blendFunction === WebGLConstants_default.ONE_MINUS_CONSTANT_ALPHA || blendFunction === WebGLConstants_default.SRC_ALPHA_SATURATE;
}
function validateCullFace(cullFace) {
return cullFace === WebGLConstants_default.FRONT || cullFace === WebGLConstants_default.BACK || cullFace === WebGLConstants_default.FRONT_AND_BACK;
}
function validateDepthFunction(depthFunction) {
return depthFunction === WebGLConstants_default.NEVER || depthFunction === WebGLConstants_default.LESS || depthFunction === WebGLConstants_default.EQUAL || depthFunction === WebGLConstants_default.LEQUAL || depthFunction === WebGLConstants_default.GREATER || depthFunction === WebGLConstants_default.NOTEQUAL || depthFunction === WebGLConstants_default.GEQUAL || depthFunction === WebGLConstants_default.ALWAYS;
}
function validateStencilFunction(stencilFunction) {
return stencilFunction === WebGLConstants_default.NEVER || stencilFunction === WebGLConstants_default.LESS || stencilFunction === WebGLConstants_default.EQUAL || stencilFunction === WebGLConstants_default.LEQUAL || stencilFunction === WebGLConstants_default.GREATER || stencilFunction === WebGLConstants_default.NOTEQUAL || stencilFunction === WebGLConstants_default.GEQUAL || stencilFunction === WebGLConstants_default.ALWAYS;
}
function validateStencilOperation(stencilOperation) {
return stencilOperation === WebGLConstants_default.ZERO || stencilOperation === WebGLConstants_default.KEEP || stencilOperation === WebGLConstants_default.REPLACE || stencilOperation === WebGLConstants_default.INCR || stencilOperation === WebGLConstants_default.DECR || stencilOperation === WebGLConstants_default.INVERT || stencilOperation === WebGLConstants_default.INCR_WRAP || stencilOperation === WebGLConstants_default.DECR_WRAP;
}
function RenderState(renderState) {
const rs = defaultValue_default(renderState, defaultValue_default.EMPTY_OBJECT);
const cull = defaultValue_default(rs.cull, defaultValue_default.EMPTY_OBJECT);
const polygonOffset = defaultValue_default(
rs.polygonOffset,
defaultValue_default.EMPTY_OBJECT
);
const scissorTest = defaultValue_default(rs.scissorTest, defaultValue_default.EMPTY_OBJECT);
const scissorTestRectangle = defaultValue_default(
scissorTest.rectangle,
defaultValue_default.EMPTY_OBJECT
);
const depthRange = defaultValue_default(rs.depthRange, defaultValue_default.EMPTY_OBJECT);
const depthTest = defaultValue_default(rs.depthTest, defaultValue_default.EMPTY_OBJECT);
const colorMask = defaultValue_default(rs.colorMask, defaultValue_default.EMPTY_OBJECT);
const blending = defaultValue_default(rs.blending, defaultValue_default.EMPTY_OBJECT);
const blendingColor = defaultValue_default(blending.color, defaultValue_default.EMPTY_OBJECT);
const stencilTest = defaultValue_default(rs.stencilTest, defaultValue_default.EMPTY_OBJECT);
const stencilTestFrontOperation = defaultValue_default(
stencilTest.frontOperation,
defaultValue_default.EMPTY_OBJECT
);
const stencilTestBackOperation = defaultValue_default(
stencilTest.backOperation,
defaultValue_default.EMPTY_OBJECT
);
const sampleCoverage = defaultValue_default(
rs.sampleCoverage,
defaultValue_default.EMPTY_OBJECT
);
const viewport = rs.viewport;
this.frontFace = defaultValue_default(rs.frontFace, WindingOrder_default.COUNTER_CLOCKWISE);
this.cull = {
enabled: defaultValue_default(cull.enabled, false),
face: defaultValue_default(cull.face, WebGLConstants_default.BACK)
};
this.lineWidth = defaultValue_default(rs.lineWidth, 1);
this.polygonOffset = {
enabled: defaultValue_default(polygonOffset.enabled, false),
factor: defaultValue_default(polygonOffset.factor, 0),
units: defaultValue_default(polygonOffset.units, 0)
};
this.scissorTest = {
enabled: defaultValue_default(scissorTest.enabled, false),
rectangle: BoundingRectangle_default.clone(scissorTestRectangle)
};
this.depthRange = {
near: defaultValue_default(depthRange.near, 0),
far: defaultValue_default(depthRange.far, 1)
};
this.depthTest = {
enabled: defaultValue_default(depthTest.enabled, false),
func: defaultValue_default(depthTest.func, WebGLConstants_default.LESS)
// func, because function is a JavaScript keyword
};
this.colorMask = {
red: defaultValue_default(colorMask.red, true),
green: defaultValue_default(colorMask.green, true),
blue: defaultValue_default(colorMask.blue, true),
alpha: defaultValue_default(colorMask.alpha, true)
};
this.depthMask = defaultValue_default(rs.depthMask, true);
this.stencilMask = defaultValue_default(rs.stencilMask, ~0);
this.blending = {
enabled: defaultValue_default(blending.enabled, false),
color: new Color_default(
defaultValue_default(blendingColor.red, 0),
defaultValue_default(blendingColor.green, 0),
defaultValue_default(blendingColor.blue, 0),
defaultValue_default(blendingColor.alpha, 0)
),
equationRgb: defaultValue_default(blending.equationRgb, WebGLConstants_default.FUNC_ADD),
equationAlpha: defaultValue_default(
blending.equationAlpha,
WebGLConstants_default.FUNC_ADD
),
functionSourceRgb: defaultValue_default(
blending.functionSourceRgb,
WebGLConstants_default.ONE
),
functionSourceAlpha: defaultValue_default(
blending.functionSourceAlpha,
WebGLConstants_default.ONE
),
functionDestinationRgb: defaultValue_default(
blending.functionDestinationRgb,
WebGLConstants_default.ZERO
),
functionDestinationAlpha: defaultValue_default(
blending.functionDestinationAlpha,
WebGLConstants_default.ZERO
)
};
this.stencilTest = {
enabled: defaultValue_default(stencilTest.enabled, false),
frontFunction: defaultValue_default(
stencilTest.frontFunction,
WebGLConstants_default.ALWAYS
),
backFunction: defaultValue_default(stencilTest.backFunction, WebGLConstants_default.ALWAYS),
reference: defaultValue_default(stencilTest.reference, 0),
mask: defaultValue_default(stencilTest.mask, ~0),
frontOperation: {
fail: defaultValue_default(stencilTestFrontOperation.fail, WebGLConstants_default.KEEP),
zFail: defaultValue_default(stencilTestFrontOperation.zFail, WebGLConstants_default.KEEP),
zPass: defaultValue_default(stencilTestFrontOperation.zPass, WebGLConstants_default.KEEP)
},
backOperation: {
fail: defaultValue_default(stencilTestBackOperation.fail, WebGLConstants_default.KEEP),
zFail: defaultValue_default(stencilTestBackOperation.zFail, WebGLConstants_default.KEEP),
zPass: defaultValue_default(stencilTestBackOperation.zPass, WebGLConstants_default.KEEP)
}
};
this.sampleCoverage = {
enabled: defaultValue_default(sampleCoverage.enabled, false),
value: defaultValue_default(sampleCoverage.value, 1),
invert: defaultValue_default(sampleCoverage.invert, false)
};
this.viewport = defined_default(viewport) ? new BoundingRectangle_default(
viewport.x,
viewport.y,
viewport.width,
viewport.height
) : void 0;
if (this.lineWidth < ContextLimits_default.minimumAliasedLineWidth || this.lineWidth > ContextLimits_default.maximumAliasedLineWidth) {
throw new DeveloperError_default(
"renderState.lineWidth is out of range. Check minimumAliasedLineWidth and maximumAliasedLineWidth."
);
}
if (!WindingOrder_default.validate(this.frontFace)) {
throw new DeveloperError_default("Invalid renderState.frontFace.");
}
if (!validateCullFace(this.cull.face)) {
throw new DeveloperError_default("Invalid renderState.cull.face.");
}
if (this.scissorTest.rectangle.width < 0 || this.scissorTest.rectangle.height < 0) {
throw new DeveloperError_default(
"renderState.scissorTest.rectangle.width and renderState.scissorTest.rectangle.height must be greater than or equal to zero."
);
}
if (this.depthRange.near > this.depthRange.far) {
throw new DeveloperError_default(
"renderState.depthRange.near can not be greater than renderState.depthRange.far."
);
}
if (this.depthRange.near < 0) {
throw new DeveloperError_default(
"renderState.depthRange.near must be greater than or equal to zero."
);
}
if (this.depthRange.far > 1) {
throw new DeveloperError_default(
"renderState.depthRange.far must be less than or equal to one."
);
}
if (!validateDepthFunction(this.depthTest.func)) {
throw new DeveloperError_default("Invalid renderState.depthTest.func.");
}
if (this.blending.color.red < 0 || this.blending.color.red > 1 || this.blending.color.green < 0 || this.blending.color.green > 1 || this.blending.color.blue < 0 || this.blending.color.blue > 1 || this.blending.color.alpha < 0 || this.blending.color.alpha > 1) {
throw new DeveloperError_default(
"renderState.blending.color components must be greater than or equal to zero and less than or equal to one."
);
}
if (!validateBlendEquation(this.blending.equationRgb)) {
throw new DeveloperError_default("Invalid renderState.blending.equationRgb.");
}
if (!validateBlendEquation(this.blending.equationAlpha)) {
throw new DeveloperError_default("Invalid renderState.blending.equationAlpha.");
}
if (!validateBlendFunction(this.blending.functionSourceRgb)) {
throw new DeveloperError_default("Invalid renderState.blending.functionSourceRgb.");
}
if (!validateBlendFunction(this.blending.functionSourceAlpha)) {
throw new DeveloperError_default(
"Invalid renderState.blending.functionSourceAlpha."
);
}
if (!validateBlendFunction(this.blending.functionDestinationRgb)) {
throw new DeveloperError_default(
"Invalid renderState.blending.functionDestinationRgb."
);
}
if (!validateBlendFunction(this.blending.functionDestinationAlpha)) {
throw new DeveloperError_default(
"Invalid renderState.blending.functionDestinationAlpha."
);
}
if (!validateStencilFunction(this.stencilTest.frontFunction)) {
throw new DeveloperError_default("Invalid renderState.stencilTest.frontFunction.");
}
if (!validateStencilFunction(this.stencilTest.backFunction)) {
throw new DeveloperError_default("Invalid renderState.stencilTest.backFunction.");
}
if (!validateStencilOperation(this.stencilTest.frontOperation.fail)) {
throw new DeveloperError_default(
"Invalid renderState.stencilTest.frontOperation.fail."
);
}
if (!validateStencilOperation(this.stencilTest.frontOperation.zFail)) {
throw new DeveloperError_default(
"Invalid renderState.stencilTest.frontOperation.zFail."
);
}
if (!validateStencilOperation(this.stencilTest.frontOperation.zPass)) {
throw new DeveloperError_default(
"Invalid renderState.stencilTest.frontOperation.zPass."
);
}
if (!validateStencilOperation(this.stencilTest.backOperation.fail)) {
throw new DeveloperError_default(
"Invalid renderState.stencilTest.backOperation.fail."
);
}
if (!validateStencilOperation(this.stencilTest.backOperation.zFail)) {
throw new DeveloperError_default(
"Invalid renderState.stencilTest.backOperation.zFail."
);
}
if (!validateStencilOperation(this.stencilTest.backOperation.zPass)) {
throw new DeveloperError_default(
"Invalid renderState.stencilTest.backOperation.zPass."
);
}
if (defined_default(this.viewport)) {
if (this.viewport.width < 0) {
throw new DeveloperError_default(
"renderState.viewport.width must be greater than or equal to zero."
);
}
if (this.viewport.height < 0) {
throw new DeveloperError_default(
"renderState.viewport.height must be greater than or equal to zero."
);
}
if (this.viewport.width > ContextLimits_default.maximumViewportWidth) {
throw new DeveloperError_default(
`renderState.viewport.width must be less than or equal to the maximum viewport width (${ContextLimits_default.maximumViewportWidth.toString()}). Check maximumViewportWidth.`
);
}
if (this.viewport.height > ContextLimits_default.maximumViewportHeight) {
throw new DeveloperError_default(
`renderState.viewport.height must be less than or equal to the maximum viewport height (${ContextLimits_default.maximumViewportHeight.toString()}). Check maximumViewportHeight.`
);
}
}
this.id = 0;
this._applyFunctions = [];
}
var nextRenderStateId = 0;
var renderStateCache = {};
RenderState.fromCache = function(renderState) {
const partialKey = JSON.stringify(renderState);
let cachedState = renderStateCache[partialKey];
if (defined_default(cachedState)) {
++cachedState.referenceCount;
return cachedState.state;
}
let states = new RenderState(renderState);
const fullKey = JSON.stringify(states);
cachedState = renderStateCache[fullKey];
if (!defined_default(cachedState)) {
states.id = nextRenderStateId++;
states = freezeRenderState_default(states);
cachedState = {
referenceCount: 0,
state: states
};
renderStateCache[fullKey] = cachedState;
}
++cachedState.referenceCount;
renderStateCache[partialKey] = {
referenceCount: 1,
state: cachedState.state
};
return cachedState.state;
};
RenderState.removeFromCache = function(renderState) {
const states = new RenderState(renderState);
const fullKey = JSON.stringify(states);
const fullCachedState = renderStateCache[fullKey];
const partialKey = JSON.stringify(renderState);
const cachedState = renderStateCache[partialKey];
if (defined_default(cachedState)) {
--cachedState.referenceCount;
if (cachedState.referenceCount === 0) {
delete renderStateCache[partialKey];
if (defined_default(fullCachedState)) {
--fullCachedState.referenceCount;
}
}
}
if (defined_default(fullCachedState) && fullCachedState.referenceCount === 0) {
delete renderStateCache[fullKey];
}
};
RenderState.getCache = function() {
return renderStateCache;
};
RenderState.clearCache = function() {
renderStateCache = {};
};
function enableOrDisable(gl, glEnum, enable) {
if (enable) {
gl.enable(glEnum);
} else {
gl.disable(glEnum);
}
}
function applyFrontFace(gl, renderState) {
gl.frontFace(renderState.frontFace);
}
function applyCull(gl, renderState) {
const cull = renderState.cull;
const enabled = cull.enabled;
enableOrDisable(gl, gl.CULL_FACE, enabled);
if (enabled) {
gl.cullFace(cull.face);
}
}
function applyLineWidth(gl, renderState) {
gl.lineWidth(renderState.lineWidth);
}
function applyPolygonOffset(gl, renderState) {
const polygonOffset = renderState.polygonOffset;
const enabled = polygonOffset.enabled;
enableOrDisable(gl, gl.POLYGON_OFFSET_FILL, enabled);
if (enabled) {
gl.polygonOffset(polygonOffset.factor, polygonOffset.units);
}
}
function applyScissorTest(gl, renderState, passState) {
const scissorTest = renderState.scissorTest;
const enabled = defined_default(passState.scissorTest) ? passState.scissorTest.enabled : scissorTest.enabled;
enableOrDisable(gl, gl.SCISSOR_TEST, enabled);
if (enabled) {
const rectangle = defined_default(passState.scissorTest) ? passState.scissorTest.rectangle : scissorTest.rectangle;
gl.scissor(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
}
}
function applyDepthRange(gl, renderState) {
const depthRange = renderState.depthRange;
gl.depthRange(depthRange.near, depthRange.far);
}
function applyDepthTest(gl, renderState) {
const depthTest = renderState.depthTest;
const enabled = depthTest.enabled;
enableOrDisable(gl, gl.DEPTH_TEST, enabled);
if (enabled) {
gl.depthFunc(depthTest.func);
}
}
function applyColorMask(gl, renderState) {
const colorMask = renderState.colorMask;
gl.colorMask(colorMask.red, colorMask.green, colorMask.blue, colorMask.alpha);
}
function applyDepthMask(gl, renderState) {
gl.depthMask(renderState.depthMask);
}
function applyStencilMask(gl, renderState) {
gl.stencilMask(renderState.stencilMask);
}
function applyBlendingColor(gl, color) {
gl.blendColor(color.red, color.green, color.blue, color.alpha);
}
function applyBlending(gl, renderState, passState) {
const blending = renderState.blending;
const enabled = defined_default(passState.blendingEnabled) ? passState.blendingEnabled : blending.enabled;
enableOrDisable(gl, gl.BLEND, enabled);
if (enabled) {
applyBlendingColor(gl, blending.color);
gl.blendEquationSeparate(blending.equationRgb, blending.equationAlpha);
gl.blendFuncSeparate(
blending.functionSourceRgb,
blending.functionDestinationRgb,
blending.functionSourceAlpha,
blending.functionDestinationAlpha
);
}
}
function applyStencilTest(gl, renderState) {
const stencilTest = renderState.stencilTest;
const enabled = stencilTest.enabled;
enableOrDisable(gl, gl.STENCIL_TEST, enabled);
if (enabled) {
const frontFunction = stencilTest.frontFunction;
const backFunction = stencilTest.backFunction;
const reference = stencilTest.reference;
const mask = stencilTest.mask;
gl.stencilFunc(frontFunction, reference, mask);
gl.stencilFuncSeparate(gl.BACK, backFunction, reference, mask);
gl.stencilFuncSeparate(gl.FRONT, frontFunction, reference, mask);
const frontOperation = stencilTest.frontOperation;
const frontOperationFail = frontOperation.fail;
const frontOperationZFail = frontOperation.zFail;
const frontOperationZPass = frontOperation.zPass;
gl.stencilOpSeparate(
gl.FRONT,
frontOperationFail,
frontOperationZFail,
frontOperationZPass
);
const backOperation = stencilTest.backOperation;
const backOperationFail = backOperation.fail;
const backOperationZFail = backOperation.zFail;
const backOperationZPass = backOperation.zPass;
gl.stencilOpSeparate(
gl.BACK,
backOperationFail,
backOperationZFail,
backOperationZPass
);
}
}
function applySampleCoverage(gl, renderState) {
const sampleCoverage = renderState.sampleCoverage;
const enabled = sampleCoverage.enabled;
enableOrDisable(gl, gl.SAMPLE_COVERAGE, enabled);
if (enabled) {
gl.sampleCoverage(sampleCoverage.value, sampleCoverage.invert);
}
}
var scratchViewport = new BoundingRectangle_default();
function applyViewport(gl, renderState, passState) {
let viewport = defaultValue_default(renderState.viewport, passState.viewport);
if (!defined_default(viewport)) {
viewport = scratchViewport;
viewport.width = passState.context.drawingBufferWidth;
viewport.height = passState.context.drawingBufferHeight;
}
passState.context.uniformState.viewport = viewport;
gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height);
}
RenderState.apply = function(gl, renderState, passState) {
applyFrontFace(gl, renderState);
applyCull(gl, renderState);
applyLineWidth(gl, renderState);
applyPolygonOffset(gl, renderState);
applyDepthRange(gl, renderState);
applyDepthTest(gl, renderState);
applyColorMask(gl, renderState);
applyDepthMask(gl, renderState);
applyStencilMask(gl, renderState);
applyStencilTest(gl, renderState);
applySampleCoverage(gl, renderState);
applyScissorTest(gl, renderState, passState);
applyBlending(gl, renderState, passState);
applyViewport(gl, renderState, passState);
};
function createFuncs(previousState, nextState) {
const funcs = [];
if (previousState.frontFace !== nextState.frontFace) {
funcs.push(applyFrontFace);
}
if (previousState.cull.enabled !== nextState.cull.enabled || previousState.cull.face !== nextState.cull.face) {
funcs.push(applyCull);
}
if (previousState.lineWidth !== nextState.lineWidth) {
funcs.push(applyLineWidth);
}
if (previousState.polygonOffset.enabled !== nextState.polygonOffset.enabled || previousState.polygonOffset.factor !== nextState.polygonOffset.factor || previousState.polygonOffset.units !== nextState.polygonOffset.units) {
funcs.push(applyPolygonOffset);
}
if (previousState.depthRange.near !== nextState.depthRange.near || previousState.depthRange.far !== nextState.depthRange.far) {
funcs.push(applyDepthRange);
}
if (previousState.depthTest.enabled !== nextState.depthTest.enabled || previousState.depthTest.func !== nextState.depthTest.func) {
funcs.push(applyDepthTest);
}
if (previousState.colorMask.red !== nextState.colorMask.red || previousState.colorMask.green !== nextState.colorMask.green || previousState.colorMask.blue !== nextState.colorMask.blue || previousState.colorMask.alpha !== nextState.colorMask.alpha) {
funcs.push(applyColorMask);
}
if (previousState.depthMask !== nextState.depthMask) {
funcs.push(applyDepthMask);
}
if (previousState.stencilMask !== nextState.stencilMask) {
funcs.push(applyStencilMask);
}
if (previousState.stencilTest.enabled !== nextState.stencilTest.enabled || previousState.stencilTest.frontFunction !== nextState.stencilTest.frontFunction || previousState.stencilTest.backFunction !== nextState.stencilTest.backFunction || previousState.stencilTest.reference !== nextState.stencilTest.reference || previousState.stencilTest.mask !== nextState.stencilTest.mask || previousState.stencilTest.frontOperation.fail !== nextState.stencilTest.frontOperation.fail || previousState.stencilTest.frontOperation.zFail !== nextState.stencilTest.frontOperation.zFail || previousState.stencilTest.backOperation.fail !== nextState.stencilTest.backOperation.fail || previousState.stencilTest.backOperation.zFail !== nextState.stencilTest.backOperation.zFail || previousState.stencilTest.backOperation.zPass !== nextState.stencilTest.backOperation.zPass) {
funcs.push(applyStencilTest);
}
if (previousState.sampleCoverage.enabled !== nextState.sampleCoverage.enabled || previousState.sampleCoverage.value !== nextState.sampleCoverage.value || previousState.sampleCoverage.invert !== nextState.sampleCoverage.invert) {
funcs.push(applySampleCoverage);
}
return funcs;
}
RenderState.partialApply = function(gl, previousRenderState, renderState, previousPassState, passState, clear2) {
if (previousRenderState !== renderState) {
let funcs = renderState._applyFunctions[previousRenderState.id];
if (!defined_default(funcs)) {
funcs = createFuncs(previousRenderState, renderState);
renderState._applyFunctions[previousRenderState.id] = funcs;
}
const len = funcs.length;
for (let i = 0; i < len; ++i) {
funcs[i](gl, renderState);
}
}
const previousScissorTest = defined_default(previousPassState.scissorTest) ? previousPassState.scissorTest : previousRenderState.scissorTest;
const scissorTest = defined_default(passState.scissorTest) ? passState.scissorTest : renderState.scissorTest;
if (previousScissorTest !== scissorTest || clear2) {
applyScissorTest(gl, renderState, passState);
}
const previousBlendingEnabled = defined_default(previousPassState.blendingEnabled) ? previousPassState.blendingEnabled : previousRenderState.blending.enabled;
const blendingEnabled = defined_default(passState.blendingEnabled) ? passState.blendingEnabled : renderState.blending.enabled;
if (previousBlendingEnabled !== blendingEnabled || blendingEnabled && previousRenderState.blending !== renderState.blending) {
applyBlending(gl, renderState, passState);
}
if (previousRenderState !== renderState || previousPassState !== passState || previousPassState.context !== passState.context) {
applyViewport(gl, renderState, passState);
}
};
RenderState.getState = function(renderState) {
if (!defined_default(renderState)) {
throw new DeveloperError_default("renderState is required.");
}
return {
frontFace: renderState.frontFace,
cull: {
enabled: renderState.cull.enabled,
face: renderState.cull.face
},
lineWidth: renderState.lineWidth,
polygonOffset: {
enabled: renderState.polygonOffset.enabled,
factor: renderState.polygonOffset.factor,
units: renderState.polygonOffset.units
},
scissorTest: {
enabled: renderState.scissorTest.enabled,
rectangle: BoundingRectangle_default.clone(renderState.scissorTest.rectangle)
},
depthRange: {
near: renderState.depthRange.near,
far: renderState.depthRange.far
},
depthTest: {
enabled: renderState.depthTest.enabled,
func: renderState.depthTest.func
},
colorMask: {
red: renderState.colorMask.red,
green: renderState.colorMask.green,
blue: renderState.colorMask.blue,
alpha: renderState.colorMask.alpha
},
depthMask: renderState.depthMask,
stencilMask: renderState.stencilMask,
blending: {
enabled: renderState.blending.enabled,
color: Color_default.clone(renderState.blending.color),
equationRgb: renderState.blending.equationRgb,
equationAlpha: renderState.blending.equationAlpha,
functionSourceRgb: renderState.blending.functionSourceRgb,
functionSourceAlpha: renderState.blending.functionSourceAlpha,
functionDestinationRgb: renderState.blending.functionDestinationRgb,
functionDestinationAlpha: renderState.blending.functionDestinationAlpha
},
stencilTest: {
enabled: renderState.stencilTest.enabled,
frontFunction: renderState.stencilTest.frontFunction,
backFunction: renderState.stencilTest.backFunction,
reference: renderState.stencilTest.reference,
mask: renderState.stencilTest.mask,
frontOperation: {
fail: renderState.stencilTest.frontOperation.fail,
zFail: renderState.stencilTest.frontOperation.zFail,
zPass: renderState.stencilTest.frontOperation.zPass
},
backOperation: {
fail: renderState.stencilTest.backOperation.fail,
zFail: renderState.stencilTest.backOperation.zFail,
zPass: renderState.stencilTest.backOperation.zPass
}
},
sampleCoverage: {
enabled: renderState.sampleCoverage.enabled,
value: renderState.sampleCoverage.value,
invert: renderState.sampleCoverage.invert
},
viewport: defined_default(renderState.viewport) ? BoundingRectangle_default.clone(renderState.viewport) : void 0
};
};
var RenderState_default = RenderState;
// packages/engine/Source/Core/Matrix2.js
function Matrix2(column0Row0, column1Row0, column0Row1, column1Row1) {
this[0] = defaultValue_default(column0Row0, 0);
this[1] = defaultValue_default(column0Row1, 0);
this[2] = defaultValue_default(column1Row0, 0);
this[3] = defaultValue_default(column1Row1, 0);
}
Matrix2.packedLength = 4;
Matrix2.pack = function(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
array[startingIndex++] = value[0];
array[startingIndex++] = value[1];
array[startingIndex++] = value[2];
array[startingIndex++] = value[3];
return array;
};
Matrix2.unpack = function(array, startingIndex, result) {
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
if (!defined_default(result)) {
result = new Matrix2();
}
result[0] = array[startingIndex++];
result[1] = array[startingIndex++];
result[2] = array[startingIndex++];
result[3] = array[startingIndex++];
return result;
};
Matrix2.packArray = function(array, result) {
Check_default.defined("array", array);
const length3 = array.length;
const resultLength = length3 * 4;
if (!defined_default(result)) {
result = new Array(resultLength);
} else if (!Array.isArray(result) && result.length !== resultLength) {
throw new DeveloperError_default(
"If result is a typed array, it must have exactly array.length * 4 elements"
);
} else if (result.length !== resultLength) {
result.length = resultLength;
}
for (let i = 0; i < length3; ++i) {
Matrix2.pack(array[i], result, i * 4);
}
return result;
};
Matrix2.unpackArray = function(array, result) {
Check_default.defined("array", array);
Check_default.typeOf.number.greaterThanOrEquals("array.length", array.length, 4);
if (array.length % 4 !== 0) {
throw new DeveloperError_default("array length must be a multiple of 4.");
}
const length3 = array.length;
if (!defined_default(result)) {
result = new Array(length3 / 4);
} else {
result.length = length3 / 4;
}
for (let i = 0; i < length3; i += 4) {
const index = i / 4;
result[index] = Matrix2.unpack(array, i, result[index]);
}
return result;
};
Matrix2.clone = function(matrix, result) {
if (!defined_default(matrix)) {
return void 0;
}
if (!defined_default(result)) {
return new Matrix2(matrix[0], matrix[2], matrix[1], matrix[3]);
}
result[0] = matrix[0];
result[1] = matrix[1];
result[2] = matrix[2];
result[3] = matrix[3];
return result;
};
Matrix2.fromArray = Matrix2.unpack;
Matrix2.fromColumnMajorArray = function(values, result) {
Check_default.defined("values", values);
return Matrix2.clone(values, result);
};
Matrix2.fromRowMajorArray = function(values, result) {
Check_default.defined("values", values);
if (!defined_default(result)) {
return new Matrix2(values[0], values[1], values[2], values[3]);
}
result[0] = values[0];
result[1] = values[2];
result[2] = values[1];
result[3] = values[3];
return result;
};
Matrix2.fromScale = function(scale, result) {
Check_default.typeOf.object("scale", scale);
if (!defined_default(result)) {
return new Matrix2(scale.x, 0, 0, scale.y);
}
result[0] = scale.x;
result[1] = 0;
result[2] = 0;
result[3] = scale.y;
return result;
};
Matrix2.fromUniformScale = function(scale, result) {
Check_default.typeOf.number("scale", scale);
if (!defined_default(result)) {
return new Matrix2(scale, 0, 0, scale);
}
result[0] = scale;
result[1] = 0;
result[2] = 0;
result[3] = scale;
return result;
};
Matrix2.fromRotation = function(angle, result) {
Check_default.typeOf.number("angle", angle);
const cosAngle = Math.cos(angle);
const sinAngle = Math.sin(angle);
if (!defined_default(result)) {
return new Matrix2(cosAngle, -sinAngle, sinAngle, cosAngle);
}
result[0] = cosAngle;
result[1] = sinAngle;
result[2] = -sinAngle;
result[3] = cosAngle;
return result;
};
Matrix2.toArray = function(matrix, result) {
Check_default.typeOf.object("matrix", matrix);
if (!defined_default(result)) {
return [matrix[0], matrix[1], matrix[2], matrix[3]];
}
result[0] = matrix[0];
result[1] = matrix[1];
result[2] = matrix[2];
result[3] = matrix[3];
return result;
};
Matrix2.getElementIndex = function(column, row) {
Check_default.typeOf.number.greaterThanOrEquals("row", row, 0);
Check_default.typeOf.number.lessThanOrEquals("row", row, 1);
Check_default.typeOf.number.greaterThanOrEquals("column", column, 0);
Check_default.typeOf.number.lessThanOrEquals("column", column, 1);
return column * 2 + row;
};
Matrix2.getColumn = function(matrix, index, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.number.greaterThanOrEquals("index", index, 0);
Check_default.typeOf.number.lessThanOrEquals("index", index, 1);
Check_default.typeOf.object("result", result);
const startIndex = index * 2;
const x = matrix[startIndex];
const y = matrix[startIndex + 1];
result.x = x;
result.y = y;
return result;
};
Matrix2.setColumn = function(matrix, index, cartesian11, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.number.greaterThanOrEquals("index", index, 0);
Check_default.typeOf.number.lessThanOrEquals("index", index, 1);
Check_default.typeOf.object("cartesian", cartesian11);
Check_default.typeOf.object("result", result);
result = Matrix2.clone(matrix, result);
const startIndex = index * 2;
result[startIndex] = cartesian11.x;
result[startIndex + 1] = cartesian11.y;
return result;
};
Matrix2.getRow = function(matrix, index, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.number.greaterThanOrEquals("index", index, 0);
Check_default.typeOf.number.lessThanOrEquals("index", index, 1);
Check_default.typeOf.object("result", result);
const x = matrix[index];
const y = matrix[index + 2];
result.x = x;
result.y = y;
return result;
};
Matrix2.setRow = function(matrix, index, cartesian11, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.number.greaterThanOrEquals("index", index, 0);
Check_default.typeOf.number.lessThanOrEquals("index", index, 1);
Check_default.typeOf.object("cartesian", cartesian11);
Check_default.typeOf.object("result", result);
result = Matrix2.clone(matrix, result);
result[index] = cartesian11.x;
result[index + 2] = cartesian11.y;
return result;
};
var scaleScratch13 = new Cartesian2_default();
Matrix2.setScale = function(matrix, scale, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.object("scale", scale);
Check_default.typeOf.object("result", result);
const existingScale = Matrix2.getScale(matrix, scaleScratch13);
const scaleRatioX = scale.x / existingScale.x;
const scaleRatioY = scale.y / existingScale.y;
result[0] = matrix[0] * scaleRatioX;
result[1] = matrix[1] * scaleRatioX;
result[2] = matrix[2] * scaleRatioY;
result[3] = matrix[3] * scaleRatioY;
return result;
};
var scaleScratch23 = new Cartesian2_default();
Matrix2.setUniformScale = function(matrix, scale, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.number("scale", scale);
Check_default.typeOf.object("result", result);
const existingScale = Matrix2.getScale(matrix, scaleScratch23);
const scaleRatioX = scale / existingScale.x;
const scaleRatioY = scale / existingScale.y;
result[0] = matrix[0] * scaleRatioX;
result[1] = matrix[1] * scaleRatioX;
result[2] = matrix[2] * scaleRatioY;
result[3] = matrix[3] * scaleRatioY;
return result;
};
var scratchColumn3 = new Cartesian2_default();
Matrix2.getScale = function(matrix, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.object("result", result);
result.x = Cartesian2_default.magnitude(
Cartesian2_default.fromElements(matrix[0], matrix[1], scratchColumn3)
);
result.y = Cartesian2_default.magnitude(
Cartesian2_default.fromElements(matrix[2], matrix[3], scratchColumn3)
);
return result;
};
var scaleScratch33 = new Cartesian2_default();
Matrix2.getMaximumScale = function(matrix) {
Matrix2.getScale(matrix, scaleScratch33);
return Cartesian2_default.maximumComponent(scaleScratch33);
};
var scaleScratch43 = new Cartesian2_default();
Matrix2.setRotation = function(matrix, rotation, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.object("result", result);
const scale = Matrix2.getScale(matrix, scaleScratch43);
result[0] = rotation[0] * scale.x;
result[1] = rotation[1] * scale.x;
result[2] = rotation[2] * scale.y;
result[3] = rotation[3] * scale.y;
return result;
};
var scaleScratch53 = new Cartesian2_default();
Matrix2.getRotation = function(matrix, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.object("result", result);
const scale = Matrix2.getScale(matrix, scaleScratch53);
result[0] = matrix[0] / scale.x;
result[1] = matrix[1] / scale.x;
result[2] = matrix[2] / scale.y;
result[3] = matrix[3] / scale.y;
return result;
};
Matrix2.multiply = function(left, right, result) {
Check_default.typeOf.object("left", left);
Check_default.typeOf.object("right", right);
Check_default.typeOf.object("result", result);
const column0Row0 = left[0] * right[0] + left[2] * right[1];
const column1Row0 = left[0] * right[2] + left[2] * right[3];
const column0Row1 = left[1] * right[0] + left[3] * right[1];
const column1Row1 = left[1] * right[2] + left[3] * right[3];
result[0] = column0Row0;
result[1] = column0Row1;
result[2] = column1Row0;
result[3] = column1Row1;
return result;
};
Matrix2.add = function(left, right, result) {
Check_default.typeOf.object("left", left);
Check_default.typeOf.object("right", right);
Check_default.typeOf.object("result", result);
result[0] = left[0] + right[0];
result[1] = left[1] + right[1];
result[2] = left[2] + right[2];
result[3] = left[3] + right[3];
return result;
};
Matrix2.subtract = function(left, right, result) {
Check_default.typeOf.object("left", left);
Check_default.typeOf.object("right", right);
Check_default.typeOf.object("result", result);
result[0] = left[0] - right[0];
result[1] = left[1] - right[1];
result[2] = left[2] - right[2];
result[3] = left[3] - right[3];
return result;
};
Matrix2.multiplyByVector = function(matrix, cartesian11, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.object("cartesian", cartesian11);
Check_default.typeOf.object("result", result);
const x = matrix[0] * cartesian11.x + matrix[2] * cartesian11.y;
const y = matrix[1] * cartesian11.x + matrix[3] * cartesian11.y;
result.x = x;
result.y = y;
return result;
};
Matrix2.multiplyByScalar = function(matrix, scalar, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.number("scalar", scalar);
Check_default.typeOf.object("result", result);
result[0] = matrix[0] * scalar;
result[1] = matrix[1] * scalar;
result[2] = matrix[2] * scalar;
result[3] = matrix[3] * scalar;
return result;
};
Matrix2.multiplyByScale = function(matrix, scale, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.object("scale", scale);
Check_default.typeOf.object("result", result);
result[0] = matrix[0] * scale.x;
result[1] = matrix[1] * scale.x;
result[2] = matrix[2] * scale.y;
result[3] = matrix[3] * scale.y;
return result;
};
Matrix2.multiplyByUniformScale = function(matrix, scale, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.number("scale", scale);
Check_default.typeOf.object("result", result);
result[0] = matrix[0] * scale;
result[1] = matrix[1] * scale;
result[2] = matrix[2] * scale;
result[3] = matrix[3] * scale;
return result;
};
Matrix2.negate = function(matrix, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.object("result", result);
result[0] = -matrix[0];
result[1] = -matrix[1];
result[2] = -matrix[2];
result[3] = -matrix[3];
return result;
};
Matrix2.transpose = function(matrix, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.object("result", result);
const column0Row0 = matrix[0];
const column0Row1 = matrix[2];
const column1Row0 = matrix[1];
const column1Row1 = matrix[3];
result[0] = column0Row0;
result[1] = column0Row1;
result[2] = column1Row0;
result[3] = column1Row1;
return result;
};
Matrix2.abs = function(matrix, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.object("result", result);
result[0] = Math.abs(matrix[0]);
result[1] = Math.abs(matrix[1]);
result[2] = Math.abs(matrix[2]);
result[3] = Math.abs(matrix[3]);
return result;
};
Matrix2.equals = function(left, right) {
return left === right || defined_default(left) && defined_default(right) && left[0] === right[0] && left[1] === right[1] && left[2] === right[2] && left[3] === right[3];
};
Matrix2.equalsArray = function(matrix, array, offset2) {
return matrix[0] === array[offset2] && matrix[1] === array[offset2 + 1] && matrix[2] === array[offset2 + 2] && matrix[3] === array[offset2 + 3];
};
Matrix2.equalsEpsilon = function(left, right, epsilon) {
epsilon = defaultValue_default(epsilon, 0);
return left === right || defined_default(left) && defined_default(right) && Math.abs(left[0] - right[0]) <= epsilon && Math.abs(left[1] - right[1]) <= epsilon && Math.abs(left[2] - right[2]) <= epsilon && Math.abs(left[3] - right[3]) <= epsilon;
};
Matrix2.IDENTITY = Object.freeze(new Matrix2(1, 0, 0, 1));
Matrix2.ZERO = Object.freeze(new Matrix2(0, 0, 0, 0));
Matrix2.COLUMN0ROW0 = 0;
Matrix2.COLUMN0ROW1 = 1;
Matrix2.COLUMN1ROW0 = 2;
Matrix2.COLUMN1ROW1 = 3;
Object.defineProperties(Matrix2.prototype, {
/**
* Gets the number of items in the collection.
* @memberof Matrix2.prototype
*
* @type {number}
*/
length: {
get: function() {
return Matrix2.packedLength;
}
}
});
Matrix2.prototype.clone = function(result) {
return Matrix2.clone(this, result);
};
Matrix2.prototype.equals = function(right) {
return Matrix2.equals(this, right);
};
Matrix2.prototype.equalsEpsilon = function(right, epsilon) {
return Matrix2.equalsEpsilon(this, right, epsilon);
};
Matrix2.prototype.toString = function() {
return `(${this[0]}, ${this[2]})
(${this[1]}, ${this[3]})`;
};
var Matrix2_default = Matrix2;
// packages/engine/Source/Renderer/createUniform.js
function createUniform(gl, activeUniform, uniformName, location2) {
switch (activeUniform.type) {
case gl.FLOAT:
return new UniformFloat(gl, activeUniform, uniformName, location2);
case gl.FLOAT_VEC2:
return new UniformFloatVec2(gl, activeUniform, uniformName, location2);
case gl.FLOAT_VEC3:
return new UniformFloatVec3(gl, activeUniform, uniformName, location2);
case gl.FLOAT_VEC4:
return new UniformFloatVec4(gl, activeUniform, uniformName, location2);
case gl.SAMPLER_2D:
case gl.SAMPLER_CUBE:
return new UniformSampler(gl, activeUniform, uniformName, location2);
case gl.INT:
case gl.BOOL:
return new UniformInt(gl, activeUniform, uniformName, location2);
case gl.INT_VEC2:
case gl.BOOL_VEC2:
return new UniformIntVec2(gl, activeUniform, uniformName, location2);
case gl.INT_VEC3:
case gl.BOOL_VEC3:
return new UniformIntVec3(gl, activeUniform, uniformName, location2);
case gl.INT_VEC4:
case gl.BOOL_VEC4:
return new UniformIntVec4(gl, activeUniform, uniformName, location2);
case gl.FLOAT_MAT2:
return new UniformMat2(gl, activeUniform, uniformName, location2);
case gl.FLOAT_MAT3:
return new UniformMat3(gl, activeUniform, uniformName, location2);
case gl.FLOAT_MAT4:
return new UniformMat4(gl, activeUniform, uniformName, location2);
default:
throw new RuntimeError_default(
`Unrecognized uniform type: ${activeUniform.type} for uniform "${uniformName}".`
);
}
}
function UniformFloat(gl, activeUniform, uniformName, location2) {
this.name = uniformName;
this.value = void 0;
this._value = 0;
this._gl = gl;
this._location = location2;
}
UniformFloat.prototype.set = function() {
if (this.value !== this._value) {
this._value = this.value;
this._gl.uniform1f(this._location, this.value);
}
};
function UniformFloatVec2(gl, activeUniform, uniformName, location2) {
this.name = uniformName;
this.value = void 0;
this._value = new Cartesian2_default();
this._gl = gl;
this._location = location2;
}
UniformFloatVec2.prototype.set = function() {
const v7 = this.value;
if (!Cartesian2_default.equals(v7, this._value)) {
Cartesian2_default.clone(v7, this._value);
this._gl.uniform2f(this._location, v7.x, v7.y);
}
};
function UniformFloatVec3(gl, activeUniform, uniformName, location2) {
this.name = uniformName;
this.value = void 0;
this._value = void 0;
this._gl = gl;
this._location = location2;
}
UniformFloatVec3.prototype.set = function() {
const v7 = this.value;
if (defined_default(v7.red)) {
if (!Color_default.equals(v7, this._value)) {
this._value = Color_default.clone(v7, this._value);
this._gl.uniform3f(this._location, v7.red, v7.green, v7.blue);
}
} else if (defined_default(v7.x)) {
if (!Cartesian3_default.equals(v7, this._value)) {
this._value = Cartesian3_default.clone(v7, this._value);
this._gl.uniform3f(this._location, v7.x, v7.y, v7.z);
}
} else {
throw new DeveloperError_default(`Invalid vec3 value for uniform "${this.name}".`);
}
};
function UniformFloatVec4(gl, activeUniform, uniformName, location2) {
this.name = uniformName;
this.value = void 0;
this._value = void 0;
this._gl = gl;
this._location = location2;
}
UniformFloatVec4.prototype.set = function() {
const v7 = this.value;
if (defined_default(v7.red)) {
if (!Color_default.equals(v7, this._value)) {
this._value = Color_default.clone(v7, this._value);
this._gl.uniform4f(this._location, v7.red, v7.green, v7.blue, v7.alpha);
}
} else if (defined_default(v7.x)) {
if (!Cartesian4_default.equals(v7, this._value)) {
this._value = Cartesian4_default.clone(v7, this._value);
this._gl.uniform4f(this._location, v7.x, v7.y, v7.z, v7.w);
}
} else {
throw new DeveloperError_default(`Invalid vec4 value for uniform "${this.name}".`);
}
};
function UniformSampler(gl, activeUniform, uniformName, location2) {
this.name = uniformName;
this.value = void 0;
this._gl = gl;
this._location = location2;
this.textureUnitIndex = void 0;
}
UniformSampler.prototype.set = function() {
const gl = this._gl;
gl.activeTexture(gl.TEXTURE0 + this.textureUnitIndex);
const v7 = this.value;
gl.bindTexture(v7._target, v7._texture);
};
UniformSampler.prototype._setSampler = function(textureUnitIndex) {
this.textureUnitIndex = textureUnitIndex;
this._gl.uniform1i(this._location, textureUnitIndex);
return textureUnitIndex + 1;
};
function UniformInt(gl, activeUniform, uniformName, location2) {
this.name = uniformName;
this.value = void 0;
this._value = 0;
this._gl = gl;
this._location = location2;
}
UniformInt.prototype.set = function() {
if (this.value !== this._value) {
this._value = this.value;
this._gl.uniform1i(this._location, this.value);
}
};
function UniformIntVec2(gl, activeUniform, uniformName, location2) {
this.name = uniformName;
this.value = void 0;
this._value = new Cartesian2_default();
this._gl = gl;
this._location = location2;
}
UniformIntVec2.prototype.set = function() {
const v7 = this.value;
if (!Cartesian2_default.equals(v7, this._value)) {
Cartesian2_default.clone(v7, this._value);
this._gl.uniform2i(this._location, v7.x, v7.y);
}
};
function UniformIntVec3(gl, activeUniform, uniformName, location2) {
this.name = uniformName;
this.value = void 0;
this._value = new Cartesian3_default();
this._gl = gl;
this._location = location2;
}
UniformIntVec3.prototype.set = function() {
const v7 = this.value;
if (!Cartesian3_default.equals(v7, this._value)) {
Cartesian3_default.clone(v7, this._value);
this._gl.uniform3i(this._location, v7.x, v7.y, v7.z);
}
};
function UniformIntVec4(gl, activeUniform, uniformName, location2) {
this.name = uniformName;
this.value = void 0;
this._value = new Cartesian4_default();
this._gl = gl;
this._location = location2;
}
UniformIntVec4.prototype.set = function() {
const v7 = this.value;
if (!Cartesian4_default.equals(v7, this._value)) {
Cartesian4_default.clone(v7, this._value);
this._gl.uniform4i(this._location, v7.x, v7.y, v7.z, v7.w);
}
};
var scratchUniformArray = new Float32Array(4);
function UniformMat2(gl, activeUniform, uniformName, location2) {
this.name = uniformName;
this.value = void 0;
this._value = new Matrix2_default();
this._gl = gl;
this._location = location2;
}
UniformMat2.prototype.set = function() {
if (!Matrix2_default.equalsArray(this.value, this._value, 0)) {
Matrix2_default.clone(this.value, this._value);
const array = Matrix2_default.toArray(this.value, scratchUniformArray);
this._gl.uniformMatrix2fv(this._location, false, array);
}
};
var scratchMat3Array = new Float32Array(9);
function UniformMat3(gl, activeUniform, uniformName, location2) {
this.name = uniformName;
this.value = void 0;
this._value = new Matrix3_default();
this._gl = gl;
this._location = location2;
}
UniformMat3.prototype.set = function() {
if (!Matrix3_default.equalsArray(this.value, this._value, 0)) {
Matrix3_default.clone(this.value, this._value);
const array = Matrix3_default.toArray(this.value, scratchMat3Array);
this._gl.uniformMatrix3fv(this._location, false, array);
}
};
var scratchMat4Array = new Float32Array(16);
function UniformMat4(gl, activeUniform, uniformName, location2) {
this.name = uniformName;
this.value = void 0;
this._value = new Matrix4_default();
this._gl = gl;
this._location = location2;
}
UniformMat4.prototype.set = function() {
if (!Matrix4_default.equalsArray(this.value, this._value, 0)) {
Matrix4_default.clone(this.value, this._value);
const array = Matrix4_default.toArray(this.value, scratchMat4Array);
this._gl.uniformMatrix4fv(this._location, false, array);
}
};
var createUniform_default = createUniform;
// packages/engine/Source/Renderer/createUniformArray.js
function createUniformArray(gl, activeUniform, uniformName, locations) {
switch (activeUniform.type) {
case gl.FLOAT:
return new UniformArrayFloat(gl, activeUniform, uniformName, locations);
case gl.FLOAT_VEC2:
return new UniformArrayFloatVec2(
gl,
activeUniform,
uniformName,
locations
);
case gl.FLOAT_VEC3:
return new UniformArrayFloatVec3(
gl,
activeUniform,
uniformName,
locations
);
case gl.FLOAT_VEC4:
return new UniformArrayFloatVec4(
gl,
activeUniform,
uniformName,
locations
);
case gl.SAMPLER_2D:
case gl.SAMPLER_CUBE:
return new UniformArraySampler(gl, activeUniform, uniformName, locations);
case gl.INT:
case gl.BOOL:
return new UniformArrayInt(gl, activeUniform, uniformName, locations);
case gl.INT_VEC2:
case gl.BOOL_VEC2:
return new UniformArrayIntVec2(gl, activeUniform, uniformName, locations);
case gl.INT_VEC3:
case gl.BOOL_VEC3:
return new UniformArrayIntVec3(gl, activeUniform, uniformName, locations);
case gl.INT_VEC4:
case gl.BOOL_VEC4:
return new UniformArrayIntVec4(gl, activeUniform, uniformName, locations);
case gl.FLOAT_MAT2:
return new UniformArrayMat2(gl, activeUniform, uniformName, locations);
case gl.FLOAT_MAT3:
return new UniformArrayMat3(gl, activeUniform, uniformName, locations);
case gl.FLOAT_MAT4:
return new UniformArrayMat4(gl, activeUniform, uniformName, locations);
default:
throw new RuntimeError_default(
`Unrecognized uniform type: ${activeUniform.type} for uniform "${uniformName}".`
);
}
}
function UniformArrayFloat(gl, activeUniform, uniformName, locations) {
const length3 = locations.length;
this.name = uniformName;
this.value = new Array(length3);
this._value = new Float32Array(length3);
this._gl = gl;
this._location = locations[0];
}
UniformArrayFloat.prototype.set = function() {
const value = this.value;
const length3 = value.length;
const arraybuffer = this._value;
let changed = false;
for (let i = 0; i < length3; ++i) {
const v7 = value[i];
if (v7 !== arraybuffer[i]) {
arraybuffer[i] = v7;
changed = true;
}
}
if (changed) {
this._gl.uniform1fv(this._location, arraybuffer);
}
};
function UniformArrayFloatVec2(gl, activeUniform, uniformName, locations) {
const length3 = locations.length;
this.name = uniformName;
this.value = new Array(length3);
this._value = new Float32Array(length3 * 2);
this._gl = gl;
this._location = locations[0];
}
UniformArrayFloatVec2.prototype.set = function() {
const value = this.value;
const length3 = value.length;
const arraybuffer = this._value;
let changed = false;
let j = 0;
for (let i = 0; i < length3; ++i) {
const v7 = value[i];
if (!Cartesian2_default.equalsArray(v7, arraybuffer, j)) {
Cartesian2_default.pack(v7, arraybuffer, j);
changed = true;
}
j += 2;
}
if (changed) {
this._gl.uniform2fv(this._location, arraybuffer);
}
};
function UniformArrayFloatVec3(gl, activeUniform, uniformName, locations) {
const length3 = locations.length;
this.name = uniformName;
this.value = new Array(length3);
this._value = new Float32Array(length3 * 3);
this._gl = gl;
this._location = locations[0];
}
UniformArrayFloatVec3.prototype.set = function() {
const value = this.value;
const length3 = value.length;
const arraybuffer = this._value;
let changed = false;
let j = 0;
for (let i = 0; i < length3; ++i) {
const v7 = value[i];
if (defined_default(v7.red)) {
if (v7.red !== arraybuffer[j] || v7.green !== arraybuffer[j + 1] || v7.blue !== arraybuffer[j + 2]) {
arraybuffer[j] = v7.red;
arraybuffer[j + 1] = v7.green;
arraybuffer[j + 2] = v7.blue;
changed = true;
}
} else if (defined_default(v7.x)) {
if (!Cartesian3_default.equalsArray(v7, arraybuffer, j)) {
Cartesian3_default.pack(v7, arraybuffer, j);
changed = true;
}
} else {
throw new DeveloperError_default("Invalid vec3 value.");
}
j += 3;
}
if (changed) {
this._gl.uniform3fv(this._location, arraybuffer);
}
};
function UniformArrayFloatVec4(gl, activeUniform, uniformName, locations) {
const length3 = locations.length;
this.name = uniformName;
this.value = new Array(length3);
this._value = new Float32Array(length3 * 4);
this._gl = gl;
this._location = locations[0];
}
UniformArrayFloatVec4.prototype.set = function() {
const value = this.value;
const length3 = value.length;
const arraybuffer = this._value;
let changed = false;
let j = 0;
for (let i = 0; i < length3; ++i) {
const v7 = value[i];
if (defined_default(v7.red)) {
if (!Color_default.equalsArray(v7, arraybuffer, j)) {
Color_default.pack(v7, arraybuffer, j);
changed = true;
}
} else if (defined_default(v7.x)) {
if (!Cartesian4_default.equalsArray(v7, arraybuffer, j)) {
Cartesian4_default.pack(v7, arraybuffer, j);
changed = true;
}
} else {
throw new DeveloperError_default("Invalid vec4 value.");
}
j += 4;
}
if (changed) {
this._gl.uniform4fv(this._location, arraybuffer);
}
};
function UniformArraySampler(gl, activeUniform, uniformName, locations) {
const length3 = locations.length;
this.name = uniformName;
this.value = new Array(length3);
this._value = new Float32Array(length3);
this._gl = gl;
this._locations = locations;
this.textureUnitIndex = void 0;
}
UniformArraySampler.prototype.set = function() {
const gl = this._gl;
const textureUnitIndex = gl.TEXTURE0 + this.textureUnitIndex;
const value = this.value;
const length3 = value.length;
for (let i = 0; i < length3; ++i) {
const v7 = value[i];
gl.activeTexture(textureUnitIndex + i);
gl.bindTexture(v7._target, v7._texture);
}
};
UniformArraySampler.prototype._setSampler = function(textureUnitIndex) {
this.textureUnitIndex = textureUnitIndex;
const locations = this._locations;
const length3 = locations.length;
for (let i = 0; i < length3; ++i) {
const index = textureUnitIndex + i;
this._gl.uniform1i(locations[i], index);
}
return textureUnitIndex + length3;
};
function UniformArrayInt(gl, activeUniform, uniformName, locations) {
const length3 = locations.length;
this.name = uniformName;
this.value = new Array(length3);
this._value = new Int32Array(length3);
this._gl = gl;
this._location = locations[0];
}
UniformArrayInt.prototype.set = function() {
const value = this.value;
const length3 = value.length;
const arraybuffer = this._value;
let changed = false;
for (let i = 0; i < length3; ++i) {
const v7 = value[i];
if (v7 !== arraybuffer[i]) {
arraybuffer[i] = v7;
changed = true;
}
}
if (changed) {
this._gl.uniform1iv(this._location, arraybuffer);
}
};
function UniformArrayIntVec2(gl, activeUniform, uniformName, locations) {
const length3 = locations.length;
this.name = uniformName;
this.value = new Array(length3);
this._value = new Int32Array(length3 * 2);
this._gl = gl;
this._location = locations[0];
}
UniformArrayIntVec2.prototype.set = function() {
const value = this.value;
const length3 = value.length;
const arraybuffer = this._value;
let changed = false;
let j = 0;
for (let i = 0; i < length3; ++i) {
const v7 = value[i];
if (!Cartesian2_default.equalsArray(v7, arraybuffer, j)) {
Cartesian2_default.pack(v7, arraybuffer, j);
changed = true;
}
j += 2;
}
if (changed) {
this._gl.uniform2iv(this._location, arraybuffer);
}
};
function UniformArrayIntVec3(gl, activeUniform, uniformName, locations) {
const length3 = locations.length;
this.name = uniformName;
this.value = new Array(length3);
this._value = new Int32Array(length3 * 3);
this._gl = gl;
this._location = locations[0];
}
UniformArrayIntVec3.prototype.set = function() {
const value = this.value;
const length3 = value.length;
const arraybuffer = this._value;
let changed = false;
let j = 0;
for (let i = 0; i < length3; ++i) {
const v7 = value[i];
if (!Cartesian3_default.equalsArray(v7, arraybuffer, j)) {
Cartesian3_default.pack(v7, arraybuffer, j);
changed = true;
}
j += 3;
}
if (changed) {
this._gl.uniform3iv(this._location, arraybuffer);
}
};
function UniformArrayIntVec4(gl, activeUniform, uniformName, locations) {
const length3 = locations.length;
this.name = uniformName;
this.value = new Array(length3);
this._value = new Int32Array(length3 * 4);
this._gl = gl;
this._location = locations[0];
}
UniformArrayIntVec4.prototype.set = function() {
const value = this.value;
const length3 = value.length;
const arraybuffer = this._value;
let changed = false;
let j = 0;
for (let i = 0; i < length3; ++i) {
const v7 = value[i];
if (!Cartesian4_default.equalsArray(v7, arraybuffer, j)) {
Cartesian4_default.pack(v7, arraybuffer, j);
changed = true;
}
j += 4;
}
if (changed) {
this._gl.uniform4iv(this._location, arraybuffer);
}
};
function UniformArrayMat2(gl, activeUniform, uniformName, locations) {
const length3 = locations.length;
this.name = uniformName;
this.value = new Array(length3);
this._value = new Float32Array(length3 * 4);
this._gl = gl;
this._location = locations[0];
}
UniformArrayMat2.prototype.set = function() {
const value = this.value;
const length3 = value.length;
const arraybuffer = this._value;
let changed = false;
let j = 0;
for (let i = 0; i < length3; ++i) {
const v7 = value[i];
if (!Matrix2_default.equalsArray(v7, arraybuffer, j)) {
Matrix2_default.pack(v7, arraybuffer, j);
changed = true;
}
j += 4;
}
if (changed) {
this._gl.uniformMatrix2fv(this._location, false, arraybuffer);
}
};
function UniformArrayMat3(gl, activeUniform, uniformName, locations) {
const length3 = locations.length;
this.name = uniformName;
this.value = new Array(length3);
this._value = new Float32Array(length3 * 9);
this._gl = gl;
this._location = locations[0];
}
UniformArrayMat3.prototype.set = function() {
const value = this.value;
const length3 = value.length;
const arraybuffer = this._value;
let changed = false;
let j = 0;
for (let i = 0; i < length3; ++i) {
const v7 = value[i];
if (!Matrix3_default.equalsArray(v7, arraybuffer, j)) {
Matrix3_default.pack(v7, arraybuffer, j);
changed = true;
}
j += 9;
}
if (changed) {
this._gl.uniformMatrix3fv(this._location, false, arraybuffer);
}
};
function UniformArrayMat4(gl, activeUniform, uniformName, locations) {
const length3 = locations.length;
this.name = uniformName;
this.value = new Array(length3);
this._value = new Float32Array(length3 * 16);
this._gl = gl;
this._location = locations[0];
}
UniformArrayMat4.prototype.set = function() {
const value = this.value;
const length3 = value.length;
const arraybuffer = this._value;
let changed = false;
let j = 0;
for (let i = 0; i < length3; ++i) {
const v7 = value[i];
if (!Matrix4_default.equalsArray(v7, arraybuffer, j)) {
Matrix4_default.pack(v7, arraybuffer, j);
changed = true;
}
j += 16;
}
if (changed) {
this._gl.uniformMatrix4fv(this._location, false, arraybuffer);
}
};
var createUniformArray_default = createUniformArray;
// packages/engine/Source/Renderer/ShaderProgram.js
var nextShaderProgramId = 0;
function ShaderProgram(options) {
let vertexShaderText = options.vertexShaderText;
let fragmentShaderText = options.fragmentShaderText;
if (typeof spector !== "undefined") {
vertexShaderText = vertexShaderText.replace(/^#line/gm, "//#line");
fragmentShaderText = fragmentShaderText.replace(/^#line/gm, "//#line");
}
const modifiedFS = handleUniformPrecisionMismatches(
vertexShaderText,
fragmentShaderText
);
this._gl = options.gl;
this._logShaderCompilation = options.logShaderCompilation;
this._debugShaders = options.debugShaders;
this._attributeLocations = options.attributeLocations;
this._program = void 0;
this._numberOfVertexAttributes = void 0;
this._vertexAttributes = void 0;
this._uniformsByName = void 0;
this._uniforms = void 0;
this._automaticUniforms = void 0;
this._manualUniforms = void 0;
this._duplicateUniformNames = modifiedFS.duplicateUniformNames;
this._cachedShader = void 0;
this.maximumTextureUnitIndex = void 0;
this._vertexShaderSource = options.vertexShaderSource;
this._vertexShaderText = options.vertexShaderText;
this._fragmentShaderSource = options.fragmentShaderSource;
this._fragmentShaderText = modifiedFS.fragmentShaderText;
this.id = nextShaderProgramId++;
}
ShaderProgram.fromCache = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
Check_default.defined("options.context", options.context);
return options.context.shaderCache.getShaderProgram(options);
};
ShaderProgram.replaceCache = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
Check_default.defined("options.context", options.context);
return options.context.shaderCache.replaceShaderProgram(options);
};
Object.defineProperties(ShaderProgram.prototype, {
/**
* GLSL source for the shader program's vertex shader.
* @memberof ShaderProgram.prototype
*
* @type {ShaderSource}
* @readonly
*/
vertexShaderSource: {
get: function() {
return this._vertexShaderSource;
}
},
/**
* GLSL source for the shader program's fragment shader.
* @memberof ShaderProgram.prototype
*
* @type {ShaderSource}
* @readonly
*/
fragmentShaderSource: {
get: function() {
return this._fragmentShaderSource;
}
},
vertexAttributes: {
get: function() {
initialize2(this);
return this._vertexAttributes;
}
},
numberOfVertexAttributes: {
get: function() {
initialize2(this);
return this._numberOfVertexAttributes;
}
},
allUniforms: {
get: function() {
initialize2(this);
return this._uniformsByName;
}
}
});
function extractUniforms(shaderText) {
const uniformNames = [];
const uniformLines = shaderText.match(/uniform.*?(?![^{]*})(?=[=\[;])/g);
if (defined_default(uniformLines)) {
const len = uniformLines.length;
for (let i = 0; i < len; i++) {
const line = uniformLines[i].trim();
const name = line.slice(line.lastIndexOf(" ") + 1);
uniformNames.push(name);
}
}
return uniformNames;
}
function handleUniformPrecisionMismatches(vertexShaderText, fragmentShaderText) {
const duplicateUniformNames = {};
if (!ContextLimits_default.highpFloatSupported || !ContextLimits_default.highpIntSupported) {
let i, j;
let uniformName;
let duplicateName;
const vertexShaderUniforms = extractUniforms(vertexShaderText);
const fragmentShaderUniforms = extractUniforms(fragmentShaderText);
const vertexUniformsCount = vertexShaderUniforms.length;
const fragmentUniformsCount = fragmentShaderUniforms.length;
for (i = 0; i < vertexUniformsCount; i++) {
for (j = 0; j < fragmentUniformsCount; j++) {
if (vertexShaderUniforms[i] === fragmentShaderUniforms[j]) {
uniformName = vertexShaderUniforms[i];
duplicateName = `czm_mediump_${uniformName}`;
const re = new RegExp(`${uniformName}\\b`, "g");
fragmentShaderText = fragmentShaderText.replace(re, duplicateName);
duplicateUniformNames[duplicateName] = uniformName;
}
}
}
}
return {
fragmentShaderText,
duplicateUniformNames
};
}
var consolePrefix = "[Cesium WebGL] ";
function createAndLinkProgram(gl, shader) {
const vsSource = shader._vertexShaderText;
const fsSource = shader._fragmentShaderText;
const vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader, vsSource);
gl.compileShader(vertexShader);
const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader, fsSource);
gl.compileShader(fragmentShader);
const program = gl.createProgram();
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
const attributeLocations8 = shader._attributeLocations;
if (defined_default(attributeLocations8)) {
for (const attribute in attributeLocations8) {
if (attributeLocations8.hasOwnProperty(attribute)) {
gl.bindAttribLocation(
program,
attributeLocations8[attribute],
attribute
);
}
}
}
gl.linkProgram(program);
let log;
if (gl.getProgramParameter(program, gl.LINK_STATUS)) {
if (shader._logShaderCompilation) {
log = gl.getShaderInfoLog(vertexShader);
if (defined_default(log) && log.length > 0) {
console.log(`${consolePrefix}Vertex shader compile log: ${log}`);
}
log = gl.getShaderInfoLog(fragmentShader);
if (defined_default(log) && log.length > 0) {
console.log(`${consolePrefix}Fragment shader compile log: ${log}`);
}
log = gl.getProgramInfoLog(program);
if (defined_default(log) && log.length > 0) {
console.log(`${consolePrefix}Shader program link log: ${log}`);
}
}
gl.deleteShader(vertexShader);
gl.deleteShader(fragmentShader);
return program;
}
let errorMessage;
const debugShaders = shader._debugShaders;
if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {
log = gl.getShaderInfoLog(fragmentShader);
console.error(`${consolePrefix}Fragment shader compile log: ${log}`);
console.error(`${consolePrefix} Fragment shader source:
${fsSource}`);
errorMessage = `Fragment shader failed to compile. Compile log: ${log}`;
} else if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) {
log = gl.getShaderInfoLog(vertexShader);
console.error(`${consolePrefix}Vertex shader compile log: ${log}`);
console.error(`${consolePrefix} Vertex shader source:
${vsSource}`);
errorMessage = `Vertex shader failed to compile. Compile log: ${log}`;
} else {
log = gl.getProgramInfoLog(program);
console.error(`${consolePrefix}Shader program link log: ${log}`);
logTranslatedSource(vertexShader, "vertex");
logTranslatedSource(fragmentShader, "fragment");
errorMessage = `Program failed to link. Link log: ${log}`;
}
gl.deleteShader(vertexShader);
gl.deleteShader(fragmentShader);
gl.deleteProgram(program);
throw new RuntimeError_default(errorMessage);
function logTranslatedSource(compiledShader, name) {
if (!defined_default(debugShaders)) {
return;
}
const translation3 = debugShaders.getTranslatedShaderSource(compiledShader);
if (translation3 === "") {
console.error(`${consolePrefix}${name} shader translation failed.`);
return;
}
console.error(
`${consolePrefix}Translated ${name} shaderSource:
${translation3}`
);
}
}
function findVertexAttributes(gl, program, numberOfAttributes2) {
const attributes = {};
for (let i = 0; i < numberOfAttributes2; ++i) {
const attr = gl.getActiveAttrib(program, i);
const location2 = gl.getAttribLocation(program, attr.name);
attributes[attr.name] = {
name: attr.name,
type: attr.type,
index: location2
};
}
return attributes;
}
function findUniforms(gl, program) {
const uniformsByName = {};
const uniforms = [];
const samplerUniforms = [];
const numberOfUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
for (let i = 0; i < numberOfUniforms; ++i) {
const activeUniform = gl.getActiveUniform(program, i);
const suffix = "[0]";
const uniformName = activeUniform.name.indexOf(
suffix,
activeUniform.name.length - suffix.length
) !== -1 ? activeUniform.name.slice(0, activeUniform.name.length - 3) : activeUniform.name;
if (uniformName.indexOf("gl_") !== 0) {
if (activeUniform.name.indexOf("[") < 0) {
const location2 = gl.getUniformLocation(program, uniformName);
if (location2 !== null) {
const uniform = createUniform_default(
gl,
activeUniform,
uniformName,
location2
);
uniformsByName[uniformName] = uniform;
uniforms.push(uniform);
if (uniform._setSampler) {
samplerUniforms.push(uniform);
}
}
} else {
let uniformArray;
let locations;
let value;
let loc;
const indexOfBracket = uniformName.indexOf("[");
if (indexOfBracket >= 0) {
uniformArray = uniformsByName[uniformName.slice(0, indexOfBracket)];
if (!defined_default(uniformArray)) {
continue;
}
locations = uniformArray._locations;
if (locations.length <= 1) {
value = uniformArray.value;
loc = gl.getUniformLocation(program, uniformName);
if (loc !== null) {
locations.push(loc);
value.push(gl.getUniform(program, loc));
}
}
} else {
locations = [];
for (let j = 0; j < activeUniform.size; ++j) {
loc = gl.getUniformLocation(program, `${uniformName}[${j}]`);
if (loc !== null) {
locations.push(loc);
}
}
uniformArray = createUniformArray_default(
gl,
activeUniform,
uniformName,
locations
);
uniformsByName[uniformName] = uniformArray;
uniforms.push(uniformArray);
if (uniformArray._setSampler) {
samplerUniforms.push(uniformArray);
}
}
}
}
}
return {
uniformsByName,
uniforms,
samplerUniforms
};
}
function partitionUniforms(shader, uniforms) {
const automaticUniforms = [];
const manualUniforms = [];
for (const uniform in uniforms) {
if (uniforms.hasOwnProperty(uniform)) {
const uniformObject = uniforms[uniform];
let uniformName = uniform;
const duplicateUniform = shader._duplicateUniformNames[uniformName];
if (defined_default(duplicateUniform)) {
uniformObject.name = duplicateUniform;
uniformName = duplicateUniform;
}
const automaticUniform = AutomaticUniforms_default[uniformName];
if (defined_default(automaticUniform)) {
automaticUniforms.push({
uniform: uniformObject,
automaticUniform
});
} else {
manualUniforms.push(uniformObject);
}
}
}
return {
automaticUniforms,
manualUniforms
};
}
function setSamplerUniforms(gl, program, samplerUniforms) {
gl.useProgram(program);
let textureUnitIndex = 0;
const length3 = samplerUniforms.length;
for (let i = 0; i < length3; ++i) {
textureUnitIndex = samplerUniforms[i]._setSampler(textureUnitIndex);
}
gl.useProgram(null);
return textureUnitIndex;
}
function initialize2(shader) {
if (defined_default(shader._program)) {
return;
}
reinitialize(shader);
}
function reinitialize(shader) {
const oldProgram = shader._program;
const gl = shader._gl;
const program = createAndLinkProgram(gl, shader, shader._debugShaders);
const numberOfVertexAttributes = gl.getProgramParameter(
program,
gl.ACTIVE_ATTRIBUTES
);
const uniforms = findUniforms(gl, program);
const partitionedUniforms = partitionUniforms(
shader,
uniforms.uniformsByName
);
shader._program = program;
shader._numberOfVertexAttributes = numberOfVertexAttributes;
shader._vertexAttributes = findVertexAttributes(
gl,
program,
numberOfVertexAttributes
);
shader._uniformsByName = uniforms.uniformsByName;
shader._uniforms = uniforms.uniforms;
shader._automaticUniforms = partitionedUniforms.automaticUniforms;
shader._manualUniforms = partitionedUniforms.manualUniforms;
shader.maximumTextureUnitIndex = setSamplerUniforms(
gl,
program,
uniforms.samplerUniforms
);
if (oldProgram) {
shader._gl.deleteProgram(oldProgram);
}
if (typeof spector !== "undefined") {
shader._program.__SPECTOR_rebuildProgram = function(vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
const originalVS = shader._vertexShaderText;
const originalFS = shader._fragmentShaderText;
const regex = / ! = /g;
shader._vertexShaderText = vertexSourceCode.replace(regex, " != ");
shader._fragmentShaderText = fragmentSourceCode.replace(regex, " != ");
try {
reinitialize(shader);
onCompiled(shader._program);
} catch (e) {
shader._vertexShaderText = originalVS;
shader._fragmentShaderText = originalFS;
const errorMatcher = /(?:Compile|Link) error: ([^]*)/;
const match = errorMatcher.exec(e.message);
if (match) {
onError(match[1]);
} else {
onError(e.message);
}
}
};
}
}
ShaderProgram.prototype._bind = function() {
initialize2(this);
this._gl.useProgram(this._program);
};
ShaderProgram.prototype._setUniforms = function(uniformMap2, uniformState, validate2) {
let len;
let i;
if (defined_default(uniformMap2)) {
const manualUniforms = this._manualUniforms;
len = manualUniforms.length;
for (i = 0; i < len; ++i) {
const mu = manualUniforms[i];
mu.value = uniformMap2[mu.name]();
}
}
const automaticUniforms = this._automaticUniforms;
len = automaticUniforms.length;
for (i = 0; i < len; ++i) {
const au = automaticUniforms[i];
au.uniform.value = au.automaticUniform.getValue(uniformState);
}
const uniforms = this._uniforms;
len = uniforms.length;
for (i = 0; i < len; ++i) {
uniforms[i].set();
}
if (validate2) {
const gl = this._gl;
const program = this._program;
gl.validateProgram(program);
if (!gl.getProgramParameter(program, gl.VALIDATE_STATUS)) {
throw new DeveloperError_default(
`Program validation failed. Program info log: ${gl.getProgramInfoLog(
program
)}`
);
}
}
};
ShaderProgram.prototype.isDestroyed = function() {
return false;
};
ShaderProgram.prototype.destroy = function() {
this._cachedShader.cache.releaseShaderProgram(this);
return void 0;
};
ShaderProgram.prototype.finalDestroy = function() {
this._gl.deleteProgram(this._program);
return destroyObject_default(this);
};
var ShaderProgram_default = ShaderProgram;
// packages/engine/Source/Renderer/ComputeEngine.js
function ComputeEngine(context) {
this._context = context;
}
var renderStateScratch;
var drawCommandScratch = new DrawCommand_default({
primitiveType: PrimitiveType_default.TRIANGLES
});
var clearCommandScratch = new ClearCommand_default({
color: new Color_default(0, 0, 0, 0)
});
function createFramebuffer(context, outputTexture) {
return new Framebuffer_default({
context,
colorTextures: [outputTexture],
destroyAttachments: false
});
}
function createViewportQuadShader(context, fragmentShaderSource) {
return ShaderProgram_default.fromCache({
context,
vertexShaderSource: ViewportQuadVS_default,
fragmentShaderSource,
attributeLocations: {
position: 0,
textureCoordinates: 1
}
});
}
function createRenderState(width, height) {
if (!defined_default(renderStateScratch) || renderStateScratch.viewport.width !== width || renderStateScratch.viewport.height !== height) {
renderStateScratch = RenderState_default.fromCache({
viewport: new BoundingRectangle_default(0, 0, width, height)
});
}
return renderStateScratch;
}
ComputeEngine.prototype.execute = function(computeCommand) {
Check_default.defined("computeCommand", computeCommand);
if (defined_default(computeCommand.preExecute)) {
computeCommand.preExecute(computeCommand);
}
if (!defined_default(computeCommand.fragmentShaderSource) && !defined_default(computeCommand.shaderProgram)) {
throw new DeveloperError_default(
"computeCommand.fragmentShaderSource or computeCommand.shaderProgram is required."
);
}
Check_default.defined("computeCommand.outputTexture", computeCommand.outputTexture);
const outputTexture = computeCommand.outputTexture;
const width = outputTexture.width;
const height = outputTexture.height;
const context = this._context;
const vertexArray = defined_default(computeCommand.vertexArray) ? computeCommand.vertexArray : context.getViewportQuadVertexArray();
const shaderProgram = defined_default(computeCommand.shaderProgram) ? computeCommand.shaderProgram : createViewportQuadShader(context, computeCommand.fragmentShaderSource);
const framebuffer = createFramebuffer(context, outputTexture);
const renderState = createRenderState(width, height);
const uniformMap2 = computeCommand.uniformMap;
const clearCommand = clearCommandScratch;
clearCommand.framebuffer = framebuffer;
clearCommand.renderState = renderState;
clearCommand.execute(context);
const drawCommand = drawCommandScratch;
drawCommand.vertexArray = vertexArray;
drawCommand.renderState = renderState;
drawCommand.shaderProgram = shaderProgram;
drawCommand.uniformMap = uniformMap2;
drawCommand.framebuffer = framebuffer;
drawCommand.execute(context);
framebuffer.destroy();
if (!computeCommand.persists) {
shaderProgram.destroy();
if (defined_default(computeCommand.vertexArray)) {
vertexArray.destroy();
}
}
if (defined_default(computeCommand.postExecute)) {
computeCommand.postExecute(outputTexture);
}
};
ComputeEngine.prototype.isDestroyed = function() {
return false;
};
ComputeEngine.prototype.destroy = function() {
return destroyObject_default(this);
};
var ComputeEngine_default = ComputeEngine;
// packages/engine/Source/Core/ComponentDatatype.js
var ComponentDatatype = {
/**
* 8-bit signed byte corresponding to gl.BYTE
and the type
* of an element in Int8Array
.
*
* @type {number}
* @constant
*/
BYTE: WebGLConstants_default.BYTE,
/**
* 8-bit unsigned byte corresponding to UNSIGNED_BYTE
and the type
* of an element in Uint8Array
.
*
* @type {number}
* @constant
*/
UNSIGNED_BYTE: WebGLConstants_default.UNSIGNED_BYTE,
/**
* 16-bit signed short corresponding to SHORT
and the type
* of an element in Int16Array
.
*
* @type {number}
* @constant
*/
SHORT: WebGLConstants_default.SHORT,
/**
* 16-bit unsigned short corresponding to UNSIGNED_SHORT
and the type
* of an element in Uint16Array
.
*
* @type {number}
* @constant
*/
UNSIGNED_SHORT: WebGLConstants_default.UNSIGNED_SHORT,
/**
* 32-bit signed int corresponding to INT
and the type
* of an element in Int32Array
.
*
* @memberOf ComponentDatatype
*
* @type {number}
* @constant
*/
INT: WebGLConstants_default.INT,
/**
* 32-bit unsigned int corresponding to UNSIGNED_INT
and the type
* of an element in Uint32Array
.
*
* @memberOf ComponentDatatype
*
* @type {number}
* @constant
*/
UNSIGNED_INT: WebGLConstants_default.UNSIGNED_INT,
/**
* 32-bit floating-point corresponding to FLOAT
and the type
* of an element in Float32Array
.
*
* @type {number}
* @constant
*/
FLOAT: WebGLConstants_default.FLOAT,
/**
* 64-bit floating-point corresponding to gl.DOUBLE
(in Desktop OpenGL;
* this is not supported in WebGL, and is emulated in Cesium via {@link GeometryPipeline.encodeAttribute})
* and the type of an element in Float64Array
.
*
* @memberOf ComponentDatatype
*
* @type {number}
* @constant
* @default 0x140A
*/
DOUBLE: WebGLConstants_default.DOUBLE
};
ComponentDatatype.getSizeInBytes = function(componentDatatype) {
if (!defined_default(componentDatatype)) {
throw new DeveloperError_default("value is required.");
}
switch (componentDatatype) {
case ComponentDatatype.BYTE:
return Int8Array.BYTES_PER_ELEMENT;
case ComponentDatatype.UNSIGNED_BYTE:
return Uint8Array.BYTES_PER_ELEMENT;
case ComponentDatatype.SHORT:
return Int16Array.BYTES_PER_ELEMENT;
case ComponentDatatype.UNSIGNED_SHORT:
return Uint16Array.BYTES_PER_ELEMENT;
case ComponentDatatype.INT:
return Int32Array.BYTES_PER_ELEMENT;
case ComponentDatatype.UNSIGNED_INT:
return Uint32Array.BYTES_PER_ELEMENT;
case ComponentDatatype.FLOAT:
return Float32Array.BYTES_PER_ELEMENT;
case ComponentDatatype.DOUBLE:
return Float64Array.BYTES_PER_ELEMENT;
default:
throw new DeveloperError_default("componentDatatype is not a valid value.");
}
};
ComponentDatatype.fromTypedArray = function(array) {
if (array instanceof Int8Array) {
return ComponentDatatype.BYTE;
}
if (array instanceof Uint8Array) {
return ComponentDatatype.UNSIGNED_BYTE;
}
if (array instanceof Int16Array) {
return ComponentDatatype.SHORT;
}
if (array instanceof Uint16Array) {
return ComponentDatatype.UNSIGNED_SHORT;
}
if (array instanceof Int32Array) {
return ComponentDatatype.INT;
}
if (array instanceof Uint32Array) {
return ComponentDatatype.UNSIGNED_INT;
}
if (array instanceof Float32Array) {
return ComponentDatatype.FLOAT;
}
if (array instanceof Float64Array) {
return ComponentDatatype.DOUBLE;
}
throw new DeveloperError_default(
"array must be an Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, or Float64Array."
);
};
ComponentDatatype.validate = function(componentDatatype) {
return defined_default(componentDatatype) && (componentDatatype === ComponentDatatype.BYTE || componentDatatype === ComponentDatatype.UNSIGNED_BYTE || componentDatatype === ComponentDatatype.SHORT || componentDatatype === ComponentDatatype.UNSIGNED_SHORT || componentDatatype === ComponentDatatype.INT || componentDatatype === ComponentDatatype.UNSIGNED_INT || componentDatatype === ComponentDatatype.FLOAT || componentDatatype === ComponentDatatype.DOUBLE);
};
ComponentDatatype.createTypedArray = function(componentDatatype, valuesOrLength) {
if (!defined_default(componentDatatype)) {
throw new DeveloperError_default("componentDatatype is required.");
}
if (!defined_default(valuesOrLength)) {
throw new DeveloperError_default("valuesOrLength is required.");
}
switch (componentDatatype) {
case ComponentDatatype.BYTE:
return new Int8Array(valuesOrLength);
case ComponentDatatype.UNSIGNED_BYTE:
return new Uint8Array(valuesOrLength);
case ComponentDatatype.SHORT:
return new Int16Array(valuesOrLength);
case ComponentDatatype.UNSIGNED_SHORT:
return new Uint16Array(valuesOrLength);
case ComponentDatatype.INT:
return new Int32Array(valuesOrLength);
case ComponentDatatype.UNSIGNED_INT:
return new Uint32Array(valuesOrLength);
case ComponentDatatype.FLOAT:
return new Float32Array(valuesOrLength);
case ComponentDatatype.DOUBLE:
return new Float64Array(valuesOrLength);
default:
throw new DeveloperError_default("componentDatatype is not a valid value.");
}
};
ComponentDatatype.createArrayBufferView = function(componentDatatype, buffer, byteOffset, length3) {
if (!defined_default(componentDatatype)) {
throw new DeveloperError_default("componentDatatype is required.");
}
if (!defined_default(buffer)) {
throw new DeveloperError_default("buffer is required.");
}
byteOffset = defaultValue_default(byteOffset, 0);
length3 = defaultValue_default(
length3,
(buffer.byteLength - byteOffset) / ComponentDatatype.getSizeInBytes(componentDatatype)
);
switch (componentDatatype) {
case ComponentDatatype.BYTE:
return new Int8Array(buffer, byteOffset, length3);
case ComponentDatatype.UNSIGNED_BYTE:
return new Uint8Array(buffer, byteOffset, length3);
case ComponentDatatype.SHORT:
return new Int16Array(buffer, byteOffset, length3);
case ComponentDatatype.UNSIGNED_SHORT:
return new Uint16Array(buffer, byteOffset, length3);
case ComponentDatatype.INT:
return new Int32Array(buffer, byteOffset, length3);
case ComponentDatatype.UNSIGNED_INT:
return new Uint32Array(buffer, byteOffset, length3);
case ComponentDatatype.FLOAT:
return new Float32Array(buffer, byteOffset, length3);
case ComponentDatatype.DOUBLE:
return new Float64Array(buffer, byteOffset, length3);
default:
throw new DeveloperError_default("componentDatatype is not a valid value.");
}
};
ComponentDatatype.fromName = function(name) {
switch (name) {
case "BYTE":
return ComponentDatatype.BYTE;
case "UNSIGNED_BYTE":
return ComponentDatatype.UNSIGNED_BYTE;
case "SHORT":
return ComponentDatatype.SHORT;
case "UNSIGNED_SHORT":
return ComponentDatatype.UNSIGNED_SHORT;
case "INT":
return ComponentDatatype.INT;
case "UNSIGNED_INT":
return ComponentDatatype.UNSIGNED_INT;
case "FLOAT":
return ComponentDatatype.FLOAT;
case "DOUBLE":
return ComponentDatatype.DOUBLE;
default:
throw new DeveloperError_default("name is not a valid value.");
}
};
var ComponentDatatype_default = Object.freeze(ComponentDatatype);
// packages/engine/Source/Core/oneTimeWarning.js
var warnings = {};
function oneTimeWarning(identifier, message) {
if (!defined_default(identifier)) {
throw new DeveloperError_default("identifier is required.");
}
if (!defined_default(warnings[identifier])) {
warnings[identifier] = true;
console.warn(defaultValue_default(message, identifier));
}
}
oneTimeWarning.geometryOutlines = "Entity geometry outlines are unsupported on terrain. Outlines will be disabled. To enable outlines, disable geometry terrain clamping by explicitly setting height to 0.";
oneTimeWarning.geometryZIndex = "Entity geometry with zIndex are unsupported when height or extrudedHeight are defined. zIndex will be ignored";
oneTimeWarning.geometryHeightReference = "Entity corridor, ellipse, polygon or rectangle with heightReference must also have a defined height. heightReference will be ignored";
oneTimeWarning.geometryExtrudedHeightReference = "Entity corridor, ellipse, polygon or rectangle with extrudedHeightReference must also have a defined extrudedHeight. extrudedHeightReference will be ignored";
var oneTimeWarning_default = oneTimeWarning;
// packages/engine/Source/Core/deprecationWarning.js
function deprecationWarning(identifier, message) {
if (!defined_default(identifier) || !defined_default(message)) {
throw new DeveloperError_default("identifier and message are required.");
}
oneTimeWarning_default(identifier, message);
}
var deprecationWarning_default = deprecationWarning;
// packages/engine/Source/Core/GeometryType.js
var GeometryType = {
NONE: 0,
TRIANGLES: 1,
LINES: 2,
POLYLINES: 3
};
var GeometryType_default = Object.freeze(GeometryType);
// packages/engine/Source/Core/Quaternion.js
function Quaternion(x, y, z, w) {
this.x = defaultValue_default(x, 0);
this.y = defaultValue_default(y, 0);
this.z = defaultValue_default(z, 0);
this.w = defaultValue_default(w, 0);
}
var fromAxisAngleScratch = new Cartesian3_default();
Quaternion.fromAxisAngle = function(axis, angle, result) {
Check_default.typeOf.object("axis", axis);
Check_default.typeOf.number("angle", angle);
const halfAngle = angle / 2;
const s = Math.sin(halfAngle);
fromAxisAngleScratch = Cartesian3_default.normalize(axis, fromAxisAngleScratch);
const x = fromAxisAngleScratch.x * s;
const y = fromAxisAngleScratch.y * s;
const z = fromAxisAngleScratch.z * s;
const w = Math.cos(halfAngle);
if (!defined_default(result)) {
return new Quaternion(x, y, z, w);
}
result.x = x;
result.y = y;
result.z = z;
result.w = w;
return result;
};
var fromRotationMatrixNext = [1, 2, 0];
var fromRotationMatrixQuat = new Array(3);
Quaternion.fromRotationMatrix = function(matrix, result) {
Check_default.typeOf.object("matrix", matrix);
let root;
let x;
let y;
let z;
let w;
const m00 = matrix[Matrix3_default.COLUMN0ROW0];
const m11 = matrix[Matrix3_default.COLUMN1ROW1];
const m22 = matrix[Matrix3_default.COLUMN2ROW2];
const trace = m00 + m11 + m22;
if (trace > 0) {
root = Math.sqrt(trace + 1);
w = 0.5 * root;
root = 0.5 / root;
x = (matrix[Matrix3_default.COLUMN1ROW2] - matrix[Matrix3_default.COLUMN2ROW1]) * root;
y = (matrix[Matrix3_default.COLUMN2ROW0] - matrix[Matrix3_default.COLUMN0ROW2]) * root;
z = (matrix[Matrix3_default.COLUMN0ROW1] - matrix[Matrix3_default.COLUMN1ROW0]) * root;
} else {
const next = fromRotationMatrixNext;
let i = 0;
if (m11 > m00) {
i = 1;
}
if (m22 > m00 && m22 > m11) {
i = 2;
}
const j = next[i];
const k = next[j];
root = Math.sqrt(
matrix[Matrix3_default.getElementIndex(i, i)] - matrix[Matrix3_default.getElementIndex(j, j)] - matrix[Matrix3_default.getElementIndex(k, k)] + 1
);
const quat = fromRotationMatrixQuat;
quat[i] = 0.5 * root;
root = 0.5 / root;
w = (matrix[Matrix3_default.getElementIndex(k, j)] - matrix[Matrix3_default.getElementIndex(j, k)]) * root;
quat[j] = (matrix[Matrix3_default.getElementIndex(j, i)] + matrix[Matrix3_default.getElementIndex(i, j)]) * root;
quat[k] = (matrix[Matrix3_default.getElementIndex(k, i)] + matrix[Matrix3_default.getElementIndex(i, k)]) * root;
x = -quat[0];
y = -quat[1];
z = -quat[2];
}
if (!defined_default(result)) {
return new Quaternion(x, y, z, w);
}
result.x = x;
result.y = y;
result.z = z;
result.w = w;
return result;
};
var scratchHPRQuaternion = new Quaternion();
var scratchHeadingQuaternion = new Quaternion();
var scratchPitchQuaternion = new Quaternion();
var scratchRollQuaternion = new Quaternion();
Quaternion.fromHeadingPitchRoll = function(headingPitchRoll, result) {
Check_default.typeOf.object("headingPitchRoll", headingPitchRoll);
scratchRollQuaternion = Quaternion.fromAxisAngle(
Cartesian3_default.UNIT_X,
headingPitchRoll.roll,
scratchHPRQuaternion
);
scratchPitchQuaternion = Quaternion.fromAxisAngle(
Cartesian3_default.UNIT_Y,
-headingPitchRoll.pitch,
result
);
result = Quaternion.multiply(
scratchPitchQuaternion,
scratchRollQuaternion,
scratchPitchQuaternion
);
scratchHeadingQuaternion = Quaternion.fromAxisAngle(
Cartesian3_default.UNIT_Z,
-headingPitchRoll.heading,
scratchHPRQuaternion
);
return Quaternion.multiply(scratchHeadingQuaternion, result, result);
};
var sampledQuaternionAxis = new Cartesian3_default();
var sampledQuaternionRotation = new Cartesian3_default();
var sampledQuaternionTempQuaternion = new Quaternion();
var sampledQuaternionQuaternion0 = new Quaternion();
var sampledQuaternionQuaternion0Conjugate = new Quaternion();
Quaternion.packedLength = 4;
Quaternion.pack = function(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
array[startingIndex++] = value.x;
array[startingIndex++] = value.y;
array[startingIndex++] = value.z;
array[startingIndex] = value.w;
return array;
};
Quaternion.unpack = function(array, startingIndex, result) {
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
if (!defined_default(result)) {
result = new Quaternion();
}
result.x = array[startingIndex];
result.y = array[startingIndex + 1];
result.z = array[startingIndex + 2];
result.w = array[startingIndex + 3];
return result;
};
Quaternion.packedInterpolationLength = 3;
Quaternion.convertPackedArrayForInterpolation = function(packedArray, startingIndex, lastIndex, result) {
Quaternion.unpack(
packedArray,
lastIndex * 4,
sampledQuaternionQuaternion0Conjugate
);
Quaternion.conjugate(
sampledQuaternionQuaternion0Conjugate,
sampledQuaternionQuaternion0Conjugate
);
for (let i = 0, len = lastIndex - startingIndex + 1; i < len; i++) {
const offset2 = i * 3;
Quaternion.unpack(
packedArray,
(startingIndex + i) * 4,
sampledQuaternionTempQuaternion
);
Quaternion.multiply(
sampledQuaternionTempQuaternion,
sampledQuaternionQuaternion0Conjugate,
sampledQuaternionTempQuaternion
);
if (sampledQuaternionTempQuaternion.w < 0) {
Quaternion.negate(
sampledQuaternionTempQuaternion,
sampledQuaternionTempQuaternion
);
}
Quaternion.computeAxis(
sampledQuaternionTempQuaternion,
sampledQuaternionAxis
);
const angle = Quaternion.computeAngle(sampledQuaternionTempQuaternion);
if (!defined_default(result)) {
result = [];
}
result[offset2] = sampledQuaternionAxis.x * angle;
result[offset2 + 1] = sampledQuaternionAxis.y * angle;
result[offset2 + 2] = sampledQuaternionAxis.z * angle;
}
};
Quaternion.unpackInterpolationResult = function(array, sourceArray, firstIndex, lastIndex, result) {
if (!defined_default(result)) {
result = new Quaternion();
}
Cartesian3_default.fromArray(array, 0, sampledQuaternionRotation);
const magnitude = Cartesian3_default.magnitude(sampledQuaternionRotation);
Quaternion.unpack(sourceArray, lastIndex * 4, sampledQuaternionQuaternion0);
if (magnitude === 0) {
Quaternion.clone(Quaternion.IDENTITY, sampledQuaternionTempQuaternion);
} else {
Quaternion.fromAxisAngle(
sampledQuaternionRotation,
magnitude,
sampledQuaternionTempQuaternion
);
}
return Quaternion.multiply(
sampledQuaternionTempQuaternion,
sampledQuaternionQuaternion0,
result
);
};
Quaternion.clone = function(quaternion, result) {
if (!defined_default(quaternion)) {
return void 0;
}
if (!defined_default(result)) {
return new Quaternion(
quaternion.x,
quaternion.y,
quaternion.z,
quaternion.w
);
}
result.x = quaternion.x;
result.y = quaternion.y;
result.z = quaternion.z;
result.w = quaternion.w;
return result;
};
Quaternion.conjugate = function(quaternion, result) {
Check_default.typeOf.object("quaternion", quaternion);
Check_default.typeOf.object("result", result);
result.x = -quaternion.x;
result.y = -quaternion.y;
result.z = -quaternion.z;
result.w = quaternion.w;
return result;
};
Quaternion.magnitudeSquared = function(quaternion) {
Check_default.typeOf.object("quaternion", quaternion);
return quaternion.x * quaternion.x + quaternion.y * quaternion.y + quaternion.z * quaternion.z + quaternion.w * quaternion.w;
};
Quaternion.magnitude = function(quaternion) {
return Math.sqrt(Quaternion.magnitudeSquared(quaternion));
};
Quaternion.normalize = function(quaternion, result) {
Check_default.typeOf.object("result", result);
const inverseMagnitude = 1 / Quaternion.magnitude(quaternion);
const x = quaternion.x * inverseMagnitude;
const y = quaternion.y * inverseMagnitude;
const z = quaternion.z * inverseMagnitude;
const w = quaternion.w * inverseMagnitude;
result.x = x;
result.y = y;
result.z = z;
result.w = w;
return result;
};
Quaternion.inverse = function(quaternion, result) {
Check_default.typeOf.object("result", result);
const magnitudeSquared = Quaternion.magnitudeSquared(quaternion);
result = Quaternion.conjugate(quaternion, result);
return Quaternion.multiplyByScalar(result, 1 / magnitudeSquared, result);
};
Quaternion.add = function(left, right, result) {
Check_default.typeOf.object("left", left);
Check_default.typeOf.object("right", right);
Check_default.typeOf.object("result", result);
result.x = left.x + right.x;
result.y = left.y + right.y;
result.z = left.z + right.z;
result.w = left.w + right.w;
return result;
};
Quaternion.subtract = function(left, right, result) {
Check_default.typeOf.object("left", left);
Check_default.typeOf.object("right", right);
Check_default.typeOf.object("result", result);
result.x = left.x - right.x;
result.y = left.y - right.y;
result.z = left.z - right.z;
result.w = left.w - right.w;
return result;
};
Quaternion.negate = function(quaternion, result) {
Check_default.typeOf.object("quaternion", quaternion);
Check_default.typeOf.object("result", result);
result.x = -quaternion.x;
result.y = -quaternion.y;
result.z = -quaternion.z;
result.w = -quaternion.w;
return result;
};
Quaternion.dot = function(left, right) {
Check_default.typeOf.object("left", left);
Check_default.typeOf.object("right", right);
return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w;
};
Quaternion.multiply = function(left, right, result) {
Check_default.typeOf.object("left", left);
Check_default.typeOf.object("right", right);
Check_default.typeOf.object("result", result);
const leftX = left.x;
const leftY = left.y;
const leftZ = left.z;
const leftW = left.w;
const rightX = right.x;
const rightY = right.y;
const rightZ = right.z;
const rightW = right.w;
const x = leftW * rightX + leftX * rightW + leftY * rightZ - leftZ * rightY;
const y = leftW * rightY - leftX * rightZ + leftY * rightW + leftZ * rightX;
const z = leftW * rightZ + leftX * rightY - leftY * rightX + leftZ * rightW;
const w = leftW * rightW - leftX * rightX - leftY * rightY - leftZ * rightZ;
result.x = x;
result.y = y;
result.z = z;
result.w = w;
return result;
};
Quaternion.multiplyByScalar = function(quaternion, scalar, result) {
Check_default.typeOf.object("quaternion", quaternion);
Check_default.typeOf.number("scalar", scalar);
Check_default.typeOf.object("result", result);
result.x = quaternion.x * scalar;
result.y = quaternion.y * scalar;
result.z = quaternion.z * scalar;
result.w = quaternion.w * scalar;
return result;
};
Quaternion.divideByScalar = function(quaternion, scalar, result) {
Check_default.typeOf.object("quaternion", quaternion);
Check_default.typeOf.number("scalar", scalar);
Check_default.typeOf.object("result", result);
result.x = quaternion.x / scalar;
result.y = quaternion.y / scalar;
result.z = quaternion.z / scalar;
result.w = quaternion.w / scalar;
return result;
};
Quaternion.computeAxis = function(quaternion, result) {
Check_default.typeOf.object("quaternion", quaternion);
Check_default.typeOf.object("result", result);
const w = quaternion.w;
if (Math.abs(w - 1) < Math_default.EPSILON6) {
result.x = result.y = result.z = 0;
return result;
}
const scalar = 1 / Math.sqrt(1 - w * w);
result.x = quaternion.x * scalar;
result.y = quaternion.y * scalar;
result.z = quaternion.z * scalar;
return result;
};
Quaternion.computeAngle = function(quaternion) {
Check_default.typeOf.object("quaternion", quaternion);
if (Math.abs(quaternion.w - 1) < Math_default.EPSILON6) {
return 0;
}
return 2 * Math.acos(quaternion.w);
};
var lerpScratch4 = new Quaternion();
Quaternion.lerp = function(start, end, t, result) {
Check_default.typeOf.object("start", start);
Check_default.typeOf.object("end", end);
Check_default.typeOf.number("t", t);
Check_default.typeOf.object("result", result);
lerpScratch4 = Quaternion.multiplyByScalar(end, t, lerpScratch4);
result = Quaternion.multiplyByScalar(start, 1 - t, result);
return Quaternion.add(lerpScratch4, result, result);
};
var slerpEndNegated = new Quaternion();
var slerpScaledP = new Quaternion();
var slerpScaledR = new Quaternion();
Quaternion.slerp = function(start, end, t, result) {
Check_default.typeOf.object("start", start);
Check_default.typeOf.object("end", end);
Check_default.typeOf.number("t", t);
Check_default.typeOf.object("result", result);
let dot2 = Quaternion.dot(start, end);
let r = end;
if (dot2 < 0) {
dot2 = -dot2;
r = slerpEndNegated = Quaternion.negate(end, slerpEndNegated);
}
if (1 - dot2 < Math_default.EPSILON6) {
return Quaternion.lerp(start, r, t, result);
}
const theta = Math.acos(dot2);
slerpScaledP = Quaternion.multiplyByScalar(
start,
Math.sin((1 - t) * theta),
slerpScaledP
);
slerpScaledR = Quaternion.multiplyByScalar(
r,
Math.sin(t * theta),
slerpScaledR
);
result = Quaternion.add(slerpScaledP, slerpScaledR, result);
return Quaternion.multiplyByScalar(result, 1 / Math.sin(theta), result);
};
Quaternion.log = function(quaternion, result) {
Check_default.typeOf.object("quaternion", quaternion);
Check_default.typeOf.object("result", result);
const theta = Math_default.acosClamped(quaternion.w);
let thetaOverSinTheta = 0;
if (theta !== 0) {
thetaOverSinTheta = theta / Math.sin(theta);
}
return Cartesian3_default.multiplyByScalar(quaternion, thetaOverSinTheta, result);
};
Quaternion.exp = function(cartesian11, result) {
Check_default.typeOf.object("cartesian", cartesian11);
Check_default.typeOf.object("result", result);
const theta = Cartesian3_default.magnitude(cartesian11);
let sinThetaOverTheta = 0;
if (theta !== 0) {
sinThetaOverTheta = Math.sin(theta) / theta;
}
result.x = cartesian11.x * sinThetaOverTheta;
result.y = cartesian11.y * sinThetaOverTheta;
result.z = cartesian11.z * sinThetaOverTheta;
result.w = Math.cos(theta);
return result;
};
var squadScratchCartesian0 = new Cartesian3_default();
var squadScratchCartesian1 = new Cartesian3_default();
var squadScratchQuaternion0 = new Quaternion();
var squadScratchQuaternion1 = new Quaternion();
Quaternion.computeInnerQuadrangle = function(q0, q12, q22, result) {
Check_default.typeOf.object("q0", q0);
Check_default.typeOf.object("q1", q12);
Check_default.typeOf.object("q2", q22);
Check_default.typeOf.object("result", result);
const qInv = Quaternion.conjugate(q12, squadScratchQuaternion0);
Quaternion.multiply(qInv, q22, squadScratchQuaternion1);
const cart0 = Quaternion.log(squadScratchQuaternion1, squadScratchCartesian0);
Quaternion.multiply(qInv, q0, squadScratchQuaternion1);
const cart1 = Quaternion.log(squadScratchQuaternion1, squadScratchCartesian1);
Cartesian3_default.add(cart0, cart1, cart0);
Cartesian3_default.multiplyByScalar(cart0, 0.25, cart0);
Cartesian3_default.negate(cart0, cart0);
Quaternion.exp(cart0, squadScratchQuaternion0);
return Quaternion.multiply(q12, squadScratchQuaternion0, result);
};
Quaternion.squad = function(q0, q12, s0, s1, t, result) {
Check_default.typeOf.object("q0", q0);
Check_default.typeOf.object("q1", q12);
Check_default.typeOf.object("s0", s0);
Check_default.typeOf.object("s1", s1);
Check_default.typeOf.number("t", t);
Check_default.typeOf.object("result", result);
const slerp0 = Quaternion.slerp(q0, q12, t, squadScratchQuaternion0);
const slerp1 = Quaternion.slerp(s0, s1, t, squadScratchQuaternion1);
return Quaternion.slerp(slerp0, slerp1, 2 * t * (1 - t), result);
};
var fastSlerpScratchQuaternion = new Quaternion();
var opmu = 1.9011074535173003;
var u = FeatureDetection_default.supportsTypedArrays() ? new Float32Array(8) : [];
var v = FeatureDetection_default.supportsTypedArrays() ? new Float32Array(8) : [];
var bT = FeatureDetection_default.supportsTypedArrays() ? new Float32Array(8) : [];
var bD = FeatureDetection_default.supportsTypedArrays() ? new Float32Array(8) : [];
for (let i = 0; i < 7; ++i) {
const s = i + 1;
const t = 2 * s + 1;
u[i] = 1 / (s * t);
v[i] = s / t;
}
u[7] = opmu / (8 * 17);
v[7] = opmu * 8 / 17;
Quaternion.fastSlerp = function(start, end, t, result) {
Check_default.typeOf.object("start", start);
Check_default.typeOf.object("end", end);
Check_default.typeOf.number("t", t);
Check_default.typeOf.object("result", result);
let x = Quaternion.dot(start, end);
let sign2;
if (x >= 0) {
sign2 = 1;
} else {
sign2 = -1;
x = -x;
}
const xm1 = x - 1;
const d = 1 - t;
const sqrT = t * t;
const sqrD = d * d;
for (let i = 7; i >= 0; --i) {
bT[i] = (u[i] * sqrT - v[i]) * xm1;
bD[i] = (u[i] * sqrD - v[i]) * xm1;
}
const cT = sign2 * t * (1 + bT[0] * (1 + bT[1] * (1 + bT[2] * (1 + bT[3] * (1 + bT[4] * (1 + bT[5] * (1 + bT[6] * (1 + bT[7]))))))));
const cD = d * (1 + bD[0] * (1 + bD[1] * (1 + bD[2] * (1 + bD[3] * (1 + bD[4] * (1 + bD[5] * (1 + bD[6] * (1 + bD[7]))))))));
const temp = Quaternion.multiplyByScalar(
start,
cD,
fastSlerpScratchQuaternion
);
Quaternion.multiplyByScalar(end, cT, result);
return Quaternion.add(temp, result, result);
};
Quaternion.fastSquad = function(q0, q12, s0, s1, t, result) {
Check_default.typeOf.object("q0", q0);
Check_default.typeOf.object("q1", q12);
Check_default.typeOf.object("s0", s0);
Check_default.typeOf.object("s1", s1);
Check_default.typeOf.number("t", t);
Check_default.typeOf.object("result", result);
const slerp0 = Quaternion.fastSlerp(q0, q12, t, squadScratchQuaternion0);
const slerp1 = Quaternion.fastSlerp(s0, s1, t, squadScratchQuaternion1);
return Quaternion.fastSlerp(slerp0, slerp1, 2 * t * (1 - t), result);
};
Quaternion.equals = function(left, right) {
return left === right || defined_default(left) && defined_default(right) && left.x === right.x && left.y === right.y && left.z === right.z && left.w === right.w;
};
Quaternion.equalsEpsilon = function(left, right, epsilon) {
epsilon = defaultValue_default(epsilon, 0);
return left === right || defined_default(left) && defined_default(right) && Math.abs(left.x - right.x) <= epsilon && Math.abs(left.y - right.y) <= epsilon && Math.abs(left.z - right.z) <= epsilon && Math.abs(left.w - right.w) <= epsilon;
};
Quaternion.ZERO = Object.freeze(new Quaternion(0, 0, 0, 0));
Quaternion.IDENTITY = Object.freeze(new Quaternion(0, 0, 0, 1));
Quaternion.prototype.clone = function(result) {
return Quaternion.clone(this, result);
};
Quaternion.prototype.equals = function(right) {
return Quaternion.equals(this, right);
};
Quaternion.prototype.equalsEpsilon = function(right, epsilon) {
return Quaternion.equalsEpsilon(this, right, epsilon);
};
Quaternion.prototype.toString = function() {
return `(${this.x}, ${this.y}, ${this.z}, ${this.w})`;
};
var Quaternion_default = Quaternion;
// packages/engine/Source/Core/binarySearch.js
function binarySearch(array, itemToFind, comparator) {
Check_default.defined("array", array);
Check_default.defined("itemToFind", itemToFind);
Check_default.defined("comparator", comparator);
let low = 0;
let high = array.length - 1;
let i;
let comparison;
while (low <= high) {
i = ~~((low + high) / 2);
comparison = comparator(array[i], itemToFind);
if (comparison < 0) {
low = i + 1;
continue;
}
if (comparison > 0) {
high = i - 1;
continue;
}
return i;
}
return ~(high + 1);
}
var binarySearch_default = binarySearch;
// packages/engine/Source/Core/EarthOrientationParametersSample.js
function EarthOrientationParametersSample(xPoleWander, yPoleWander, xPoleOffset, yPoleOffset, ut1MinusUtc) {
this.xPoleWander = xPoleWander;
this.yPoleWander = yPoleWander;
this.xPoleOffset = xPoleOffset;
this.yPoleOffset = yPoleOffset;
this.ut1MinusUtc = ut1MinusUtc;
}
var EarthOrientationParametersSample_default = EarthOrientationParametersSample;
// packages/engine/Source/Core/GregorianDate.js
function GregorianDate(year, month, day, hour, minute, second, millisecond, isLeapSecond) {
this.year = year;
this.month = month;
this.day = day;
this.hour = hour;
this.minute = minute;
this.second = second;
this.millisecond = millisecond;
this.isLeapSecond = isLeapSecond;
}
var GregorianDate_default = GregorianDate;
// packages/engine/Source/Core/isLeapYear.js
function isLeapYear(year) {
if (year === null || isNaN(year)) {
throw new DeveloperError_default("year is required and must be a number.");
}
return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
}
var isLeapYear_default = isLeapYear;
// packages/engine/Source/Core/LeapSecond.js
function LeapSecond(date, offset2) {
this.julianDate = date;
this.offset = offset2;
}
var LeapSecond_default = LeapSecond;
// packages/engine/Source/Core/TimeConstants.js
var TimeConstants = {
/**
* The number of seconds in one millisecond: 0.001
* @type {number}
* @constant
*/
SECONDS_PER_MILLISECOND: 1e-3,
/**
* The number of seconds in one minute: 60
.
* @type {number}
* @constant
*/
SECONDS_PER_MINUTE: 60,
/**
* The number of minutes in one hour: 60
.
* @type {number}
* @constant
*/
MINUTES_PER_HOUR: 60,
/**
* The number of hours in one day: 24
.
* @type {number}
* @constant
*/
HOURS_PER_DAY: 24,
/**
* The number of seconds in one hour: 3600
.
* @type {number}
* @constant
*/
SECONDS_PER_HOUR: 3600,
/**
* The number of minutes in one day: 1440
.
* @type {number}
* @constant
*/
MINUTES_PER_DAY: 1440,
/**
* The number of seconds in one day, ignoring leap seconds: 86400
.
* @type {number}
* @constant
*/
SECONDS_PER_DAY: 86400,
/**
* The number of days in one Julian century: 36525
.
* @type {number}
* @constant
*/
DAYS_PER_JULIAN_CENTURY: 36525,
/**
* One trillionth of a second.
* @type {number}
* @constant
*/
PICOSECOND: 1e-9,
/**
* The number of days to subtract from a Julian date to determine the
* modified Julian date, which gives the number of days since midnight
* on November 17, 1858.
* @type {number}
* @constant
*/
MODIFIED_JULIAN_DATE_DIFFERENCE: 24000005e-1
};
var TimeConstants_default = Object.freeze(TimeConstants);
// packages/engine/Source/Core/TimeStandard.js
var TimeStandard = {
/**
* Represents the coordinated Universal Time (UTC) time standard.
*
* UTC is related to TAI according to the relationship
* UTC = TAI - deltaT
where deltaT
is the number of leap
* seconds which have been introduced as of the time in TAI.
*
* @type {number}
* @constant
*/
UTC: 0,
/**
* Represents the International Atomic Time (TAI) time standard.
* TAI is the principal time standard to which the other time standards are related.
*
* @type {number}
* @constant
*/
TAI: 1
};
var TimeStandard_default = Object.freeze(TimeStandard);
// packages/engine/Source/Core/JulianDate.js
var gregorianDateScratch = new GregorianDate_default();
var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var daysInLeapFeburary = 29;
function compareLeapSecondDates(leapSecond, dateToFind) {
return JulianDate.compare(leapSecond.julianDate, dateToFind.julianDate);
}
var binarySearchScratchLeapSecond = new LeapSecond_default();
function convertUtcToTai(julianDate) {
binarySearchScratchLeapSecond.julianDate = julianDate;
const leapSeconds = JulianDate.leapSeconds;
let index = binarySearch_default(
leapSeconds,
binarySearchScratchLeapSecond,
compareLeapSecondDates
);
if (index < 0) {
index = ~index;
}
if (index >= leapSeconds.length) {
index = leapSeconds.length - 1;
}
let offset2 = leapSeconds[index].offset;
if (index > 0) {
const difference = JulianDate.secondsDifference(
leapSeconds[index].julianDate,
julianDate
);
if (difference > offset2) {
index--;
offset2 = leapSeconds[index].offset;
}
}
JulianDate.addSeconds(julianDate, offset2, julianDate);
}
function convertTaiToUtc(julianDate, result) {
binarySearchScratchLeapSecond.julianDate = julianDate;
const leapSeconds = JulianDate.leapSeconds;
let index = binarySearch_default(
leapSeconds,
binarySearchScratchLeapSecond,
compareLeapSecondDates
);
if (index < 0) {
index = ~index;
}
if (index === 0) {
return JulianDate.addSeconds(julianDate, -leapSeconds[0].offset, result);
}
if (index >= leapSeconds.length) {
return JulianDate.addSeconds(
julianDate,
-leapSeconds[index - 1].offset,
result
);
}
const difference = JulianDate.secondsDifference(
leapSeconds[index].julianDate,
julianDate
);
if (difference === 0) {
return JulianDate.addSeconds(
julianDate,
-leapSeconds[index].offset,
result
);
}
if (difference <= 1) {
return void 0;
}
return JulianDate.addSeconds(
julianDate,
-leapSeconds[--index].offset,
result
);
}
function setComponents(wholeDays, secondsOfDay, julianDate) {
const extraDays = secondsOfDay / TimeConstants_default.SECONDS_PER_DAY | 0;
wholeDays += extraDays;
secondsOfDay -= TimeConstants_default.SECONDS_PER_DAY * extraDays;
if (secondsOfDay < 0) {
wholeDays--;
secondsOfDay += TimeConstants_default.SECONDS_PER_DAY;
}
julianDate.dayNumber = wholeDays;
julianDate.secondsOfDay = secondsOfDay;
return julianDate;
}
function computeJulianDateComponents(year, month, day, hour, minute, second, millisecond) {
const a3 = (month - 14) / 12 | 0;
const b = year + 4800 + a3;
let dayNumber = (1461 * b / 4 | 0) + (367 * (month - 2 - 12 * a3) / 12 | 0) - (3 * ((b + 100) / 100 | 0) / 4 | 0) + day - 32075;
hour = hour - 12;
if (hour < 0) {
hour += 24;
}
const secondsOfDay = second + (hour * TimeConstants_default.SECONDS_PER_HOUR + minute * TimeConstants_default.SECONDS_PER_MINUTE + millisecond * TimeConstants_default.SECONDS_PER_MILLISECOND);
if (secondsOfDay >= 43200) {
dayNumber -= 1;
}
return [dayNumber, secondsOfDay];
}
var matchCalendarYear = /^(\d{4})$/;
var matchCalendarMonth = /^(\d{4})-(\d{2})$/;
var matchOrdinalDate = /^(\d{4})-?(\d{3})$/;
var matchWeekDate = /^(\d{4})-?W(\d{2})-?(\d{1})?$/;
var matchCalendarDate = /^(\d{4})-?(\d{2})-?(\d{2})$/;
var utcOffset = /([Z+\-])?(\d{2})?:?(\d{2})?$/;
var matchHours = /^(\d{2})(\.\d+)?/.source + utcOffset.source;
var matchHoursMinutes = /^(\d{2}):?(\d{2})(\.\d+)?/.source + utcOffset.source;
var matchHoursMinutesSeconds = /^(\d{2}):?(\d{2}):?(\d{2})(\.\d+)?/.source + utcOffset.source;
var iso8601ErrorMessage = "Invalid ISO 8601 date.";
function JulianDate(julianDayNumber, secondsOfDay, timeStandard) {
this.dayNumber = void 0;
this.secondsOfDay = void 0;
julianDayNumber = defaultValue_default(julianDayNumber, 0);
secondsOfDay = defaultValue_default(secondsOfDay, 0);
timeStandard = defaultValue_default(timeStandard, TimeStandard_default.UTC);
const wholeDays = julianDayNumber | 0;
secondsOfDay = secondsOfDay + (julianDayNumber - wholeDays) * TimeConstants_default.SECONDS_PER_DAY;
setComponents(wholeDays, secondsOfDay, this);
if (timeStandard === TimeStandard_default.UTC) {
convertUtcToTai(this);
}
}
JulianDate.fromGregorianDate = function(date, result) {
if (!(date instanceof GregorianDate_default)) {
throw new DeveloperError_default("date must be a valid GregorianDate.");
}
const components = computeJulianDateComponents(
date.year,
date.month,
date.day,
date.hour,
date.minute,
date.second,
date.millisecond
);
if (!defined_default(result)) {
return new JulianDate(components[0], components[1], TimeStandard_default.UTC);
}
setComponents(components[0], components[1], result);
convertUtcToTai(result);
return result;
};
JulianDate.fromDate = function(date, result) {
if (!(date instanceof Date) || isNaN(date.getTime())) {
throw new DeveloperError_default("date must be a valid JavaScript Date.");
}
const components = computeJulianDateComponents(
date.getUTCFullYear(),
date.getUTCMonth() + 1,
date.getUTCDate(),
date.getUTCHours(),
date.getUTCMinutes(),
date.getUTCSeconds(),
date.getUTCMilliseconds()
);
if (!defined_default(result)) {
return new JulianDate(components[0], components[1], TimeStandard_default.UTC);
}
setComponents(components[0], components[1], result);
convertUtcToTai(result);
return result;
};
JulianDate.fromIso8601 = function(iso8601String, result) {
if (typeof iso8601String !== "string") {
throw new DeveloperError_default(iso8601ErrorMessage);
}
iso8601String = iso8601String.replace(",", ".");
let tokens = iso8601String.split("T");
let year;
let month = 1;
let day = 1;
let hour = 0;
let minute = 0;
let second = 0;
let millisecond = 0;
const date = tokens[0];
const time = tokens[1];
let tmp2;
let inLeapYear;
if (!defined_default(date)) {
throw new DeveloperError_default(iso8601ErrorMessage);
}
let dashCount;
tokens = date.match(matchCalendarDate);
if (tokens !== null) {
dashCount = date.split("-").length - 1;
if (dashCount > 0 && dashCount !== 2) {
throw new DeveloperError_default(iso8601ErrorMessage);
}
year = +tokens[1];
month = +tokens[2];
day = +tokens[3];
} else {
tokens = date.match(matchCalendarMonth);
if (tokens !== null) {
year = +tokens[1];
month = +tokens[2];
} else {
tokens = date.match(matchCalendarYear);
if (tokens !== null) {
year = +tokens[1];
} else {
let dayOfYear;
tokens = date.match(matchOrdinalDate);
if (tokens !== null) {
year = +tokens[1];
dayOfYear = +tokens[2];
inLeapYear = isLeapYear_default(year);
if (dayOfYear < 1 || inLeapYear && dayOfYear > 366 || !inLeapYear && dayOfYear > 365) {
throw new DeveloperError_default(iso8601ErrorMessage);
}
} else {
tokens = date.match(matchWeekDate);
if (tokens !== null) {
year = +tokens[1];
const weekNumber = +tokens[2];
const dayOfWeek = +tokens[3] || 0;
dashCount = date.split("-").length - 1;
if (dashCount > 0 && (!defined_default(tokens[3]) && dashCount !== 1 || defined_default(tokens[3]) && dashCount !== 2)) {
throw new DeveloperError_default(iso8601ErrorMessage);
}
const january4 = new Date(Date.UTC(year, 0, 4));
dayOfYear = weekNumber * 7 + dayOfWeek - january4.getUTCDay() - 3;
} else {
throw new DeveloperError_default(iso8601ErrorMessage);
}
}
tmp2 = new Date(Date.UTC(year, 0, 1));
tmp2.setUTCDate(dayOfYear);
month = tmp2.getUTCMonth() + 1;
day = tmp2.getUTCDate();
}
}
}
inLeapYear = isLeapYear_default(year);
if (month < 1 || month > 12 || day < 1 || (month !== 2 || !inLeapYear) && day > daysInMonth[month - 1] || inLeapYear && month === 2 && day > daysInLeapFeburary) {
throw new DeveloperError_default(iso8601ErrorMessage);
}
let offsetIndex;
if (defined_default(time)) {
tokens = time.match(matchHoursMinutesSeconds);
if (tokens !== null) {
dashCount = time.split(":").length - 1;
if (dashCount > 0 && dashCount !== 2 && dashCount !== 3) {
throw new DeveloperError_default(iso8601ErrorMessage);
}
hour = +tokens[1];
minute = +tokens[2];
second = +tokens[3];
millisecond = +(tokens[4] || 0) * 1e3;
offsetIndex = 5;
} else {
tokens = time.match(matchHoursMinutes);
if (tokens !== null) {
dashCount = time.split(":").length - 1;
if (dashCount > 2) {
throw new DeveloperError_default(iso8601ErrorMessage);
}
hour = +tokens[1];
minute = +tokens[2];
second = +(tokens[3] || 0) * 60;
offsetIndex = 4;
} else {
tokens = time.match(matchHours);
if (tokens !== null) {
hour = +tokens[1];
minute = +(tokens[2] || 0) * 60;
offsetIndex = 3;
} else {
throw new DeveloperError_default(iso8601ErrorMessage);
}
}
}
if (minute >= 60 || second >= 61 || hour > 24 || hour === 24 && (minute > 0 || second > 0 || millisecond > 0)) {
throw new DeveloperError_default(iso8601ErrorMessage);
}
const offset2 = tokens[offsetIndex];
const offsetHours = +tokens[offsetIndex + 1];
const offsetMinutes = +(tokens[offsetIndex + 2] || 0);
switch (offset2) {
case "+":
hour = hour - offsetHours;
minute = minute - offsetMinutes;
break;
case "-":
hour = hour + offsetHours;
minute = minute + offsetMinutes;
break;
case "Z":
break;
default:
minute = minute + new Date(
Date.UTC(year, month - 1, day, hour, minute)
).getTimezoneOffset();
break;
}
}
const isLeapSecond = second === 60;
if (isLeapSecond) {
second--;
}
while (minute >= 60) {
minute -= 60;
hour++;
}
while (hour >= 24) {
hour -= 24;
day++;
}
tmp2 = inLeapYear && month === 2 ? daysInLeapFeburary : daysInMonth[month - 1];
while (day > tmp2) {
day -= tmp2;
month++;
if (month > 12) {
month -= 12;
year++;
}
tmp2 = inLeapYear && month === 2 ? daysInLeapFeburary : daysInMonth[month - 1];
}
while (minute < 0) {
minute += 60;
hour--;
}
while (hour < 0) {
hour += 24;
day--;
}
while (day < 1) {
month--;
if (month < 1) {
month += 12;
year--;
}
tmp2 = inLeapYear && month === 2 ? daysInLeapFeburary : daysInMonth[month - 1];
day += tmp2;
}
const components = computeJulianDateComponents(
year,
month,
day,
hour,
minute,
second,
millisecond
);
if (!defined_default(result)) {
result = new JulianDate(components[0], components[1], TimeStandard_default.UTC);
} else {
setComponents(components[0], components[1], result);
convertUtcToTai(result);
}
if (isLeapSecond) {
JulianDate.addSeconds(result, 1, result);
}
return result;
};
JulianDate.now = function(result) {
return JulianDate.fromDate(/* @__PURE__ */ new Date(), result);
};
var toGregorianDateScratch = new JulianDate(0, 0, TimeStandard_default.TAI);
JulianDate.toGregorianDate = function(julianDate, result) {
if (!defined_default(julianDate)) {
throw new DeveloperError_default("julianDate is required.");
}
let isLeapSecond = false;
let thisUtc = convertTaiToUtc(julianDate, toGregorianDateScratch);
if (!defined_default(thisUtc)) {
JulianDate.addSeconds(julianDate, -1, toGregorianDateScratch);
thisUtc = convertTaiToUtc(toGregorianDateScratch, toGregorianDateScratch);
isLeapSecond = true;
}
let julianDayNumber = thisUtc.dayNumber;
const secondsOfDay = thisUtc.secondsOfDay;
if (secondsOfDay >= 43200) {
julianDayNumber += 1;
}
let L = julianDayNumber + 68569 | 0;
const N = 4 * L / 146097 | 0;
L = L - ((146097 * N + 3) / 4 | 0) | 0;
const I = 4e3 * (L + 1) / 1461001 | 0;
L = L - (1461 * I / 4 | 0) + 31 | 0;
const J = 80 * L / 2447 | 0;
const day = L - (2447 * J / 80 | 0) | 0;
L = J / 11 | 0;
const month = J + 2 - 12 * L | 0;
const year = 100 * (N - 49) + I + L | 0;
let hour = secondsOfDay / TimeConstants_default.SECONDS_PER_HOUR | 0;
let remainingSeconds = secondsOfDay - hour * TimeConstants_default.SECONDS_PER_HOUR;
const minute = remainingSeconds / TimeConstants_default.SECONDS_PER_MINUTE | 0;
remainingSeconds = remainingSeconds - minute * TimeConstants_default.SECONDS_PER_MINUTE;
let second = remainingSeconds | 0;
const millisecond = (remainingSeconds - second) / TimeConstants_default.SECONDS_PER_MILLISECOND;
hour += 12;
if (hour > 23) {
hour -= 24;
}
if (isLeapSecond) {
second += 1;
}
if (!defined_default(result)) {
return new GregorianDate_default(
year,
month,
day,
hour,
minute,
second,
millisecond,
isLeapSecond
);
}
result.year = year;
result.month = month;
result.day = day;
result.hour = hour;
result.minute = minute;
result.second = second;
result.millisecond = millisecond;
result.isLeapSecond = isLeapSecond;
return result;
};
JulianDate.toDate = function(julianDate) {
if (!defined_default(julianDate)) {
throw new DeveloperError_default("julianDate is required.");
}
const gDate = JulianDate.toGregorianDate(julianDate, gregorianDateScratch);
let second = gDate.second;
if (gDate.isLeapSecond) {
second -= 1;
}
return new Date(
Date.UTC(
gDate.year,
gDate.month - 1,
gDate.day,
gDate.hour,
gDate.minute,
second,
gDate.millisecond
)
);
};
JulianDate.toIso8601 = function(julianDate, precision) {
if (!defined_default(julianDate)) {
throw new DeveloperError_default("julianDate is required.");
}
const gDate = JulianDate.toGregorianDate(julianDate, gregorianDateScratch);
let year = gDate.year;
let month = gDate.month;
let day = gDate.day;
let hour = gDate.hour;
const minute = gDate.minute;
const second = gDate.second;
const millisecond = gDate.millisecond;
if (year === 1e4 && month === 1 && day === 1 && hour === 0 && minute === 0 && second === 0 && millisecond === 0) {
year = 9999;
month = 12;
day = 31;
hour = 24;
}
let millisecondStr;
if (!defined_default(precision) && millisecond !== 0) {
millisecondStr = (millisecond * 0.01).toString().replace(".", "");
return `${year.toString().padStart(4, "0")}-${month.toString().padStart(2, "0")}-${day.toString().padStart(2, "0")}T${hour.toString().padStart(2, "0")}:${minute.toString().padStart(2, "0")}:${second.toString().padStart(2, "0")}.${millisecondStr}Z`;
}
if (!defined_default(precision) || precision === 0) {
return `${year.toString().padStart(4, "0")}-${month.toString().padStart(2, "0")}-${day.toString().padStart(2, "0")}T${hour.toString().padStart(2, "0")}:${minute.toString().padStart(2, "0")}:${second.toString().padStart(2, "0")}Z`;
}
millisecondStr = (millisecond * 0.01).toFixed(precision).replace(".", "").slice(0, precision);
return `${year.toString().padStart(4, "0")}-${month.toString().padStart(2, "0")}-${day.toString().padStart(2, "0")}T${hour.toString().padStart(2, "0")}:${minute.toString().padStart(2, "0")}:${second.toString().padStart(2, "0")}.${millisecondStr}Z`;
};
JulianDate.clone = function(julianDate, result) {
if (!defined_default(julianDate)) {
return void 0;
}
if (!defined_default(result)) {
return new JulianDate(
julianDate.dayNumber,
julianDate.secondsOfDay,
TimeStandard_default.TAI
);
}
result.dayNumber = julianDate.dayNumber;
result.secondsOfDay = julianDate.secondsOfDay;
return result;
};
JulianDate.compare = function(left, right) {
if (!defined_default(left)) {
throw new DeveloperError_default("left is required.");
}
if (!defined_default(right)) {
throw new DeveloperError_default("right is required.");
}
const julianDayNumberDifference = left.dayNumber - right.dayNumber;
if (julianDayNumberDifference !== 0) {
return julianDayNumberDifference;
}
return left.secondsOfDay - right.secondsOfDay;
};
JulianDate.equals = function(left, right) {
return left === right || defined_default(left) && defined_default(right) && left.dayNumber === right.dayNumber && left.secondsOfDay === right.secondsOfDay;
};
JulianDate.equalsEpsilon = function(left, right, epsilon) {
epsilon = defaultValue_default(epsilon, 0);
return left === right || defined_default(left) && defined_default(right) && Math.abs(JulianDate.secondsDifference(left, right)) <= epsilon;
};
JulianDate.totalDays = function(julianDate) {
if (!defined_default(julianDate)) {
throw new DeveloperError_default("julianDate is required.");
}
return julianDate.dayNumber + julianDate.secondsOfDay / TimeConstants_default.SECONDS_PER_DAY;
};
JulianDate.secondsDifference = function(left, right) {
if (!defined_default(left)) {
throw new DeveloperError_default("left is required.");
}
if (!defined_default(right)) {
throw new DeveloperError_default("right is required.");
}
const dayDifference = (left.dayNumber - right.dayNumber) * TimeConstants_default.SECONDS_PER_DAY;
return dayDifference + (left.secondsOfDay - right.secondsOfDay);
};
JulianDate.daysDifference = function(left, right) {
if (!defined_default(left)) {
throw new DeveloperError_default("left is required.");
}
if (!defined_default(right)) {
throw new DeveloperError_default("right is required.");
}
const dayDifference = left.dayNumber - right.dayNumber;
const secondDifference = (left.secondsOfDay - right.secondsOfDay) / TimeConstants_default.SECONDS_PER_DAY;
return dayDifference + secondDifference;
};
JulianDate.computeTaiMinusUtc = function(julianDate) {
binarySearchScratchLeapSecond.julianDate = julianDate;
const leapSeconds = JulianDate.leapSeconds;
let index = binarySearch_default(
leapSeconds,
binarySearchScratchLeapSecond,
compareLeapSecondDates
);
if (index < 0) {
index = ~index;
--index;
if (index < 0) {
index = 0;
}
}
return leapSeconds[index].offset;
};
JulianDate.addSeconds = function(julianDate, seconds, result) {
if (!defined_default(julianDate)) {
throw new DeveloperError_default("julianDate is required.");
}
if (!defined_default(seconds)) {
throw new DeveloperError_default("seconds is required.");
}
if (!defined_default(result)) {
throw new DeveloperError_default("result is required.");
}
return setComponents(
julianDate.dayNumber,
julianDate.secondsOfDay + seconds,
result
);
};
JulianDate.addMinutes = function(julianDate, minutes, result) {
if (!defined_default(julianDate)) {
throw new DeveloperError_default("julianDate is required.");
}
if (!defined_default(minutes)) {
throw new DeveloperError_default("minutes is required.");
}
if (!defined_default(result)) {
throw new DeveloperError_default("result is required.");
}
const newSecondsOfDay = julianDate.secondsOfDay + minutes * TimeConstants_default.SECONDS_PER_MINUTE;
return setComponents(julianDate.dayNumber, newSecondsOfDay, result);
};
JulianDate.addHours = function(julianDate, hours, result) {
if (!defined_default(julianDate)) {
throw new DeveloperError_default("julianDate is required.");
}
if (!defined_default(hours)) {
throw new DeveloperError_default("hours is required.");
}
if (!defined_default(result)) {
throw new DeveloperError_default("result is required.");
}
const newSecondsOfDay = julianDate.secondsOfDay + hours * TimeConstants_default.SECONDS_PER_HOUR;
return setComponents(julianDate.dayNumber, newSecondsOfDay, result);
};
JulianDate.addDays = function(julianDate, days, result) {
if (!defined_default(julianDate)) {
throw new DeveloperError_default("julianDate is required.");
}
if (!defined_default(days)) {
throw new DeveloperError_default("days is required.");
}
if (!defined_default(result)) {
throw new DeveloperError_default("result is required.");
}
const newJulianDayNumber = julianDate.dayNumber + days;
return setComponents(newJulianDayNumber, julianDate.secondsOfDay, result);
};
JulianDate.lessThan = function(left, right) {
return JulianDate.compare(left, right) < 0;
};
JulianDate.lessThanOrEquals = function(left, right) {
return JulianDate.compare(left, right) <= 0;
};
JulianDate.greaterThan = function(left, right) {
return JulianDate.compare(left, right) > 0;
};
JulianDate.greaterThanOrEquals = function(left, right) {
return JulianDate.compare(left, right) >= 0;
};
JulianDate.prototype.clone = function(result) {
return JulianDate.clone(this, result);
};
JulianDate.prototype.equals = function(right) {
return JulianDate.equals(this, right);
};
JulianDate.prototype.equalsEpsilon = function(right, epsilon) {
return JulianDate.equalsEpsilon(this, right, epsilon);
};
JulianDate.prototype.toString = function() {
return JulianDate.toIso8601(this);
};
JulianDate.leapSeconds = [
new LeapSecond_default(new JulianDate(2441317, 43210, TimeStandard_default.TAI), 10),
// January 1, 1972 00:00:00 UTC
new LeapSecond_default(new JulianDate(2441499, 43211, TimeStandard_default.TAI), 11),
// July 1, 1972 00:00:00 UTC
new LeapSecond_default(new JulianDate(2441683, 43212, TimeStandard_default.TAI), 12),
// January 1, 1973 00:00:00 UTC
new LeapSecond_default(new JulianDate(2442048, 43213, TimeStandard_default.TAI), 13),
// January 1, 1974 00:00:00 UTC
new LeapSecond_default(new JulianDate(2442413, 43214, TimeStandard_default.TAI), 14),
// January 1, 1975 00:00:00 UTC
new LeapSecond_default(new JulianDate(2442778, 43215, TimeStandard_default.TAI), 15),
// January 1, 1976 00:00:00 UTC
new LeapSecond_default(new JulianDate(2443144, 43216, TimeStandard_default.TAI), 16),
// January 1, 1977 00:00:00 UTC
new LeapSecond_default(new JulianDate(2443509, 43217, TimeStandard_default.TAI), 17),
// January 1, 1978 00:00:00 UTC
new LeapSecond_default(new JulianDate(2443874, 43218, TimeStandard_default.TAI), 18),
// January 1, 1979 00:00:00 UTC
new LeapSecond_default(new JulianDate(2444239, 43219, TimeStandard_default.TAI), 19),
// January 1, 1980 00:00:00 UTC
new LeapSecond_default(new JulianDate(2444786, 43220, TimeStandard_default.TAI), 20),
// July 1, 1981 00:00:00 UTC
new LeapSecond_default(new JulianDate(2445151, 43221, TimeStandard_default.TAI), 21),
// July 1, 1982 00:00:00 UTC
new LeapSecond_default(new JulianDate(2445516, 43222, TimeStandard_default.TAI), 22),
// July 1, 1983 00:00:00 UTC
new LeapSecond_default(new JulianDate(2446247, 43223, TimeStandard_default.TAI), 23),
// July 1, 1985 00:00:00 UTC
new LeapSecond_default(new JulianDate(2447161, 43224, TimeStandard_default.TAI), 24),
// January 1, 1988 00:00:00 UTC
new LeapSecond_default(new JulianDate(2447892, 43225, TimeStandard_default.TAI), 25),
// January 1, 1990 00:00:00 UTC
new LeapSecond_default(new JulianDate(2448257, 43226, TimeStandard_default.TAI), 26),
// January 1, 1991 00:00:00 UTC
new LeapSecond_default(new JulianDate(2448804, 43227, TimeStandard_default.TAI), 27),
// July 1, 1992 00:00:00 UTC
new LeapSecond_default(new JulianDate(2449169, 43228, TimeStandard_default.TAI), 28),
// July 1, 1993 00:00:00 UTC
new LeapSecond_default(new JulianDate(2449534, 43229, TimeStandard_default.TAI), 29),
// July 1, 1994 00:00:00 UTC
new LeapSecond_default(new JulianDate(2450083, 43230, TimeStandard_default.TAI), 30),
// January 1, 1996 00:00:00 UTC
new LeapSecond_default(new JulianDate(2450630, 43231, TimeStandard_default.TAI), 31),
// July 1, 1997 00:00:00 UTC
new LeapSecond_default(new JulianDate(2451179, 43232, TimeStandard_default.TAI), 32),
// January 1, 1999 00:00:00 UTC
new LeapSecond_default(new JulianDate(2453736, 43233, TimeStandard_default.TAI), 33),
// January 1, 2006 00:00:00 UTC
new LeapSecond_default(new JulianDate(2454832, 43234, TimeStandard_default.TAI), 34),
// January 1, 2009 00:00:00 UTC
new LeapSecond_default(new JulianDate(2456109, 43235, TimeStandard_default.TAI), 35),
// July 1, 2012 00:00:00 UTC
new LeapSecond_default(new JulianDate(2457204, 43236, TimeStandard_default.TAI), 36),
// July 1, 2015 00:00:00 UTC
new LeapSecond_default(new JulianDate(2457754, 43237, TimeStandard_default.TAI), 37)
// January 1, 2017 00:00:00 UTC
];
var JulianDate_default = JulianDate;
// packages/engine/Source/Core/Resource.js
var import_urijs6 = __toESM(require_URI(), 1);
// packages/engine/Source/Core/appendForwardSlash.js
function appendForwardSlash(url2) {
if (url2.length === 0 || url2[url2.length - 1] !== "/") {
url2 = `${url2}/`;
}
return url2;
}
var appendForwardSlash_default = appendForwardSlash;
// packages/engine/Source/Core/clone.js
function clone(object2, deep) {
if (object2 === null || typeof object2 !== "object") {
return object2;
}
deep = defaultValue_default(deep, false);
const result = new object2.constructor();
for (const propertyName in object2) {
if (object2.hasOwnProperty(propertyName)) {
let value = object2[propertyName];
if (deep) {
value = clone(value, deep);
}
result[propertyName] = value;
}
}
return result;
}
var clone_default = clone;
// packages/engine/Source/Core/combine.js
function combine(object1, object2, deep) {
deep = defaultValue_default(deep, false);
const result = {};
const object1Defined = defined_default(object1);
const object2Defined = defined_default(object2);
let property;
let object1Value;
let object2Value;
if (object1Defined) {
for (property in object1) {
if (object1.hasOwnProperty(property)) {
object1Value = object1[property];
if (object2Defined && deep && typeof object1Value === "object" && object2.hasOwnProperty(property)) {
object2Value = object2[property];
if (typeof object2Value === "object") {
result[property] = combine(object1Value, object2Value, deep);
} else {
result[property] = object1Value;
}
} else {
result[property] = object1Value;
}
}
}
}
if (object2Defined) {
for (property in object2) {
if (object2.hasOwnProperty(property) && !result.hasOwnProperty(property)) {
object2Value = object2[property];
result[property] = object2Value;
}
}
}
return result;
}
var combine_default = combine;
// packages/engine/Source/Core/defer.js
function defer() {
let resolve2;
let reject;
const promise = new Promise(function(res, rej) {
resolve2 = res;
reject = rej;
});
return {
resolve: resolve2,
reject,
promise
};
}
var defer_default = defer;
// packages/engine/Source/Core/getAbsoluteUri.js
var import_urijs = __toESM(require_URI(), 1);
function getAbsoluteUri(relative, base) {
let documentObject;
if (typeof document !== "undefined") {
documentObject = document;
}
return getAbsoluteUri._implementation(relative, base, documentObject);
}
getAbsoluteUri._implementation = function(relative, base, documentObject) {
if (!defined_default(relative)) {
throw new DeveloperError_default("relative uri is required.");
}
if (!defined_default(base)) {
if (typeof documentObject === "undefined") {
return relative;
}
base = defaultValue_default(documentObject.baseURI, documentObject.location.href);
}
const relativeUri = new import_urijs.default(relative);
if (relativeUri.scheme() !== "") {
return relativeUri.toString();
}
return relativeUri.absoluteTo(base).toString();
};
var getAbsoluteUri_default = getAbsoluteUri;
// packages/engine/Source/Core/getBaseUri.js
var import_urijs2 = __toESM(require_URI(), 1);
function getBaseUri(uri, includeQuery) {
if (!defined_default(uri)) {
throw new DeveloperError_default("uri is required.");
}
let basePath = "";
const i = uri.lastIndexOf("/");
if (i !== -1) {
basePath = uri.substring(0, i + 1);
}
if (!includeQuery) {
return basePath;
}
uri = new import_urijs2.default(uri);
if (uri.query().length !== 0) {
basePath += `?${uri.query()}`;
}
if (uri.fragment().length !== 0) {
basePath += `#${uri.fragment()}`;
}
return basePath;
}
var getBaseUri_default = getBaseUri;
// packages/engine/Source/Core/getExtensionFromUri.js
var import_urijs3 = __toESM(require_URI(), 1);
function getExtensionFromUri(uri) {
if (!defined_default(uri)) {
throw new DeveloperError_default("uri is required.");
}
const uriObject = new import_urijs3.default(uri);
uriObject.normalize();
let path = uriObject.path();
let index = path.lastIndexOf("/");
if (index !== -1) {
path = path.substr(index + 1);
}
index = path.lastIndexOf(".");
if (index === -1) {
path = "";
} else {
path = path.substr(index + 1);
}
return path;
}
var getExtensionFromUri_default = getExtensionFromUri;
// packages/engine/Source/Core/getImagePixels.js
var context2DsByWidthAndHeight = {};
function getImagePixels(image, width, height) {
if (!defined_default(width)) {
width = image.width;
}
if (!defined_default(height)) {
height = image.height;
}
let context2DsByHeight = context2DsByWidthAndHeight[width];
if (!defined_default(context2DsByHeight)) {
context2DsByHeight = {};
context2DsByWidthAndHeight[width] = context2DsByHeight;
}
let context2d = context2DsByHeight[height];
if (!defined_default(context2d)) {
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
context2d = canvas.getContext("2d", { willReadFrequently: true });
context2d.globalCompositeOperation = "copy";
context2DsByHeight[height] = context2d;
}
context2d.drawImage(image, 0, 0, width, height);
return context2d.getImageData(0, 0, width, height).data;
}
var getImagePixels_default = getImagePixels;
// packages/engine/Source/Core/isBlobUri.js
var blobUriRegex = /^blob:/i;
function isBlobUri(uri) {
Check_default.typeOf.string("uri", uri);
return blobUriRegex.test(uri);
}
var isBlobUri_default = isBlobUri;
// packages/engine/Source/Core/isCrossOriginUrl.js
var a;
function isCrossOriginUrl(url2) {
if (!defined_default(a)) {
a = document.createElement("a");
}
a.href = window.location.href;
const host = a.host;
const protocol = a.protocol;
a.href = url2;
a.href = a.href;
return protocol !== a.protocol || host !== a.host;
}
var isCrossOriginUrl_default = isCrossOriginUrl;
// packages/engine/Source/Core/isDataUri.js
var dataUriRegex = /^data:/i;
function isDataUri(uri) {
Check_default.typeOf.string("uri", uri);
return dataUriRegex.test(uri);
}
var isDataUri_default = isDataUri;
// packages/engine/Source/Core/loadAndExecuteScript.js
function loadAndExecuteScript(url2) {
const script = document.createElement("script");
script.async = true;
script.src = url2;
return new Promise((resolve2, reject) => {
if (window.crossOriginIsolated) {
script.setAttribute("crossorigin", "anonymous");
}
const head = document.getElementsByTagName("head")[0];
script.onload = function() {
script.onload = void 0;
head.removeChild(script);
resolve2();
};
script.onerror = function(e) {
reject(e);
};
head.appendChild(script);
});
}
var loadAndExecuteScript_default = loadAndExecuteScript;
// packages/engine/Source/Core/objectToQuery.js
function objectToQuery(obj) {
if (!defined_default(obj)) {
throw new DeveloperError_default("obj is required.");
}
let result = "";
for (const propName in obj) {
if (obj.hasOwnProperty(propName)) {
const value = obj[propName];
const part = `${encodeURIComponent(propName)}=`;
if (Array.isArray(value)) {
for (let i = 0, len = value.length; i < len; ++i) {
result += `${part + encodeURIComponent(value[i])}&`;
}
} else {
result += `${part + encodeURIComponent(value)}&`;
}
}
}
result = result.slice(0, -1);
return result;
}
var objectToQuery_default = objectToQuery;
// packages/engine/Source/Core/queryToObject.js
function queryToObject(queryString) {
if (!defined_default(queryString)) {
throw new DeveloperError_default("queryString is required.");
}
const result = {};
if (queryString === "") {
return result;
}
const parts = queryString.replace(/\+/g, "%20").split(/[&;]/);
for (let i = 0, len = parts.length; i < len; ++i) {
const subparts = parts[i].split("=");
const name = decodeURIComponent(subparts[0]);
let value = subparts[1];
if (defined_default(value)) {
value = decodeURIComponent(value);
} else {
value = "";
}
const resultValue = result[name];
if (typeof resultValue === "string") {
result[name] = [resultValue, value];
} else if (Array.isArray(resultValue)) {
resultValue.push(value);
} else {
result[name] = value;
}
}
return result;
}
var queryToObject_default = queryToObject;
// packages/engine/Source/Core/RequestState.js
var RequestState = {
/**
* Initial unissued state.
*
* @type {number}
* @constant
*/
UNISSUED: 0,
/**
* Issued but not yet active. Will become active when open slots are available.
*
* @type {number}
* @constant
*/
ISSUED: 1,
/**
* Actual http request has been sent.
*
* @type {number}
* @constant
*/
ACTIVE: 2,
/**
* Request completed successfully.
*
* @type {number}
* @constant
*/
RECEIVED: 3,
/**
* Request was cancelled, either explicitly or automatically because of low priority.
*
* @type {number}
* @constant
*/
CANCELLED: 4,
/**
* Request failed.
*
* @type {number}
* @constant
*/
FAILED: 5
};
var RequestState_default = Object.freeze(RequestState);
// packages/engine/Source/Core/RequestType.js
var RequestType = {
/**
* Terrain request.
*
* @type {number}
* @constant
*/
TERRAIN: 0,
/**
* Imagery request.
*
* @type {number}
* @constant
*/
IMAGERY: 1,
/**
* 3D Tiles request.
*
* @type {number}
* @constant
*/
TILES3D: 2,
/**
* Other request.
*
* @type {number}
* @constant
*/
OTHER: 3
};
var RequestType_default = Object.freeze(RequestType);
// packages/engine/Source/Core/Request.js
function Request(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const throttleByServer = defaultValue_default(options.throttleByServer, false);
const throttle = defaultValue_default(options.throttle, false);
this.url = options.url;
this.requestFunction = options.requestFunction;
this.cancelFunction = options.cancelFunction;
this.priorityFunction = options.priorityFunction;
this.priority = defaultValue_default(options.priority, 0);
this.throttle = throttle;
this.throttleByServer = throttleByServer;
this.type = defaultValue_default(options.type, RequestType_default.OTHER);
this.serverKey = options.serverKey;
this.state = RequestState_default.UNISSUED;
this.deferred = void 0;
this.cancelled = false;
}
Request.prototype.cancel = function() {
this.cancelled = true;
};
Request.prototype.clone = function(result) {
if (!defined_default(result)) {
return new Request(this);
}
result.url = this.url;
result.requestFunction = this.requestFunction;
result.cancelFunction = this.cancelFunction;
result.priorityFunction = this.priorityFunction;
result.priority = this.priority;
result.throttle = this.throttle;
result.throttleByServer = this.throttleByServer;
result.type = this.type;
result.serverKey = this.serverKey;
result.state = RequestState_default.UNISSUED;
result.deferred = void 0;
result.cancelled = false;
return result;
};
var Request_default = Request;
// packages/engine/Source/Core/parseResponseHeaders.js
function parseResponseHeaders(headerString) {
const headers = {};
if (!headerString) {
return headers;
}
const headerPairs = headerString.split("\r\n");
for (let i = 0; i < headerPairs.length; ++i) {
const headerPair = headerPairs[i];
const index = headerPair.indexOf(": ");
if (index > 0) {
const key = headerPair.substring(0, index);
const val = headerPair.substring(index + 2);
headers[key] = val;
}
}
return headers;
}
var parseResponseHeaders_default = parseResponseHeaders;
// packages/engine/Source/Core/RequestErrorEvent.js
function RequestErrorEvent(statusCode, response, responseHeaders) {
this.statusCode = statusCode;
this.response = response;
this.responseHeaders = responseHeaders;
if (typeof this.responseHeaders === "string") {
this.responseHeaders = parseResponseHeaders_default(this.responseHeaders);
}
}
RequestErrorEvent.prototype.toString = function() {
let str = "Request has failed.";
if (defined_default(this.statusCode)) {
str += ` Status Code: ${this.statusCode}`;
}
return str;
};
var RequestErrorEvent_default = RequestErrorEvent;
// packages/engine/Source/Core/RequestScheduler.js
var import_urijs4 = __toESM(require_URI(), 1);
// packages/engine/Source/Core/Event.js
function Event() {
this._listeners = [];
this._scopes = [];
this._toRemove = [];
this._insideRaiseEvent = false;
}
Object.defineProperties(Event.prototype, {
/**
* The number of listeners currently subscribed to the event.
* @memberof Event.prototype
* @type {number}
* @readonly
*/
numberOfListeners: {
get: function() {
return this._listeners.length - this._toRemove.length;
}
}
});
Event.prototype.addEventListener = function(listener, scope) {
Check_default.typeOf.func("listener", listener);
this._listeners.push(listener);
this._scopes.push(scope);
const event = this;
return function() {
event.removeEventListener(listener, scope);
};
};
Event.prototype.removeEventListener = function(listener, scope) {
Check_default.typeOf.func("listener", listener);
const listeners = this._listeners;
const scopes = this._scopes;
let index = -1;
for (let i = 0; i < listeners.length; i++) {
if (listeners[i] === listener && scopes[i] === scope) {
index = i;
break;
}
}
if (index !== -1) {
if (this._insideRaiseEvent) {
this._toRemove.push(index);
listeners[index] = void 0;
scopes[index] = void 0;
} else {
listeners.splice(index, 1);
scopes.splice(index, 1);
}
return true;
}
return false;
};
function compareNumber(a3, b) {
return b - a3;
}
Event.prototype.raiseEvent = function() {
this._insideRaiseEvent = true;
let i;
const listeners = this._listeners;
const scopes = this._scopes;
let length3 = listeners.length;
for (i = 0; i < length3; i++) {
const listener = listeners[i];
if (defined_default(listener)) {
listeners[i].apply(scopes[i], arguments);
}
}
const toRemove = this._toRemove;
length3 = toRemove.length;
if (length3 > 0) {
toRemove.sort(compareNumber);
for (i = 0; i < length3; i++) {
const index = toRemove[i];
listeners.splice(index, 1);
scopes.splice(index, 1);
}
toRemove.length = 0;
}
this._insideRaiseEvent = false;
};
var Event_default = Event;
// packages/engine/Source/Core/Heap.js
function Heap(options) {
Check_default.typeOf.object("options", options);
Check_default.defined("options.comparator", options.comparator);
this._comparator = options.comparator;
this._array = [];
this._length = 0;
this._maximumLength = void 0;
}
Object.defineProperties(Heap.prototype, {
/**
* Gets the length of the heap.
*
* @memberof Heap.prototype
*
* @type {number}
* @readonly
*/
length: {
get: function() {
return this._length;
}
},
/**
* Gets the internal array.
*
* @memberof Heap.prototype
*
* @type {Array}
* @readonly
*/
internalArray: {
get: function() {
return this._array;
}
},
/**
* Gets and sets the maximum length of the heap.
*
* @memberof Heap.prototype
*
* @type {number}
*/
maximumLength: {
get: function() {
return this._maximumLength;
},
set: function(value) {
Check_default.typeOf.number.greaterThanOrEquals("maximumLength", value, 0);
const originalLength = this._length;
if (value < originalLength) {
const array = this._array;
for (let i = value; i < originalLength; ++i) {
array[i] = void 0;
}
this._length = value;
array.length = value;
}
this._maximumLength = value;
}
},
/**
* The comparator to use for the heap. If comparator(a, b) is less than 0, sort a to a lower index than b, otherwise sort to a higher index.
*
* @memberof Heap.prototype
*
* @type {Heap.ComparatorCallback}
*/
comparator: {
get: function() {
return this._comparator;
}
}
});
function swap(array, a3, b) {
const temp = array[a3];
array[a3] = array[b];
array[b] = temp;
}
Heap.prototype.reserve = function(length3) {
length3 = defaultValue_default(length3, this._length);
this._array.length = length3;
};
Heap.prototype.heapify = function(index) {
index = defaultValue_default(index, 0);
const length3 = this._length;
const comparator = this._comparator;
const array = this._array;
let candidate = -1;
let inserting = true;
while (inserting) {
const right = 2 * (index + 1);
const left = right - 1;
if (left < length3 && comparator(array[left], array[index]) < 0) {
candidate = left;
} else {
candidate = index;
}
if (right < length3 && comparator(array[right], array[candidate]) < 0) {
candidate = right;
}
if (candidate !== index) {
swap(array, candidate, index);
index = candidate;
} else {
inserting = false;
}
}
};
Heap.prototype.resort = function() {
const length3 = this._length;
for (let i = Math.ceil(length3 / 2); i >= 0; --i) {
this.heapify(i);
}
};
Heap.prototype.insert = function(element) {
Check_default.defined("element", element);
const array = this._array;
const comparator = this._comparator;
const maximumLength = this._maximumLength;
let index = this._length++;
if (index < array.length) {
array[index] = element;
} else {
array.push(element);
}
while (index !== 0) {
const parent = Math.floor((index - 1) / 2);
if (comparator(array[index], array[parent]) < 0) {
swap(array, index, parent);
index = parent;
} else {
break;
}
}
let removedElement;
if (defined_default(maximumLength) && this._length > maximumLength) {
removedElement = array[maximumLength];
this._length = maximumLength;
}
return removedElement;
};
Heap.prototype.pop = function(index) {
index = defaultValue_default(index, 0);
if (this._length === 0) {
return void 0;
}
Check_default.typeOf.number.lessThan("index", index, this._length);
const array = this._array;
const root = array[index];
swap(array, index, --this._length);
this.heapify(index);
array[this._length] = void 0;
return root;
};
var Heap_default = Heap;
// packages/engine/Source/Core/RequestScheduler.js
function sortRequests(a3, b) {
return a3.priority - b.priority;
}
var statistics = {
numberOfAttemptedRequests: 0,
numberOfActiveRequests: 0,
numberOfCancelledRequests: 0,
numberOfCancelledActiveRequests: 0,
numberOfFailedRequests: 0,
numberOfActiveRequestsEver: 0,
lastNumberOfActiveRequests: 0
};
var priorityHeapLength = 20;
var requestHeap = new Heap_default({
comparator: sortRequests
});
requestHeap.maximumLength = priorityHeapLength;
requestHeap.reserve(priorityHeapLength);
var activeRequests = [];
var numberOfActiveRequestsByServer = {};
var pageUri = typeof document !== "undefined" ? new import_urijs4.default(document.location.href) : new import_urijs4.default();
var requestCompletedEvent = new Event_default();
function RequestScheduler() {
}
RequestScheduler.maximumRequests = 50;
RequestScheduler.maximumRequestsPerServer = 6;
RequestScheduler.requestsByServer = {
"api.cesium.com:443": 18,
"assets.ion.cesium.com:443": 18,
"ibasemaps-api.arcgis.com:443": 18
};
RequestScheduler.throttleRequests = true;
RequestScheduler.debugShowStatistics = false;
RequestScheduler.requestCompletedEvent = requestCompletedEvent;
Object.defineProperties(RequestScheduler, {
/**
* Returns the statistics used by the request scheduler.
*
* @memberof RequestScheduler
*
* @type {object}
* @readonly
* @private
*/
statistics: {
get: function() {
return statistics;
}
},
/**
* The maximum size of the priority heap. This limits the number of requests that are sorted by priority. Only applies to requests that are not yet active.
*
* @memberof RequestScheduler
*
* @type {number}
* @default 20
* @private
*/
priorityHeapLength: {
get: function() {
return priorityHeapLength;
},
set: function(value) {
if (value < priorityHeapLength) {
while (requestHeap.length > value) {
const request = requestHeap.pop();
cancelRequest(request);
}
}
priorityHeapLength = value;
requestHeap.maximumLength = value;
requestHeap.reserve(value);
}
}
});
function updatePriority(request) {
if (defined_default(request.priorityFunction)) {
request.priority = request.priorityFunction();
}
}
RequestScheduler.serverHasOpenSlots = function(serverKey, desiredRequests) {
desiredRequests = defaultValue_default(desiredRequests, 1);
const maxRequests = defaultValue_default(
RequestScheduler.requestsByServer[serverKey],
RequestScheduler.maximumRequestsPerServer
);
const hasOpenSlotsServer = numberOfActiveRequestsByServer[serverKey] + desiredRequests <= maxRequests;
return hasOpenSlotsServer;
};
RequestScheduler.heapHasOpenSlots = function(desiredRequests) {
const hasOpenSlotsHeap = requestHeap.length + desiredRequests <= priorityHeapLength;
return hasOpenSlotsHeap;
};
function issueRequest(request) {
if (request.state === RequestState_default.UNISSUED) {
request.state = RequestState_default.ISSUED;
request.deferred = defer_default();
}
return request.deferred.promise;
}
function getRequestReceivedFunction(request) {
return function(results) {
if (request.state === RequestState_default.CANCELLED) {
return;
}
const deferred = request.deferred;
--statistics.numberOfActiveRequests;
--numberOfActiveRequestsByServer[request.serverKey];
requestCompletedEvent.raiseEvent();
request.state = RequestState_default.RECEIVED;
request.deferred = void 0;
deferred.resolve(results);
};
}
function getRequestFailedFunction(request) {
return function(error) {
if (request.state === RequestState_default.CANCELLED) {
return;
}
++statistics.numberOfFailedRequests;
--statistics.numberOfActiveRequests;
--numberOfActiveRequestsByServer[request.serverKey];
requestCompletedEvent.raiseEvent(error);
request.state = RequestState_default.FAILED;
request.deferred.reject(error);
};
}
function startRequest(request) {
const promise = issueRequest(request);
request.state = RequestState_default.ACTIVE;
activeRequests.push(request);
++statistics.numberOfActiveRequests;
++statistics.numberOfActiveRequestsEver;
++numberOfActiveRequestsByServer[request.serverKey];
request.requestFunction().then(getRequestReceivedFunction(request)).catch(getRequestFailedFunction(request));
return promise;
}
function cancelRequest(request) {
const active = request.state === RequestState_default.ACTIVE;
request.state = RequestState_default.CANCELLED;
++statistics.numberOfCancelledRequests;
if (defined_default(request.deferred)) {
const deferred = request.deferred;
request.deferred = void 0;
deferred.reject();
}
if (active) {
--statistics.numberOfActiveRequests;
--numberOfActiveRequestsByServer[request.serverKey];
++statistics.numberOfCancelledActiveRequests;
}
if (defined_default(request.cancelFunction)) {
request.cancelFunction();
}
}
RequestScheduler.update = function() {
let i;
let request;
let removeCount = 0;
const activeLength = activeRequests.length;
for (i = 0; i < activeLength; ++i) {
request = activeRequests[i];
if (request.cancelled) {
cancelRequest(request);
}
if (request.state !== RequestState_default.ACTIVE) {
++removeCount;
continue;
}
if (removeCount > 0) {
activeRequests[i - removeCount] = request;
}
}
activeRequests.length -= removeCount;
const issuedRequests = requestHeap.internalArray;
const issuedLength = requestHeap.length;
for (i = 0; i < issuedLength; ++i) {
updatePriority(issuedRequests[i]);
}
requestHeap.resort();
const openSlots = Math.max(
RequestScheduler.maximumRequests - activeRequests.length,
0
);
let filledSlots = 0;
while (filledSlots < openSlots && requestHeap.length > 0) {
request = requestHeap.pop();
if (request.cancelled) {
cancelRequest(request);
continue;
}
if (request.throttleByServer && !RequestScheduler.serverHasOpenSlots(request.serverKey)) {
cancelRequest(request);
continue;
}
startRequest(request);
++filledSlots;
}
updateStatistics();
};
RequestScheduler.getServerKey = function(url2) {
Check_default.typeOf.string("url", url2);
let uri = new import_urijs4.default(url2);
if (uri.scheme() === "") {
uri = uri.absoluteTo(pageUri);
uri.normalize();
}
let serverKey = uri.authority();
if (!/:/.test(serverKey)) {
serverKey = `${serverKey}:${uri.scheme() === "https" ? "443" : "80"}`;
}
const length3 = numberOfActiveRequestsByServer[serverKey];
if (!defined_default(length3)) {
numberOfActiveRequestsByServer[serverKey] = 0;
}
return serverKey;
};
RequestScheduler.request = function(request) {
Check_default.typeOf.object("request", request);
Check_default.typeOf.string("request.url", request.url);
Check_default.typeOf.func("request.requestFunction", request.requestFunction);
if (isDataUri_default(request.url) || isBlobUri_default(request.url)) {
requestCompletedEvent.raiseEvent();
request.state = RequestState_default.RECEIVED;
return request.requestFunction();
}
++statistics.numberOfAttemptedRequests;
if (!defined_default(request.serverKey)) {
request.serverKey = RequestScheduler.getServerKey(request.url);
}
if (RequestScheduler.throttleRequests && request.throttleByServer && !RequestScheduler.serverHasOpenSlots(request.serverKey)) {
return void 0;
}
if (!RequestScheduler.throttleRequests || !request.throttle) {
return startRequest(request);
}
if (activeRequests.length >= RequestScheduler.maximumRequests) {
return void 0;
}
updatePriority(request);
const removedRequest = requestHeap.insert(request);
if (defined_default(removedRequest)) {
if (removedRequest === request) {
return void 0;
}
cancelRequest(removedRequest);
}
return issueRequest(request);
};
function updateStatistics() {
if (!RequestScheduler.debugShowStatistics) {
return;
}
if (statistics.numberOfActiveRequests === 0 && statistics.lastNumberOfActiveRequests > 0) {
if (statistics.numberOfAttemptedRequests > 0) {
console.log(
`Number of attempted requests: ${statistics.numberOfAttemptedRequests}`
);
statistics.numberOfAttemptedRequests = 0;
}
if (statistics.numberOfCancelledRequests > 0) {
console.log(
`Number of cancelled requests: ${statistics.numberOfCancelledRequests}`
);
statistics.numberOfCancelledRequests = 0;
}
if (statistics.numberOfCancelledActiveRequests > 0) {
console.log(
`Number of cancelled active requests: ${statistics.numberOfCancelledActiveRequests}`
);
statistics.numberOfCancelledActiveRequests = 0;
}
if (statistics.numberOfFailedRequests > 0) {
console.log(
`Number of failed requests: ${statistics.numberOfFailedRequests}`
);
statistics.numberOfFailedRequests = 0;
}
}
statistics.lastNumberOfActiveRequests = statistics.numberOfActiveRequests;
}
RequestScheduler.clearForSpecs = function() {
while (requestHeap.length > 0) {
const request = requestHeap.pop();
cancelRequest(request);
}
const length3 = activeRequests.length;
for (let i = 0; i < length3; ++i) {
cancelRequest(activeRequests[i]);
}
activeRequests.length = 0;
numberOfActiveRequestsByServer = {};
statistics.numberOfAttemptedRequests = 0;
statistics.numberOfActiveRequests = 0;
statistics.numberOfCancelledRequests = 0;
statistics.numberOfCancelledActiveRequests = 0;
statistics.numberOfFailedRequests = 0;
statistics.numberOfActiveRequestsEver = 0;
statistics.lastNumberOfActiveRequests = 0;
};
RequestScheduler.numberOfActiveRequestsByServer = function(serverKey) {
return numberOfActiveRequestsByServer[serverKey];
};
RequestScheduler.requestHeap = requestHeap;
var RequestScheduler_default = RequestScheduler;
// packages/engine/Source/Core/TrustedServers.js
var import_urijs5 = __toESM(require_URI(), 1);
var TrustedServers = {};
var _servers = {};
TrustedServers.add = function(host, port) {
if (!defined_default(host)) {
throw new DeveloperError_default("host is required.");
}
if (!defined_default(port) || port <= 0) {
throw new DeveloperError_default("port is required to be greater than 0.");
}
const authority = `${host.toLowerCase()}:${port}`;
if (!defined_default(_servers[authority])) {
_servers[authority] = true;
}
};
TrustedServers.remove = function(host, port) {
if (!defined_default(host)) {
throw new DeveloperError_default("host is required.");
}
if (!defined_default(port) || port <= 0) {
throw new DeveloperError_default("port is required to be greater than 0.");
}
const authority = `${host.toLowerCase()}:${port}`;
if (defined_default(_servers[authority])) {
delete _servers[authority];
}
};
function getAuthority(url2) {
const uri = new import_urijs5.default(url2);
uri.normalize();
let authority = uri.authority();
if (authority.length === 0) {
return void 0;
}
uri.authority(authority);
if (authority.indexOf("@") !== -1) {
const parts = authority.split("@");
authority = parts[1];
}
if (authority.indexOf(":") === -1) {
let scheme = uri.scheme();
if (scheme.length === 0) {
scheme = window.location.protocol;
scheme = scheme.substring(0, scheme.length - 1);
}
if (scheme === "http") {
authority += ":80";
} else if (scheme === "https") {
authority += ":443";
} else {
return void 0;
}
}
return authority;
}
TrustedServers.contains = function(url2) {
if (!defined_default(url2)) {
throw new DeveloperError_default("url is required.");
}
const authority = getAuthority(url2);
if (defined_default(authority) && defined_default(_servers[authority])) {
return true;
}
return false;
};
TrustedServers.clear = function() {
_servers = {};
};
var TrustedServers_default = TrustedServers;
// packages/engine/Source/Core/Resource.js
var xhrBlobSupported = function() {
try {
const xhr = new XMLHttpRequest();
xhr.open("GET", "#", true);
xhr.responseType = "blob";
return xhr.responseType === "blob";
} catch (e) {
return false;
}
}();
function Resource(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
if (typeof options === "string") {
options = {
url: options
};
}
Check_default.typeOf.string("options.url", options.url);
this._url = void 0;
this._templateValues = defaultClone(options.templateValues, {});
this._queryParameters = defaultClone(options.queryParameters, {});
this.headers = defaultClone(options.headers, {});
this.request = defaultValue_default(options.request, new Request_default());
this.proxy = options.proxy;
this.retryCallback = options.retryCallback;
this.retryAttempts = defaultValue_default(options.retryAttempts, 0);
this._retryCount = 0;
const parseUrl = defaultValue_default(options.parseUrl, true);
if (parseUrl) {
this.parseUrl(options.url, true, true);
} else {
this._url = options.url;
}
}
function defaultClone(value, defaultValue2) {
return defined_default(value) ? clone_default(value) : defaultValue2;
}
Resource.createIfNeeded = function(resource) {
if (resource instanceof Resource) {
return resource.getDerivedResource({
request: resource.request
});
}
if (typeof resource !== "string") {
return resource;
}
return new Resource({
url: resource
});
};
var supportsImageBitmapOptionsPromise;
Resource.supportsImageBitmapOptions = function() {
if (defined_default(supportsImageBitmapOptionsPromise)) {
return supportsImageBitmapOptionsPromise;
}
if (typeof createImageBitmap !== "function") {
supportsImageBitmapOptionsPromise = Promise.resolve(false);
return supportsImageBitmapOptionsPromise;
}
const imageDataUri = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAABGdBTUEAAE4g3rEiDgAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAADElEQVQI12Ng6GAAAAEUAIngE3ZiAAAAAElFTkSuQmCC";
supportsImageBitmapOptionsPromise = Resource.fetchBlob({
url: imageDataUri
}).then(function(blob) {
const imageBitmapOptions = {
imageOrientation: "flipY",
// default is "none"
premultiplyAlpha: "none",
// default is "default"
colorSpaceConversion: "none"
// default is "default"
};
return Promise.all([
createImageBitmap(blob, imageBitmapOptions),
createImageBitmap(blob)
]);
}).then(function(imageBitmaps) {
const colorWithOptions = getImagePixels_default(imageBitmaps[0]);
const colorWithDefaults = getImagePixels_default(imageBitmaps[1]);
return colorWithOptions[1] !== colorWithDefaults[1];
}).catch(function() {
return false;
});
return supportsImageBitmapOptionsPromise;
};
Object.defineProperties(Resource, {
/**
* Returns true if blobs are supported.
*
* @memberof Resource
* @type {boolean}
*
* @readonly
*/
isBlobSupported: {
get: function() {
return xhrBlobSupported;
}
}
});
Object.defineProperties(Resource.prototype, {
/**
* Query parameters appended to the url.
*
* @memberof Resource.prototype
* @type {object}
*
* @readonly
*/
queryParameters: {
get: function() {
return this._queryParameters;
}
},
/**
* The key/value pairs used to replace template parameters in the url.
*
* @memberof Resource.prototype
* @type {object}
*
* @readonly
*/
templateValues: {
get: function() {
return this._templateValues;
}
},
/**
* The url to the resource with template values replaced, query string appended and encoded by proxy if one was set.
*
* @memberof Resource.prototype
* @type {string}
*/
url: {
get: function() {
return this.getUrlComponent(true, true);
},
set: function(value) {
this.parseUrl(value, false, false);
}
},
/**
* The file extension of the resource.
*
* @memberof Resource.prototype
* @type {string}
*
* @readonly
*/
extension: {
get: function() {
return getExtensionFromUri_default(this._url);
}
},
/**
* True if the Resource refers to a data URI.
*
* @memberof Resource.prototype
* @type {boolean}
*/
isDataUri: {
get: function() {
return isDataUri_default(this._url);
}
},
/**
* True if the Resource refers to a blob URI.
*
* @memberof Resource.prototype
* @type {boolean}
*/
isBlobUri: {
get: function() {
return isBlobUri_default(this._url);
}
},
/**
* True if the Resource refers to a cross origin URL.
*
* @memberof Resource.prototype
* @type {boolean}
*/
isCrossOriginUrl: {
get: function() {
return isCrossOriginUrl_default(this._url);
}
},
/**
* True if the Resource has request headers. This is equivalent to checking if the headers property has any keys.
*
* @memberof Resource.prototype
* @type {boolean}
*/
hasHeaders: {
get: function() {
return Object.keys(this.headers).length > 0;
}
}
});
Resource.prototype.toString = function() {
return this.getUrlComponent(true, true);
};
Resource.prototype.parseUrl = function(url2, merge2, preserveQuery, baseUrl) {
let uri = new import_urijs6.default(url2);
const query = parseQueryString(uri.query());
this._queryParameters = merge2 ? combineQueryParameters(query, this.queryParameters, preserveQuery) : query;
uri.search("");
uri.fragment("");
if (defined_default(baseUrl) && uri.scheme() === "") {
uri = uri.absoluteTo(getAbsoluteUri_default(baseUrl));
}
this._url = uri.toString();
};
function parseQueryString(queryString) {
if (queryString.length === 0) {
return {};
}
if (queryString.indexOf("=") === -1) {
return { [queryString]: void 0 };
}
return queryToObject_default(queryString);
}
function combineQueryParameters(q12, q22, preserveQueryParameters) {
if (!preserveQueryParameters) {
return combine_default(q12, q22);
}
const result = clone_default(q12, true);
for (const param in q22) {
if (q22.hasOwnProperty(param)) {
let value = result[param];
const q2Value = q22[param];
if (defined_default(value)) {
if (!Array.isArray(value)) {
value = result[param] = [value];
}
result[param] = value.concat(q2Value);
} else {
result[param] = Array.isArray(q2Value) ? q2Value.slice() : q2Value;
}
}
}
return result;
}
Resource.prototype.getUrlComponent = function(query, proxy) {
if (this.isDataUri) {
return this._url;
}
let url2 = this._url;
if (query) {
url2 = `${url2}${stringifyQuery(this.queryParameters)}`;
}
url2 = url2.replace(/%7B/g, "{").replace(/%7D/g, "}");
const templateValues = this._templateValues;
if (Object.keys(templateValues).length > 0) {
url2 = url2.replace(/{(.*?)}/g, function(match, key) {
const replacement = templateValues[key];
if (defined_default(replacement)) {
return encodeURIComponent(replacement);
}
return match;
});
}
if (proxy && defined_default(this.proxy)) {
url2 = this.proxy.getURL(url2);
}
return url2;
};
function stringifyQuery(queryObject) {
const keys = Object.keys(queryObject);
if (keys.length === 0) {
return "";
}
if (keys.length === 1 && !defined_default(queryObject[keys[0]])) {
return `?${keys[0]}`;
}
return `?${objectToQuery_default(queryObject)}`;
}
Resource.prototype.setQueryParameters = function(params, useAsDefault) {
if (useAsDefault) {
this._queryParameters = combineQueryParameters(
this._queryParameters,
params,
false
);
} else {
this._queryParameters = combineQueryParameters(
params,
this._queryParameters,
false
);
}
};
Resource.prototype.appendQueryParameters = function(params) {
this._queryParameters = combineQueryParameters(
params,
this._queryParameters,
true
);
};
Resource.prototype.setTemplateValues = function(template, useAsDefault) {
if (useAsDefault) {
this._templateValues = combine_default(this._templateValues, template);
} else {
this._templateValues = combine_default(template, this._templateValues);
}
};
Resource.prototype.getDerivedResource = function(options) {
const resource = this.clone();
resource._retryCount = 0;
if (defined_default(options.url)) {
const preserveQuery = defaultValue_default(options.preserveQueryParameters, false);
resource.parseUrl(options.url, true, preserveQuery, this._url);
}
if (defined_default(options.queryParameters)) {
resource._queryParameters = combine_default(
options.queryParameters,
resource.queryParameters
);
}
if (defined_default(options.templateValues)) {
resource._templateValues = combine_default(
options.templateValues,
resource.templateValues
);
}
if (defined_default(options.headers)) {
resource.headers = combine_default(options.headers, resource.headers);
}
if (defined_default(options.proxy)) {
resource.proxy = options.proxy;
}
if (defined_default(options.request)) {
resource.request = options.request;
}
if (defined_default(options.retryCallback)) {
resource.retryCallback = options.retryCallback;
}
if (defined_default(options.retryAttempts)) {
resource.retryAttempts = options.retryAttempts;
}
return resource;
};
Resource.prototype.retryOnError = function(error) {
const retryCallback2 = this.retryCallback;
if (typeof retryCallback2 !== "function" || this._retryCount >= this.retryAttempts) {
return Promise.resolve(false);
}
const that = this;
return Promise.resolve(retryCallback2(this, error)).then(function(result) {
++that._retryCount;
return result;
});
};
Resource.prototype.clone = function(result) {
if (!defined_default(result)) {
return new Resource({
url: this._url,
queryParameters: this.queryParameters,
templateValues: this.templateValues,
headers: this.headers,
proxy: this.proxy,
retryCallback: this.retryCallback,
retryAttempts: this.retryAttempts,
request: this.request.clone(),
parseUrl: false
});
}
result._url = this._url;
result._queryParameters = clone_default(this._queryParameters);
result._templateValues = clone_default(this._templateValues);
result.headers = clone_default(this.headers);
result.proxy = this.proxy;
result.retryCallback = this.retryCallback;
result.retryAttempts = this.retryAttempts;
result._retryCount = 0;
result.request = this.request.clone();
return result;
};
Resource.prototype.getBaseUri = function(includeQuery) {
return getBaseUri_default(this.getUrlComponent(includeQuery), includeQuery);
};
Resource.prototype.appendForwardSlash = function() {
this._url = appendForwardSlash_default(this._url);
};
Resource.prototype.fetchArrayBuffer = function() {
return this.fetch({
responseType: "arraybuffer"
});
};
Resource.fetchArrayBuffer = function(options) {
const resource = new Resource(options);
return resource.fetchArrayBuffer();
};
Resource.prototype.fetchBlob = function() {
return this.fetch({
responseType: "blob"
});
};
Resource.fetchBlob = function(options) {
const resource = new Resource(options);
return resource.fetchBlob();
};
Resource.prototype.fetchImage = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const preferImageBitmap = defaultValue_default(options.preferImageBitmap, false);
const preferBlob = defaultValue_default(options.preferBlob, false);
const flipY = defaultValue_default(options.flipY, false);
const skipColorSpaceConversion = defaultValue_default(
options.skipColorSpaceConversion,
false
);
checkAndResetRequest(this.request);
if (!xhrBlobSupported || this.isDataUri || this.isBlobUri || !this.hasHeaders && !preferBlob) {
return fetchImage({
resource: this,
flipY,
skipColorSpaceConversion,
preferImageBitmap
});
}
const blobPromise = this.fetchBlob();
if (!defined_default(blobPromise)) {
return;
}
let supportsImageBitmap;
let useImageBitmap;
let generatedBlobResource;
let generatedBlob;
return Resource.supportsImageBitmapOptions().then(function(result) {
supportsImageBitmap = result;
useImageBitmap = supportsImageBitmap && preferImageBitmap;
return blobPromise;
}).then(function(blob) {
if (!defined_default(blob)) {
return;
}
generatedBlob = blob;
if (useImageBitmap) {
return Resource.createImageBitmapFromBlob(blob, {
flipY,
premultiplyAlpha: false,
skipColorSpaceConversion
});
}
const blobUrl = window.URL.createObjectURL(blob);
generatedBlobResource = new Resource({
url: blobUrl
});
return fetchImage({
resource: generatedBlobResource,
flipY,
skipColorSpaceConversion,
preferImageBitmap: false
});
}).then(function(image) {
if (!defined_default(image)) {
return;
}
image.blob = generatedBlob;
if (useImageBitmap) {
return image;
}
window.URL.revokeObjectURL(generatedBlobResource.url);
return image;
}).catch(function(error) {
if (defined_default(generatedBlobResource)) {
window.URL.revokeObjectURL(generatedBlobResource.url);
}
error.blob = generatedBlob;
return Promise.reject(error);
});
};
function fetchImage(options) {
const resource = options.resource;
const flipY = options.flipY;
const skipColorSpaceConversion = options.skipColorSpaceConversion;
const preferImageBitmap = options.preferImageBitmap;
const request = resource.request;
request.url = resource.url;
request.requestFunction = function() {
let crossOrigin = false;
if (!resource.isDataUri && !resource.isBlobUri) {
crossOrigin = resource.isCrossOriginUrl;
}
const deferred = defer_default();
Resource._Implementations.createImage(
request,
crossOrigin,
deferred,
flipY,
skipColorSpaceConversion,
preferImageBitmap
);
return deferred.promise;
};
const promise = RequestScheduler_default.request(request);
if (!defined_default(promise)) {
return;
}
return promise.catch(function(e) {
if (request.state !== RequestState_default.FAILED) {
return Promise.reject(e);
}
return resource.retryOnError(e).then(function(retry) {
if (retry) {
request.state = RequestState_default.UNISSUED;
request.deferred = void 0;
return fetchImage({
resource,
flipY,
skipColorSpaceConversion,
preferImageBitmap
});
}
return Promise.reject(e);
});
});
}
Resource.fetchImage = function(options) {
const resource = new Resource(options);
return resource.fetchImage({
flipY: options.flipY,
skipColorSpaceConversion: options.skipColorSpaceConversion,
preferBlob: options.preferBlob,
preferImageBitmap: options.preferImageBitmap
});
};
Resource.prototype.fetchText = function() {
return this.fetch({
responseType: "text"
});
};
Resource.fetchText = function(options) {
const resource = new Resource(options);
return resource.fetchText();
};
Resource.prototype.fetchJson = function() {
const promise = this.fetch({
responseType: "text",
headers: {
Accept: "application/json,*/*;q=0.01"
}
});
if (!defined_default(promise)) {
return void 0;
}
return promise.then(function(value) {
if (!defined_default(value)) {
return;
}
return JSON.parse(value);
});
};
Resource.fetchJson = function(options) {
const resource = new Resource(options);
return resource.fetchJson();
};
Resource.prototype.fetchXML = function() {
return this.fetch({
responseType: "document",
overrideMimeType: "text/xml"
});
};
Resource.fetchXML = function(options) {
const resource = new Resource(options);
return resource.fetchXML();
};
Resource.prototype.fetchJsonp = function(callbackParameterName) {
callbackParameterName = defaultValue_default(callbackParameterName, "callback");
checkAndResetRequest(this.request);
let functionName;
do {
functionName = `loadJsonp${Math_default.nextRandomNumber().toString().substring(2, 8)}`;
} while (defined_default(window[functionName]));
return fetchJsonp(this, callbackParameterName, functionName);
};
function fetchJsonp(resource, callbackParameterName, functionName) {
const callbackQuery = {};
callbackQuery[callbackParameterName] = functionName;
resource.setQueryParameters(callbackQuery);
const request = resource.request;
const url2 = resource.url;
request.url = url2;
request.requestFunction = function() {
const deferred = defer_default();
window[functionName] = function(data) {
deferred.resolve(data);
try {
delete window[functionName];
} catch (e) {
window[functionName] = void 0;
}
};
Resource._Implementations.loadAndExecuteScript(url2, functionName, deferred);
return deferred.promise;
};
const promise = RequestScheduler_default.request(request);
if (!defined_default(promise)) {
return;
}
return promise.catch(function(e) {
if (request.state !== RequestState_default.FAILED) {
return Promise.reject(e);
}
return resource.retryOnError(e).then(function(retry) {
if (retry) {
request.state = RequestState_default.UNISSUED;
request.deferred = void 0;
return fetchJsonp(resource, callbackParameterName, functionName);
}
return Promise.reject(e);
});
});
}
Resource.fetchJsonp = function(options) {
const resource = new Resource(options);
return resource.fetchJsonp(options.callbackParameterName);
};
Resource.prototype._makeRequest = function(options) {
const resource = this;
checkAndResetRequest(resource.request);
const request = resource.request;
const url2 = resource.url;
request.url = url2;
request.requestFunction = function() {
const responseType = options.responseType;
const headers = combine_default(options.headers, resource.headers);
const overrideMimeType = options.overrideMimeType;
const method = options.method;
const data = options.data;
const deferred = defer_default();
const xhr = Resource._Implementations.loadWithXhr(
url2,
responseType,
method,
data,
headers,
deferred,
overrideMimeType
);
if (defined_default(xhr) && defined_default(xhr.abort)) {
request.cancelFunction = function() {
xhr.abort();
};
}
return deferred.promise;
};
const promise = RequestScheduler_default.request(request);
if (!defined_default(promise)) {
return;
}
return promise.then(function(data) {
request.cancelFunction = void 0;
return data;
}).catch(function(e) {
request.cancelFunction = void 0;
if (request.state !== RequestState_default.FAILED) {
return Promise.reject(e);
}
return resource.retryOnError(e).then(function(retry) {
if (retry) {
request.state = RequestState_default.UNISSUED;
request.deferred = void 0;
return resource.fetch(options);
}
return Promise.reject(e);
});
});
};
function checkAndResetRequest(request) {
if (request.state === RequestState_default.ISSUED || request.state === RequestState_default.ACTIVE) {
throw new RuntimeError_default("The Resource is already being fetched.");
}
request.state = RequestState_default.UNISSUED;
request.deferred = void 0;
}
var dataUriRegex2 = /^data:(.*?)(;base64)?,(.*)$/;
function decodeDataUriText(isBase64, data) {
const result = decodeURIComponent(data);
if (isBase64) {
return atob(result);
}
return result;
}
function decodeDataUriArrayBuffer(isBase64, data) {
const byteString = decodeDataUriText(isBase64, data);
const buffer = new ArrayBuffer(byteString.length);
const view = new Uint8Array(buffer);
for (let i = 0; i < byteString.length; i++) {
view[i] = byteString.charCodeAt(i);
}
return buffer;
}
function decodeDataUri(dataUriRegexResult, responseType) {
responseType = defaultValue_default(responseType, "");
const mimeType = dataUriRegexResult[1];
const isBase64 = !!dataUriRegexResult[2];
const data = dataUriRegexResult[3];
let buffer;
let parser3;
switch (responseType) {
case "":
case "text":
return decodeDataUriText(isBase64, data);
case "arraybuffer":
return decodeDataUriArrayBuffer(isBase64, data);
case "blob":
buffer = decodeDataUriArrayBuffer(isBase64, data);
return new Blob([buffer], {
type: mimeType
});
case "document":
parser3 = new DOMParser();
return parser3.parseFromString(
decodeDataUriText(isBase64, data),
mimeType
);
case "json":
return JSON.parse(decodeDataUriText(isBase64, data));
default:
throw new DeveloperError_default(`Unhandled responseType: ${responseType}`);
}
}
Resource.prototype.fetch = function(options) {
options = defaultClone(options, {});
options.method = "GET";
return this._makeRequest(options);
};
Resource.fetch = function(options) {
const resource = new Resource(options);
return resource.fetch({
// Make copy of just the needed fields because headers can be passed to both the constructor and to fetch
responseType: options.responseType,
overrideMimeType: options.overrideMimeType
});
};
Resource.prototype.delete = function(options) {
options = defaultClone(options, {});
options.method = "DELETE";
return this._makeRequest(options);
};
Resource.delete = function(options) {
const resource = new Resource(options);
return resource.delete({
// Make copy of just the needed fields because headers can be passed to both the constructor and to fetch
responseType: options.responseType,
overrideMimeType: options.overrideMimeType,
data: options.data
});
};
Resource.prototype.head = function(options) {
options = defaultClone(options, {});
options.method = "HEAD";
return this._makeRequest(options);
};
Resource.head = function(options) {
const resource = new Resource(options);
return resource.head({
// Make copy of just the needed fields because headers can be passed to both the constructor and to fetch
responseType: options.responseType,
overrideMimeType: options.overrideMimeType
});
};
Resource.prototype.options = function(options) {
options = defaultClone(options, {});
options.method = "OPTIONS";
return this._makeRequest(options);
};
Resource.options = function(options) {
const resource = new Resource(options);
return resource.options({
// Make copy of just the needed fields because headers can be passed to both the constructor and to fetch
responseType: options.responseType,
overrideMimeType: options.overrideMimeType
});
};
Resource.prototype.post = function(data, options) {
Check_default.defined("data", data);
options = defaultClone(options, {});
options.method = "POST";
options.data = data;
return this._makeRequest(options);
};
Resource.post = function(options) {
const resource = new Resource(options);
return resource.post(options.data, {
// Make copy of just the needed fields because headers can be passed to both the constructor and to post
responseType: options.responseType,
overrideMimeType: options.overrideMimeType
});
};
Resource.prototype.put = function(data, options) {
Check_default.defined("data", data);
options = defaultClone(options, {});
options.method = "PUT";
options.data = data;
return this._makeRequest(options);
};
Resource.put = function(options) {
const resource = new Resource(options);
return resource.put(options.data, {
// Make copy of just the needed fields because headers can be passed to both the constructor and to post
responseType: options.responseType,
overrideMimeType: options.overrideMimeType
});
};
Resource.prototype.patch = function(data, options) {
Check_default.defined("data", data);
options = defaultClone(options, {});
options.method = "PATCH";
options.data = data;
return this._makeRequest(options);
};
Resource.patch = function(options) {
const resource = new Resource(options);
return resource.patch(options.data, {
// Make copy of just the needed fields because headers can be passed to both the constructor and to post
responseType: options.responseType,
overrideMimeType: options.overrideMimeType
});
};
Resource._Implementations = {};
Resource._Implementations.loadImageElement = function(url2, crossOrigin, deferred) {
const image = new Image();
image.onload = function() {
if (image.naturalWidth === 0 && image.naturalHeight === 0 && image.width === 0 && image.height === 0) {
image.width = 300;
image.height = 150;
}
deferred.resolve(image);
};
image.onerror = function(e) {
deferred.reject(e);
};
if (crossOrigin) {
if (TrustedServers_default.contains(url2)) {
image.crossOrigin = "use-credentials";
} else {
image.crossOrigin = "";
}
}
image.src = url2;
};
Resource._Implementations.createImage = function(request, crossOrigin, deferred, flipY, skipColorSpaceConversion, preferImageBitmap) {
const url2 = request.url;
Resource.supportsImageBitmapOptions().then(function(supportsImageBitmap) {
if (!(supportsImageBitmap && preferImageBitmap)) {
Resource._Implementations.loadImageElement(url2, crossOrigin, deferred);
return;
}
const responseType = "blob";
const method = "GET";
const xhrDeferred = defer_default();
const xhr = Resource._Implementations.loadWithXhr(
url2,
responseType,
method,
void 0,
void 0,
xhrDeferred,
void 0,
void 0,
void 0
);
if (defined_default(xhr) && defined_default(xhr.abort)) {
request.cancelFunction = function() {
xhr.abort();
};
}
return xhrDeferred.promise.then(function(blob) {
if (!defined_default(blob)) {
deferred.reject(
new RuntimeError_default(
`Successfully retrieved ${url2} but it contained no content.`
)
);
return;
}
return Resource.createImageBitmapFromBlob(blob, {
flipY,
premultiplyAlpha: false,
skipColorSpaceConversion
});
}).then(function(image) {
deferred.resolve(image);
});
}).catch(function(e) {
deferred.reject(e);
});
};
Resource.createImageBitmapFromBlob = function(blob, options) {
Check_default.defined("options", options);
Check_default.typeOf.bool("options.flipY", options.flipY);
Check_default.typeOf.bool("options.premultiplyAlpha", options.premultiplyAlpha);
Check_default.typeOf.bool(
"options.skipColorSpaceConversion",
options.skipColorSpaceConversion
);
return createImageBitmap(blob, {
imageOrientation: options.flipY ? "flipY" : "none",
premultiplyAlpha: options.premultiplyAlpha ? "premultiply" : "none",
colorSpaceConversion: options.skipColorSpaceConversion ? "none" : "default"
});
};
function decodeResponse(loadWithHttpResponse, responseType) {
switch (responseType) {
case "text":
return loadWithHttpResponse.toString("utf8");
case "json":
return JSON.parse(loadWithHttpResponse.toString("utf8"));
default:
return new Uint8Array(loadWithHttpResponse).buffer;
}
}
function loadWithHttpRequest(url2, responseType, method, data, headers, deferred, overrideMimeType) {
let URL2;
let zlib;
Promise.all([import("url"), import("zlib")]).then(([urlImport, zlibImport]) => {
URL2 = urlImport.parse(url2);
zlib = zlibImport;
return URL2.protocol === "https:" ? import("https") : import("http");
}).then((http) => {
const options = {
protocol: URL2.protocol,
hostname: URL2.hostname,
port: URL2.port,
path: URL2.path,
query: URL2.query,
method,
headers
};
http.request(options).on("response", function(res) {
if (res.statusCode < 200 || res.statusCode >= 300) {
deferred.reject(
new RequestErrorEvent_default(res.statusCode, res, res.headers)
);
return;
}
const chunkArray = [];
res.on("data", function(chunk) {
chunkArray.push(chunk);
});
res.on("end", function() {
const result = Buffer.concat(chunkArray);
if (res.headers["content-encoding"] === "gzip") {
zlib.gunzip(result, function(error, resultUnzipped) {
if (error) {
deferred.reject(
new RuntimeError_default("Error decompressing response.")
);
} else {
deferred.resolve(
decodeResponse(resultUnzipped, responseType)
);
}
});
} else {
deferred.resolve(decodeResponse(result, responseType));
}
});
}).on("error", function(e) {
deferred.reject(new RequestErrorEvent_default());
}).end();
});
}
var noXMLHttpRequest = typeof XMLHttpRequest === "undefined";
Resource._Implementations.loadWithXhr = function(url2, responseType, method, data, headers, deferred, overrideMimeType) {
const dataUriRegexResult = dataUriRegex2.exec(url2);
if (dataUriRegexResult !== null) {
deferred.resolve(decodeDataUri(dataUriRegexResult, responseType));
return;
}
if (noXMLHttpRequest) {
loadWithHttpRequest(
url2,
responseType,
method,
data,
headers,
deferred,
overrideMimeType
);
return;
}
const xhr = new XMLHttpRequest();
if (TrustedServers_default.contains(url2)) {
xhr.withCredentials = true;
}
xhr.open(method, url2, true);
if (defined_default(overrideMimeType) && defined_default(xhr.overrideMimeType)) {
xhr.overrideMimeType(overrideMimeType);
}
if (defined_default(headers)) {
for (const key in headers) {
if (headers.hasOwnProperty(key)) {
xhr.setRequestHeader(key, headers[key]);
}
}
}
if (defined_default(responseType)) {
xhr.responseType = responseType;
}
let localFile = false;
if (typeof url2 === "string") {
localFile = url2.indexOf("file://") === 0 || typeof window !== "undefined" && window.location.origin === "file://";
}
xhr.onload = function() {
if ((xhr.status < 200 || xhr.status >= 300) && !(localFile && xhr.status === 0)) {
deferred.reject(
new RequestErrorEvent_default(
xhr.status,
xhr.response,
xhr.getAllResponseHeaders()
)
);
return;
}
const response = xhr.response;
const browserResponseType = xhr.responseType;
if (method === "HEAD" || method === "OPTIONS") {
const responseHeaderString = xhr.getAllResponseHeaders();
const splitHeaders = responseHeaderString.trim().split(/[\r\n]+/);
const responseHeaders = {};
splitHeaders.forEach(function(line) {
const parts = line.split(": ");
const header = parts.shift();
responseHeaders[header] = parts.join(": ");
});
deferred.resolve(responseHeaders);
return;
}
if (xhr.status === 204) {
deferred.resolve();
} else if (defined_default(response) && (!defined_default(responseType) || browserResponseType === responseType)) {
deferred.resolve(response);
} else if (responseType === "json" && typeof response === "string") {
try {
deferred.resolve(JSON.parse(response));
} catch (e) {
deferred.reject(e);
}
} else if ((browserResponseType === "" || browserResponseType === "document") && defined_default(xhr.responseXML) && xhr.responseXML.hasChildNodes()) {
deferred.resolve(xhr.responseXML);
} else if ((browserResponseType === "" || browserResponseType === "text") && defined_default(xhr.responseText)) {
deferred.resolve(xhr.responseText);
} else {
deferred.reject(
new RuntimeError_default("Invalid XMLHttpRequest response type.")
);
}
};
xhr.onerror = function(e) {
deferred.reject(new RequestErrorEvent_default());
};
xhr.send(data);
return xhr;
};
Resource._Implementations.loadAndExecuteScript = function(url2, functionName, deferred) {
return loadAndExecuteScript_default(url2, functionName).catch(function(e) {
deferred.reject(e);
});
};
Resource._DefaultImplementations = {};
Resource._DefaultImplementations.createImage = Resource._Implementations.createImage;
Resource._DefaultImplementations.loadWithXhr = Resource._Implementations.loadWithXhr;
Resource._DefaultImplementations.loadAndExecuteScript = Resource._Implementations.loadAndExecuteScript;
Resource.DEFAULT = Object.freeze(
new Resource({
url: typeof document === "undefined" ? "" : document.location.href.split("?")[0]
})
);
var Resource_default = Resource;
// packages/engine/Source/Core/EarthOrientationParameters.js
function EarthOrientationParameters(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this._dates = void 0;
this._samples = void 0;
this._dateColumn = -1;
this._xPoleWanderRadiansColumn = -1;
this._yPoleWanderRadiansColumn = -1;
this._ut1MinusUtcSecondsColumn = -1;
this._xCelestialPoleOffsetRadiansColumn = -1;
this._yCelestialPoleOffsetRadiansColumn = -1;
this._taiMinusUtcSecondsColumn = -1;
this._columnCount = 0;
this._lastIndex = -1;
this._addNewLeapSeconds = defaultValue_default(options.addNewLeapSeconds, true);
if (defined_default(options.data)) {
onDataReady(this, options.data);
} else {
onDataReady(this, {
columnNames: [
"dateIso8601",
"modifiedJulianDateUtc",
"xPoleWanderRadians",
"yPoleWanderRadians",
"ut1MinusUtcSeconds",
"lengthOfDayCorrectionSeconds",
"xCelestialPoleOffsetRadians",
"yCelestialPoleOffsetRadians",
"taiMinusUtcSeconds"
],
samples: []
});
}
}
EarthOrientationParameters.fromUrl = async function(url2, options) {
Check_default.defined("url", url2);
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const resource = Resource_default.createIfNeeded(url2);
let eopData;
try {
eopData = await resource.fetchJson();
} catch (e) {
throw new RuntimeError_default(
`An error occurred while retrieving the EOP data from the URL ${resource.url}.`
);
}
return new EarthOrientationParameters({
addNewLeapSeconds: options.addNewLeapSeconds,
data: eopData
});
};
EarthOrientationParameters.NONE = Object.freeze({
compute: function(date, result) {
if (!defined_default(result)) {
result = new EarthOrientationParametersSample_default(0, 0, 0, 0, 0);
} else {
result.xPoleWander = 0;
result.yPoleWander = 0;
result.xPoleOffset = 0;
result.yPoleOffset = 0;
result.ut1MinusUtc = 0;
}
return result;
}
});
EarthOrientationParameters.prototype.compute = function(date, result) {
if (!defined_default(this._samples)) {
return void 0;
}
if (!defined_default(result)) {
result = new EarthOrientationParametersSample_default(0, 0, 0, 0, 0);
}
if (this._samples.length === 0) {
result.xPoleWander = 0;
result.yPoleWander = 0;
result.xPoleOffset = 0;
result.yPoleOffset = 0;
result.ut1MinusUtc = 0;
return result;
}
const dates = this._dates;
const lastIndex = this._lastIndex;
let before = 0;
let after = 0;
if (defined_default(lastIndex)) {
const previousIndexDate = dates[lastIndex];
const nextIndexDate = dates[lastIndex + 1];
const isAfterPrevious = JulianDate_default.lessThanOrEquals(
previousIndexDate,
date
);
const isAfterLastSample = !defined_default(nextIndexDate);
const isBeforeNext = isAfterLastSample || JulianDate_default.greaterThanOrEquals(nextIndexDate, date);
if (isAfterPrevious && isBeforeNext) {
before = lastIndex;
if (!isAfterLastSample && nextIndexDate.equals(date)) {
++before;
}
after = before + 1;
interpolate(this, dates, this._samples, date, before, after, result);
return result;
}
}
let index = binarySearch_default(dates, date, JulianDate_default.compare, this._dateColumn);
if (index >= 0) {
if (index < dates.length - 1 && dates[index + 1].equals(date)) {
++index;
}
before = index;
after = index;
} else {
after = ~index;
before = after - 1;
if (before < 0) {
before = 0;
}
}
this._lastIndex = before;
interpolate(this, dates, this._samples, date, before, after, result);
return result;
};
function compareLeapSecondDates2(leapSecond, dateToFind) {
return JulianDate_default.compare(leapSecond.julianDate, dateToFind);
}
function onDataReady(eop, eopData) {
if (!defined_default(eopData.columnNames)) {
throw new RuntimeError_default(
"Error in loaded EOP data: The columnNames property is required."
);
}
if (!defined_default(eopData.samples)) {
throw new RuntimeError_default(
"Error in loaded EOP data: The samples property is required."
);
}
const dateColumn = eopData.columnNames.indexOf("modifiedJulianDateUtc");
const xPoleWanderRadiansColumn = eopData.columnNames.indexOf(
"xPoleWanderRadians"
);
const yPoleWanderRadiansColumn = eopData.columnNames.indexOf(
"yPoleWanderRadians"
);
const ut1MinusUtcSecondsColumn = eopData.columnNames.indexOf(
"ut1MinusUtcSeconds"
);
const xCelestialPoleOffsetRadiansColumn = eopData.columnNames.indexOf(
"xCelestialPoleOffsetRadians"
);
const yCelestialPoleOffsetRadiansColumn = eopData.columnNames.indexOf(
"yCelestialPoleOffsetRadians"
);
const taiMinusUtcSecondsColumn = eopData.columnNames.indexOf(
"taiMinusUtcSeconds"
);
if (dateColumn < 0 || xPoleWanderRadiansColumn < 0 || yPoleWanderRadiansColumn < 0 || ut1MinusUtcSecondsColumn < 0 || xCelestialPoleOffsetRadiansColumn < 0 || yCelestialPoleOffsetRadiansColumn < 0 || taiMinusUtcSecondsColumn < 0) {
throw new RuntimeError_default(
"Error in loaded EOP data: The columnNames property must include modifiedJulianDateUtc, xPoleWanderRadians, yPoleWanderRadians, ut1MinusUtcSeconds, xCelestialPoleOffsetRadians, yCelestialPoleOffsetRadians, and taiMinusUtcSeconds columns"
);
}
const samples = eop._samples = eopData.samples;
const dates = eop._dates = [];
eop._dateColumn = dateColumn;
eop._xPoleWanderRadiansColumn = xPoleWanderRadiansColumn;
eop._yPoleWanderRadiansColumn = yPoleWanderRadiansColumn;
eop._ut1MinusUtcSecondsColumn = ut1MinusUtcSecondsColumn;
eop._xCelestialPoleOffsetRadiansColumn = xCelestialPoleOffsetRadiansColumn;
eop._yCelestialPoleOffsetRadiansColumn = yCelestialPoleOffsetRadiansColumn;
eop._taiMinusUtcSecondsColumn = taiMinusUtcSecondsColumn;
eop._columnCount = eopData.columnNames.length;
eop._lastIndex = void 0;
let lastTaiMinusUtc;
const addNewLeapSeconds = eop._addNewLeapSeconds;
for (let i = 0, len = samples.length; i < len; i += eop._columnCount) {
const mjd = samples[i + dateColumn];
const taiMinusUtc = samples[i + taiMinusUtcSecondsColumn];
const day = mjd + TimeConstants_default.MODIFIED_JULIAN_DATE_DIFFERENCE;
const date = new JulianDate_default(day, taiMinusUtc, TimeStandard_default.TAI);
dates.push(date);
if (addNewLeapSeconds) {
if (taiMinusUtc !== lastTaiMinusUtc && defined_default(lastTaiMinusUtc)) {
const leapSeconds = JulianDate_default.leapSeconds;
const leapSecondIndex = binarySearch_default(
leapSeconds,
date,
compareLeapSecondDates2
);
if (leapSecondIndex < 0) {
const leapSecond = new LeapSecond_default(date, taiMinusUtc);
leapSeconds.splice(~leapSecondIndex, 0, leapSecond);
}
}
lastTaiMinusUtc = taiMinusUtc;
}
}
}
function fillResultFromIndex(eop, samples, index, columnCount, result) {
const start = index * columnCount;
result.xPoleWander = samples[start + eop._xPoleWanderRadiansColumn];
result.yPoleWander = samples[start + eop._yPoleWanderRadiansColumn];
result.xPoleOffset = samples[start + eop._xCelestialPoleOffsetRadiansColumn];
result.yPoleOffset = samples[start + eop._yCelestialPoleOffsetRadiansColumn];
result.ut1MinusUtc = samples[start + eop._ut1MinusUtcSecondsColumn];
}
function linearInterp(dx, y1, y2) {
return y1 + dx * (y2 - y1);
}
function interpolate(eop, dates, samples, date, before, after, result) {
const columnCount = eop._columnCount;
if (after > dates.length - 1) {
result.xPoleWander = 0;
result.yPoleWander = 0;
result.xPoleOffset = 0;
result.yPoleOffset = 0;
result.ut1MinusUtc = 0;
return result;
}
const beforeDate = dates[before];
const afterDate = dates[after];
if (beforeDate.equals(afterDate) || date.equals(beforeDate)) {
fillResultFromIndex(eop, samples, before, columnCount, result);
return result;
} else if (date.equals(afterDate)) {
fillResultFromIndex(eop, samples, after, columnCount, result);
return result;
}
const factor2 = JulianDate_default.secondsDifference(date, beforeDate) / JulianDate_default.secondsDifference(afterDate, beforeDate);
const startBefore = before * columnCount;
const startAfter = after * columnCount;
let beforeUt1MinusUtc = samples[startBefore + eop._ut1MinusUtcSecondsColumn];
let afterUt1MinusUtc = samples[startAfter + eop._ut1MinusUtcSecondsColumn];
const offsetDifference = afterUt1MinusUtc - beforeUt1MinusUtc;
if (offsetDifference > 0.5 || offsetDifference < -0.5) {
const beforeTaiMinusUtc = samples[startBefore + eop._taiMinusUtcSecondsColumn];
const afterTaiMinusUtc = samples[startAfter + eop._taiMinusUtcSecondsColumn];
if (beforeTaiMinusUtc !== afterTaiMinusUtc) {
if (afterDate.equals(date)) {
beforeUt1MinusUtc = afterUt1MinusUtc;
} else {
afterUt1MinusUtc -= afterTaiMinusUtc - beforeTaiMinusUtc;
}
}
}
result.xPoleWander = linearInterp(
factor2,
samples[startBefore + eop._xPoleWanderRadiansColumn],
samples[startAfter + eop._xPoleWanderRadiansColumn]
);
result.yPoleWander = linearInterp(
factor2,
samples[startBefore + eop._yPoleWanderRadiansColumn],
samples[startAfter + eop._yPoleWanderRadiansColumn]
);
result.xPoleOffset = linearInterp(
factor2,
samples[startBefore + eop._xCelestialPoleOffsetRadiansColumn],
samples[startAfter + eop._xCelestialPoleOffsetRadiansColumn]
);
result.yPoleOffset = linearInterp(
factor2,
samples[startBefore + eop._yCelestialPoleOffsetRadiansColumn],
samples[startAfter + eop._yCelestialPoleOffsetRadiansColumn]
);
result.ut1MinusUtc = linearInterp(
factor2,
beforeUt1MinusUtc,
afterUt1MinusUtc
);
return result;
}
var EarthOrientationParameters_default = EarthOrientationParameters;
// packages/engine/Source/Core/HeadingPitchRoll.js
function HeadingPitchRoll(heading, pitch, roll) {
this.heading = defaultValue_default(heading, 0);
this.pitch = defaultValue_default(pitch, 0);
this.roll = defaultValue_default(roll, 0);
}
HeadingPitchRoll.fromQuaternion = function(quaternion, result) {
if (!defined_default(quaternion)) {
throw new DeveloperError_default("quaternion is required");
}
if (!defined_default(result)) {
result = new HeadingPitchRoll();
}
const test = 2 * (quaternion.w * quaternion.y - quaternion.z * quaternion.x);
const denominatorRoll = 1 - 2 * (quaternion.x * quaternion.x + quaternion.y * quaternion.y);
const numeratorRoll = 2 * (quaternion.w * quaternion.x + quaternion.y * quaternion.z);
const denominatorHeading = 1 - 2 * (quaternion.y * quaternion.y + quaternion.z * quaternion.z);
const numeratorHeading = 2 * (quaternion.w * quaternion.z + quaternion.x * quaternion.y);
result.heading = -Math.atan2(numeratorHeading, denominatorHeading);
result.roll = Math.atan2(numeratorRoll, denominatorRoll);
result.pitch = -Math_default.asinClamped(test);
return result;
};
HeadingPitchRoll.fromDegrees = function(heading, pitch, roll, result) {
if (!defined_default(heading)) {
throw new DeveloperError_default("heading is required");
}
if (!defined_default(pitch)) {
throw new DeveloperError_default("pitch is required");
}
if (!defined_default(roll)) {
throw new DeveloperError_default("roll is required");
}
if (!defined_default(result)) {
result = new HeadingPitchRoll();
}
result.heading = heading * Math_default.RADIANS_PER_DEGREE;
result.pitch = pitch * Math_default.RADIANS_PER_DEGREE;
result.roll = roll * Math_default.RADIANS_PER_DEGREE;
return result;
};
HeadingPitchRoll.clone = function(headingPitchRoll, result) {
if (!defined_default(headingPitchRoll)) {
return void 0;
}
if (!defined_default(result)) {
return new HeadingPitchRoll(
headingPitchRoll.heading,
headingPitchRoll.pitch,
headingPitchRoll.roll
);
}
result.heading = headingPitchRoll.heading;
result.pitch = headingPitchRoll.pitch;
result.roll = headingPitchRoll.roll;
return result;
};
HeadingPitchRoll.equals = function(left, right) {
return left === right || defined_default(left) && defined_default(right) && left.heading === right.heading && left.pitch === right.pitch && left.roll === right.roll;
};
HeadingPitchRoll.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
return left === right || defined_default(left) && defined_default(right) && Math_default.equalsEpsilon(
left.heading,
right.heading,
relativeEpsilon,
absoluteEpsilon
) && Math_default.equalsEpsilon(
left.pitch,
right.pitch,
relativeEpsilon,
absoluteEpsilon
) && Math_default.equalsEpsilon(
left.roll,
right.roll,
relativeEpsilon,
absoluteEpsilon
);
};
HeadingPitchRoll.prototype.clone = function(result) {
return HeadingPitchRoll.clone(this, result);
};
HeadingPitchRoll.prototype.equals = function(right) {
return HeadingPitchRoll.equals(this, right);
};
HeadingPitchRoll.prototype.equalsEpsilon = function(right, relativeEpsilon, absoluteEpsilon) {
return HeadingPitchRoll.equalsEpsilon(
this,
right,
relativeEpsilon,
absoluteEpsilon
);
};
HeadingPitchRoll.prototype.toString = function() {
return `(${this.heading}, ${this.pitch}, ${this.roll})`;
};
var HeadingPitchRoll_default = HeadingPitchRoll;
// packages/engine/Source/Core/buildModuleUrl.js
var cesiumScriptRegex = /((?:.*\/)|^)Cesium\.js(?:\?|\#|$)/;
function getBaseUrlFromCesiumScript() {
const scripts = document.getElementsByTagName("script");
for (let i = 0, len = scripts.length; i < len; ++i) {
const src = scripts[i].getAttribute("src");
const result = cesiumScriptRegex.exec(src);
if (result !== null) {
return result[1];
}
}
return void 0;
}
var a2;
function tryMakeAbsolute(url2) {
if (typeof document === "undefined") {
return url2;
}
if (!defined_default(a2)) {
a2 = document.createElement("a");
}
a2.href = url2;
a2.href = a2.href;
return a2.href;
}
var baseResource;
function getCesiumBaseUrl() {
if (defined_default(baseResource)) {
return baseResource;
}
let baseUrlString;
if (typeof CESIUM_BASE_URL !== "undefined") {
baseUrlString = CESIUM_BASE_URL;
} else if (typeof define === "object" && defined_default(define.amd) && !define.amd.toUrlUndefined && defined_default(__require.toUrl)) {
baseUrlString = getAbsoluteUri_default(
"..",
buildModuleUrl("Core/buildModuleUrl.js")
);
} else {
baseUrlString = getBaseUrlFromCesiumScript();
}
if (!defined_default(baseUrlString)) {
throw new DeveloperError_default(
"Unable to determine Cesium base URL automatically, try defining a global variable called CESIUM_BASE_URL."
);
}
baseResource = new Resource_default({
url: tryMakeAbsolute(baseUrlString)
});
baseResource.appendForwardSlash();
return baseResource;
}
function buildModuleUrlFromRequireToUrl(moduleID) {
return tryMakeAbsolute(__require.toUrl(`../${moduleID}`));
}
function buildModuleUrlFromBaseUrl(moduleID) {
const resource = getCesiumBaseUrl().getDerivedResource({
url: moduleID
});
return resource.url;
}
var implementation;
function buildModuleUrl(relativeUrl) {
if (!defined_default(implementation)) {
if (typeof define === "object" && defined_default(define.amd) && !define.amd.toUrlUndefined && defined_default(__require.toUrl)) {
implementation = buildModuleUrlFromRequireToUrl;
} else {
implementation = buildModuleUrlFromBaseUrl;
}
}
const url2 = implementation(relativeUrl);
return url2;
}
buildModuleUrl._cesiumScriptRegex = cesiumScriptRegex;
buildModuleUrl._buildModuleUrlFromBaseUrl = buildModuleUrlFromBaseUrl;
buildModuleUrl._clearBaseResource = function() {
baseResource = void 0;
};
buildModuleUrl.setBaseUrl = function(value) {
baseResource = Resource_default.DEFAULT.getDerivedResource({
url: value
});
};
buildModuleUrl.getCesiumBaseUrl = getCesiumBaseUrl;
var buildModuleUrl_default = buildModuleUrl;
// packages/engine/Source/Core/Iau2006XysSample.js
function Iau2006XysSample(x, y, s) {
this.x = x;
this.y = y;
this.s = s;
}
var Iau2006XysSample_default = Iau2006XysSample;
// packages/engine/Source/Core/Iau2006XysData.js
function Iau2006XysData(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this._xysFileUrlTemplate = Resource_default.createIfNeeded(
options.xysFileUrlTemplate
);
this._interpolationOrder = defaultValue_default(options.interpolationOrder, 9);
this._sampleZeroJulianEphemerisDate = defaultValue_default(
options.sampleZeroJulianEphemerisDate,
24423965e-1
);
this._sampleZeroDateTT = new JulianDate_default(
this._sampleZeroJulianEphemerisDate,
0,
TimeStandard_default.TAI
);
this._stepSizeDays = defaultValue_default(options.stepSizeDays, 1);
this._samplesPerXysFile = defaultValue_default(options.samplesPerXysFile, 1e3);
this._totalSamples = defaultValue_default(options.totalSamples, 27426);
this._samples = new Array(this._totalSamples * 3);
this._chunkDownloadsInProgress = [];
const order = this._interpolationOrder;
const denom = this._denominators = new Array(order + 1);
const xTable = this._xTable = new Array(order + 1);
const stepN = Math.pow(this._stepSizeDays, order);
for (let i = 0; i <= order; ++i) {
denom[i] = stepN;
xTable[i] = i * this._stepSizeDays;
for (let j = 0; j <= order; ++j) {
if (j !== i) {
denom[i] *= i - j;
}
}
denom[i] = 1 / denom[i];
}
this._work = new Array(order + 1);
this._coef = new Array(order + 1);
}
var julianDateScratch = new JulianDate_default(0, 0, TimeStandard_default.TAI);
function getDaysSinceEpoch(xys, dayTT, secondTT) {
const dateTT2 = julianDateScratch;
dateTT2.dayNumber = dayTT;
dateTT2.secondsOfDay = secondTT;
return JulianDate_default.daysDifference(dateTT2, xys._sampleZeroDateTT);
}
Iau2006XysData.prototype.preload = function(startDayTT, startSecondTT, stopDayTT, stopSecondTT) {
const startDaysSinceEpoch = getDaysSinceEpoch(
this,
startDayTT,
startSecondTT
);
const stopDaysSinceEpoch = getDaysSinceEpoch(this, stopDayTT, stopSecondTT);
let startIndex = startDaysSinceEpoch / this._stepSizeDays - this._interpolationOrder / 2 | 0;
if (startIndex < 0) {
startIndex = 0;
}
let stopIndex = stopDaysSinceEpoch / this._stepSizeDays - this._interpolationOrder / 2 | 0 + this._interpolationOrder;
if (stopIndex >= this._totalSamples) {
stopIndex = this._totalSamples - 1;
}
const startChunk = startIndex / this._samplesPerXysFile | 0;
const stopChunk = stopIndex / this._samplesPerXysFile | 0;
const promises = [];
for (let i = startChunk; i <= stopChunk; ++i) {
promises.push(requestXysChunk(this, i));
}
return Promise.all(promises);
};
Iau2006XysData.prototype.computeXysRadians = function(dayTT, secondTT, result) {
const daysSinceEpoch = getDaysSinceEpoch(this, dayTT, secondTT);
if (daysSinceEpoch < 0) {
return void 0;
}
const centerIndex = daysSinceEpoch / this._stepSizeDays | 0;
if (centerIndex >= this._totalSamples) {
return void 0;
}
const degree = this._interpolationOrder;
let firstIndex = centerIndex - (degree / 2 | 0);
if (firstIndex < 0) {
firstIndex = 0;
}
let lastIndex = firstIndex + degree;
if (lastIndex >= this._totalSamples) {
lastIndex = this._totalSamples - 1;
firstIndex = lastIndex - degree;
if (firstIndex < 0) {
firstIndex = 0;
}
}
let isDataMissing = false;
const samples = this._samples;
if (!defined_default(samples[firstIndex * 3])) {
requestXysChunk(this, firstIndex / this._samplesPerXysFile | 0);
isDataMissing = true;
}
if (!defined_default(samples[lastIndex * 3])) {
requestXysChunk(this, lastIndex / this._samplesPerXysFile | 0);
isDataMissing = true;
}
if (isDataMissing) {
return void 0;
}
if (!defined_default(result)) {
result = new Iau2006XysSample_default(0, 0, 0);
} else {
result.x = 0;
result.y = 0;
result.s = 0;
}
const x = daysSinceEpoch - firstIndex * this._stepSizeDays;
const work = this._work;
const denom = this._denominators;
const coef = this._coef;
const xTable = this._xTable;
let i, j;
for (i = 0; i <= degree; ++i) {
work[i] = x - xTable[i];
}
for (i = 0; i <= degree; ++i) {
coef[i] = 1;
for (j = 0; j <= degree; ++j) {
if (j !== i) {
coef[i] *= work[j];
}
}
coef[i] *= denom[i];
let sampleIndex = (firstIndex + i) * 3;
result.x += coef[i] * samples[sampleIndex++];
result.y += coef[i] * samples[sampleIndex++];
result.s += coef[i] * samples[sampleIndex];
}
return result;
};
function requestXysChunk(xysData, chunkIndex) {
if (xysData._chunkDownloadsInProgress[chunkIndex]) {
return xysData._chunkDownloadsInProgress[chunkIndex];
}
let chunkUrl;
const xysFileUrlTemplate = xysData._xysFileUrlTemplate;
if (defined_default(xysFileUrlTemplate)) {
chunkUrl = xysFileUrlTemplate.getDerivedResource({
templateValues: {
0: chunkIndex
}
});
} else {
chunkUrl = new Resource_default({
url: buildModuleUrl_default(`Assets/IAU2006_XYS/IAU2006_XYS_${chunkIndex}.json`)
});
}
const promise = chunkUrl.fetchJson().then(function(chunk) {
xysData._chunkDownloadsInProgress[chunkIndex] = false;
const samples = xysData._samples;
const newSamples = chunk.samples;
const startIndex = chunkIndex * xysData._samplesPerXysFile * 3;
for (let i = 0, len = newSamples.length; i < len; ++i) {
samples[startIndex + i] = newSamples[i];
}
});
xysData._chunkDownloadsInProgress[chunkIndex] = promise;
return promise;
}
var Iau2006XysData_default = Iau2006XysData;
// packages/engine/Source/Core/Transforms.js
var Transforms = {};
var vectorProductLocalFrame = {
up: {
south: "east",
north: "west",
west: "south",
east: "north"
},
down: {
south: "west",
north: "east",
west: "north",
east: "south"
},
south: {
up: "west",
down: "east",
west: "down",
east: "up"
},
north: {
up: "east",
down: "west",
west: "up",
east: "down"
},
west: {
up: "north",
down: "south",
north: "down",
south: "up"
},
east: {
up: "south",
down: "north",
north: "up",
south: "down"
}
};
var degeneratePositionLocalFrame = {
north: [-1, 0, 0],
east: [0, 1, 0],
up: [0, 0, 1],
south: [1, 0, 0],
west: [0, -1, 0],
down: [0, 0, -1]
};
var localFrameToFixedFrameCache = {};
var scratchCalculateCartesian = {
east: new Cartesian3_default(),
north: new Cartesian3_default(),
up: new Cartesian3_default(),
west: new Cartesian3_default(),
south: new Cartesian3_default(),
down: new Cartesian3_default()
};
var scratchFirstCartesian = new Cartesian3_default();
var scratchSecondCartesian = new Cartesian3_default();
var scratchThirdCartesian = new Cartesian3_default();
Transforms.localFrameToFixedFrameGenerator = function(firstAxis, secondAxis) {
if (!vectorProductLocalFrame.hasOwnProperty(firstAxis) || !vectorProductLocalFrame[firstAxis].hasOwnProperty(secondAxis)) {
throw new DeveloperError_default(
"firstAxis and secondAxis must be east, north, up, west, south or down."
);
}
const thirdAxis = vectorProductLocalFrame[firstAxis][secondAxis];
let resultat;
const hashAxis = firstAxis + secondAxis;
if (defined_default(localFrameToFixedFrameCache[hashAxis])) {
resultat = localFrameToFixedFrameCache[hashAxis];
} else {
resultat = function(origin, ellipsoid, result) {
if (!defined_default(origin)) {
throw new DeveloperError_default("origin is required.");
}
if (!defined_default(result)) {
result = new Matrix4_default();
}
if (Cartesian3_default.equalsEpsilon(origin, Cartesian3_default.ZERO, Math_default.EPSILON14)) {
Cartesian3_default.unpack(
degeneratePositionLocalFrame[firstAxis],
0,
scratchFirstCartesian
);
Cartesian3_default.unpack(
degeneratePositionLocalFrame[secondAxis],
0,
scratchSecondCartesian
);
Cartesian3_default.unpack(
degeneratePositionLocalFrame[thirdAxis],
0,
scratchThirdCartesian
);
} else if (Math_default.equalsEpsilon(origin.x, 0, Math_default.EPSILON14) && Math_default.equalsEpsilon(origin.y, 0, Math_default.EPSILON14)) {
const sign2 = Math_default.sign(origin.z);
Cartesian3_default.unpack(
degeneratePositionLocalFrame[firstAxis],
0,
scratchFirstCartesian
);
if (firstAxis !== "east" && firstAxis !== "west") {
Cartesian3_default.multiplyByScalar(
scratchFirstCartesian,
sign2,
scratchFirstCartesian
);
}
Cartesian3_default.unpack(
degeneratePositionLocalFrame[secondAxis],
0,
scratchSecondCartesian
);
if (secondAxis !== "east" && secondAxis !== "west") {
Cartesian3_default.multiplyByScalar(
scratchSecondCartesian,
sign2,
scratchSecondCartesian
);
}
Cartesian3_default.unpack(
degeneratePositionLocalFrame[thirdAxis],
0,
scratchThirdCartesian
);
if (thirdAxis !== "east" && thirdAxis !== "west") {
Cartesian3_default.multiplyByScalar(
scratchThirdCartesian,
sign2,
scratchThirdCartesian
);
}
} else {
ellipsoid = defaultValue_default(ellipsoid, Ellipsoid_default.WGS84);
ellipsoid.geodeticSurfaceNormal(origin, scratchCalculateCartesian.up);
const up = scratchCalculateCartesian.up;
const east = scratchCalculateCartesian.east;
east.x = -origin.y;
east.y = origin.x;
east.z = 0;
Cartesian3_default.normalize(east, scratchCalculateCartesian.east);
Cartesian3_default.cross(up, east, scratchCalculateCartesian.north);
Cartesian3_default.multiplyByScalar(
scratchCalculateCartesian.up,
-1,
scratchCalculateCartesian.down
);
Cartesian3_default.multiplyByScalar(
scratchCalculateCartesian.east,
-1,
scratchCalculateCartesian.west
);
Cartesian3_default.multiplyByScalar(
scratchCalculateCartesian.north,
-1,
scratchCalculateCartesian.south
);
scratchFirstCartesian = scratchCalculateCartesian[firstAxis];
scratchSecondCartesian = scratchCalculateCartesian[secondAxis];
scratchThirdCartesian = scratchCalculateCartesian[thirdAxis];
}
result[0] = scratchFirstCartesian.x;
result[1] = scratchFirstCartesian.y;
result[2] = scratchFirstCartesian.z;
result[3] = 0;
result[4] = scratchSecondCartesian.x;
result[5] = scratchSecondCartesian.y;
result[6] = scratchSecondCartesian.z;
result[7] = 0;
result[8] = scratchThirdCartesian.x;
result[9] = scratchThirdCartesian.y;
result[10] = scratchThirdCartesian.z;
result[11] = 0;
result[12] = origin.x;
result[13] = origin.y;
result[14] = origin.z;
result[15] = 1;
return result;
};
localFrameToFixedFrameCache[hashAxis] = resultat;
}
return resultat;
};
Transforms.eastNorthUpToFixedFrame = Transforms.localFrameToFixedFrameGenerator(
"east",
"north"
);
Transforms.northEastDownToFixedFrame = Transforms.localFrameToFixedFrameGenerator(
"north",
"east"
);
Transforms.northUpEastToFixedFrame = Transforms.localFrameToFixedFrameGenerator(
"north",
"up"
);
Transforms.northWestUpToFixedFrame = Transforms.localFrameToFixedFrameGenerator(
"north",
"west"
);
var scratchHPRQuaternion2 = new Quaternion_default();
var scratchScale = new Cartesian3_default(1, 1, 1);
var scratchHPRMatrix4 = new Matrix4_default();
Transforms.headingPitchRollToFixedFrame = function(origin, headingPitchRoll, ellipsoid, fixedFrameTransform, result) {
Check_default.typeOf.object("HeadingPitchRoll", headingPitchRoll);
fixedFrameTransform = defaultValue_default(
fixedFrameTransform,
Transforms.eastNorthUpToFixedFrame
);
const hprQuaternion = Quaternion_default.fromHeadingPitchRoll(
headingPitchRoll,
scratchHPRQuaternion2
);
const hprMatrix = Matrix4_default.fromTranslationQuaternionRotationScale(
Cartesian3_default.ZERO,
hprQuaternion,
scratchScale,
scratchHPRMatrix4
);
result = fixedFrameTransform(origin, ellipsoid, result);
return Matrix4_default.multiply(result, hprMatrix, result);
};
var scratchENUMatrix4 = new Matrix4_default();
var scratchHPRMatrix3 = new Matrix3_default();
Transforms.headingPitchRollQuaternion = function(origin, headingPitchRoll, ellipsoid, fixedFrameTransform, result) {
Check_default.typeOf.object("HeadingPitchRoll", headingPitchRoll);
const transform3 = Transforms.headingPitchRollToFixedFrame(
origin,
headingPitchRoll,
ellipsoid,
fixedFrameTransform,
scratchENUMatrix4
);
const rotation = Matrix4_default.getMatrix3(transform3, scratchHPRMatrix3);
return Quaternion_default.fromRotationMatrix(rotation, result);
};
var noScale = new Cartesian3_default(1, 1, 1);
var hprCenterScratch = new Cartesian3_default();
var ffScratch = new Matrix4_default();
var hprTransformScratch = new Matrix4_default();
var hprRotationScratch = new Matrix3_default();
var hprQuaternionScratch = new Quaternion_default();
Transforms.fixedFrameToHeadingPitchRoll = function(transform3, ellipsoid, fixedFrameTransform, result) {
Check_default.defined("transform", transform3);
ellipsoid = defaultValue_default(ellipsoid, Ellipsoid_default.WGS84);
fixedFrameTransform = defaultValue_default(
fixedFrameTransform,
Transforms.eastNorthUpToFixedFrame
);
if (!defined_default(result)) {
result = new HeadingPitchRoll_default();
}
const center = Matrix4_default.getTranslation(transform3, hprCenterScratch);
if (Cartesian3_default.equals(center, Cartesian3_default.ZERO)) {
result.heading = 0;
result.pitch = 0;
result.roll = 0;
return result;
}
let toFixedFrame = Matrix4_default.inverseTransformation(
fixedFrameTransform(center, ellipsoid, ffScratch),
ffScratch
);
let transformCopy = Matrix4_default.setScale(transform3, noScale, hprTransformScratch);
transformCopy = Matrix4_default.setTranslation(
transformCopy,
Cartesian3_default.ZERO,
transformCopy
);
toFixedFrame = Matrix4_default.multiply(toFixedFrame, transformCopy, toFixedFrame);
let quaternionRotation = Quaternion_default.fromRotationMatrix(
Matrix4_default.getMatrix3(toFixedFrame, hprRotationScratch),
hprQuaternionScratch
);
quaternionRotation = Quaternion_default.normalize(
quaternionRotation,
quaternionRotation
);
return HeadingPitchRoll_default.fromQuaternion(quaternionRotation, result);
};
var gmstConstant0 = 6 * 3600 + 41 * 60 + 50.54841;
var gmstConstant1 = 8640184812866e-6;
var gmstConstant2 = 0.093104;
var gmstConstant3 = -62e-7;
var rateCoef = 11772758384668e-32;
var wgs84WRPrecessing = 72921158553e-15;
var twoPiOverSecondsInDay = Math_default.TWO_PI / 86400;
var dateInUtc = new JulianDate_default();
Transforms.computeTemeToPseudoFixedMatrix = function(date, result) {
if (!defined_default(date)) {
throw new DeveloperError_default("date is required.");
}
dateInUtc = JulianDate_default.addSeconds(
date,
-JulianDate_default.computeTaiMinusUtc(date),
dateInUtc
);
const utcDayNumber = dateInUtc.dayNumber;
const utcSecondsIntoDay = dateInUtc.secondsOfDay;
let t;
const diffDays = utcDayNumber - 2451545;
if (utcSecondsIntoDay >= 43200) {
t = (diffDays + 0.5) / TimeConstants_default.DAYS_PER_JULIAN_CENTURY;
} else {
t = (diffDays - 0.5) / TimeConstants_default.DAYS_PER_JULIAN_CENTURY;
}
const gmst0 = gmstConstant0 + t * (gmstConstant1 + t * (gmstConstant2 + t * gmstConstant3));
const angle = gmst0 * twoPiOverSecondsInDay % Math_default.TWO_PI;
const ratio = wgs84WRPrecessing + rateCoef * (utcDayNumber - 24515455e-1);
const secondsSinceMidnight = (utcSecondsIntoDay + TimeConstants_default.SECONDS_PER_DAY * 0.5) % TimeConstants_default.SECONDS_PER_DAY;
const gha = angle + ratio * secondsSinceMidnight;
const cosGha = Math.cos(gha);
const sinGha = Math.sin(gha);
if (!defined_default(result)) {
return new Matrix3_default(
cosGha,
sinGha,
0,
-sinGha,
cosGha,
0,
0,
0,
1
);
}
result[0] = cosGha;
result[1] = -sinGha;
result[2] = 0;
result[3] = sinGha;
result[4] = cosGha;
result[5] = 0;
result[6] = 0;
result[7] = 0;
result[8] = 1;
return result;
};
Transforms.iau2006XysData = new Iau2006XysData_default();
Transforms.earthOrientationParameters = EarthOrientationParameters_default.NONE;
var ttMinusTai = 32.184;
var j2000ttDays = 2451545;
Transforms.preloadIcrfFixed = function(timeInterval) {
const startDayTT = timeInterval.start.dayNumber;
const startSecondTT = timeInterval.start.secondsOfDay + ttMinusTai;
const stopDayTT = timeInterval.stop.dayNumber;
const stopSecondTT = timeInterval.stop.secondsOfDay + ttMinusTai;
return Transforms.iau2006XysData.preload(
startDayTT,
startSecondTT,
stopDayTT,
stopSecondTT
);
};
Transforms.computeIcrfToFixedMatrix = function(date, result) {
if (!defined_default(date)) {
throw new DeveloperError_default("date is required.");
}
if (!defined_default(result)) {
result = new Matrix3_default();
}
const fixedToIcrfMtx = Transforms.computeFixedToIcrfMatrix(date, result);
if (!defined_default(fixedToIcrfMtx)) {
return void 0;
}
return Matrix3_default.transpose(fixedToIcrfMtx, result);
};
var xysScratch = new Iau2006XysSample_default(0, 0, 0);
var eopScratch = new EarthOrientationParametersSample_default(
0,
0,
0,
0,
0,
0
);
var rotation1Scratch = new Matrix3_default();
var rotation2Scratch = new Matrix3_default();
Transforms.computeFixedToIcrfMatrix = function(date, result) {
if (!defined_default(date)) {
throw new DeveloperError_default("date is required.");
}
if (!defined_default(result)) {
result = new Matrix3_default();
}
const eop = Transforms.earthOrientationParameters.compute(date, eopScratch);
if (!defined_default(eop)) {
return void 0;
}
const dayTT = date.dayNumber;
const secondTT = date.secondsOfDay + ttMinusTai;
const xys = Transforms.iau2006XysData.computeXysRadians(
dayTT,
secondTT,
xysScratch
);
if (!defined_default(xys)) {
return void 0;
}
const x = xys.x + eop.xPoleOffset;
const y = xys.y + eop.yPoleOffset;
const a3 = 1 / (1 + Math.sqrt(1 - x * x - y * y));
const rotation1 = rotation1Scratch;
rotation1[0] = 1 - a3 * x * x;
rotation1[3] = -a3 * x * y;
rotation1[6] = x;
rotation1[1] = -a3 * x * y;
rotation1[4] = 1 - a3 * y * y;
rotation1[7] = y;
rotation1[2] = -x;
rotation1[5] = -y;
rotation1[8] = 1 - a3 * (x * x + y * y);
const rotation2 = Matrix3_default.fromRotationZ(-xys.s, rotation2Scratch);
const matrixQ = Matrix3_default.multiply(rotation1, rotation2, rotation1Scratch);
const dateUt1day = date.dayNumber;
const dateUt1sec = date.secondsOfDay - JulianDate_default.computeTaiMinusUtc(date) + eop.ut1MinusUtc;
const daysSinceJ2000 = dateUt1day - 2451545;
const fractionOfDay = dateUt1sec / TimeConstants_default.SECONDS_PER_DAY;
let era = 0.779057273264 + fractionOfDay + 0.00273781191135448 * (daysSinceJ2000 + fractionOfDay);
era = era % 1 * Math_default.TWO_PI;
const earthRotation = Matrix3_default.fromRotationZ(era, rotation2Scratch);
const pfToIcrf = Matrix3_default.multiply(matrixQ, earthRotation, rotation1Scratch);
const cosxp = Math.cos(eop.xPoleWander);
const cosyp = Math.cos(eop.yPoleWander);
const sinxp = Math.sin(eop.xPoleWander);
const sinyp = Math.sin(eop.yPoleWander);
let ttt = dayTT - j2000ttDays + secondTT / TimeConstants_default.SECONDS_PER_DAY;
ttt /= 36525;
const sp = -47e-6 * ttt * Math_default.RADIANS_PER_DEGREE / 3600;
const cossp = Math.cos(sp);
const sinsp = Math.sin(sp);
const fToPfMtx = rotation2Scratch;
fToPfMtx[0] = cosxp * cossp;
fToPfMtx[1] = cosxp * sinsp;
fToPfMtx[2] = sinxp;
fToPfMtx[3] = -cosyp * sinsp + sinyp * sinxp * cossp;
fToPfMtx[4] = cosyp * cossp + sinyp * sinxp * sinsp;
fToPfMtx[5] = -sinyp * cosxp;
fToPfMtx[6] = -sinyp * sinsp - cosyp * sinxp * cossp;
fToPfMtx[7] = sinyp * cossp - cosyp * sinxp * sinsp;
fToPfMtx[8] = cosyp * cosxp;
return Matrix3_default.multiply(pfToIcrf, fToPfMtx, result);
};
var pointToWindowCoordinatesTemp = new Cartesian4_default();
Transforms.pointToWindowCoordinates = function(modelViewProjectionMatrix, viewportTransformation, point, result) {
result = Transforms.pointToGLWindowCoordinates(
modelViewProjectionMatrix,
viewportTransformation,
point,
result
);
result.y = 2 * viewportTransformation[5] - result.y;
return result;
};
Transforms.pointToGLWindowCoordinates = function(modelViewProjectionMatrix, viewportTransformation, point, result) {
if (!defined_default(modelViewProjectionMatrix)) {
throw new DeveloperError_default("modelViewProjectionMatrix is required.");
}
if (!defined_default(viewportTransformation)) {
throw new DeveloperError_default("viewportTransformation is required.");
}
if (!defined_default(point)) {
throw new DeveloperError_default("point is required.");
}
if (!defined_default(result)) {
result = new Cartesian2_default();
}
const tmp2 = pointToWindowCoordinatesTemp;
Matrix4_default.multiplyByVector(
modelViewProjectionMatrix,
Cartesian4_default.fromElements(point.x, point.y, point.z, 1, tmp2),
tmp2
);
Cartesian4_default.multiplyByScalar(tmp2, 1 / tmp2.w, tmp2);
Matrix4_default.multiplyByVector(viewportTransformation, tmp2, tmp2);
return Cartesian2_default.fromCartesian4(tmp2, result);
};
var normalScratch = new Cartesian3_default();
var rightScratch = new Cartesian3_default();
var upScratch = new Cartesian3_default();
Transforms.rotationMatrixFromPositionVelocity = function(position, velocity, ellipsoid, result) {
if (!defined_default(position)) {
throw new DeveloperError_default("position is required.");
}
if (!defined_default(velocity)) {
throw new DeveloperError_default("velocity is required.");
}
const normal2 = defaultValue_default(ellipsoid, Ellipsoid_default.WGS84).geodeticSurfaceNormal(
position,
normalScratch
);
let right = Cartesian3_default.cross(velocity, normal2, rightScratch);
if (Cartesian3_default.equalsEpsilon(right, Cartesian3_default.ZERO, Math_default.EPSILON6)) {
right = Cartesian3_default.clone(Cartesian3_default.UNIT_X, right);
}
const up = Cartesian3_default.cross(right, velocity, upScratch);
Cartesian3_default.normalize(up, up);
Cartesian3_default.cross(velocity, up, right);
Cartesian3_default.negate(right, right);
Cartesian3_default.normalize(right, right);
if (!defined_default(result)) {
result = new Matrix3_default();
}
result[0] = velocity.x;
result[1] = velocity.y;
result[2] = velocity.z;
result[3] = right.x;
result[4] = right.y;
result[5] = right.z;
result[6] = up.x;
result[7] = up.y;
result[8] = up.z;
return result;
};
var swizzleMatrix = new Matrix4_default(
0,
0,
1,
0,
1,
0,
0,
0,
0,
1,
0,
0,
0,
0,
0,
1
);
var scratchCartographic = new Cartographic_default();
var scratchCartesian3Projection = new Cartesian3_default();
var scratchCenter = new Cartesian3_default();
var scratchRotation = new Matrix3_default();
var scratchFromENU = new Matrix4_default();
var scratchToENU = new Matrix4_default();
Transforms.basisTo2D = function(projection, matrix, result) {
if (!defined_default(projection)) {
throw new DeveloperError_default("projection is required.");
}
if (!defined_default(matrix)) {
throw new DeveloperError_default("matrix is required.");
}
if (!defined_default(result)) {
throw new DeveloperError_default("result is required.");
}
const rtcCenter = Matrix4_default.getTranslation(matrix, scratchCenter);
const ellipsoid = projection.ellipsoid;
const cartographic2 = ellipsoid.cartesianToCartographic(
rtcCenter,
scratchCartographic
);
const projectedPosition2 = projection.project(
cartographic2,
scratchCartesian3Projection
);
Cartesian3_default.fromElements(
projectedPosition2.z,
projectedPosition2.x,
projectedPosition2.y,
projectedPosition2
);
const fromENU = Transforms.eastNorthUpToFixedFrame(
rtcCenter,
ellipsoid,
scratchFromENU
);
const toENU = Matrix4_default.inverseTransformation(fromENU, scratchToENU);
const rotation = Matrix4_default.getMatrix3(matrix, scratchRotation);
const local = Matrix4_default.multiplyByMatrix3(toENU, rotation, result);
Matrix4_default.multiply(swizzleMatrix, local, result);
Matrix4_default.setTranslation(result, projectedPosition2, result);
return result;
};
Transforms.wgs84To2DModelMatrix = function(projection, center, result) {
if (!defined_default(projection)) {
throw new DeveloperError_default("projection is required.");
}
if (!defined_default(center)) {
throw new DeveloperError_default("center is required.");
}
if (!defined_default(result)) {
throw new DeveloperError_default("result is required.");
}
const ellipsoid = projection.ellipsoid;
const fromENU = Transforms.eastNorthUpToFixedFrame(
center,
ellipsoid,
scratchFromENU
);
const toENU = Matrix4_default.inverseTransformation(fromENU, scratchToENU);
const cartographic2 = ellipsoid.cartesianToCartographic(
center,
scratchCartographic
);
const projectedPosition2 = projection.project(
cartographic2,
scratchCartesian3Projection
);
Cartesian3_default.fromElements(
projectedPosition2.z,
projectedPosition2.x,
projectedPosition2.y,
projectedPosition2
);
const translation3 = Matrix4_default.fromTranslation(
projectedPosition2,
scratchFromENU
);
Matrix4_default.multiply(swizzleMatrix, toENU, result);
Matrix4_default.multiply(translation3, result, result);
return result;
};
var Transforms_default = Transforms;
// packages/engine/Source/Core/Geometry.js
function Geometry(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
Check_default.typeOf.object("options.attributes", options.attributes);
this.attributes = options.attributes;
this.indices = options.indices;
this.primitiveType = defaultValue_default(
options.primitiveType,
PrimitiveType_default.TRIANGLES
);
this.boundingSphere = options.boundingSphere;
this.geometryType = defaultValue_default(options.geometryType, GeometryType_default.NONE);
this.boundingSphereCV = options.boundingSphereCV;
this.offsetAttribute = options.offsetAttribute;
}
Geometry.computeNumberOfVertices = function(geometry) {
Check_default.typeOf.object("geometry", geometry);
let numberOfVertices = -1;
for (const property in geometry.attributes) {
if (geometry.attributes.hasOwnProperty(property) && defined_default(geometry.attributes[property]) && defined_default(geometry.attributes[property].values)) {
const attribute = geometry.attributes[property];
const num = attribute.values.length / attribute.componentsPerAttribute;
if (numberOfVertices !== num && numberOfVertices !== -1) {
throw new DeveloperError_default(
"All attribute lists must have the same number of attributes."
);
}
numberOfVertices = num;
}
}
return numberOfVertices;
};
var rectangleCenterScratch = new Cartographic_default();
var enuCenterScratch = new Cartesian3_default();
var fixedFrameToEnuScratch = new Matrix4_default();
var boundingRectanglePointsCartographicScratch = [
new Cartographic_default(),
new Cartographic_default(),
new Cartographic_default()
];
var boundingRectanglePointsEnuScratch = [
new Cartesian2_default(),
new Cartesian2_default(),
new Cartesian2_default()
];
var points2DScratch = [new Cartesian2_default(), new Cartesian2_default(), new Cartesian2_default()];
var pointEnuScratch = new Cartesian3_default();
var enuRotationScratch = new Quaternion_default();
var enuRotationMatrixScratch = new Matrix4_default();
var rotation2DScratch = new Matrix2_default();
Geometry._textureCoordinateRotationPoints = function(positions, stRotation, ellipsoid, boundingRectangle) {
let i;
const rectangleCenter = Rectangle_default.center(
boundingRectangle,
rectangleCenterScratch
);
const enuCenter = Cartographic_default.toCartesian(
rectangleCenter,
ellipsoid,
enuCenterScratch
);
const enuToFixedFrame = Transforms_default.eastNorthUpToFixedFrame(
enuCenter,
ellipsoid,
fixedFrameToEnuScratch
);
const fixedFrameToEnu = Matrix4_default.inverse(
enuToFixedFrame,
fixedFrameToEnuScratch
);
const boundingPointsEnu = boundingRectanglePointsEnuScratch;
const boundingPointsCarto = boundingRectanglePointsCartographicScratch;
boundingPointsCarto[0].longitude = boundingRectangle.west;
boundingPointsCarto[0].latitude = boundingRectangle.south;
boundingPointsCarto[1].longitude = boundingRectangle.west;
boundingPointsCarto[1].latitude = boundingRectangle.north;
boundingPointsCarto[2].longitude = boundingRectangle.east;
boundingPointsCarto[2].latitude = boundingRectangle.south;
let posEnu = pointEnuScratch;
for (i = 0; i < 3; i++) {
Cartographic_default.toCartesian(boundingPointsCarto[i], ellipsoid, posEnu);
posEnu = Matrix4_default.multiplyByPointAsVector(fixedFrameToEnu, posEnu, posEnu);
boundingPointsEnu[i].x = posEnu.x;
boundingPointsEnu[i].y = posEnu.y;
}
const rotation = Quaternion_default.fromAxisAngle(
Cartesian3_default.UNIT_Z,
-stRotation,
enuRotationScratch
);
const textureMatrix = Matrix3_default.fromQuaternion(
rotation,
enuRotationMatrixScratch
);
const positionsLength = positions.length;
let enuMinX = Number.POSITIVE_INFINITY;
let enuMinY = Number.POSITIVE_INFINITY;
let enuMaxX = Number.NEGATIVE_INFINITY;
let enuMaxY = Number.NEGATIVE_INFINITY;
for (i = 0; i < positionsLength; i++) {
posEnu = Matrix4_default.multiplyByPointAsVector(
fixedFrameToEnu,
positions[i],
posEnu
);
posEnu = Matrix3_default.multiplyByVector(textureMatrix, posEnu, posEnu);
enuMinX = Math.min(enuMinX, posEnu.x);
enuMinY = Math.min(enuMinY, posEnu.y);
enuMaxX = Math.max(enuMaxX, posEnu.x);
enuMaxY = Math.max(enuMaxY, posEnu.y);
}
const toDesiredInComputed = Matrix2_default.fromRotation(
stRotation,
rotation2DScratch
);
const points2D = points2DScratch;
points2D[0].x = enuMinX;
points2D[0].y = enuMinY;
points2D[1].x = enuMinX;
points2D[1].y = enuMaxY;
points2D[2].x = enuMaxX;
points2D[2].y = enuMinY;
const boundingEnuMin = boundingPointsEnu[0];
const boundingPointsWidth = boundingPointsEnu[2].x - boundingEnuMin.x;
const boundingPointsHeight = boundingPointsEnu[1].y - boundingEnuMin.y;
for (i = 0; i < 3; i++) {
const point2D = points2D[i];
Matrix2_default.multiplyByVector(toDesiredInComputed, point2D, point2D);
point2D.x = (point2D.x - boundingEnuMin.x) / boundingPointsWidth;
point2D.y = (point2D.y - boundingEnuMin.y) / boundingPointsHeight;
}
const minXYCorner = points2D[0];
const maxYCorner = points2D[1];
const maxXCorner = points2D[2];
const result = new Array(6);
Cartesian2_default.pack(minXYCorner, result);
Cartesian2_default.pack(maxYCorner, result, 2);
Cartesian2_default.pack(maxXCorner, result, 4);
return result;
};
var Geometry_default = Geometry;
// packages/engine/Source/Core/GeometryAttribute.js
function GeometryAttribute(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
if (!defined_default(options.componentDatatype)) {
throw new DeveloperError_default("options.componentDatatype is required.");
}
if (!defined_default(options.componentsPerAttribute)) {
throw new DeveloperError_default("options.componentsPerAttribute is required.");
}
if (options.componentsPerAttribute < 1 || options.componentsPerAttribute > 4) {
throw new DeveloperError_default(
"options.componentsPerAttribute must be between 1 and 4."
);
}
if (!defined_default(options.values)) {
throw new DeveloperError_default("options.values is required.");
}
this.componentDatatype = options.componentDatatype;
this.componentsPerAttribute = options.componentsPerAttribute;
this.normalize = defaultValue_default(options.normalize, false);
this.values = options.values;
}
var GeometryAttribute_default = GeometryAttribute;
// packages/engine/Source/Core/CompressedTextureBuffer.js
function CompressedTextureBuffer(internalFormat, pixelDatatype, width, height, buffer) {
this._format = internalFormat;
this._datatype = pixelDatatype;
this._width = width;
this._height = height;
this._buffer = buffer;
}
Object.defineProperties(CompressedTextureBuffer.prototype, {
/**
* The format of the compressed texture.
* @type {PixelFormat}
* @readonly
* @memberof CompressedTextureBuffer.prototype
*/
internalFormat: {
get: function() {
return this._format;
}
},
/**
* The datatype of the compressed texture.
* @type {PixelDatatype}
* @readonly
* @memberof CompressedTextureBuffer.prototype
*/
pixelDatatype: {
get: function() {
return this._datatype;
}
},
/**
* The width of the texture.
* @type {number}
* @readonly
* @memberof CompressedTextureBuffer.prototype
*/
width: {
get: function() {
return this._width;
}
},
/**
* The height of the texture.
* @type {number}
* @readonly
* @memberof CompressedTextureBuffer.prototype
*/
height: {
get: function() {
return this._height;
}
},
/**
* The compressed texture buffer.
* @type {Uint8Array}
* @readonly
* @memberof CompressedTextureBuffer.prototype
*/
bufferView: {
get: function() {
return this._buffer;
}
}
});
CompressedTextureBuffer.clone = function(object2) {
if (!defined_default(object2)) {
return void 0;
}
return new CompressedTextureBuffer(
object2._format,
object2._datatype,
object2._width,
object2._height,
object2._buffer
);
};
CompressedTextureBuffer.prototype.clone = function() {
return CompressedTextureBuffer.clone(this);
};
var CompressedTextureBuffer_default = CompressedTextureBuffer;
// packages/engine/Source/Core/TaskProcessor.js
var import_urijs7 = __toESM(require_URI(), 1);
function canTransferArrayBuffer() {
if (!defined_default(TaskProcessor._canTransferArrayBuffer)) {
const worker = new Worker(
getWorkerUrl("Workers/transferTypedArrayTest.js")
);
worker.postMessage = defaultValue_default(
worker.webkitPostMessage,
worker.postMessage
);
const value = 99;
const array = new Int8Array([value]);
try {
worker.postMessage(
{
array
},
[array.buffer]
);
} catch (e) {
TaskProcessor._canTransferArrayBuffer = false;
return TaskProcessor._canTransferArrayBuffer;
}
const deferred = defer_default();
worker.onmessage = function(event) {
const array2 = event.data.array;
const result = defined_default(array2) && array2[0] === value;
deferred.resolve(result);
worker.terminate();
TaskProcessor._canTransferArrayBuffer = result;
};
TaskProcessor._canTransferArrayBuffer = deferred.promise;
}
return TaskProcessor._canTransferArrayBuffer;
}
var taskCompletedEvent = new Event_default();
function completeTask(processor, data) {
--processor._activeTasks;
const id = data.id;
if (!defined_default(id)) {
return;
}
const deferreds = processor._deferreds;
const deferred = deferreds[id];
if (defined_default(data.error)) {
let error = data.error;
if (error.name === "RuntimeError") {
error = new RuntimeError_default(data.error.message);
error.stack = data.error.stack;
} else if (error.name === "DeveloperError") {
error = new DeveloperError_default(data.error.message);
error.stack = data.error.stack;
}
taskCompletedEvent.raiseEvent(error);
deferred.reject(error);
} else {
taskCompletedEvent.raiseEvent();
deferred.resolve(data.result);
}
delete deferreds[id];
}
function getWorkerUrl(moduleID) {
let url2 = buildModuleUrl_default(moduleID);
if (isCrossOriginUrl_default(url2)) {
const script = `importScripts("${url2}");`;
let blob;
try {
blob = new Blob([script], {
type: "application/javascript"
});
} catch (e) {
const BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
const blobBuilder = new BlobBuilder();
blobBuilder.append(script);
blob = blobBuilder.getBlob("application/javascript");
}
const URL2 = window.URL || window.webkitURL;
url2 = URL2.createObjectURL(blob);
}
return url2;
}
var bootstrapperUrlResult;
function getBootstrapperUrl() {
if (!defined_default(bootstrapperUrlResult)) {
bootstrapperUrlResult = getWorkerUrl("Workers/cesiumWorkerBootstrapper.js");
}
return bootstrapperUrlResult;
}
function createWorker(processor) {
const worker = new Worker(getBootstrapperUrl());
worker.postMessage = defaultValue_default(
worker.webkitPostMessage,
worker.postMessage
);
const bootstrapMessage = {
loaderConfig: {
paths: {
Workers: buildModuleUrl_default("Workers")
},
baseUrl: buildModuleUrl_default.getCesiumBaseUrl().url
},
workerModule: processor._workerPath
};
worker.postMessage(bootstrapMessage);
worker.onmessage = function(event) {
completeTask(processor, event.data);
};
return worker;
}
function getWebAssemblyLoaderConfig(processor, wasmOptions) {
const config2 = {
modulePath: void 0,
wasmBinaryFile: void 0,
wasmBinary: void 0
};
if (!FeatureDetection_default.supportsWebAssembly()) {
if (!defined_default(wasmOptions.fallbackModulePath)) {
throw new RuntimeError_default(
`This browser does not support Web Assembly, and no backup module was provided for ${processor._workerPath}`
);
}
config2.modulePath = buildModuleUrl_default(wasmOptions.fallbackModulePath);
return Promise.resolve(config2);
}
config2.modulePath = buildModuleUrl_default(wasmOptions.modulePath);
config2.wasmBinaryFile = buildModuleUrl_default(wasmOptions.wasmBinaryFile);
return Resource_default.fetchArrayBuffer({
url: config2.wasmBinaryFile
}).then(function(arrayBuffer) {
config2.wasmBinary = arrayBuffer;
return config2;
});
}
function TaskProcessor(workerPath, maximumActiveTasks) {
const uri = new import_urijs7.default(workerPath);
this._workerPath = uri.scheme().length !== 0 && uri.fragment().length === 0 ? workerPath : TaskProcessor._workerModulePrefix + workerPath;
this._maximumActiveTasks = defaultValue_default(
maximumActiveTasks,
Number.POSITIVE_INFINITY
);
this._activeTasks = 0;
this._deferreds = {};
this._nextID = 0;
}
var emptyTransferableObjectArray = [];
TaskProcessor.prototype.scheduleTask = function(parameters, transferableObjects) {
if (!defined_default(this._worker)) {
this._worker = createWorker(this);
}
if (this._activeTasks >= this._maximumActiveTasks) {
return void 0;
}
++this._activeTasks;
const processor = this;
return Promise.resolve(canTransferArrayBuffer()).then(function(canTransferArrayBuffer2) {
if (!defined_default(transferableObjects)) {
transferableObjects = emptyTransferableObjectArray;
} else if (!canTransferArrayBuffer2) {
transferableObjects.length = 0;
}
const id = processor._nextID++;
const deferred = defer_default();
processor._deferreds[id] = deferred;
processor._worker.postMessage(
{
id,
parameters,
canTransferArrayBuffer: canTransferArrayBuffer2
},
transferableObjects
);
return deferred.promise;
});
};
TaskProcessor.prototype.initWebAssemblyModule = function(webAssemblyOptions) {
if (!defined_default(this._worker)) {
this._worker = createWorker(this);
}
const deferred = defer_default();
const processor = this;
const worker = this._worker;
getWebAssemblyLoaderConfig(this, webAssemblyOptions).then(function(wasmConfig) {
return Promise.resolve(canTransferArrayBuffer()).then(function(canTransferArrayBuffer2) {
let transferableObjects;
const binary = wasmConfig.wasmBinary;
if (defined_default(binary) && canTransferArrayBuffer2) {
transferableObjects = [binary];
}
worker.onmessage = function(event) {
worker.onmessage = function(event2) {
completeTask(processor, event2.data);
};
deferred.resolve(event.data);
};
worker.postMessage(
{ webAssemblyConfig: wasmConfig },
transferableObjects
);
});
});
return deferred.promise;
};
TaskProcessor.prototype.isDestroyed = function() {
return false;
};
TaskProcessor.prototype.destroy = function() {
if (defined_default(this._worker)) {
this._worker.terminate();
}
return destroyObject_default(this);
};
TaskProcessor.taskCompletedEvent = taskCompletedEvent;
TaskProcessor._defaultWorkerModulePrefix = "Workers/";
TaskProcessor._workerModulePrefix = TaskProcessor._defaultWorkerModulePrefix;
TaskProcessor._canTransferArrayBuffer = void 0;
var TaskProcessor_default = TaskProcessor;
// packages/engine/Source/Core/KTX2Transcoder.js
function KTX2Transcoder() {
}
KTX2Transcoder._transcodeTaskProcessor = new TaskProcessor_default(
"transcodeKTX2",
Number.POSITIVE_INFINITY
// KTX2 transcoding is used in place of Resource.fetchImage, so it can't reject as "just soooo busy right now"
);
KTX2Transcoder._readyPromise = void 0;
function makeReadyPromise() {
const readyPromise = KTX2Transcoder._transcodeTaskProcessor.initWebAssemblyModule({
modulePath: "ThirdParty/Workers/basis_transcoder.js",
wasmBinaryFile: "ThirdParty/basis_transcoder.wasm"
}).then(function() {
return KTX2Transcoder._transcodeTaskProcessor;
});
KTX2Transcoder._readyPromise = readyPromise;
}
KTX2Transcoder.transcode = function(ktx2Buffer, supportedTargetFormats) {
Check_default.defined("supportedTargetFormats", supportedTargetFormats);
if (!defined_default(KTX2Transcoder._readyPromise)) {
makeReadyPromise();
}
return KTX2Transcoder._readyPromise.then(function(taskProcessor3) {
let parameters;
if (ktx2Buffer instanceof ArrayBuffer) {
const view = new Uint8Array(ktx2Buffer);
parameters = {
supportedTargetFormats,
ktx2Buffer: view
};
return taskProcessor3.scheduleTask(parameters, [ktx2Buffer]);
}
parameters = {
supportedTargetFormats,
ktx2Buffer
};
return taskProcessor3.scheduleTask(parameters, [ktx2Buffer.buffer]);
}).then(function(result) {
const levelsLength = result.length;
const faceKeys = Object.keys(result[0]);
const faceKeysLength = faceKeys.length;
let i;
for (i = 0; i < levelsLength; i++) {
const faces2 = result[i];
for (let j = 0; j < faceKeysLength; j++) {
const face = faces2[faceKeys[j]];
faces2[faceKeys[j]] = new CompressedTextureBuffer_default(
face.internalFormat,
face.datatype,
face.width,
face.height,
face.levelBuffer
);
}
}
if (faceKeysLength === 1) {
for (i = 0; i < levelsLength; ++i) {
result[i] = result[i][faceKeys[0]];
}
if (levelsLength === 1) {
result = result[0];
}
}
return result;
}).catch(function(error) {
throw error;
});
};
var KTX2Transcoder_default = KTX2Transcoder;
// packages/engine/Source/Core/loadKTX2.js
var supportedTranscoderFormats;
loadKTX2.setKTX2SupportedFormats = function(s3tc, pvrtc, astc, etc, etc1, bc7) {
supportedTranscoderFormats = {
s3tc,
pvrtc,
astc,
etc,
etc1,
bc7
};
};
function loadKTX2(resourceOrUrlOrBuffer) {
Check_default.defined("resourceOrUrlOrBuffer", resourceOrUrlOrBuffer);
let loadPromise;
if (resourceOrUrlOrBuffer instanceof ArrayBuffer || ArrayBuffer.isView(resourceOrUrlOrBuffer)) {
loadPromise = Promise.resolve(resourceOrUrlOrBuffer);
} else {
const resource = Resource_default.createIfNeeded(resourceOrUrlOrBuffer);
loadPromise = resource.fetchArrayBuffer();
}
return loadPromise.then(function(data) {
return KTX2Transcoder_default.transcode(data, supportedTranscoderFormats);
});
}
var loadKTX2_default = loadKTX2;
// packages/engine/Source/Renderer/CubeMapFace.js
function CubeMapFace(context, texture, textureTarget, targetFace, internalFormat, pixelFormat, pixelDatatype, size, preMultiplyAlpha, flipY, initialized) {
this._context = context;
this._texture = texture;
this._textureTarget = textureTarget;
this._targetFace = targetFace;
this._pixelDatatype = pixelDatatype;
this._internalFormat = internalFormat;
this._pixelFormat = pixelFormat;
this._size = size;
this._preMultiplyAlpha = preMultiplyAlpha;
this._flipY = flipY;
this._initialized = initialized;
}
Object.defineProperties(CubeMapFace.prototype, {
pixelFormat: {
get: function() {
return this._pixelFormat;
}
},
pixelDatatype: {
get: function() {
return this._pixelDatatype;
}
},
_target: {
get: function() {
return this._targetFace;
}
}
});
CubeMapFace.prototype.copyFrom = function(options) {
Check_default.defined("options", options);
const xOffset = defaultValue_default(options.xOffset, 0);
const yOffset = defaultValue_default(options.yOffset, 0);
Check_default.defined("options.source", options.source);
Check_default.typeOf.number.greaterThanOrEquals("xOffset", xOffset, 0);
Check_default.typeOf.number.greaterThanOrEquals("yOffset", yOffset, 0);
if (xOffset + options.source.width > this._size) {
throw new DeveloperError_default(
"xOffset + options.source.width must be less than or equal to width."
);
}
if (yOffset + options.source.height > this._size) {
throw new DeveloperError_default(
"yOffset + options.source.height must be less than or equal to height."
);
}
const source = options.source;
const gl = this._context._gl;
const target = this._textureTarget;
const targetFace = this._targetFace;
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(target, this._texture);
const width = source.width;
const height = source.height;
let arrayBufferView = source.arrayBufferView;
const size = this._size;
const pixelFormat = this._pixelFormat;
const internalFormat = this._internalFormat;
const pixelDatatype = this._pixelDatatype;
const preMultiplyAlpha = this._preMultiplyAlpha;
const flipY = this._flipY;
const skipColorSpaceConversion = defaultValue_default(
options.skipColorSpaceConversion,
false
);
let unpackAlignment = 4;
if (defined_default(arrayBufferView)) {
unpackAlignment = PixelFormat_default.alignmentInBytes(
pixelFormat,
pixelDatatype,
width
);
}
gl.pixelStorei(gl.UNPACK_ALIGNMENT, unpackAlignment);
if (skipColorSpaceConversion) {
gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE);
} else {
gl.pixelStorei(
gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,
gl.BROWSER_DEFAULT_WEBGL
);
}
let uploaded = false;
if (!this._initialized) {
if (xOffset === 0 && yOffset === 0 && width === size && height === size) {
if (defined_default(arrayBufferView)) {
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
if (flipY) {
arrayBufferView = PixelFormat_default.flipY(
arrayBufferView,
pixelFormat,
pixelDatatype,
size,
size
);
}
gl.texImage2D(
targetFace,
0,
internalFormat,
size,
size,
0,
pixelFormat,
PixelDatatype_default.toWebGLConstant(pixelDatatype, this._context),
arrayBufferView
);
} else {
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, preMultiplyAlpha);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY);
gl.texImage2D(
targetFace,
0,
internalFormat,
pixelFormat,
PixelDatatype_default.toWebGLConstant(pixelDatatype, this._context),
source
);
}
uploaded = true;
} else {
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
const bufferView = PixelFormat_default.createTypedArray(
pixelFormat,
pixelDatatype,
size,
size
);
gl.texImage2D(
targetFace,
0,
internalFormat,
size,
size,
0,
pixelFormat,
PixelDatatype_default.toWebGLConstant(pixelDatatype, this._context),
bufferView
);
}
this._initialized = true;
}
if (!uploaded) {
if (defined_default(arrayBufferView)) {
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
if (flipY) {
arrayBufferView = PixelFormat_default.flipY(
arrayBufferView,
pixelFormat,
pixelDatatype,
width,
height
);
}
gl.texSubImage2D(
targetFace,
0,
xOffset,
yOffset,
width,
height,
pixelFormat,
PixelDatatype_default.toWebGLConstant(pixelDatatype, this._context),
arrayBufferView
);
} else {
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, preMultiplyAlpha);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY);
gl.texSubImage2D(
targetFace,
0,
xOffset,
yOffset,
pixelFormat,
PixelDatatype_default.toWebGLConstant(pixelDatatype, this._context),
source
);
}
}
gl.bindTexture(target, null);
};
CubeMapFace.prototype.copyFromFramebuffer = function(xOffset, yOffset, framebufferXOffset, framebufferYOffset, width, height) {
xOffset = defaultValue_default(xOffset, 0);
yOffset = defaultValue_default(yOffset, 0);
framebufferXOffset = defaultValue_default(framebufferXOffset, 0);
framebufferYOffset = defaultValue_default(framebufferYOffset, 0);
width = defaultValue_default(width, this._size);
height = defaultValue_default(height, this._size);
Check_default.typeOf.number.greaterThanOrEquals("xOffset", xOffset, 0);
Check_default.typeOf.number.greaterThanOrEquals("yOffset", yOffset, 0);
Check_default.typeOf.number.greaterThanOrEquals(
"framebufferXOffset",
framebufferXOffset,
0
);
Check_default.typeOf.number.greaterThanOrEquals(
"framebufferYOffset",
framebufferYOffset,
0
);
if (xOffset + width > this._size) {
throw new DeveloperError_default(
"xOffset + source.width must be less than or equal to width."
);
}
if (yOffset + height > this._size) {
throw new DeveloperError_default(
"yOffset + source.height must be less than or equal to height."
);
}
if (this._pixelDatatype === PixelDatatype_default.FLOAT) {
throw new DeveloperError_default(
"Cannot call copyFromFramebuffer when the texture pixel data type is FLOAT."
);
}
if (this._pixelDatatype === PixelDatatype_default.HALF_FLOAT) {
throw new DeveloperError_default(
"Cannot call copyFromFramebuffer when the texture pixel data type is HALF_FLOAT."
);
}
const gl = this._context._gl;
const target = this._textureTarget;
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(target, this._texture);
gl.copyTexSubImage2D(
this._targetFace,
0,
xOffset,
yOffset,
framebufferXOffset,
framebufferYOffset,
width,
height
);
gl.bindTexture(target, null);
this._initialized = true;
};
var CubeMapFace_default = CubeMapFace;
// packages/engine/Source/Renderer/MipmapHint.js
var MipmapHint = {
DONT_CARE: WebGLConstants_default.DONT_CARE,
FASTEST: WebGLConstants_default.FASTEST,
NICEST: WebGLConstants_default.NICEST,
validate: function(mipmapHint) {
return mipmapHint === MipmapHint.DONT_CARE || mipmapHint === MipmapHint.FASTEST || mipmapHint === MipmapHint.NICEST;
}
};
var MipmapHint_default = Object.freeze(MipmapHint);
// packages/engine/Source/Renderer/TextureMagnificationFilter.js
var TextureMagnificationFilter = {
/**
* Samples the texture by returning the closest pixel.
*
* @type {number}
* @constant
*/
NEAREST: WebGLConstants_default.NEAREST,
/**
* Samples the texture through bi-linear interpolation of the four nearest pixels. This produces smoother results than NEAREST
filtering.
*
* @type {number}
* @constant
*/
LINEAR: WebGLConstants_default.LINEAR
};
TextureMagnificationFilter.validate = function(textureMagnificationFilter) {
return textureMagnificationFilter === TextureMagnificationFilter.NEAREST || textureMagnificationFilter === TextureMagnificationFilter.LINEAR;
};
var TextureMagnificationFilter_default = Object.freeze(TextureMagnificationFilter);
// packages/engine/Source/Renderer/TextureMinificationFilter.js
var TextureMinificationFilter = {
/**
* Samples the texture by returning the closest pixel.
*
* @type {number}
* @constant
*/
NEAREST: WebGLConstants_default.NEAREST,
/**
* Samples the texture through bi-linear interpolation of the four nearest pixels. This produces smoother results than NEAREST
filtering.
*
* @type {number}
* @constant
*/
LINEAR: WebGLConstants_default.LINEAR,
/**
* Selects the nearest mip level and applies nearest sampling within that level.
* 1/pi
.\n *\n * @alias czm_oneOverPi\n * @glslConstant\n *\n * @see CesiumMath.ONE_OVER_PI\n *\n * @example\n * // GLSL declaration\n * const float czm_oneOverPi = ...;\n *\n * // Example\n * float pi = 1.0 / czm_oneOverPi;\n */\nconst float czm_oneOverPi = 0.3183098861837907;\n";
// packages/engine/Source/Shaders/Builtin/Constants/oneOverTwoPi.js
var oneOverTwoPi_default = "/**\n * A built-in GLSL floating-point constant for 1/2pi
.\n *\n * @alias czm_oneOverTwoPi\n * @glslConstant\n *\n * @see CesiumMath.ONE_OVER_TWO_PI\n *\n * @example\n * // GLSL declaration\n * const float czm_oneOverTwoPi = ...;\n *\n * // Example\n * float pi = 2.0 * czm_oneOverTwoPi;\n */\nconst float czm_oneOverTwoPi = 0.15915494309189535;\n";
// packages/engine/Source/Shaders/Builtin/Constants/passCesium3DTile.js
var passCesium3DTile_default = "/**\n * The automatic GLSL constant for {@link Pass#CESIUM_3D_TILE}\n *\n * @name czm_passCesium3DTile\n * @glslConstant\n *\n * @see czm_pass\n */\nconst float czm_passCesium3DTile = 4.0;\n";
// packages/engine/Source/Shaders/Builtin/Constants/passCesium3DTileClassification.js
var passCesium3DTileClassification_default = "/**\n * The automatic GLSL constant for {@link Pass#CESIUM_3D_TILE_CLASSIFICATION}\n *\n * @name czm_passCesium3DTileClassification\n * @glslConstant\n *\n * @see czm_pass\n */\nconst float czm_passCesium3DTileClassification = 5.0;\n";
// packages/engine/Source/Shaders/Builtin/Constants/passCesium3DTileClassificationIgnoreShow.js
var passCesium3DTileClassificationIgnoreShow_default = "/**\n * The automatic GLSL constant for {@link Pass#CESIUM_3D_TILE_CLASSIFICATION_IGNORE_SHOW}\n *\n * @name czm_passCesium3DTileClassificationIgnoreShow\n * @glslConstant\n *\n * @see czm_pass\n */\nconst float czm_passCesium3DTileClassificationIgnoreShow = 6.0;\n";
// packages/engine/Source/Shaders/Builtin/Constants/passClassification.js
var passClassification_default = "/**\n * The automatic GLSL constant for {@link Pass#CLASSIFICATION}\n *\n * @name czm_passClassification\n * @glslConstant\n *\n * @see czm_pass\n */\nconst float czm_passClassification = 7.0;\n";
// packages/engine/Source/Shaders/Builtin/Constants/passCompute.js
var passCompute_default = "/**\n * The automatic GLSL constant for {@link Pass#COMPUTE}\n *\n * @name czm_passCompute\n * @glslConstant\n *\n * @see czm_pass\n */\nconst float czm_passCompute = 1.0;\n";
// packages/engine/Source/Shaders/Builtin/Constants/passEnvironment.js
var passEnvironment_default = "/**\n * The automatic GLSL constant for {@link Pass#ENVIRONMENT}\n *\n * @name czm_passEnvironment\n * @glslConstant\n *\n * @see czm_pass\n */\nconst float czm_passEnvironment = 0.0;\n";
// packages/engine/Source/Shaders/Builtin/Constants/passGlobe.js
var passGlobe_default = "/**\n * The automatic GLSL constant for {@link Pass#GLOBE}\n *\n * @name czm_passGlobe\n * @glslConstant\n *\n * @see czm_pass\n */\nconst float czm_passGlobe = 2.0;\n";
// packages/engine/Source/Shaders/Builtin/Constants/passOpaque.js
var passOpaque_default = "/**\n * The automatic GLSL constant for {@link Pass#OPAQUE}\n *\n * @name czm_passOpaque\n * @glslConstant\n *\n * @see czm_pass\n */\nconst float czm_passOpaque = 7.0;\n";
// packages/engine/Source/Shaders/Builtin/Constants/passOverlay.js
var passOverlay_default = "/**\n * The automatic GLSL constant for {@link Pass#OVERLAY}\n *\n * @name czm_passOverlay\n * @glslConstant\n *\n * @see czm_pass\n */\nconst float czm_passOverlay = 10.0;\n";
// packages/engine/Source/Shaders/Builtin/Constants/passTerrainClassification.js
var passTerrainClassification_default = "/**\n * The automatic GLSL constant for {@link Pass#TERRAIN_CLASSIFICATION}\n *\n * @name czm_passTerrainClassification\n * @glslConstant\n *\n * @see czm_pass\n */\nconst float czm_passTerrainClassification = 3.0;\n";
// packages/engine/Source/Shaders/Builtin/Constants/passTranslucent.js
var passTranslucent_default = "/**\n * The automatic GLSL constant for {@link Pass#TRANSLUCENT}\n *\n * @name czm_passTranslucent\n * @glslConstant\n *\n * @see czm_pass\n */\nconst float czm_passTranslucent = 8.0;\n";
// packages/engine/Source/Shaders/Builtin/Constants/passVoxels.js
var passVoxels_default = "/**\n * The automatic GLSL constant for {@link Pass#VOXELS}\n *\n * @name czm_passVoxels\n * @glslConstant\n *\n * @see czm_pass\n */\nconst float czm_passVoxels = 9.0;\n";
// packages/engine/Source/Shaders/Builtin/Constants/pi.js
var pi_default = "/**\n * A built-in GLSL floating-point constant for Math.PI
.\n *\n * @alias czm_pi\n * @glslConstant\n *\n * @see CesiumMath.PI\n *\n * @example\n * // GLSL declaration\n * const float czm_pi = ...;\n *\n * // Example\n * float twoPi = 2.0 * czm_pi;\n */\nconst float czm_pi = 3.141592653589793;\n";
// packages/engine/Source/Shaders/Builtin/Constants/piOverFour.js
var piOverFour_default = "/**\n * A built-in GLSL floating-point constant for pi/4
.\n *\n * @alias czm_piOverFour\n * @glslConstant\n *\n * @see CesiumMath.PI_OVER_FOUR\n *\n * @example\n * // GLSL declaration\n * const float czm_piOverFour = ...;\n *\n * // Example\n * float pi = 4.0 * czm_piOverFour;\n */\nconst float czm_piOverFour = 0.7853981633974483;\n";
// packages/engine/Source/Shaders/Builtin/Constants/piOverSix.js
var piOverSix_default = "/**\n * A built-in GLSL floating-point constant for pi/6
.\n *\n * @alias czm_piOverSix\n * @glslConstant\n *\n * @see CesiumMath.PI_OVER_SIX\n *\n * @example\n * // GLSL declaration\n * const float czm_piOverSix = ...;\n *\n * // Example\n * float pi = 6.0 * czm_piOverSix;\n */\nconst float czm_piOverSix = 0.5235987755982988;\n";
// packages/engine/Source/Shaders/Builtin/Constants/piOverThree.js
var piOverThree_default = "/**\n * A built-in GLSL floating-point constant for pi/3
.\n *\n * @alias czm_piOverThree\n * @glslConstant\n *\n * @see CesiumMath.PI_OVER_THREE\n *\n * @example\n * // GLSL declaration\n * const float czm_piOverThree = ...;\n *\n * // Example\n * float pi = 3.0 * czm_piOverThree;\n */\nconst float czm_piOverThree = 1.0471975511965976;\n";
// packages/engine/Source/Shaders/Builtin/Constants/piOverTwo.js
var piOverTwo_default = "/**\n * A built-in GLSL floating-point constant for pi/2
.\n *\n * @alias czm_piOverTwo\n * @glslConstant\n *\n * @see CesiumMath.PI_OVER_TWO\n *\n * @example\n * // GLSL declaration\n * const float czm_piOverTwo = ...;\n *\n * // Example\n * float pi = 2.0 * czm_piOverTwo;\n */\nconst float czm_piOverTwo = 1.5707963267948966;\n";
// packages/engine/Source/Shaders/Builtin/Constants/radiansPerDegree.js
var radiansPerDegree_default = "/**\n * A built-in GLSL floating-point constant for converting degrees to radians.\n *\n * @alias czm_radiansPerDegree\n * @glslConstant\n *\n * @see CesiumMath.RADIANS_PER_DEGREE\n *\n * @example\n * // GLSL declaration\n * const float czm_radiansPerDegree = ...;\n *\n * // Example\n * float rad = czm_radiansPerDegree * deg;\n */\nconst float czm_radiansPerDegree = 0.017453292519943295;\n";
// packages/engine/Source/Shaders/Builtin/Constants/sceneMode2D.js
var sceneMode2D_default = "/**\n * The constant identifier for the 2D {@link SceneMode}\n *\n * @name czm_sceneMode2D\n * @glslConstant\n * @see czm_sceneMode\n * @see czm_sceneModeColumbusView\n * @see czm_sceneMode3D\n * @see czm_sceneModeMorphing\n */\nconst float czm_sceneMode2D = 2.0;\n";
// packages/engine/Source/Shaders/Builtin/Constants/sceneMode3D.js
var sceneMode3D_default = "/**\n * The constant identifier for the 3D {@link SceneMode}\n *\n * @name czm_sceneMode3D\n * @glslConstant\n * @see czm_sceneMode\n * @see czm_sceneMode2D\n * @see czm_sceneModeColumbusView\n * @see czm_sceneModeMorphing\n */\nconst float czm_sceneMode3D = 3.0;\n";
// packages/engine/Source/Shaders/Builtin/Constants/sceneModeColumbusView.js
var sceneModeColumbusView_default = "/**\n * The constant identifier for the Columbus View {@link SceneMode}\n *\n * @name czm_sceneModeColumbusView\n * @glslConstant\n * @see czm_sceneMode\n * @see czm_sceneMode2D\n * @see czm_sceneMode3D\n * @see czm_sceneModeMorphing\n */\nconst float czm_sceneModeColumbusView = 1.0;\n";
// packages/engine/Source/Shaders/Builtin/Constants/sceneModeMorphing.js
var sceneModeMorphing_default = "/**\n * The constant identifier for the Morphing {@link SceneMode}\n *\n * @name czm_sceneModeMorphing\n * @glslConstant\n * @see czm_sceneMode\n * @see czm_sceneMode2D\n * @see czm_sceneModeColumbusView\n * @see czm_sceneMode3D\n */\nconst float czm_sceneModeMorphing = 0.0;\n";
// packages/engine/Source/Shaders/Builtin/Constants/solarRadius.js
var solarRadius_default = "/**\n * A built-in GLSL floating-point constant for one solar radius.\n *\n * @alias czm_solarRadius\n * @glslConstant\n *\n * @see CesiumMath.SOLAR_RADIUS\n *\n * @example\n * // GLSL declaration\n * const float czm_solarRadius = ...;\n */\nconst float czm_solarRadius = 695500000.0;\n";
// packages/engine/Source/Shaders/Builtin/Constants/threePiOver2.js
var threePiOver2_default = "/**\n * A built-in GLSL floating-point constant for 3pi/2
.\n *\n * @alias czm_threePiOver2\n * @glslConstant\n *\n * @see CesiumMath.THREE_PI_OVER_TWO\n *\n * @example\n * // GLSL declaration\n * const float czm_threePiOver2 = ...;\n *\n * // Example\n * float pi = (2.0 / 3.0) * czm_threePiOver2;\n */\nconst float czm_threePiOver2 = 4.71238898038469;\n";
// packages/engine/Source/Shaders/Builtin/Constants/twoPi.js
var twoPi_default = "/**\n * A built-in GLSL floating-point constant for 2pi
.\n *\n * @alias czm_twoPi\n * @glslConstant\n *\n * @see CesiumMath.TWO_PI\n *\n * @example\n * // GLSL declaration\n * const float czm_twoPi = ...;\n *\n * // Example\n * float pi = czm_twoPi / 2.0;\n */\nconst float czm_twoPi = 6.283185307179586;\n";
// packages/engine/Source/Shaders/Builtin/Constants/webMercatorMaxLatitude.js
var webMercatorMaxLatitude_default = "/**\n * The maximum latitude, in radians, both North and South, supported by a Web Mercator\n * (EPSG:3857) projection. Technically, the Mercator projection is defined\n * for any latitude up to (but not including) 90 degrees, but it makes sense\n * to cut it off sooner because it grows exponentially with increasing latitude.\n * The logic behind this particular cutoff value, which is the one used by\n * Google Maps, Bing Maps, and Esri, is that it makes the projection\n * square. That is, the rectangle is equal in the X and Y directions.\n *\n * The constant value is computed as follows:\n * czm_pi * 0.5 - (2.0 * atan(exp(-czm_pi)))\n *\n * @name czm_webMercatorMaxLatitude\n * @glslConstant\n */\nconst float czm_webMercatorMaxLatitude = 1.4844222297453324;\n";
// packages/engine/Source/Shaders/Builtin/Structs/depthRangeStruct.js
var depthRangeStruct_default = "/**\n * @name czm_depthRangeStruct\n * @glslStruct\n */\nstruct czm_depthRangeStruct\n{\n float near;\n float far;\n};\n";
// packages/engine/Source/Shaders/Builtin/Structs/material.js
var material_default = "/**\n * Holds material information that can be used for lighting. Returned by all czm_getMaterial functions.\n *\n * @name czm_material\n * @glslStruct\n *\n * @property {vec3} diffuse Incoming light that scatters evenly in all directions.\n * @property {float} specular Intensity of incoming light reflecting in a single direction.\n * @property {float} shininess The sharpness of the specular reflection. Higher values create a smaller, more focused specular highlight.\n * @property {vec3} normal Surface's normal in eye coordinates. It is used for effects such as normal mapping. The default is the surface's unmodified normal.\n * @property {vec3} emission Light emitted by the material equally in all directions. The default is vec3(0.0), which emits no light.\n * @property {float} alpha Alpha of this material. 0.0 is completely transparent; 1.0 is completely opaque.\n */\nstruct czm_material\n{\n vec3 diffuse;\n float specular;\n float shininess;\n vec3 normal;\n vec3 emission;\n float alpha;\n};\n";
// packages/engine/Source/Shaders/Builtin/Structs/materialInput.js
var materialInput_default = "/**\n * Used as input to every material's czm_getMaterial function.\n *\n * @name czm_materialInput\n * @glslStruct\n *\n * @property {float} s 1D texture coordinates.\n * @property {vec2} st 2D texture coordinates.\n * @property {vec3} str 3D texture coordinates.\n * @property {vec3} normalEC Unperturbed surface normal in eye coordinates.\n * @property {mat3} tangentToEyeMatrix Matrix for converting a tangent space normal to eye space.\n * @property {vec3} positionToEyeEC Vector from the fragment to the eye in eye coordinates. The magnitude is the distance in meters from the fragment to the eye.\n * @property {float} height The height of the terrain in meters above or below the WGS84 ellipsoid. Only available for globe materials.\n * @property {float} slope The slope of the terrain in radians. 0 is flat; pi/2 is vertical. Only available for globe materials.\n * @property {float} aspect The aspect of the terrain in radians. 0 is East, pi/2 is North, pi is West, 3pi/2 is South. Only available for globe materials.\n */\nstruct czm_materialInput\n{\n float s;\n vec2 st;\n vec3 str;\n vec3 normalEC;\n mat3 tangentToEyeMatrix;\n vec3 positionToEyeEC;\n float height;\n float slope;\n float aspect;\n};\n";
// packages/engine/Source/Shaders/Builtin/Structs/modelMaterial.js
var modelMaterial_default = "/**\n * Struct for representing a material for a {@link Model}. The model\n * rendering pipeline will pass this struct between material, custom shaders,\n * and lighting stages. This is not to be confused with {@link czm_material}\n * which is used by the older Fabric materials system, although they are similar.\n * color1
or color2
.\n * @param {float} dist The distance to the edge in texture coordinates.\n * @param {float} [fuzzFactor=0.1] Controls the blurriness between the two colors.\n * @returns {vec4} The anti-aliased color.\n *\n * @example\n * // GLSL declarations\n * vec4 czm_antialias(vec4 color1, vec4 color2, vec4 currentColor, float dist, float fuzzFactor);\n * vec4 czm_antialias(vec4 color1, vec4 color2, vec4 currentColor, float dist);\n *\n * // get the color for a material that has a sharp edge at the line y = 0.5 in texture space\n * float dist = abs(textureCoordinates.t - 0.5);\n * vec4 currentColor = mix(bottomColor, topColor, step(0.5, textureCoordinates.t));\n * vec4 color = czm_antialias(bottomColor, topColor, currentColor, dist, 0.1);\n */\nvec4 czm_antialias(vec4 color1, vec4 color2, vec4 currentColor, float dist, float fuzzFactor)\n{\n float val1 = clamp(dist / fuzzFactor, 0.0, 1.0);\n float val2 = clamp((dist - 0.5) / fuzzFactor, 0.0, 1.0);\n val1 = val1 * (1.0 - val2);\n val1 = val1 * val1 * (3.0 - (2.0 * val1));\n val1 = pow(val1, 0.5); //makes the transition nicer\n \n vec4 midColor = (color1 + color2) * 0.5;\n return mix(midColor, currentColor, val1);\n}\n\nvec4 czm_antialias(vec4 color1, vec4 color2, vec4 currentColor, float dist)\n{\n return czm_antialias(color1, color2, currentColor, dist, 0.1);\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/approximateSphericalCoordinates.js
var approximateSphericalCoordinates_default = "/**\n * Approximately computes spherical coordinates given a normal.\n * Uses approximate inverse trigonometry for speed and consistency,\n * since inverse trigonometry can differ from vendor-to-vendor and when compared with the CPU.\n *\n * @name czm_approximateSphericalCoordinates\n * @glslFunction\n *\n * @param {vec3} normal arbitrary-length normal.\n *\n * @returns {vec2} Approximate latitude and longitude spherical coordinates.\n */\nvec2 czm_approximateSphericalCoordinates(vec3 normal) {\n // Project into plane with vertical for latitude\n float latitudeApproximation = czm_fastApproximateAtan(sqrt(normal.x * normal.x + normal.y * normal.y), normal.z);\n float longitudeApproximation = czm_fastApproximateAtan(normal.x, normal.y);\n return vec2(latitudeApproximation, longitudeApproximation);\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/backFacing.js
var backFacing_default = "/**\n * Determines if the fragment is back facing\n *\n * @name czm_backFacing\n * @glslFunction \n * \n * @returns {bool} true
if the fragment is back facing; otherwise, false
.\n */\nbool czm_backFacing()\n{\n // !gl_FrontFacing doesn't work as expected on Mac/Intel so use the more verbose form instead. See https://github.com/CesiumGS/cesium/pull/8494.\n return gl_FrontFacing == false;\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/branchFreeTernary.js
var branchFreeTernary_default = "/**\n * Branchless ternary operator to be used when it's inexpensive to explicitly\n * evaluate both possibilities for a float expression.\n *\n * @name czm_branchFreeTernary\n * @glslFunction\n *\n * @param {bool} comparison A comparison statement\n * @param {float} a Value to return if the comparison is true.\n * @param {float} b Value to return if the comparison is false.\n *\n * @returns {float} equivalent of comparison ? a : b\n */\nfloat czm_branchFreeTernary(bool comparison, float a, float b) {\n float useA = float(comparison);\n return a * useA + b * (1.0 - useA);\n}\n\n/**\n * Branchless ternary operator to be used when it's inexpensive to explicitly\n * evaluate both possibilities for a vec2 expression.\n *\n * @name czm_branchFreeTernary\n * @glslFunction\n *\n * @param {bool} comparison A comparison statement\n * @param {vec2} a Value to return if the comparison is true.\n * @param {vec2} b Value to return if the comparison is false.\n *\n * @returns {vec2} equivalent of comparison ? a : b\n */\nvec2 czm_branchFreeTernary(bool comparison, vec2 a, vec2 b) {\n float useA = float(comparison);\n return a * useA + b * (1.0 - useA);\n}\n\n/**\n * Branchless ternary operator to be used when it's inexpensive to explicitly\n * evaluate both possibilities for a vec3 expression.\n *\n * @name czm_branchFreeTernary\n * @glslFunction\n *\n * @param {bool} comparison A comparison statement\n * @param {vec3} a Value to return if the comparison is true.\n * @param {vec3} b Value to return if the comparison is false.\n *\n * @returns {vec3} equivalent of comparison ? a : b\n */\nvec3 czm_branchFreeTernary(bool comparison, vec3 a, vec3 b) {\n float useA = float(comparison);\n return a * useA + b * (1.0 - useA);\n}\n\n/**\n * Branchless ternary operator to be used when it's inexpensive to explicitly\n * evaluate both possibilities for a vec4 expression.\n *\n * @name czm_branchFreeTernary\n * @glslFunction\n *\n * @param {bool} comparison A comparison statement\n * @param {vec3} a Value to return if the comparison is true.\n * @param {vec3} b Value to return if the comparison is false.\n *\n * @returns {vec3} equivalent of comparison ? a : b\n */\nvec4 czm_branchFreeTernary(bool comparison, vec4 a, vec4 b) {\n float useA = float(comparison);\n return a * useA + b * (1.0 - useA);\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/cascadeColor.js
var cascadeColor_default = "\nvec4 czm_cascadeColor(vec4 weights)\n{\n return vec4(1.0, 0.0, 0.0, 1.0) * weights.x +\n vec4(0.0, 1.0, 0.0, 1.0) * weights.y +\n vec4(0.0, 0.0, 1.0, 1.0) * weights.z +\n vec4(1.0, 0.0, 1.0, 1.0) * weights.w;\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/cascadeDistance.js
var cascadeDistance_default = "\nuniform vec4 shadowMap_cascadeDistances;\n\nfloat czm_cascadeDistance(vec4 weights)\n{\n return dot(shadowMap_cascadeDistances, weights);\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/cascadeMatrix.js
var cascadeMatrix_default = "\nuniform mat4 shadowMap_cascadeMatrices[4];\n\nmat4 czm_cascadeMatrix(vec4 weights)\n{\n return shadowMap_cascadeMatrices[0] * weights.x +\n shadowMap_cascadeMatrices[1] * weights.y +\n shadowMap_cascadeMatrices[2] * weights.z +\n shadowMap_cascadeMatrices[3] * weights.w;\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/cascadeWeights.js
var cascadeWeights_default = "\nuniform vec4 shadowMap_cascadeSplits[2];\n\nvec4 czm_cascadeWeights(float depthEye)\n{\n // One component is set to 1.0 and all others set to 0.0.\n vec4 near = step(shadowMap_cascadeSplits[0], vec4(depthEye));\n vec4 far = step(depthEye, shadowMap_cascadeSplits[1]);\n return near * far;\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/columbusViewMorph.js
var columbusViewMorph_default = "/**\n * DOC_TBA\n *\n * @name czm_columbusViewMorph\n * @glslFunction\n */\nvec4 czm_columbusViewMorph(vec4 position2D, vec4 position3D, float time)\n{\n // Just linear for now.\n vec3 p = mix(position2D.xyz, position3D.xyz, time);\n return vec4(p, 1.0);\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/computePosition.js
var computePosition_default = "/**\n * Returns a position in model coordinates relative to eye taking into\n * account the current scene mode: 3D, 2D, or Columbus view.\n * position3DHigh
, \n * position3DLow
, position2DHigh
, and position2DLow
, \n * and should be used when writing a vertex shader for an {@link Appearance}.\n *
\n * The ellipsoid is assumed to be centered at the model coordinate's origin.\n *\n * @name czm_eastNorthUpToEyeCoordinates\n * @glslFunction\n *\n * @param {vec3} positionMC The position on the ellipsoid in model coordinates.\n * @param {vec3} normalEC The normalized ellipsoid surface normal, at positionMC
, in eye coordinates.\n *\n * @returns {mat3} A 3x3 rotation matrix that transforms vectors from the east-north-up coordinate system to eye coordinates.\n *\n * @example\n * // Transform a vector defined in the east-north-up coordinate \n * // system, (0, 0, 1) which is the surface normal, to eye \n * // coordinates.\n * mat3 m = czm_eastNorthUpToEyeCoordinates(positionMC, normalEC);\n * vec3 normalEC = m * vec3(0.0, 0.0, 1.0);\n */\nmat3 czm_eastNorthUpToEyeCoordinates(vec3 positionMC, vec3 normalEC)\n{\n vec3 tangentMC = normalize(vec3(-positionMC.y, positionMC.x, 0.0)); // normalized surface tangent in model coordinates\n vec3 tangentEC = normalize(czm_normal3D * tangentMC); // normalized surface tangent in eye coordiantes\n vec3 bitangentEC = normalize(cross(normalEC, tangentEC)); // normalized surface bitangent in eye coordinates\n\n return mat3(\n tangentEC.x, tangentEC.y, tangentEC.z,\n bitangentEC.x, bitangentEC.y, bitangentEC.z,\n normalEC.x, normalEC.y, normalEC.z);\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/ellipsoidContainsPoint.js
var ellipsoidContainsPoint_default = "/**\n * DOC_TBA\n *\n * @name czm_ellipsoidContainsPoint\n * @glslFunction\n *\n */\nbool czm_ellipsoidContainsPoint(vec3 ellipsoid_inverseRadii, vec3 point)\n{\n vec3 scaled = ellipsoid_inverseRadii * (czm_inverseModelView * vec4(point, 1.0)).xyz;\n return (dot(scaled, scaled) <= 1.0);\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/ellipsoidWgs84TextureCoordinates.js
var ellipsoidWgs84TextureCoordinates_default = "/**\n * DOC_TBA\n *\n * @name czm_ellipsoidWgs84TextureCoordinates\n * @glslFunction\n */\nvec2 czm_ellipsoidWgs84TextureCoordinates(vec3 normal)\n{\n return vec2(atan(normal.y, normal.x) * czm_oneOverTwoPi + 0.5, asin(normal.z) * czm_oneOverPi + 0.5);\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/equalsEpsilon.js
var equalsEpsilon_default = "/**\n * Compares left
and right
componentwise. Returns true
\n * if they are within epsilon
and false
otherwise. The inputs\n * left
and right
can be float
s, vec2
s,\n * vec3
s, or vec4
s.\n *\n * @name czm_equalsEpsilon\n * @glslFunction\n *\n * @param {} left The first vector.\n * @param {} right The second vector.\n * @param {float} epsilon The epsilon to use for equality testing.\n * @returns {bool} true
if the components are within epsilon
and false
otherwise.\n *\n * @example\n * // GLSL declarations\n * bool czm_equalsEpsilon(float left, float right, float epsilon);\n * bool czm_equalsEpsilon(vec2 left, vec2 right, float epsilon);\n * bool czm_equalsEpsilon(vec3 left, vec3 right, float epsilon);\n * bool czm_equalsEpsilon(vec4 left, vec4 right, float epsilon);\n */\nbool czm_equalsEpsilon(vec4 left, vec4 right, float epsilon) {\n return all(lessThanEqual(abs(left - right), vec4(epsilon)));\n}\n\nbool czm_equalsEpsilon(vec3 left, vec3 right, float epsilon) {\n return all(lessThanEqual(abs(left - right), vec3(epsilon)));\n}\n\nbool czm_equalsEpsilon(vec2 left, vec2 right, float epsilon) {\n return all(lessThanEqual(abs(left - right), vec2(epsilon)));\n}\n\nbool czm_equalsEpsilon(float left, float right, float epsilon) {\n return (abs(left - right) <= epsilon);\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/eyeOffset.js
var eyeOffset_default = "/**\n * DOC_TBA\n *\n * @name czm_eyeOffset\n * @glslFunction\n *\n * @param {vec4} positionEC DOC_TBA.\n * @param {vec3} eyeOffset DOC_TBA.\n *\n * @returns {vec4} DOC_TBA.\n */\nvec4 czm_eyeOffset(vec4 positionEC, vec3 eyeOffset)\n{\n // This equation is approximate in x and y.\n vec4 p = positionEC;\n vec4 zEyeOffset = normalize(p) * eyeOffset.z;\n p.xy += eyeOffset.xy + zEyeOffset.xy;\n p.z += zEyeOffset.z;\n return p;\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/eyeToWindowCoordinates.js
var eyeToWindowCoordinates_default = "/**\n * Transforms a position from eye to window coordinates. The transformation\n * from eye to clip coordinates is done using {@link czm_projection}.\n * The transform from normalized device coordinates to window coordinates is\n * done using {@link czm_viewportTransformation}, which assumes a depth range\n * of near = 0
and far = 1
.\n *
\n * This transform is useful when there is a need to manipulate window coordinates\n * in a vertex shader as done by {@link BillboardCollection}.\n *\n * @name czm_eyeToWindowCoordinates\n * @glslFunction\n *\n * @param {vec4} position The position in eye coordinates to transform.\n *\n * @returns {vec4} The transformed position in window coordinates.\n *\n * @see czm_modelToWindowCoordinates\n * @see czm_projection\n * @see czm_viewportTransformation\n * @see BillboardCollection\n *\n * @example\n * vec4 positionWC = czm_eyeToWindowCoordinates(positionEC);\n */\nvec4 czm_eyeToWindowCoordinates(vec4 positionEC)\n{\n vec4 q = czm_projection * positionEC; // clip coordinates\n q.xyz /= q.w; // normalized device coordinates\n q.xyz = (czm_viewportTransformation * vec4(q.xyz, 1.0)).xyz; // window coordinates\n return q;\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/fastApproximateAtan.js
var fastApproximateAtan_default = `/**
* Approxiamtes atan over the range [0, 1]. Safe to flip output for negative input.
*
* Based on Michal Drobot's approximation from ShaderFastLibs, which in turn is based on
* "Efficient approximations for the arctangent function," Rajan, S. Sichun Wang Inkol, R. Joyal, A., May 2006.
* Adapted from ShaderFastLibs under MIT License.
*
* Chosen for the following characteristics over range [0, 1]:
* - basically no error at 0 and 1, important for getting around range limit (naive atan2 via atan requires infinite range atan)
* - no visible artifacts from first-derivative discontinuities, unlike latitude via range-reduced sqrt asin approximations (at equator)
*
* The original code is x * (-0.1784 * abs(x) - 0.0663 * x * x + 1.0301);
* Removed the abs() in here because it isn't needed, the input range is guaranteed as [0, 1] by how we're approximating atan2.
*
* @name czm_fastApproximateAtan
* @glslFunction
*
* @param {float} x Value between 0 and 1 inclusive.
*
* @returns {float} Approximation of atan(x)
*/
float czm_fastApproximateAtan(float x) {
return x * (-0.1784 * x - 0.0663 * x * x + 1.0301);
}
/**
* Approximation of atan2.
*
* Range reduction math based on nvidia's cg reference implementation for atan2: http://developer.download.nvidia.com/cg/atan2.html
* However, we replaced their atan curve with Michael Drobot's (see above).
*
* @name czm_fastApproximateAtan
* @glslFunction
*
* @param {float} x Value between -1 and 1 inclusive.
* @param {float} y Value between -1 and 1 inclusive.
*
* @returns {float} Approximation of atan2(x, y)
*/
float czm_fastApproximateAtan(float x, float y) {
// atan approximations are usually only reliable over [-1, 1], or, in our case, [0, 1] due to modifications.
// So range-reduce using abs and by flipping whether x or y is on top.
float t = abs(x); // t used as swap and atan result.
float opposite = abs(y);
float adjacent = max(t, opposite);
opposite = min(t, opposite);
t = czm_fastApproximateAtan(opposite / adjacent);
// Undo range reduction
t = czm_branchFreeTernary(abs(y) > abs(x), czm_piOverTwo - t, t);
t = czm_branchFreeTernary(x < 0.0, czm_pi - t, t);
t = czm_branchFreeTernary(y < 0.0, -t, t);
return t;
}
`;
// packages/engine/Source/Shaders/Builtin/Functions/fog.js
var fog_default = "/**\n * Gets the color with fog at a distance from the camera.\n *\n * @name czm_fog\n * @glslFunction\n *\n * @param {float} distanceToCamera The distance to the camera in meters.\n * @param {vec3} color The original color.\n * @param {vec3} fogColor The color of the fog.\n *\n * @returns {vec3} The color adjusted for fog at the distance from the camera.\n */\nvec3 czm_fog(float distanceToCamera, vec3 color, vec3 fogColor)\n{\n float scalar = distanceToCamera * czm_fogDensity;\n float fog = 1.0 - exp(-(scalar * scalar));\n return mix(color, fogColor, fog);\n}\n\n/**\n * Gets the color with fog at a distance from the camera.\n *\n * @name czm_fog\n * @glslFunction\n *\n * @param {float} distanceToCamera The distance to the camera in meters.\n * @param {vec3} color The original color.\n * @param {vec3} fogColor The color of the fog.\n * @param {float} fogModifierConstant A constant to modify the appearance of fog.\n *\n * @returns {vec3} The color adjusted for fog at the distance from the camera.\n */\nvec3 czm_fog(float distanceToCamera, vec3 color, vec3 fogColor, float fogModifierConstant)\n{\n float scalar = distanceToCamera * czm_fogDensity;\n float fog = 1.0 - exp(-((fogModifierConstant * scalar + fogModifierConstant) * (scalar * (1.0 + fogModifierConstant))));\n return mix(color, fogColor, fog);\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/gammaCorrect.js
var gammaCorrect_default = "/**\n * Converts a color from RGB space to linear space.\n *\n * @name czm_gammaCorrect\n * @glslFunction\n *\n * @param {vec3} color The color in RGB space.\n * @returns {vec3} The color in linear space.\n */\nvec3 czm_gammaCorrect(vec3 color) {\n#ifdef HDR\n color = pow(color, vec3(czm_gamma));\n#endif\n return color;\n}\n\nvec4 czm_gammaCorrect(vec4 color) {\n#ifdef HDR\n color.rgb = pow(color.rgb, vec3(czm_gamma));\n#endif\n return color;\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/geodeticSurfaceNormal.js
var geodeticSurfaceNormal_default = "/**\n * DOC_TBA\n *\n * @name czm_geodeticSurfaceNormal\n * @glslFunction\n *\n * @param {vec3} positionOnEllipsoid DOC_TBA\n * @param {vec3} ellipsoidCenter DOC_TBA\n * @param {vec3} oneOverEllipsoidRadiiSquared DOC_TBA\n * \n * @returns {vec3} DOC_TBA.\n */\nvec3 czm_geodeticSurfaceNormal(vec3 positionOnEllipsoid, vec3 ellipsoidCenter, vec3 oneOverEllipsoidRadiiSquared)\n{\n return normalize((positionOnEllipsoid - ellipsoidCenter) * oneOverEllipsoidRadiiSquared);\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/getDefaultMaterial.js
var getDefaultMaterial_default = "/**\n * An czm_material with default values. Every material's czm_getMaterial\n * should use this default material as a base for the material it returns.\n * The default normal value is given by materialInput.normalEC.\n *\n * @name czm_getDefaultMaterial\n * @glslFunction\n *\n * @param {czm_materialInput} input The input used to construct the default material.\n *\n * @returns {czm_material} The default material.\n *\n * @see czm_materialInput\n * @see czm_material\n * @see czm_getMaterial\n */\nczm_material czm_getDefaultMaterial(czm_materialInput materialInput)\n{\n czm_material material;\n material.diffuse = vec3(0.0);\n material.specular = 0.0;\n material.shininess = 1.0;\n material.normal = materialInput.normalEC;\n material.emission = vec3(0.0);\n material.alpha = 1.0;\n return material;\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/getLambertDiffuse.js
var getLambertDiffuse_default = "/**\n * Calculates the intensity of diffusely reflected light.\n *\n * @name czm_getLambertDiffuse\n * @glslFunction\n *\n * @param {vec3} lightDirectionEC Unit vector pointing to the light source in eye coordinates.\n * @param {vec3} normalEC The surface normal in eye coordinates.\n *\n * @returns {float} The intensity of the diffuse reflection.\n *\n * @see czm_phong\n *\n * @example\n * float diffuseIntensity = czm_getLambertDiffuse(lightDirectionEC, normalEC);\n * float specularIntensity = czm_getSpecular(lightDirectionEC, toEyeEC, normalEC, 200);\n * vec3 color = (diffuseColor * diffuseIntensity) + (specularColor * specularIntensity);\n */\nfloat czm_getLambertDiffuse(vec3 lightDirectionEC, vec3 normalEC)\n{\n return max(dot(lightDirectionEC, normalEC), 0.0);\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/getSpecular.js
var getSpecular_default = "/**\n * Calculates the specular intensity of reflected light.\n *\n * @name czm_getSpecular\n * @glslFunction\n *\n * @param {vec3} lightDirectionEC Unit vector pointing to the light source in eye coordinates.\n * @param {vec3} toEyeEC Unit vector pointing to the eye position in eye coordinates.\n * @param {vec3} normalEC The surface normal in eye coordinates.\n * @param {float} shininess The sharpness of the specular reflection. Higher values create a smaller, more focused specular highlight.\n *\n * @returns {float} The intensity of the specular highlight.\n *\n * @see czm_phong\n *\n * @example\n * float diffuseIntensity = czm_getLambertDiffuse(lightDirectionEC, normalEC);\n * float specularIntensity = czm_getSpecular(lightDirectionEC, toEyeEC, normalEC, 200);\n * vec3 color = (diffuseColor * diffuseIntensity) + (specularColor * specularIntensity);\n */\nfloat czm_getSpecular(vec3 lightDirectionEC, vec3 toEyeEC, vec3 normalEC, float shininess)\n{\n vec3 toReflectedLight = reflect(-lightDirectionEC, normalEC);\n float specular = max(dot(toReflectedLight, toEyeEC), 0.0);\n\n // pow has undefined behavior if both parameters <= 0.\n // Prevent this by making sure shininess is at least czm_epsilon2.\n return pow(specular, max(shininess, czm_epsilon2));\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/getWaterNoise.js
var getWaterNoise_default = "/**\n * @private\n */\nvec4 czm_getWaterNoise(sampler2D normalMap, vec2 uv, float time, float angleInRadians)\n{\n float cosAngle = cos(angleInRadians);\n float sinAngle = sin(angleInRadians);\n\n // time dependent sampling directions\n vec2 s0 = vec2(1.0/17.0, 0.0);\n vec2 s1 = vec2(-1.0/29.0, 0.0);\n vec2 s2 = vec2(1.0/101.0, 1.0/59.0);\n vec2 s3 = vec2(-1.0/109.0, -1.0/57.0);\n\n // rotate sampling direction by specified angle\n s0 = vec2((cosAngle * s0.x) - (sinAngle * s0.y), (sinAngle * s0.x) + (cosAngle * s0.y));\n s1 = vec2((cosAngle * s1.x) - (sinAngle * s1.y), (sinAngle * s1.x) + (cosAngle * s1.y));\n s2 = vec2((cosAngle * s2.x) - (sinAngle * s2.y), (sinAngle * s2.x) + (cosAngle * s2.y));\n s3 = vec2((cosAngle * s3.x) - (sinAngle * s3.y), (sinAngle * s3.x) + (cosAngle * s3.y));\n\n vec2 uv0 = (uv/103.0) + (time * s0);\n vec2 uv1 = uv/107.0 + (time * s1) + vec2(0.23);\n vec2 uv2 = uv/vec2(897.0, 983.0) + (time * s2) + vec2(0.51);\n vec2 uv3 = uv/vec2(991.0, 877.0) + (time * s3) + vec2(0.71);\n\n uv0 = fract(uv0);\n uv1 = fract(uv1);\n uv2 = fract(uv2);\n uv3 = fract(uv3);\n vec4 noise = (texture(normalMap, uv0)) +\n (texture(normalMap, uv1)) +\n (texture(normalMap, uv2)) +\n (texture(normalMap, uv3));\n\n // average and scale to between -1 and 1\n return ((noise / 4.0) - 0.5) * 2.0;\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/hue.js
var hue_default = "/**\n * Adjusts the hue of a color.\n * \n * @name czm_hue\n * @glslFunction\n * \n * @param {vec3} rgb The color.\n * @param {float} adjustment The amount to adjust the hue of the color in radians.\n *\n * @returns {float} The color with the hue adjusted.\n *\n * @example\n * vec3 adjustHue = czm_hue(color, czm_pi); // The same as czm_hue(color, -czm_pi)\n */\nvec3 czm_hue(vec3 rgb, float adjustment)\n{\n const mat3 toYIQ = mat3(0.299, 0.587, 0.114,\n 0.595716, -0.274453, -0.321263,\n 0.211456, -0.522591, 0.311135);\n const mat3 toRGB = mat3(1.0, 0.9563, 0.6210,\n 1.0, -0.2721, -0.6474,\n 1.0, -1.107, 1.7046);\n \n vec3 yiq = toYIQ * rgb;\n float hue = atan(yiq.z, yiq.y) + adjustment;\n float chroma = sqrt(yiq.z * yiq.z + yiq.y * yiq.y);\n \n vec3 color = vec3(yiq.x, chroma * cos(hue), chroma * sin(hue));\n return toRGB * color;\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/inverseGamma.js
var inverseGamma_default = "/**\n * Converts a color in linear space to RGB space.\n *\n * @name czm_inverseGamma\n * @glslFunction\n *\n * @param {vec3} color The color in linear space.\n * @returns {vec3} The color in RGB space.\n */\nvec3 czm_inverseGamma(vec3 color) {\n return pow(color, vec3(1.0 / czm_gamma));\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/isEmpty.js
var isEmpty_default = "/**\n * Determines if a time interval is empty.\n *\n * @name czm_isEmpty\n * @glslFunction \n * \n * @param {czm_raySegment} interval The interval to test.\n * \n * @returns {bool} true
if the time interval is empty; otherwise, false
.\n *\n * @example\n * bool b0 = czm_isEmpty(czm_emptyRaySegment); // true\n * bool b1 = czm_isEmpty(czm_raySegment(0.0, 1.0)); // false\n * bool b2 = czm_isEmpty(czm_raySegment(1.0, 1.0)); // false, contains 1.0.\n */\nbool czm_isEmpty(czm_raySegment interval)\n{\n return (interval.stop < 0.0);\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/isFull.js
var isFull_default = "/**\n * Determines if a time interval is empty.\n *\n * @name czm_isFull\n * @glslFunction \n * \n * @param {czm_raySegment} interval The interval to test.\n * \n * @returns {bool} true
if the time interval is empty; otherwise, false
.\n *\n * @example\n * bool b0 = czm_isEmpty(czm_emptyRaySegment); // true\n * bool b1 = czm_isEmpty(czm_raySegment(0.0, 1.0)); // false\n * bool b2 = czm_isEmpty(czm_raySegment(1.0, 1.0)); // false, contains 1.0.\n */\nbool czm_isFull(czm_raySegment interval)\n{\n return (interval.start == 0.0 && interval.stop == czm_infinity);\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/latitudeToWebMercatorFraction.js
var latitudeToWebMercatorFraction_default = "/**\n * Computes the fraction of a Web Wercator rectangle at which a given geodetic latitude is located.\n *\n * @name czm_latitudeToWebMercatorFraction\n * @glslFunction\n *\n * @param {float} latitude The geodetic latitude, in radians.\n * @param {float} southMercatorY The Web Mercator coordinate of the southern boundary of the rectangle.\n * @param {float} oneOverMercatorHeight The total height of the rectangle in Web Mercator coordinates.\n *\n * @returns {float} The fraction of the rectangle at which the latitude occurs. If the latitude is the southern\n * boundary of the rectangle, the return value will be zero. If it is the northern boundary, the return\n * value will be 1.0. Latitudes in between are mapped according to the Web Mercator projection.\n */ \nfloat czm_latitudeToWebMercatorFraction(float latitude, float southMercatorY, float oneOverMercatorHeight)\n{\n float sinLatitude = sin(latitude);\n float mercatorY = 0.5 * log((1.0 + sinLatitude) / (1.0 - sinLatitude));\n \n return (mercatorY - southMercatorY) * oneOverMercatorHeight;\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/lineDistance.js
var lineDistance_default = "/**\n * Computes distance from an point in 2D to a line in 2D.\n *\n * @name czm_lineDistance\n * @glslFunction\n *\n * param {vec2} point1 A point along the line.\n * param {vec2} point2 A point along the line.\n * param {vec2} point A point that may or may not be on the line.\n * returns {float} The distance from the point to the line.\n */\nfloat czm_lineDistance(vec2 point1, vec2 point2, vec2 point) {\n return abs((point2.y - point1.y) * point.x - (point2.x - point1.x) * point.y + point2.x * point1.y - point2.y * point1.x) / distance(point2, point1);\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/linearToSrgb.js
var linearToSrgb_default = "/**\n * Converts a linear RGB color to an sRGB color.\n *\n * @param {vec3|vec4} linearIn The color in linear color space.\n * @returns {vec3|vec4} The color in sRGB color space. The vector type matches the input.\n */\nvec3 czm_linearToSrgb(vec3 linearIn) \n{\n return pow(linearIn, vec3(1.0/2.2));\n}\n\nvec4 czm_linearToSrgb(vec4 linearIn) \n{\n vec3 srgbOut = pow(linearIn.rgb, vec3(1.0/2.2));\n return vec4(srgbOut, linearIn.a);\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/luminance.js
var luminance_default = "/**\n * Computes the luminance of a color. \n *\n * @name czm_luminance\n * @glslFunction\n *\n * @param {vec3} rgb The color.\n * \n * @returns {float} The luminance.\n *\n * @example\n * float light = czm_luminance(vec3(0.0)); // 0.0\n * float dark = czm_luminance(vec3(1.0)); // ~1.0 \n */\nfloat czm_luminance(vec3 rgb)\n{\n // Algorithm from Chapter 10 of Graphics Shaders.\n const vec3 W = vec3(0.2125, 0.7154, 0.0721);\n return dot(rgb, W);\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/metersPerPixel.js
var metersPerPixel_default = "/**\n * Computes the size of a pixel in meters at a distance from the eye.\n * near = 0
and far = 1
.\n *
\n * This transform is useful when there is a need to manipulate window coordinates\n * in a vertex shader as done by {@link BillboardCollection}.\n *
\n * This function should not be confused with {@link czm_viewportOrthographic},\n * which is an orthographic projection matrix that transforms from window \n * coordinates to clip coordinates.\n *\n * @name czm_modelToWindowCoordinates\n * @glslFunction\n *\n * @param {vec4} position The position in model coordinates to transform.\n *\n * @returns {vec4} The transformed position in window coordinates.\n *\n * @see czm_eyeToWindowCoordinates\n * @see czm_modelViewProjection\n * @see czm_viewportTransformation\n * @see czm_viewportOrthographic\n * @see BillboardCollection\n *\n * @example\n * vec4 positionWC = czm_modelToWindowCoordinates(positionMC);\n */\nvec4 czm_modelToWindowCoordinates(vec4 position)\n{\n vec4 q = czm_modelViewProjection * position; // clip coordinates\n q.xyz /= q.w; // normalized device coordinates\n q.xyz = (czm_viewportTransformation * vec4(q.xyz, 1.0)).xyz; // window coordinates\n return q;\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/multiplyWithColorBalance.js
var multiplyWithColorBalance_default = "/**\n * DOC_TBA\n *\n * @name czm_multiplyWithColorBalance\n * @glslFunction\n */\nvec3 czm_multiplyWithColorBalance(vec3 left, vec3 right)\n{\n // Algorithm from Chapter 10 of Graphics Shaders.\n const vec3 W = vec3(0.2125, 0.7154, 0.0721);\n \n vec3 target = left * right;\n float leftLuminance = dot(left, W);\n float rightLuminance = dot(right, W);\n float targetLuminance = dot(target, W);\n \n return ((leftLuminance + rightLuminance) / (2.0 * targetLuminance)) * target;\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/nearFarScalar.js
var nearFarScalar_default = "/**\n * Computes a value that scales with distance. The scaling is clamped at the near and\n * far distances, and does not extrapolate. This function works with the\n * {@link NearFarScalar} JavaScript class.\n *\n * @name czm_nearFarScalar\n * @glslFunction\n *\n * @param {vec4} nearFarScalar A vector with 4 components: Near distance (x), Near value (y), Far distance (z), Far value (w).\n * @param {float} cameraDistSq The square of the current distance from the camera.\n *\n * @returns {float} The value at this distance.\n */\nfloat czm_nearFarScalar(vec4 nearFarScalar, float cameraDistSq)\n{\n float valueAtMin = nearFarScalar.y;\n float valueAtMax = nearFarScalar.w;\n float nearDistanceSq = nearFarScalar.x * nearFarScalar.x;\n float farDistanceSq = nearFarScalar.z * nearFarScalar.z;\n\n float t = (cameraDistSq - nearDistanceSq) / (farDistanceSq - nearDistanceSq);\n\n t = pow(clamp(t, 0.0, 1.0), 0.2);\n\n return mix(valueAtMin, valueAtMax, t);\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/octDecode.js
var octDecode_default = ` /**
* Decodes a unit-length vector in 'oct' encoding to a normalized 3-component Cartesian vector.
* The 'oct' encoding is described in "A Survey of Efficient Representations of Independent Unit Vectors",
* Cigolle et al 2014: http://jcgt.org/published/0003/02/01/
*
* @name czm_octDecode
* @param {vec2} encoded The oct-encoded, unit-length vector
* @param {float} range The maximum value of the SNORM range. The encoded vector is stored in log2(rangeMax+1) bits.
* @returns {vec3} The decoded and normalized vector
*/
vec3 czm_octDecode(vec2 encoded, float range)
{
if (encoded.x == 0.0 && encoded.y == 0.0) {
return vec3(0.0, 0.0, 0.0);
}
encoded = encoded / range * 2.0 - 1.0;
vec3 v = vec3(encoded.x, encoded.y, 1.0 - abs(encoded.x) - abs(encoded.y));
if (v.z < 0.0)
{
v.xy = (1.0 - abs(v.yx)) * czm_signNotZero(v.xy);
}
return normalize(v);
}
/**
* Decodes a unit-length vector in 'oct' encoding to a normalized 3-component Cartesian vector.
* The 'oct' encoding is described in "A Survey of Efficient Representations of Independent Unit Vectors",
* Cigolle et al 2014: http://jcgt.org/published/0003/02/01/
*
* @name czm_octDecode
* @param {vec2} encoded The oct-encoded, unit-length vector
* @returns {vec3} The decoded and normalized vector
*/
vec3 czm_octDecode(vec2 encoded)
{
return czm_octDecode(encoded, 255.0);
}
/**
* Decodes a unit-length vector in 'oct' encoding packed into a floating-point number to a normalized 3-component Cartesian vector.
* The 'oct' encoding is described in "A Survey of Efficient Representations of Independent Unit Vectors",
* Cigolle et al 2014: http://jcgt.org/published/0003/02/01/
*
* @name czm_octDecode
* @param {float} encoded The oct-encoded, unit-length vector
* @returns {vec3} The decoded and normalized vector
*/
vec3 czm_octDecode(float encoded)
{
float temp = encoded / 256.0;
float x = floor(temp);
float y = (temp - x) * 256.0;
return czm_octDecode(vec2(x, y));
}
/**
* Decodes three unit-length vectors in 'oct' encoding packed into two floating-point numbers to normalized 3-component Cartesian vectors.
* The 'oct' encoding is described in "A Survey of Efficient Representations of Independent Unit Vectors",
* Cigolle et al 2014: http://jcgt.org/published/0003/02/01/
*
* @name czm_octDecode
* @param {vec2} encoded The packed oct-encoded, unit-length vectors.
* @param {vec3} vector1 One decoded and normalized vector.
* @param {vec3} vector2 One decoded and normalized vector.
* @param {vec3} vector3 One decoded and normalized vector.
*/
void czm_octDecode(vec2 encoded, out vec3 vector1, out vec3 vector2, out vec3 vector3)
{
float temp = encoded.x / 65536.0;
float x = floor(temp);
float encodedFloat1 = (temp - x) * 65536.0;
temp = encoded.y / 65536.0;
float y = floor(temp);
float encodedFloat2 = (temp - y) * 65536.0;
vector1 = czm_octDecode(encodedFloat1);
vector2 = czm_octDecode(encodedFloat2);
vector3 = czm_octDecode(vec2(x, y));
}
`;
// packages/engine/Source/Shaders/Builtin/Functions/packDepth.js
var packDepth_default = "/**\n * Packs a depth value into a vec3 that can be represented by unsigned bytes.\n *\n * @name czm_packDepth\n * @glslFunction\n *\n * @param {float} depth The floating-point depth.\n * @returns {vec3} The packed depth.\n */\nvec4 czm_packDepth(float depth)\n{\n // See Aras Pranckevi\u010Dius' post Encoding Floats to RGBA\n // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/\n vec4 enc = vec4(1.0, 255.0, 65025.0, 16581375.0) * depth;\n enc = fract(enc);\n enc -= enc.yzww * vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0);\n return enc;\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/pbrLighting.js
var pbrLighting_default = "vec3 lambertianDiffuse(vec3 diffuseColor)\n{\n return diffuseColor / czm_pi;\n}\n\nvec3 fresnelSchlick2(vec3 f0, vec3 f90, float VdotH)\n{\n return f0 + (f90 - f0) * pow(clamp(1.0 - VdotH, 0.0, 1.0), 5.0);\n}\n\nfloat smithVisibilityG1(float NdotV, float roughness)\n{\n // this is the k value for direct lighting.\n // for image based lighting it will be roughness^2 / 2\n float k = (roughness + 1.0) * (roughness + 1.0) / 8.0;\n return NdotV / (NdotV * (1.0 - k) + k);\n}\n\nfloat smithVisibilityGGX(float roughness, float NdotL, float NdotV)\n{\n return (\n smithVisibilityG1(NdotL, roughness) *\n smithVisibilityG1(NdotV, roughness)\n );\n}\n\nfloat GGX(float roughness, float NdotH)\n{\n float roughnessSquared = roughness * roughness;\n float f = (NdotH * roughnessSquared - NdotH) * NdotH + 1.0;\n return roughnessSquared / (czm_pi * f * f);\n}\n\n/**\n * Compute the diffuse and specular contributions using physically based\n * rendering. This function only handles direct lighting.\n * time
can be positive, negative, or zero.\n *\n * @name czm_pointAlongRay\n * @glslFunction\n *\n * @param {czm_ray} ray The ray to compute the point along.\n * @param {float} time The time along the ray.\n * \n * @returns {vec3} The point along the ray at the given time.\n * \n * @example\n * czm_ray ray = czm_ray(vec3(0.0), vec3(1.0, 0.0, 0.0)); // origin, direction\n * vec3 v = czm_pointAlongRay(ray, 2.0); // (2.0, 0.0, 0.0)\n */\nvec3 czm_pointAlongRay(czm_ray ray, float time)\n{\n return ray.origin + (time * ray.direction);\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/rayEllipsoidIntersectionInterval.js
var rayEllipsoidIntersectionInterval_default = "/**\n * DOC_TBA\n *\n * @name czm_rayEllipsoidIntersectionInterval\n * @glslFunction\n */\nczm_raySegment czm_rayEllipsoidIntersectionInterval(czm_ray ray, vec3 ellipsoid_center, vec3 ellipsoid_inverseRadii)\n{\n // ray and ellipsoid center in eye coordinates. radii in model coordinates.\n vec3 q = ellipsoid_inverseRadii * (czm_inverseModelView * vec4(ray.origin, 1.0)).xyz;\n vec3 w = ellipsoid_inverseRadii * (czm_inverseModelView * vec4(ray.direction, 0.0)).xyz;\n\n q = q - ellipsoid_inverseRadii * (czm_inverseModelView * vec4(ellipsoid_center, 1.0)).xyz;\n\n float q2 = dot(q, q);\n float qw = dot(q, w);\n\n if (q2 > 1.0) // Outside ellipsoid.\n {\n if (qw >= 0.0) // Looking outward or tangent (0 intersections).\n {\n return czm_emptyRaySegment;\n }\n else // qw < 0.0.\n {\n float qw2 = qw * qw;\n float difference = q2 - 1.0; // Positively valued.\n float w2 = dot(w, w);\n float product = w2 * difference;\n\n if (qw2 < product) // Imaginary roots (0 intersections).\n {\n return czm_emptyRaySegment;\n }\n else if (qw2 > product) // Distinct roots (2 intersections).\n {\n float discriminant = qw * qw - product;\n float temp = -qw + sqrt(discriminant); // Avoid cancellation.\n float root0 = temp / w2;\n float root1 = difference / temp;\n if (root0 < root1)\n {\n czm_raySegment i = czm_raySegment(root0, root1);\n return i;\n }\n else\n {\n czm_raySegment i = czm_raySegment(root1, root0);\n return i;\n }\n }\n else // qw2 == product. Repeated roots (2 intersections).\n {\n float root = sqrt(difference / w2);\n czm_raySegment i = czm_raySegment(root, root);\n return i;\n }\n }\n }\n else if (q2 < 1.0) // Inside ellipsoid (2 intersections).\n {\n float difference = q2 - 1.0; // Negatively valued.\n float w2 = dot(w, w);\n float product = w2 * difference; // Negatively valued.\n float discriminant = qw * qw - product;\n float temp = -qw + sqrt(discriminant); // Positively valued.\n czm_raySegment i = czm_raySegment(0.0, temp / w2);\n return i;\n }\n else // q2 == 1.0. On ellipsoid.\n {\n if (qw < 0.0) // Looking inward.\n {\n float w2 = dot(w, w);\n czm_raySegment i = czm_raySegment(0.0, -qw / w2);\n return i;\n }\n else // qw >= 0.0. Looking outward or tangent.\n {\n return czm_emptyRaySegment;\n }\n }\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/raySphereIntersectionInterval.js
var raySphereIntersectionInterval_default = "/**\n * Compute the intersection interval of a ray with a sphere.\n *\n * @name czm_raySphereIntersectionInterval\n * @glslFunction\n *\n * @param {czm_ray} ray The ray.\n * @param {vec3} center The center of the sphere.\n * @param {float} radius The radius of the sphere.\n * @return {czm_raySegment} The intersection interval of the ray with the sphere.\n */\nczm_raySegment czm_raySphereIntersectionInterval(czm_ray ray, vec3 center, float radius)\n{\n vec3 o = ray.origin;\n vec3 d = ray.direction;\n\n vec3 oc = o - center;\n\n float a = dot(d, d);\n float b = 2.0 * dot(d, oc);\n float c = dot(oc, oc) - (radius * radius);\n\n float det = (b * b) - (4.0 * a * c);\n\n if (det < 0.0) {\n return czm_emptyRaySegment;\n }\n\n float sqrtDet = sqrt(det);\n\n float t0 = (-b - sqrtDet) / (2.0 * a);\n float t1 = (-b + sqrtDet) / (2.0 * a);\n\n czm_raySegment result = czm_raySegment(t0, t1);\n return result;\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/readDepth.js
var readDepth_default = "float czm_readDepth(sampler2D depthTexture, vec2 texCoords)\n{\n return czm_reverseLogDepth(texture(depthTexture, texCoords).r);\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/readNonPerspective.js
var readNonPerspective_default = "/**\n * Reads a value previously transformed with {@link czm_writeNonPerspective}\n * by dividing it by `w`, the value used in the perspective divide.\n * This function is intended to be called in a fragment shader to access a\n * `varying` that should not be subject to perspective interpolation.\n * For example, screen-space texture coordinates. The value should have been\n * previously written in the vertex shader with a call to\n * {@link czm_writeNonPerspective}.\n *\n * @name czm_readNonPerspective\n * @glslFunction\n *\n * @param {float|vec2|vec3|vec4} value The non-perspective value to be read.\n * @param {float} oneOverW One over the perspective divide value, `w`. Usually this is simply `gl_FragCoord.w`.\n * @returns {float|vec2|vec3|vec4} The usable value.\n */\nfloat czm_readNonPerspective(float value, float oneOverW) {\n return value * oneOverW;\n}\n\nvec2 czm_readNonPerspective(vec2 value, float oneOverW) {\n return value * oneOverW;\n}\n\nvec3 czm_readNonPerspective(vec3 value, float oneOverW) {\n return value * oneOverW;\n}\n\nvec4 czm_readNonPerspective(vec4 value, float oneOverW) {\n return value * oneOverW;\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/reverseLogDepth.js
var reverseLogDepth_default = "float czm_reverseLogDepth(float logZ)\n{\n#ifdef LOG_DEPTH\n float near = czm_currentFrustum.x;\n float far = czm_currentFrustum.y;\n float log2Depth = logZ * czm_log2FarDepthFromNearPlusOne;\n float depthFromNear = pow(2.0, log2Depth) - 1.0;\n return far * (1.0 - near / (depthFromNear + near)) / (far - near);\n#endif\n return logZ;\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/round.js
var round_default = "/**\n * Round a floating point value. This function exists because round() doesn't\n * exist in GLSL 1.00. \n *\n * @param {float|vec2|vec3|vec4} value The value to round\n * @param {float|vec2|vec3|vec3} The rounded value. The type matches the input.\n */\nfloat czm_round(float value) {\n return floor(value + 0.5);\n}\n\nvec2 czm_round(vec2 value) {\n return floor(value + 0.5);\n}\n\nvec3 czm_round(vec3 value) {\n return floor(value + 0.5);\n}\n\nvec4 czm_round(vec4 value) {\n return floor(value + 0.5);\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/sampleOctahedralProjection.js
var sampleOctahedralProjection_default = "/**\n * Samples the 4 neighboring pixels and return the weighted average.\n *\n * @private\n */\nvec3 czm_sampleOctahedralProjectionWithFiltering(sampler2D projectedMap, vec2 textureSize, vec3 direction, float lod)\n{\n direction /= dot(vec3(1.0), abs(direction));\n vec2 rev = abs(direction.zx) - vec2(1.0);\n vec2 neg = vec2(direction.x < 0.0 ? rev.x : -rev.x,\n direction.z < 0.0 ? rev.y : -rev.y);\n vec2 uv = direction.y < 0.0 ? neg : direction.xz;\n vec2 coord = 0.5 * uv + vec2(0.5);\n vec2 pixel = 1.0 / textureSize;\n\n if (lod > 0.0)\n {\n // Each subseqeuent mip level is half the size\n float scale = 1.0 / pow(2.0, lod);\n float offset = ((textureSize.y + 1.0) / textureSize.x);\n\n coord.x *= offset;\n coord *= scale;\n\n coord.x += offset + pixel.x;\n coord.y += (1.0 - (1.0 / pow(2.0, lod - 1.0))) + pixel.y * (lod - 1.0) * 2.0;\n }\n else\n {\n coord.x *= (textureSize.y / textureSize.x);\n }\n\n // Do bilinear filtering\n #ifndef OES_texture_float_linear\n vec3 color1 = texture(projectedMap, coord + vec2(0.0, pixel.y)).rgb;\n vec3 color2 = texture(projectedMap, coord + vec2(pixel.x, 0.0)).rgb;\n vec3 color3 = texture(projectedMap, coord + pixel).rgb;\n vec3 color4 = texture(projectedMap, coord).rgb;\n\n vec2 texturePosition = coord * textureSize;\n\n float fu = fract(texturePosition.x);\n float fv = fract(texturePosition.y);\n\n vec3 average1 = mix(color4, color2, fu);\n vec3 average2 = mix(color1, color3, fu);\n\n vec3 color = mix(average1, average2, fv);\n #else\n vec3 color = texture(projectedMap, coord).rgb;\n #endif\n\n return color;\n}\n\n\n/**\n * Samples from a cube map that has been projected using an octahedral projection from the given direction.\n *\n * @name czm_sampleOctahedralProjection\n * @glslFunction\n *\n * @param {sampler2D} projectedMap The texture with the octahedral projected cube map.\n * @param {vec2} textureSize The width and height dimensions in pixels of the projected map.\n * @param {vec3} direction The normalized direction used to sample the cube map.\n * @param {float} lod The level of detail to sample.\n * @param {float} maxLod The maximum level of detail.\n * @returns {vec3} The color of the cube map at the direction.\n */\nvec3 czm_sampleOctahedralProjection(sampler2D projectedMap, vec2 textureSize, vec3 direction, float lod, float maxLod) {\n float currentLod = floor(lod + 0.5);\n float nextLod = min(currentLod + 1.0, maxLod);\n\n vec3 colorCurrentLod = czm_sampleOctahedralProjectionWithFiltering(projectedMap, textureSize, direction, currentLod);\n vec3 colorNextLod = czm_sampleOctahedralProjectionWithFiltering(projectedMap, textureSize, direction, nextLod);\n\n return mix(colorNextLod, colorCurrentLod, nextLod - lod);\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/saturation.js
var saturation_default = "/**\n * Adjusts the saturation of a color.\n * \n * @name czm_saturation\n * @glslFunction\n * \n * @param {vec3} rgb The color.\n * @param {float} adjustment The amount to adjust the saturation of the color.\n *\n * @returns {float} The color with the saturation adjusted.\n *\n * @example\n * vec3 greyScale = czm_saturation(color, 0.0);\n * vec3 doubleSaturation = czm_saturation(color, 2.0);\n */\nvec3 czm_saturation(vec3 rgb, float adjustment)\n{\n // Algorithm from Chapter 16 of OpenGL Shading Language\n const vec3 W = vec3(0.2125, 0.7154, 0.0721);\n vec3 intensity = vec3(dot(rgb, W));\n return mix(intensity, rgb, adjustment);\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/shadowDepthCompare.js
var shadowDepthCompare_default = "\nfloat czm_sampleShadowMap(highp samplerCube shadowMap, vec3 d)\n{\n return czm_unpackDepth(czm_textureCube(shadowMap, d));\n}\n\nfloat czm_sampleShadowMap(highp sampler2D shadowMap, vec2 uv)\n{\n#ifdef USE_SHADOW_DEPTH_TEXTURE\n return texture(shadowMap, uv).r;\n#else\n return czm_unpackDepth(texture(shadowMap, uv));\n#endif\n}\n\nfloat czm_shadowDepthCompare(samplerCube shadowMap, vec3 uv, float depth)\n{\n return step(depth, czm_sampleShadowMap(shadowMap, uv));\n}\n\nfloat czm_shadowDepthCompare(sampler2D shadowMap, vec2 uv, float depth)\n{\n return step(depth, czm_sampleShadowMap(shadowMap, uv));\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/shadowVisibility.js
var shadowVisibility_default = "\nfloat czm_private_shadowVisibility(float visibility, float nDotL, float normalShadingSmooth, float darkness)\n{\n#ifdef USE_NORMAL_SHADING\n#ifdef USE_NORMAL_SHADING_SMOOTH\n float strength = clamp(nDotL / normalShadingSmooth, 0.0, 1.0);\n#else\n float strength = step(0.0, nDotL);\n#endif\n visibility *= strength;\n#endif\n\n visibility = max(visibility, darkness);\n return visibility;\n}\n\n#ifdef USE_CUBE_MAP_SHADOW\nfloat czm_shadowVisibility(samplerCube shadowMap, czm_shadowParameters shadowParameters)\n{\n float depthBias = shadowParameters.depthBias;\n float depth = shadowParameters.depth;\n float nDotL = shadowParameters.nDotL;\n float normalShadingSmooth = shadowParameters.normalShadingSmooth;\n float darkness = shadowParameters.darkness;\n vec3 uvw = shadowParameters.texCoords;\n\n depth -= depthBias;\n float visibility = czm_shadowDepthCompare(shadowMap, uvw, depth);\n return czm_private_shadowVisibility(visibility, nDotL, normalShadingSmooth, darkness);\n}\n#else\nfloat czm_shadowVisibility(sampler2D shadowMap, czm_shadowParameters shadowParameters)\n{\n float depthBias = shadowParameters.depthBias;\n float depth = shadowParameters.depth;\n float nDotL = shadowParameters.nDotL;\n float normalShadingSmooth = shadowParameters.normalShadingSmooth;\n float darkness = shadowParameters.darkness;\n vec2 uv = shadowParameters.texCoords;\n\n depth -= depthBias;\n#ifdef USE_SOFT_SHADOWS\n vec2 texelStepSize = shadowParameters.texelStepSize;\n float radius = 1.0;\n float dx0 = -texelStepSize.x * radius;\n float dy0 = -texelStepSize.y * radius;\n float dx1 = texelStepSize.x * radius;\n float dy1 = texelStepSize.y * radius;\n float visibility = (\n czm_shadowDepthCompare(shadowMap, uv, depth) +\n czm_shadowDepthCompare(shadowMap, uv + vec2(dx0, dy0), depth) +\n czm_shadowDepthCompare(shadowMap, uv + vec2(0.0, dy0), depth) +\n czm_shadowDepthCompare(shadowMap, uv + vec2(dx1, dy0), depth) +\n czm_shadowDepthCompare(shadowMap, uv + vec2(dx0, 0.0), depth) +\n czm_shadowDepthCompare(shadowMap, uv + vec2(dx1, 0.0), depth) +\n czm_shadowDepthCompare(shadowMap, uv + vec2(dx0, dy1), depth) +\n czm_shadowDepthCompare(shadowMap, uv + vec2(0.0, dy1), depth) +\n czm_shadowDepthCompare(shadowMap, uv + vec2(dx1, dy1), depth)\n ) * (1.0 / 9.0);\n#else\n float visibility = czm_shadowDepthCompare(shadowMap, uv, depth);\n#endif\n\n return czm_private_shadowVisibility(visibility, nDotL, normalShadingSmooth, darkness);\n}\n#endif\n";
// packages/engine/Source/Shaders/Builtin/Functions/signNotZero.js
var signNotZero_default = "/**\n * Returns 1.0 if the given value is positive or zero, and -1.0 if it is negative. This is similar to the GLSL\n * built-in function sign
except that returns 1.0 instead of 0.0 when the input value is 0.0.\n * \n * @name czm_signNotZero\n * @glslFunction\n *\n * @param {} value The value for which to determine the sign.\n * @returns {} 1.0 if the value is positive or zero, -1.0 if the value is negative.\n */\nfloat czm_signNotZero(float value)\n{\n return value >= 0.0 ? 1.0 : -1.0;\n}\n\nvec2 czm_signNotZero(vec2 value)\n{\n return vec2(czm_signNotZero(value.x), czm_signNotZero(value.y));\n}\n\nvec3 czm_signNotZero(vec3 value)\n{\n return vec3(czm_signNotZero(value.x), czm_signNotZero(value.y), czm_signNotZero(value.z));\n}\n\nvec4 czm_signNotZero(vec4 value)\n{\n return vec4(czm_signNotZero(value.x), czm_signNotZero(value.y), czm_signNotZero(value.z), czm_signNotZero(value.w));\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/sphericalHarmonics.js
var sphericalHarmonics_default = "/**\n * Computes a color from the third order spherical harmonic coefficients and a normalized direction vector.\n * vec3
) that was encoded with {@link EncodedCartesian3},\n * and then provided to the shader as separate high
and low
bits to\n * be relative to the eye. As shown in the example, the position can then be transformed in eye\n * or clip coordinates using {@link czm_modelViewRelativeToEye} or {@link czm_modelViewProjectionRelativeToEye},\n * respectively.\n * matrix
can be\n * a mat2
, mat3
, or mat4
.\n *\n * @name czm_transpose\n * @glslFunction\n *\n * @param {} matrix The matrix to transpose.\n *\n * @returns {} The transposed matrix.\n *\n * @example\n * // GLSL declarations\n * mat2 czm_transpose(mat2 matrix);\n * mat3 czm_transpose(mat3 matrix);\n * mat4 czm_transpose(mat4 matrix);\n *\n * // Transpose a 3x3 rotation matrix to find its inverse.\n * mat3 eastNorthUpToEye = czm_eastNorthUpToEyeCoordinates(\n * positionMC, normalEC);\n * mat3 eyeToEastNorthUp = czm_transpose(eastNorthUpToEye);\n */\nmat2 czm_transpose(mat2 matrix)\n{\n return mat2(\n matrix[0][0], matrix[1][0],\n matrix[0][1], matrix[1][1]);\n}\n\nmat3 czm_transpose(mat3 matrix)\n{\n return mat3(\n matrix[0][0], matrix[1][0], matrix[2][0],\n matrix[0][1], matrix[1][1], matrix[2][1],\n matrix[0][2], matrix[1][2], matrix[2][2]);\n}\n\nmat4 czm_transpose(mat4 matrix)\n{\n return mat4(\n matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],\n matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],\n matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],\n matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/unpackDepth.js
var unpackDepth_default = "/**\n * Unpacks a vec4 depth value to a float in [0, 1) range.\n *\n * @name czm_unpackDepth\n * @glslFunction\n *\n * @param {vec4} packedDepth The packed depth.\n *\n * @returns {float} The floating-point depth in [0, 1) range.\n */\n float czm_unpackDepth(vec4 packedDepth)\n {\n // See Aras Pranckevi\u010Dius' post Encoding Floats to RGBA\n // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/\n return dot(packedDepth, vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0));\n }\n";
// packages/engine/Source/Shaders/Builtin/Functions/unpackFloat.js
var unpackFloat_default = "/**\n * Unpack an IEEE 754 single-precision float that is packed as a little-endian unsigned normalized vec4.\n *\n * @name czm_unpackFloat\n * @glslFunction\n *\n * @param {vec4} packedFloat The packed float.\n *\n * @returns {float} The floating-point depth in arbitrary range.\n */\nfloat czm_unpackFloat(vec4 packedFloat)\n{\n // Convert to [0.0, 255.0] and round to integer\n packedFloat = floor(packedFloat * 255.0 + 0.5);\n float sign = 1.0 - step(128.0, packedFloat[3]) * 2.0;\n float exponent = 2.0 * mod(packedFloat[3], 128.0) + step(128.0, packedFloat[2]) - 127.0; \n if (exponent == -127.0)\n {\n return 0.0;\n }\n float mantissa = mod(packedFloat[2], 128.0) * 65536.0 + packedFloat[1] * 256.0 + packedFloat[0] + float(0x800000);\n float result = sign * exp2(exponent - 23.0) * mantissa;\n return result;\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/unpackUint.js
var unpackUint_default = "/**\n * Unpack unsigned integers of 1-4 bytes. in WebGL 1, there is no uint type,\n * so the return value is an int.\n * czm_viewportTransformation
. The transformation from\n * normalized device coordinates to clip coordinates is done using fragmentCoordinate.w
,\n * which is expected to be the scalar used in the perspective divide. The transformation\n * from clip to eye coordinates is done using {@link czm_inverseProjection}.\n *\n * @name czm_windowToEyeCoordinates\n * @glslFunction\n *\n * @param {vec4} fragmentCoordinate The position in window coordinates to transform.\n *\n * @returns {vec4} The transformed position in eye coordinates.\n *\n * @see czm_modelToWindowCoordinates\n * @see czm_eyeToWindowCoordinates\n * @see czm_inverseProjection\n * @see czm_viewport\n * @see czm_viewportTransformation\n *\n * @example\n * vec4 positionEC = czm_windowToEyeCoordinates(gl_FragCoord);\n */\nvec4 czm_windowToEyeCoordinates(vec4 fragmentCoordinate)\n{\n vec2 screenCoordXY = (fragmentCoordinate.xy - czm_viewport.xy) / czm_viewport.zw;\n return czm_screenToEyeCoordinates(vec4(screenCoordXY, fragmentCoordinate.zw));\n}\n\nvec4 czm_screenToEyeCoordinates(vec2 screenCoordinateXY, float depthOrLogDepth)\n{\n // See reverseLogDepth.glsl. This is separate to re-use the pow.\n#if defined(LOG_DEPTH) || defined(LOG_DEPTH_READ_ONLY)\n float near = czm_currentFrustum.x;\n float far = czm_currentFrustum.y;\n float log2Depth = depthOrLogDepth * czm_log2FarDepthFromNearPlusOne;\n float depthFromNear = pow(2.0, log2Depth) - 1.0;\n float depthFromCamera = depthFromNear + near;\n vec4 screenCoord = vec4(screenCoordinateXY, far * (1.0 - near / depthFromCamera) / (far - near), 1.0);\n vec4 eyeCoordinate = czm_screenToEyeCoordinates(screenCoord);\n eyeCoordinate.w = 1.0 / depthFromCamera; // Better precision\n return eyeCoordinate;\n#else\n vec4 screenCoord = vec4(screenCoordinateXY, depthOrLogDepth, 1.0);\n vec4 eyeCoordinate = czm_screenToEyeCoordinates(screenCoord);\n#endif\n return eyeCoordinate;\n}\n\n/**\n * Transforms a position given as window x/y and a depth or a log depth from window to eye coordinates.\n * This function produces more accurate results for window positions with log depth than\n * conventionally unpacking the log depth using czm_reverseLogDepth and using the standard version\n * of czm_windowToEyeCoordinates.\n *\n * @name czm_windowToEyeCoordinates\n * @glslFunction\n *\n * @param {vec2} fragmentCoordinateXY The XY position in window coordinates to transform.\n * @param {float} depthOrLogDepth A depth or log depth for the fragment.\n *\n * @see czm_modelToWindowCoordinates\n * @see czm_eyeToWindowCoordinates\n * @see czm_inverseProjection\n * @see czm_viewport\n * @see czm_viewportTransformation\n *\n * @returns {vec4} The transformed position in eye coordinates.\n */\nvec4 czm_windowToEyeCoordinates(vec2 fragmentCoordinateXY, float depthOrLogDepth)\n{\n vec2 screenCoordXY = (fragmentCoordinateXY.xy - czm_viewport.xy) / czm_viewport.zw;\n return czm_screenToEyeCoordinates(screenCoordXY, depthOrLogDepth);\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/writeDepthClamp.js
var writeDepthClamp_default = "// emulated noperspective\n#if !defined(LOG_DEPTH)\nin float v_WindowZ;\n#endif\n\n/**\n * Emulates GL_DEPTH_CLAMP. Clamps a fragment to the near and far plane\n * by writing the fragment's depth. See czm_depthClamp for more details.\n *\n * @name czm_writeDepthClamp\n * @glslFunction\n *\n * @example\n * out_FragColor = color;\n * czm_writeDepthClamp();\n *\n * @see czm_depthClamp\n */\nvoid czm_writeDepthClamp()\n{\n#if (!defined(LOG_DEPTH) && (__VERSION__ == 300 || defined(GL_EXT_frag_depth)))\n gl_FragDepth = clamp(v_WindowZ * gl_FragCoord.w, 0.0, 1.0);\n#endif\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/writeLogDepth.js
var writeLogDepth_default = "#ifdef LOG_DEPTH\nin float v_depthFromNearPlusOne;\n\n#ifdef POLYGON_OFFSET\nuniform vec2 u_polygonOffset;\n#ifdef GL_OES_standard_derivatives\n#extension GL_OES_standard_derivatives : enable\n#endif\n#endif\n\n#endif\n\n/**\n * Writes the fragment depth to the logarithmic depth buffer.\n * x
) and the far distance (y
) of the frustum defined by the camera.
* This is the largest possible frustum, not an individual frustum used for multi-frustum rendering.
* @memberof UniformState.prototype
* @type {Cartesian2}
*/
entireFrustum: {
get: function() {
return this._entireFrustum;
}
},
/**
* The near distance (x
) and the far distance (y
) of the frustum defined by the camera.
* This is the individual frustum used for multi-frustum rendering.
* @memberof UniformState.prototype
* @type {Cartesian2}
*/
currentFrustum: {
get: function() {
return this._currentFrustum;
}
},
/**
* The distances to the frustum planes. The top, bottom, left and right distances are
* the x, y, z, and w components, respectively.
* @memberof UniformState.prototype
* @type {Cartesian4}
*/
frustumPlanes: {
get: function() {
return this._frustumPlanes;
}
},
/**
* The far plane's distance from the near plane, plus 1.0.
*
* @memberof UniformState.prototype
* @type {number}
*/
farDepthFromNearPlusOne: {
get: function() {
return this._farDepthFromNearPlusOne;
}
},
/**
* The log2 of {@link UniformState#farDepthFromNearPlusOne}.
*
* @memberof UniformState.prototype
* @type {number}
*/
log2FarDepthFromNearPlusOne: {
get: function() {
return this._log2FarDepthFromNearPlusOne;
}
},
/**
* 1.0 divided by {@link UniformState#log2FarDepthFromNearPlusOne}.
*
* @memberof UniformState.prototype
* @type {number}
*/
oneOverLog2FarDepthFromNearPlusOne: {
get: function() {
return this._oneOverLog2FarDepthFromNearPlusOne;
}
},
/**
* The height in meters of the eye (camera) above or below the ellipsoid.
* @memberof UniformState.prototype
* @type {number}
*/
eyeHeight: {
get: function() {
return this._eyeHeight;
}
},
/**
* The height (x
) and the height squared (y
)
* in meters of the eye (camera) above the 2D world plane. This uniform is only valid
* when the {@link SceneMode} is SCENE2D
.
* @memberof UniformState.prototype
* @type {Cartesian2}
*/
eyeHeight2D: {
get: function() {
return this._eyeHeight2D;
}
},
/**
* The sun position in 3D world coordinates at the current scene time.
* @memberof UniformState.prototype
* @type {Cartesian3}
*/
sunPositionWC: {
get: function() {
return this._sunPositionWC;
}
},
/**
* The sun position in 2D world coordinates at the current scene time.
* @memberof UniformState.prototype
* @type {Cartesian3}
*/
sunPositionColumbusView: {
get: function() {
return this._sunPositionColumbusView;
}
},
/**
* A normalized vector to the sun in 3D world coordinates at the current scene time. Even in 2D or
* Columbus View mode, this returns the direction to the sun in the 3D scene.
* @memberof UniformState.prototype
* @type {Cartesian3}
*/
sunDirectionWC: {
get: function() {
return this._sunDirectionWC;
}
},
/**
* A normalized vector to the sun in eye coordinates at the current scene time. In 3D mode, this
* returns the actual vector from the camera position to the sun position. In 2D and Columbus View, it returns
* the vector from the equivalent 3D camera position to the position of the sun in the 3D scene.
* @memberof UniformState.prototype
* @type {Cartesian3}
*/
sunDirectionEC: {
get: function() {
return this._sunDirectionEC;
}
},
/**
* A normalized vector to the moon in eye coordinates at the current scene time. In 3D mode, this
* returns the actual vector from the camera position to the moon position. In 2D and Columbus View, it returns
* the vector from the equivalent 3D camera position to the position of the moon in the 3D scene.
* @memberof UniformState.prototype
* @type {Cartesian3}
*/
moonDirectionEC: {
get: function() {
return this._moonDirectionEC;
}
},
/**
* A normalized vector to the scene's light source in 3D world coordinates. Even in 2D or
* Columbus View mode, this returns the direction to the light in the 3D scene.
* @memberof UniformState.prototype
* @type {Cartesian3}
*/
lightDirectionWC: {
get: function() {
return this._lightDirectionWC;
}
},
/**
* A normalized vector to the scene's light source in eye coordinates. In 3D mode, this
* returns the actual vector from the camera position to the light. In 2D and Columbus View, it returns
* the vector from the equivalent 3D camera position in the 3D scene.
* @memberof UniformState.prototype
* @type {Cartesian3}
*/
lightDirectionEC: {
get: function() {
return this._lightDirectionEC;
}
},
/**
* The color of light emitted by the scene's light source. This is equivalent to the light
* color multiplied by the light intensity limited to a maximum luminance of 1.0 suitable
* for non-HDR lighting.
* @memberof UniformState.prototype
* @type {Cartesian3}
*/
lightColor: {
get: function() {
return this._lightColor;
}
},
/**
* The high dynamic range color of light emitted by the scene's light source. This is equivalent to
* the light color multiplied by the light intensity suitable for HDR lighting.
* @memberof UniformState.prototype
* @type {Cartesian3}
*/
lightColorHdr: {
get: function() {
return this._lightColorHdr;
}
},
/**
* The high bits of the camera position.
* @memberof UniformState.prototype
* @type {Cartesian3}
*/
encodedCameraPositionMCHigh: {
get: function() {
cleanEncodedCameraPositionMC(this);
return this._encodedCameraPositionMC.high;
}
},
/**
* The low bits of the camera position.
* @memberof UniformState.prototype
* @type {Cartesian3}
*/
encodedCameraPositionMCLow: {
get: function() {
cleanEncodedCameraPositionMC(this);
return this._encodedCameraPositionMC.low;
}
},
/**
* A 3x3 matrix that transforms from True Equator Mean Equinox (TEME) axes to the
* pseudo-fixed axes at the Scene's current time.
* @memberof UniformState.prototype
* @type {Matrix3}
*/
temeToPseudoFixedMatrix: {
get: function() {
return this._temeToPseudoFixed;
}
},
/**
* Gets the scaling factor for transforming from the canvas
* pixel space to canvas coordinate space.
* @memberof UniformState.prototype
* @type {number}
*/
pixelRatio: {
get: function() {
return this._pixelRatio;
}
},
/**
* A scalar used to mix a color with the fog color based on the distance to the camera.
* @memberof UniformState.prototype
* @type {number}
*/
fogDensity: {
get: function() {
return this._fogDensity;
}
},
/**
* A scalar that represents the geometric tolerance per meter
* @memberof UniformState.prototype
* @type {number}
*/
geometricToleranceOverMeter: {
get: function() {
return this._geometricToleranceOverMeter;
}
},
/**
* @memberof UniformState.prototype
* @type {Pass}
*/
pass: {
get: function() {
return this._pass;
}
},
/**
* The current background color
* @memberof UniformState.prototype
* @type {Color}
*/
backgroundColor: {
get: function() {
return this._backgroundColor;
}
},
/**
* The look up texture used to find the BRDF for a material
* @memberof UniformState.prototype
* @type {Texture}
*/
brdfLut: {
get: function() {
return this._brdfLut;
}
},
/**
* The environment map of the scene
* @memberof UniformState.prototype
* @type {CubeMap}
*/
environmentMap: {
get: function() {
return this._environmentMap;
}
},
/**
* The spherical harmonic coefficients of the scene.
* @memberof UniformState.prototype
* @type {Cartesian3[]}
*/
sphericalHarmonicCoefficients: {
get: function() {
return this._sphericalHarmonicCoefficients;
}
},
/**
* The specular environment map atlas of the scene.
* @memberof UniformState.prototype
* @type {Texture}
*/
specularEnvironmentMaps: {
get: function() {
return this._specularEnvironmentMaps;
}
},
/**
* The dimensions of the specular environment map atlas of the scene.
* @memberof UniformState.prototype
* @type {Cartesian2}
*/
specularEnvironmentMapsDimensions: {
get: function() {
return this._specularEnvironmentMapsDimensions;
}
},
/**
* The maximum level-of-detail of the specular environment map atlas of the scene.
* @memberof UniformState.prototype
* @type {number}
*/
specularEnvironmentMapsMaximumLOD: {
get: function() {
return this._specularEnvironmentMapsMaximumLOD;
}
},
/**
* The splitter position to use when rendering with a splitter. This will be in pixel coordinates relative to the canvas.
* @memberof UniformState.prototype
* @type {number}
*/
splitPosition: {
get: function() {
return this._splitPosition;
}
},
/**
* The distance from the camera at which to disable the depth test of billboards, labels and points
* to, for example, prevent clipping against terrain. When set to zero, the depth test should always
* be applied. When less than zero, the depth test should never be applied.
*
* @memberof UniformState.prototype
* @type {number}
*/
minimumDisableDepthTestDistance: {
get: function() {
return this._minimumDisableDepthTestDistance;
}
},
/**
* The highlight color of unclassified 3D Tiles.
*
* @memberof UniformState.prototype
* @type {Color}
*/
invertClassificationColor: {
get: function() {
return this._invertClassificationColor;
}
},
/**
* Whether or not the current projection is orthographic in 3D.
*
* @memberOf UniformState.prototype
* @type {boolean}
*/
orthographicIn3D: {
get: function() {
return this._orthographicIn3D;
}
},
/**
* The current ellipsoid.
*
* @memberOf UniformState.prototype
* @type {Ellipsoid}
*/
ellipsoid: {
get: function() {
return defaultValue_default(this._ellipsoid, Ellipsoid_default.WGS84);
}
}
});
function setView(uniformState, matrix) {
Matrix4_default.clone(matrix, uniformState._view);
Matrix4_default.getMatrix3(matrix, uniformState._viewRotation);
uniformState._view3DDirty = true;
uniformState._inverseView3DDirty = true;
uniformState._modelViewDirty = true;
uniformState._modelView3DDirty = true;
uniformState._modelViewRelativeToEyeDirty = true;
uniformState._inverseModelViewDirty = true;
uniformState._inverseModelView3DDirty = true;
uniformState._viewProjectionDirty = true;
uniformState._inverseViewProjectionDirty = true;
uniformState._modelViewProjectionDirty = true;
uniformState._modelViewProjectionRelativeToEyeDirty = true;
uniformState._modelViewInfiniteProjectionDirty = true;
uniformState._normalDirty = true;
uniformState._inverseNormalDirty = true;
uniformState._normal3DDirty = true;
uniformState._inverseNormal3DDirty = true;
}
function setInverseView(uniformState, matrix) {
Matrix4_default.clone(matrix, uniformState._inverseView);
Matrix4_default.getMatrix3(matrix, uniformState._inverseViewRotation);
}
function setProjection(uniformState, matrix) {
Matrix4_default.clone(matrix, uniformState._projection);
uniformState._inverseProjectionDirty = true;
uniformState._viewProjectionDirty = true;
uniformState._inverseViewProjectionDirty = true;
uniformState._modelViewProjectionDirty = true;
uniformState._modelViewProjectionRelativeToEyeDirty = true;
}
function setInfiniteProjection(uniformState, matrix) {
Matrix4_default.clone(matrix, uniformState._infiniteProjection);
uniformState._modelViewInfiniteProjectionDirty = true;
}
function setCamera(uniformState, camera) {
Cartesian3_default.clone(camera.positionWC, uniformState._cameraPosition);
Cartesian3_default.clone(camera.directionWC, uniformState._cameraDirection);
Cartesian3_default.clone(camera.rightWC, uniformState._cameraRight);
Cartesian3_default.clone(camera.upWC, uniformState._cameraUp);
const positionCartographic = camera.positionCartographic;
if (!defined_default(positionCartographic)) {
uniformState._eyeHeight = -uniformState._ellipsoid.maximumRadius;
} else {
uniformState._eyeHeight = positionCartographic.height;
}
uniformState._encodedCameraPositionMCDirty = true;
}
var transformMatrix = new Matrix3_default();
var sunCartographicScratch = new Cartographic_default();
function setSunAndMoonDirections(uniformState, frameState) {
if (!defined_default(
Transforms_default.computeIcrfToFixedMatrix(frameState.time, transformMatrix)
)) {
transformMatrix = Transforms_default.computeTemeToPseudoFixedMatrix(
frameState.time,
transformMatrix
);
}
let position = Simon1994PlanetaryPositions_default.computeSunPositionInEarthInertialFrame(
frameState.time,
uniformState._sunPositionWC
);
Matrix3_default.multiplyByVector(transformMatrix, position, position);
Cartesian3_default.normalize(position, uniformState._sunDirectionWC);
position = Matrix3_default.multiplyByVector(
uniformState.viewRotation3D,
position,
uniformState._sunDirectionEC
);
Cartesian3_default.normalize(position, position);
position = Simon1994PlanetaryPositions_default.computeMoonPositionInEarthInertialFrame(
frameState.time,
uniformState._moonDirectionEC
);
Matrix3_default.multiplyByVector(transformMatrix, position, position);
Matrix3_default.multiplyByVector(uniformState.viewRotation3D, position, position);
Cartesian3_default.normalize(position, position);
const projection = frameState.mapProjection;
const ellipsoid = projection.ellipsoid;
const sunCartographic = ellipsoid.cartesianToCartographic(
uniformState._sunPositionWC,
sunCartographicScratch
);
projection.project(sunCartographic, uniformState._sunPositionColumbusView);
}
UniformState.prototype.updateCamera = function(camera) {
setView(this, camera.viewMatrix);
setInverseView(this, camera.inverseViewMatrix);
setCamera(this, camera);
this._entireFrustum.x = camera.frustum.near;
this._entireFrustum.y = camera.frustum.far;
this.updateFrustum(camera.frustum);
this._orthographicIn3D = this._mode !== SceneMode_default.SCENE2D && camera.frustum instanceof OrthographicFrustum_default;
};
UniformState.prototype.updateFrustum = function(frustum) {
setProjection(this, frustum.projectionMatrix);
if (defined_default(frustum.infiniteProjectionMatrix)) {
setInfiniteProjection(this, frustum.infiniteProjectionMatrix);
}
this._currentFrustum.x = frustum.near;
this._currentFrustum.y = frustum.far;
this._farDepthFromNearPlusOne = frustum.far - frustum.near + 1;
this._log2FarDepthFromNearPlusOne = Math_default.log2(
this._farDepthFromNearPlusOne
);
this._oneOverLog2FarDepthFromNearPlusOne = 1 / this._log2FarDepthFromNearPlusOne;
const offCenterFrustum = frustum.offCenterFrustum;
if (defined_default(offCenterFrustum)) {
frustum = offCenterFrustum;
}
this._frustumPlanes.x = frustum.top;
this._frustumPlanes.y = frustum.bottom;
this._frustumPlanes.z = frustum.left;
this._frustumPlanes.w = frustum.right;
};
UniformState.prototype.updatePass = function(pass) {
this._pass = pass;
};
var EMPTY_ARRAY = [];
var defaultLight = new SunLight_default();
UniformState.prototype.update = function(frameState) {
this._mode = frameState.mode;
this._mapProjection = frameState.mapProjection;
this._ellipsoid = frameState.mapProjection.ellipsoid;
this._pixelRatio = frameState.pixelRatio;
const camera = frameState.camera;
this.updateCamera(camera);
if (frameState.mode === SceneMode_default.SCENE2D) {
this._frustum2DWidth = camera.frustum.right - camera.frustum.left;
this._eyeHeight2D.x = this._frustum2DWidth * 0.5;
this._eyeHeight2D.y = this._eyeHeight2D.x * this._eyeHeight2D.x;
} else {
this._frustum2DWidth = 0;
this._eyeHeight2D.x = 0;
this._eyeHeight2D.y = 0;
}
setSunAndMoonDirections(this, frameState);
const light = defaultValue_default(frameState.light, defaultLight);
if (light instanceof SunLight_default) {
this._lightDirectionWC = Cartesian3_default.clone(
this._sunDirectionWC,
this._lightDirectionWC
);
this._lightDirectionEC = Cartesian3_default.clone(
this._sunDirectionEC,
this._lightDirectionEC
);
} else {
this._lightDirectionWC = Cartesian3_default.normalize(
Cartesian3_default.negate(light.direction, this._lightDirectionWC),
this._lightDirectionWC
);
this._lightDirectionEC = Matrix3_default.multiplyByVector(
this.viewRotation3D,
this._lightDirectionWC,
this._lightDirectionEC
);
}
const lightColor = light.color;
let lightColorHdr = Cartesian3_default.fromElements(
lightColor.red,
lightColor.green,
lightColor.blue,
this._lightColorHdr
);
lightColorHdr = Cartesian3_default.multiplyByScalar(
lightColorHdr,
light.intensity,
lightColorHdr
);
const maximumComponent = Cartesian3_default.maximumComponent(lightColorHdr);
if (maximumComponent > 1) {
Cartesian3_default.divideByScalar(
lightColorHdr,
maximumComponent,
this._lightColor
);
} else {
Cartesian3_default.clone(lightColorHdr, this._lightColor);
}
const brdfLutGenerator = frameState.brdfLutGenerator;
const brdfLut = defined_default(brdfLutGenerator) ? brdfLutGenerator.colorTexture : void 0;
this._brdfLut = brdfLut;
this._environmentMap = defaultValue_default(
frameState.environmentMap,
frameState.context.defaultCubeMap
);
this._sphericalHarmonicCoefficients = defaultValue_default(
frameState.sphericalHarmonicCoefficients,
EMPTY_ARRAY
);
this._specularEnvironmentMaps = frameState.specularEnvironmentMaps;
this._specularEnvironmentMapsMaximumLOD = frameState.specularEnvironmentMapsMaximumLOD;
if (defined_default(this._specularEnvironmentMaps)) {
Cartesian2_default.clone(
this._specularEnvironmentMaps.dimensions,
this._specularEnvironmentMapsDimensions
);
}
this._fogDensity = frameState.fog.density;
this._invertClassificationColor = frameState.invertClassificationColor;
this._frameState = frameState;
this._temeToPseudoFixed = Transforms_default.computeTemeToPseudoFixedMatrix(
frameState.time,
this._temeToPseudoFixed
);
this._splitPosition = frameState.splitPosition * frameState.context.drawingBufferWidth;
const fov = camera.frustum.fov;
const viewport = this._viewport;
let pixelSizePerMeter;
if (defined_default(fov)) {
if (viewport.height > viewport.width) {
pixelSizePerMeter = Math.tan(0.5 * fov) * 2 / viewport.height;
} else {
pixelSizePerMeter = Math.tan(0.5 * fov) * 2 / viewport.width;
}
} else {
pixelSizePerMeter = 1 / Math.max(viewport.width, viewport.height);
}
this._geometricToleranceOverMeter = pixelSizePerMeter * frameState.maximumScreenSpaceError;
Color_default.clone(frameState.backgroundColor, this._backgroundColor);
this._minimumDisableDepthTestDistance = frameState.minimumDisableDepthTestDistance;
this._minimumDisableDepthTestDistance *= this._minimumDisableDepthTestDistance;
if (this._minimumDisableDepthTestDistance === Number.POSITIVE_INFINITY) {
this._minimumDisableDepthTestDistance = -1;
}
};
function cleanViewport(uniformState) {
if (uniformState._viewportDirty) {
const v7 = uniformState._viewport;
Matrix4_default.computeOrthographicOffCenter(
v7.x,
v7.x + v7.width,
v7.y,
v7.y + v7.height,
0,
1,
uniformState._viewportOrthographicMatrix
);
Matrix4_default.computeViewportTransformation(
v7,
0,
1,
uniformState._viewportTransformation
);
uniformState._viewportDirty = false;
}
}
function cleanInverseProjection(uniformState) {
if (uniformState._inverseProjectionDirty) {
uniformState._inverseProjectionDirty = false;
if (uniformState._mode !== SceneMode_default.SCENE2D && uniformState._mode !== SceneMode_default.MORPHING && !uniformState._orthographicIn3D) {
Matrix4_default.inverse(
uniformState._projection,
uniformState._inverseProjection
);
} else {
Matrix4_default.clone(Matrix4_default.ZERO, uniformState._inverseProjection);
}
}
}
function cleanModelView(uniformState) {
if (uniformState._modelViewDirty) {
uniformState._modelViewDirty = false;
Matrix4_default.multiplyTransformation(
uniformState._view,
uniformState._model,
uniformState._modelView
);
}
}
function cleanModelView3D(uniformState) {
if (uniformState._modelView3DDirty) {
uniformState._modelView3DDirty = false;
Matrix4_default.multiplyTransformation(
uniformState.view3D,
uniformState._model,
uniformState._modelView3D
);
}
}
function cleanInverseModelView(uniformState) {
if (uniformState._inverseModelViewDirty) {
uniformState._inverseModelViewDirty = false;
Matrix4_default.inverse(uniformState.modelView, uniformState._inverseModelView);
}
}
function cleanInverseModelView3D(uniformState) {
if (uniformState._inverseModelView3DDirty) {
uniformState._inverseModelView3DDirty = false;
Matrix4_default.inverse(uniformState.modelView3D, uniformState._inverseModelView3D);
}
}
function cleanViewProjection(uniformState) {
if (uniformState._viewProjectionDirty) {
uniformState._viewProjectionDirty = false;
Matrix4_default.multiply(
uniformState._projection,
uniformState._view,
uniformState._viewProjection
);
}
}
function cleanInverseViewProjection(uniformState) {
if (uniformState._inverseViewProjectionDirty) {
uniformState._inverseViewProjectionDirty = false;
Matrix4_default.inverse(
uniformState.viewProjection,
uniformState._inverseViewProjection
);
}
}
function cleanModelViewProjection(uniformState) {
if (uniformState._modelViewProjectionDirty) {
uniformState._modelViewProjectionDirty = false;
Matrix4_default.multiply(
uniformState._projection,
uniformState.modelView,
uniformState._modelViewProjection
);
}
}
function cleanModelViewRelativeToEye(uniformState) {
if (uniformState._modelViewRelativeToEyeDirty) {
uniformState._modelViewRelativeToEyeDirty = false;
const mv = uniformState.modelView;
const mvRte = uniformState._modelViewRelativeToEye;
mvRte[0] = mv[0];
mvRte[1] = mv[1];
mvRte[2] = mv[2];
mvRte[3] = mv[3];
mvRte[4] = mv[4];
mvRte[5] = mv[5];
mvRte[6] = mv[6];
mvRte[7] = mv[7];
mvRte[8] = mv[8];
mvRte[9] = mv[9];
mvRte[10] = mv[10];
mvRte[11] = mv[11];
mvRte[12] = 0;
mvRte[13] = 0;
mvRte[14] = 0;
mvRte[15] = mv[15];
}
}
function cleanInverseModelViewProjection(uniformState) {
if (uniformState._inverseModelViewProjectionDirty) {
uniformState._inverseModelViewProjectionDirty = false;
Matrix4_default.inverse(
uniformState.modelViewProjection,
uniformState._inverseModelViewProjection
);
}
}
function cleanModelViewProjectionRelativeToEye(uniformState) {
if (uniformState._modelViewProjectionRelativeToEyeDirty) {
uniformState._modelViewProjectionRelativeToEyeDirty = false;
Matrix4_default.multiply(
uniformState._projection,
uniformState.modelViewRelativeToEye,
uniformState._modelViewProjectionRelativeToEye
);
}
}
function cleanModelViewInfiniteProjection(uniformState) {
if (uniformState._modelViewInfiniteProjectionDirty) {
uniformState._modelViewInfiniteProjectionDirty = false;
Matrix4_default.multiply(
uniformState._infiniteProjection,
uniformState.modelView,
uniformState._modelViewInfiniteProjection
);
}
}
function cleanNormal(uniformState) {
if (uniformState._normalDirty) {
uniformState._normalDirty = false;
const m = uniformState._normal;
Matrix4_default.getMatrix3(uniformState.inverseModelView, m);
Matrix3_default.getRotation(m, m);
Matrix3_default.transpose(m, m);
}
}
function cleanNormal3D(uniformState) {
if (uniformState._normal3DDirty) {
uniformState._normal3DDirty = false;
const m = uniformState._normal3D;
Matrix4_default.getMatrix3(uniformState.inverseModelView3D, m);
Matrix3_default.getRotation(m, m);
Matrix3_default.transpose(m, m);
}
}
function cleanInverseNormal(uniformState) {
if (uniformState._inverseNormalDirty) {
uniformState._inverseNormalDirty = false;
Matrix4_default.getMatrix3(
uniformState.inverseModelView,
uniformState._inverseNormal
);
Matrix3_default.getRotation(
uniformState._inverseNormal,
uniformState._inverseNormal
);
}
}
function cleanInverseNormal3D(uniformState) {
if (uniformState._inverseNormal3DDirty) {
uniformState._inverseNormal3DDirty = false;
Matrix4_default.getMatrix3(
uniformState.inverseModelView3D,
uniformState._inverseNormal3D
);
Matrix3_default.getRotation(
uniformState._inverseNormal3D,
uniformState._inverseNormal3D
);
}
}
var cameraPositionMC = new Cartesian3_default();
function cleanEncodedCameraPositionMC(uniformState) {
if (uniformState._encodedCameraPositionMCDirty) {
uniformState._encodedCameraPositionMCDirty = false;
Matrix4_default.multiplyByPoint(
uniformState.inverseModel,
uniformState._cameraPosition,
cameraPositionMC
);
EncodedCartesian3_default.fromCartesian(
cameraPositionMC,
uniformState._encodedCameraPositionMC
);
}
}
var view2Dto3DPScratch = new Cartesian3_default();
var view2Dto3DRScratch = new Cartesian3_default();
var view2Dto3DUScratch = new Cartesian3_default();
var view2Dto3DDScratch = new Cartesian3_default();
var view2Dto3DCartographicScratch = new Cartographic_default();
var view2Dto3DCartesian3Scratch = new Cartesian3_default();
var view2Dto3DMatrix4Scratch = new Matrix4_default();
function view2Dto3D(position2D, direction2D, right2D, up2D, frustum2DWidth, mode2, projection, result) {
const p = view2Dto3DPScratch;
p.x = position2D.y;
p.y = position2D.z;
p.z = position2D.x;
const r = view2Dto3DRScratch;
r.x = right2D.y;
r.y = right2D.z;
r.z = right2D.x;
const u3 = view2Dto3DUScratch;
u3.x = up2D.y;
u3.y = up2D.z;
u3.z = up2D.x;
const d = view2Dto3DDScratch;
d.x = direction2D.y;
d.y = direction2D.z;
d.z = direction2D.x;
if (mode2 === SceneMode_default.SCENE2D) {
p.z = frustum2DWidth * 0.5;
}
const cartographic2 = projection.unproject(p, view2Dto3DCartographicScratch);
cartographic2.longitude = Math_default.clamp(
cartographic2.longitude,
-Math.PI,
Math.PI
);
cartographic2.latitude = Math_default.clamp(
cartographic2.latitude,
-Math_default.PI_OVER_TWO,
Math_default.PI_OVER_TWO
);
const ellipsoid = projection.ellipsoid;
const position3D = ellipsoid.cartographicToCartesian(
cartographic2,
view2Dto3DCartesian3Scratch
);
const enuToFixed = Transforms_default.eastNorthUpToFixedFrame(
position3D,
ellipsoid,
view2Dto3DMatrix4Scratch
);
Matrix4_default.multiplyByPointAsVector(enuToFixed, r, r);
Matrix4_default.multiplyByPointAsVector(enuToFixed, u3, u3);
Matrix4_default.multiplyByPointAsVector(enuToFixed, d, d);
if (!defined_default(result)) {
result = new Matrix4_default();
}
result[0] = r.x;
result[1] = u3.x;
result[2] = -d.x;
result[3] = 0;
result[4] = r.y;
result[5] = u3.y;
result[6] = -d.y;
result[7] = 0;
result[8] = r.z;
result[9] = u3.z;
result[10] = -d.z;
result[11] = 0;
result[12] = -Cartesian3_default.dot(r, position3D);
result[13] = -Cartesian3_default.dot(u3, position3D);
result[14] = Cartesian3_default.dot(d, position3D);
result[15] = 1;
return result;
}
function updateView3D(that) {
if (that._view3DDirty) {
if (that._mode === SceneMode_default.SCENE3D) {
Matrix4_default.clone(that._view, that._view3D);
} else {
view2Dto3D(
that._cameraPosition,
that._cameraDirection,
that._cameraRight,
that._cameraUp,
that._frustum2DWidth,
that._mode,
that._mapProjection,
that._view3D
);
}
Matrix4_default.getMatrix3(that._view3D, that._viewRotation3D);
that._view3DDirty = false;
}
}
function updateInverseView3D(that) {
if (that._inverseView3DDirty) {
Matrix4_default.inverseTransformation(that.view3D, that._inverseView3D);
Matrix4_default.getMatrix3(that._inverseView3D, that._inverseViewRotation3D);
that._inverseView3DDirty = false;
}
}
var UniformState_default = UniformState;
// packages/engine/Source/Renderer/VertexArray.js
function addAttribute(attributes, attribute, index, context) {
const hasVertexBuffer = defined_default(attribute.vertexBuffer);
const hasValue = defined_default(attribute.value);
const componentsPerAttribute = attribute.value ? attribute.value.length : attribute.componentsPerAttribute;
if (!hasVertexBuffer && !hasValue) {
throw new DeveloperError_default("attribute must have a vertexBuffer or a value.");
}
if (hasVertexBuffer && hasValue) {
throw new DeveloperError_default(
"attribute cannot have both a vertexBuffer and a value. It must have either a vertexBuffer property defining per-vertex data or a value property defining data for all vertices."
);
}
if (componentsPerAttribute !== 1 && componentsPerAttribute !== 2 && componentsPerAttribute !== 3 && componentsPerAttribute !== 4) {
if (hasValue) {
throw new DeveloperError_default(
"attribute.value.length must be in the range [1, 4]."
);
}
throw new DeveloperError_default(
"attribute.componentsPerAttribute must be in the range [1, 4]."
);
}
if (defined_default(attribute.componentDatatype) && !ComponentDatatype_default.validate(attribute.componentDatatype)) {
throw new DeveloperError_default(
"attribute must have a valid componentDatatype or not specify it."
);
}
if (defined_default(attribute.strideInBytes) && attribute.strideInBytes > 255) {
throw new DeveloperError_default(
"attribute must have a strideInBytes less than or equal to 255 or not specify it."
);
}
if (defined_default(attribute.instanceDivisor) && attribute.instanceDivisor > 0 && !context.instancedArrays) {
throw new DeveloperError_default("instanced arrays is not supported");
}
if (defined_default(attribute.instanceDivisor) && attribute.instanceDivisor < 0) {
throw new DeveloperError_default(
"attribute must have an instanceDivisor greater than or equal to zero"
);
}
if (defined_default(attribute.instanceDivisor) && hasValue) {
throw new DeveloperError_default(
"attribute cannot have have an instanceDivisor if it is not backed by a buffer"
);
}
if (defined_default(attribute.instanceDivisor) && attribute.instanceDivisor > 0 && attribute.index === 0) {
throw new DeveloperError_default(
"attribute zero cannot have an instanceDivisor greater than 0"
);
}
const attr = {
index: defaultValue_default(attribute.index, index),
enabled: defaultValue_default(attribute.enabled, true),
vertexBuffer: attribute.vertexBuffer,
value: hasValue ? attribute.value.slice(0) : void 0,
componentsPerAttribute,
componentDatatype: defaultValue_default(
attribute.componentDatatype,
ComponentDatatype_default.FLOAT
),
normalize: defaultValue_default(attribute.normalize, false),
offsetInBytes: defaultValue_default(attribute.offsetInBytes, 0),
strideInBytes: defaultValue_default(attribute.strideInBytes, 0),
instanceDivisor: defaultValue_default(attribute.instanceDivisor, 0)
};
if (hasVertexBuffer) {
attr.vertexAttrib = function(gl) {
const index2 = this.index;
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer._getBuffer());
gl.vertexAttribPointer(
index2,
this.componentsPerAttribute,
this.componentDatatype,
this.normalize,
this.strideInBytes,
this.offsetInBytes
);
gl.enableVertexAttribArray(index2);
if (this.instanceDivisor > 0) {
context.glVertexAttribDivisor(index2, this.instanceDivisor);
context._vertexAttribDivisors[index2] = this.instanceDivisor;
context._previousDrawInstanced = true;
}
};
attr.disableVertexAttribArray = function(gl) {
gl.disableVertexAttribArray(this.index);
if (this.instanceDivisor > 0) {
context.glVertexAttribDivisor(index, 0);
}
};
} else {
switch (attr.componentsPerAttribute) {
case 1:
attr.vertexAttrib = function(gl) {
gl.vertexAttrib1fv(this.index, this.value);
};
break;
case 2:
attr.vertexAttrib = function(gl) {
gl.vertexAttrib2fv(this.index, this.value);
};
break;
case 3:
attr.vertexAttrib = function(gl) {
gl.vertexAttrib3fv(this.index, this.value);
};
break;
case 4:
attr.vertexAttrib = function(gl) {
gl.vertexAttrib4fv(this.index, this.value);
};
break;
}
attr.disableVertexAttribArray = function(gl) {
};
}
attributes.push(attr);
}
function bind(gl, attributes, indexBuffer) {
for (let i = 0; i < attributes.length; ++i) {
const attribute = attributes[i];
if (attribute.enabled) {
attribute.vertexAttrib(gl);
}
}
if (defined_default(indexBuffer)) {
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer._getBuffer());
}
}
function VertexArray(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
Check_default.defined("options.context", options.context);
Check_default.defined("options.attributes", options.attributes);
const context = options.context;
const gl = context._gl;
const attributes = options.attributes;
const indexBuffer = options.indexBuffer;
let i;
const vaAttributes = [];
let numberOfVertices = 1;
let hasInstancedAttributes = false;
let hasConstantAttributes = false;
let length3 = attributes.length;
for (i = 0; i < length3; ++i) {
addAttribute(vaAttributes, attributes[i], i, context);
}
length3 = vaAttributes.length;
for (i = 0; i < length3; ++i) {
const attribute = vaAttributes[i];
if (defined_default(attribute.vertexBuffer) && attribute.instanceDivisor === 0) {
const bytes = attribute.strideInBytes || attribute.componentsPerAttribute * ComponentDatatype_default.getSizeInBytes(attribute.componentDatatype);
numberOfVertices = attribute.vertexBuffer.sizeInBytes / bytes;
break;
}
}
for (i = 0; i < length3; ++i) {
if (vaAttributes[i].instanceDivisor > 0) {
hasInstancedAttributes = true;
}
if (defined_default(vaAttributes[i].value)) {
hasConstantAttributes = true;
}
}
const uniqueIndices = {};
for (i = 0; i < length3; ++i) {
const index = vaAttributes[i].index;
if (uniqueIndices[index]) {
throw new DeveloperError_default(
`Index ${index} is used by more than one attribute.`
);
}
uniqueIndices[index] = true;
}
let vao;
if (context.vertexArrayObject) {
vao = context.glCreateVertexArray();
context.glBindVertexArray(vao);
bind(gl, vaAttributes, indexBuffer);
context.glBindVertexArray(null);
}
this._numberOfVertices = numberOfVertices;
this._hasInstancedAttributes = hasInstancedAttributes;
this._hasConstantAttributes = hasConstantAttributes;
this._context = context;
this._gl = gl;
this._vao = vao;
this._attributes = vaAttributes;
this._indexBuffer = indexBuffer;
}
function computeNumberOfVertices(attribute) {
return attribute.values.length / attribute.componentsPerAttribute;
}
function computeAttributeSizeInBytes(attribute) {
return ComponentDatatype_default.getSizeInBytes(attribute.componentDatatype) * attribute.componentsPerAttribute;
}
function interleaveAttributes(attributes) {
let j;
let name;
let attribute;
const names = [];
for (name in attributes) {
if (attributes.hasOwnProperty(name) && defined_default(attributes[name]) && defined_default(attributes[name].values)) {
names.push(name);
if (attributes[name].componentDatatype === ComponentDatatype_default.DOUBLE) {
attributes[name].componentDatatype = ComponentDatatype_default.FLOAT;
attributes[name].values = ComponentDatatype_default.createTypedArray(
ComponentDatatype_default.FLOAT,
attributes[name].values
);
}
}
}
let numberOfVertices;
const namesLength = names.length;
if (namesLength > 0) {
numberOfVertices = computeNumberOfVertices(attributes[names[0]]);
for (j = 1; j < namesLength; ++j) {
const currentNumberOfVertices = computeNumberOfVertices(
attributes[names[j]]
);
if (currentNumberOfVertices !== numberOfVertices) {
throw new RuntimeError_default(
`${"Each attribute list must have the same number of vertices. Attribute "}${names[j]} has a different number of vertices (${currentNumberOfVertices.toString()}) than attribute ${names[0]} (${numberOfVertices.toString()}).`
);
}
}
}
names.sort(function(left, right) {
return ComponentDatatype_default.getSizeInBytes(attributes[right].componentDatatype) - ComponentDatatype_default.getSizeInBytes(attributes[left].componentDatatype);
});
let vertexSizeInBytes = 0;
const offsetsInBytes = {};
for (j = 0; j < namesLength; ++j) {
name = names[j];
attribute = attributes[name];
offsetsInBytes[name] = vertexSizeInBytes;
vertexSizeInBytes += computeAttributeSizeInBytes(attribute);
}
if (vertexSizeInBytes > 0) {
const maxComponentSizeInBytes = ComponentDatatype_default.getSizeInBytes(
attributes[names[0]].componentDatatype
);
const remainder = vertexSizeInBytes % maxComponentSizeInBytes;
if (remainder !== 0) {
vertexSizeInBytes += maxComponentSizeInBytes - remainder;
}
const vertexBufferSizeInBytes = numberOfVertices * vertexSizeInBytes;
const buffer = new ArrayBuffer(vertexBufferSizeInBytes);
const views = {};
for (j = 0; j < namesLength; ++j) {
name = names[j];
const sizeInBytes = ComponentDatatype_default.getSizeInBytes(
attributes[name].componentDatatype
);
views[name] = {
pointer: ComponentDatatype_default.createTypedArray(
attributes[name].componentDatatype,
buffer
),
index: offsetsInBytes[name] / sizeInBytes,
// Offset in ComponentType
strideInComponentType: vertexSizeInBytes / sizeInBytes
};
}
for (j = 0; j < numberOfVertices; ++j) {
for (let n = 0; n < namesLength; ++n) {
name = names[n];
attribute = attributes[name];
const values = attribute.values;
const view = views[name];
const pointer = view.pointer;
const numberOfComponents = attribute.componentsPerAttribute;
for (let k = 0; k < numberOfComponents; ++k) {
pointer[view.index + k] = values[j * numberOfComponents + k];
}
view.index += view.strideInComponentType;
}
}
return {
buffer,
offsetsInBytes,
vertexSizeInBytes
};
}
return void 0;
}
VertexArray.fromGeometry = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
Check_default.defined("options.context", options.context);
const context = options.context;
const geometry = defaultValue_default(options.geometry, defaultValue_default.EMPTY_OBJECT);
const bufferUsage = defaultValue_default(
options.bufferUsage,
BufferUsage_default.DYNAMIC_DRAW
);
const attributeLocations8 = defaultValue_default(
options.attributeLocations,
defaultValue_default.EMPTY_OBJECT
);
const interleave = defaultValue_default(options.interleave, false);
const createdVAAttributes = options.vertexArrayAttributes;
let name;
let attribute;
let vertexBuffer;
const vaAttributes = defined_default(createdVAAttributes) ? createdVAAttributes : [];
const attributes = geometry.attributes;
if (interleave) {
const interleavedAttributes = interleaveAttributes(attributes);
if (defined_default(interleavedAttributes)) {
vertexBuffer = Buffer_default.createVertexBuffer({
context,
typedArray: interleavedAttributes.buffer,
usage: bufferUsage
});
const offsetsInBytes = interleavedAttributes.offsetsInBytes;
const strideInBytes = interleavedAttributes.vertexSizeInBytes;
for (name in attributes) {
if (attributes.hasOwnProperty(name) && defined_default(attributes[name])) {
attribute = attributes[name];
if (defined_default(attribute.values)) {
vaAttributes.push({
index: attributeLocations8[name],
vertexBuffer,
componentDatatype: attribute.componentDatatype,
componentsPerAttribute: attribute.componentsPerAttribute,
normalize: attribute.normalize,
offsetInBytes: offsetsInBytes[name],
strideInBytes
});
} else {
vaAttributes.push({
index: attributeLocations8[name],
value: attribute.value,
componentDatatype: attribute.componentDatatype,
normalize: attribute.normalize
});
}
}
}
}
} else {
for (name in attributes) {
if (attributes.hasOwnProperty(name) && defined_default(attributes[name])) {
attribute = attributes[name];
let componentDatatype = attribute.componentDatatype;
if (componentDatatype === ComponentDatatype_default.DOUBLE) {
componentDatatype = ComponentDatatype_default.FLOAT;
}
vertexBuffer = void 0;
if (defined_default(attribute.values)) {
vertexBuffer = Buffer_default.createVertexBuffer({
context,
typedArray: ComponentDatatype_default.createTypedArray(
componentDatatype,
attribute.values
),
usage: bufferUsage
});
}
vaAttributes.push({
index: attributeLocations8[name],
vertexBuffer,
value: attribute.value,
componentDatatype,
componentsPerAttribute: attribute.componentsPerAttribute,
normalize: attribute.normalize
});
}
}
}
let indexBuffer;
const indices2 = geometry.indices;
if (defined_default(indices2)) {
if (Geometry_default.computeNumberOfVertices(geometry) >= Math_default.SIXTY_FOUR_KILOBYTES && context.elementIndexUint) {
indexBuffer = Buffer_default.createIndexBuffer({
context,
typedArray: new Uint32Array(indices2),
usage: bufferUsage,
indexDatatype: IndexDatatype_default.UNSIGNED_INT
});
} else {
indexBuffer = Buffer_default.createIndexBuffer({
context,
typedArray: new Uint16Array(indices2),
usage: bufferUsage,
indexDatatype: IndexDatatype_default.UNSIGNED_SHORT
});
}
}
return new VertexArray({
context,
attributes: vaAttributes,
indexBuffer
});
};
Object.defineProperties(VertexArray.prototype, {
numberOfAttributes: {
get: function() {
return this._attributes.length;
}
},
numberOfVertices: {
get: function() {
return this._numberOfVertices;
}
},
indexBuffer: {
get: function() {
return this._indexBuffer;
}
}
});
VertexArray.prototype.getAttribute = function(index) {
Check_default.defined("index", index);
return this._attributes[index];
};
function setVertexAttribDivisor(vertexArray) {
const context = vertexArray._context;
const hasInstancedAttributes = vertexArray._hasInstancedAttributes;
if (!hasInstancedAttributes && !context._previousDrawInstanced) {
return;
}
context._previousDrawInstanced = hasInstancedAttributes;
const divisors = context._vertexAttribDivisors;
const attributes = vertexArray._attributes;
const maxAttributes = ContextLimits_default.maximumVertexAttributes;
let i;
if (hasInstancedAttributes) {
const length3 = attributes.length;
for (i = 0; i < length3; ++i) {
const attribute = attributes[i];
if (attribute.enabled) {
const divisor = attribute.instanceDivisor;
const index = attribute.index;
if (divisor !== divisors[index]) {
context.glVertexAttribDivisor(index, divisor);
divisors[index] = divisor;
}
}
}
} else {
for (i = 0; i < maxAttributes; ++i) {
if (divisors[i] > 0) {
context.glVertexAttribDivisor(i, 0);
divisors[i] = 0;
}
}
}
}
function setConstantAttributes(vertexArray, gl) {
const attributes = vertexArray._attributes;
const length3 = attributes.length;
for (let i = 0; i < length3; ++i) {
const attribute = attributes[i];
if (attribute.enabled && defined_default(attribute.value)) {
attribute.vertexAttrib(gl);
}
}
}
VertexArray.prototype._bind = function() {
if (defined_default(this._vao)) {
this._context.glBindVertexArray(this._vao);
if (this._context.instancedArrays) {
setVertexAttribDivisor(this);
}
if (this._hasConstantAttributes) {
setConstantAttributes(this, this._gl);
}
} else {
bind(this._gl, this._attributes, this._indexBuffer);
}
};
VertexArray.prototype._unBind = function() {
if (defined_default(this._vao)) {
this._context.glBindVertexArray(null);
} else {
const attributes = this._attributes;
const gl = this._gl;
for (let i = 0; i < attributes.length; ++i) {
const attribute = attributes[i];
if (attribute.enabled) {
attribute.disableVertexAttribArray(gl);
}
}
if (this._indexBuffer) {
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
}
}
};
VertexArray.prototype.isDestroyed = function() {
return false;
};
VertexArray.prototype.destroy = function() {
const attributes = this._attributes;
for (let i = 0; i < attributes.length; ++i) {
const vertexBuffer = attributes[i].vertexBuffer;
if (defined_default(vertexBuffer) && !vertexBuffer.isDestroyed() && vertexBuffer.vertexArrayDestroyable) {
vertexBuffer.destroy();
}
}
const indexBuffer = this._indexBuffer;
if (defined_default(indexBuffer) && !indexBuffer.isDestroyed() && indexBuffer.vertexArrayDestroyable) {
indexBuffer.destroy();
}
if (defined_default(this._vao)) {
this._context.glDeleteVertexArray(this._vao);
}
return destroyObject_default(this);
};
var VertexArray_default = VertexArray;
// packages/engine/Source/Renderer/Context.js
function Context(canvas, options) {
Check_default.defined("canvas", canvas);
const {
getWebGLStub,
requestWebgl1,
webgl: webglOptions = {},
allowTextureFilterAnisotropic = true
} = defaultValue_default(options, {});
webglOptions.alpha = defaultValue_default(webglOptions.alpha, false);
webglOptions.stencil = defaultValue_default(webglOptions.stencil, true);
webglOptions.powerPreference = defaultValue_default(
webglOptions.powerPreference,
"high-performance"
);
const glContext = defined_default(getWebGLStub) ? getWebGLStub(canvas, webglOptions) : getWebGLContext(canvas, webglOptions, requestWebgl1);
const webgl2Supported = typeof WebGL2RenderingContext !== "undefined";
const webgl2 = webgl2Supported && glContext instanceof WebGL2RenderingContext;
this._canvas = canvas;
this._originalGLContext = glContext;
this._gl = glContext;
this._webgl2 = webgl2;
this._id = createGuid_default();
this.validateFramebuffer = false;
this.validateShaderProgram = false;
this.logShaderCompilation = false;
this._throwOnWebGLError = false;
this._shaderCache = new ShaderCache_default(this);
this._textureCache = new TextureCache_default();
const gl = glContext;
this._stencilBits = gl.getParameter(gl.STENCIL_BITS);
ContextLimits_default._maximumCombinedTextureImageUnits = gl.getParameter(
gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS
);
ContextLimits_default._maximumCubeMapSize = gl.getParameter(
gl.MAX_CUBE_MAP_TEXTURE_SIZE
);
ContextLimits_default._maximumFragmentUniformVectors = gl.getParameter(
gl.MAX_FRAGMENT_UNIFORM_VECTORS
);
ContextLimits_default._maximumTextureImageUnits = gl.getParameter(
gl.MAX_TEXTURE_IMAGE_UNITS
);
ContextLimits_default._maximumRenderbufferSize = gl.getParameter(
gl.MAX_RENDERBUFFER_SIZE
);
ContextLimits_default._maximumTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
ContextLimits_default._maximumVaryingVectors = gl.getParameter(
gl.MAX_VARYING_VECTORS
);
ContextLimits_default._maximumVertexAttributes = gl.getParameter(
gl.MAX_VERTEX_ATTRIBS
);
ContextLimits_default._maximumVertexTextureImageUnits = gl.getParameter(
gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS
);
ContextLimits_default._maximumVertexUniformVectors = gl.getParameter(
gl.MAX_VERTEX_UNIFORM_VECTORS
);
ContextLimits_default._maximumSamples = this._webgl2 ? gl.getParameter(gl.MAX_SAMPLES) : 0;
const aliasedLineWidthRange = gl.getParameter(gl.ALIASED_LINE_WIDTH_RANGE);
ContextLimits_default._minimumAliasedLineWidth = aliasedLineWidthRange[0];
ContextLimits_default._maximumAliasedLineWidth = aliasedLineWidthRange[1];
const aliasedPointSizeRange = gl.getParameter(gl.ALIASED_POINT_SIZE_RANGE);
ContextLimits_default._minimumAliasedPointSize = aliasedPointSizeRange[0];
ContextLimits_default._maximumAliasedPointSize = aliasedPointSizeRange[1];
const maximumViewportDimensions = gl.getParameter(gl.MAX_VIEWPORT_DIMS);
ContextLimits_default._maximumViewportWidth = maximumViewportDimensions[0];
ContextLimits_default._maximumViewportHeight = maximumViewportDimensions[1];
const highpFloat = gl.getShaderPrecisionFormat(
gl.FRAGMENT_SHADER,
gl.HIGH_FLOAT
);
ContextLimits_default._highpFloatSupported = highpFloat.precision !== 0;
const highpInt = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_INT);
ContextLimits_default._highpIntSupported = highpInt.rangeMax !== 0;
this._antialias = gl.getContextAttributes().antialias;
this._standardDerivatives = !!getExtension(gl, ["OES_standard_derivatives"]);
this._blendMinmax = !!getExtension(gl, ["EXT_blend_minmax"]);
this._elementIndexUint = !!getExtension(gl, ["OES_element_index_uint"]);
this._depthTexture = !!getExtension(gl, [
"WEBGL_depth_texture",
"WEBKIT_WEBGL_depth_texture"
]);
this._fragDepth = !!getExtension(gl, ["EXT_frag_depth"]);
this._debugShaders = getExtension(gl, ["WEBGL_debug_shaders"]);
this._textureFloat = !!getExtension(gl, ["OES_texture_float"]);
this._textureHalfFloat = !!getExtension(gl, ["OES_texture_half_float"]);
this._textureFloatLinear = !!getExtension(gl, ["OES_texture_float_linear"]);
this._textureHalfFloatLinear = !!getExtension(gl, [
"OES_texture_half_float_linear"
]);
this._colorBufferFloat = !!getExtension(gl, [
"EXT_color_buffer_float",
"WEBGL_color_buffer_float"
]);
this._floatBlend = !!getExtension(gl, ["EXT_float_blend"]);
this._colorBufferHalfFloat = !!getExtension(gl, [
"EXT_color_buffer_half_float"
]);
this._s3tc = !!getExtension(gl, [
"WEBGL_compressed_texture_s3tc",
"MOZ_WEBGL_compressed_texture_s3tc",
"WEBKIT_WEBGL_compressed_texture_s3tc"
]);
this._pvrtc = !!getExtension(gl, [
"WEBGL_compressed_texture_pvrtc",
"WEBKIT_WEBGL_compressed_texture_pvrtc"
]);
this._astc = !!getExtension(gl, ["WEBGL_compressed_texture_astc"]);
this._etc = !!getExtension(gl, ["WEBG_compressed_texture_etc"]);
this._etc1 = !!getExtension(gl, ["WEBGL_compressed_texture_etc1"]);
this._bc7 = !!getExtension(gl, ["EXT_texture_compression_bptc"]);
loadKTX2_default.setKTX2SupportedFormats(
this._s3tc,
this._pvrtc,
this._astc,
this._etc,
this._etc1,
this._bc7
);
const textureFilterAnisotropic = allowTextureFilterAnisotropic ? getExtension(gl, [
"EXT_texture_filter_anisotropic",
"WEBKIT_EXT_texture_filter_anisotropic"
]) : void 0;
this._textureFilterAnisotropic = textureFilterAnisotropic;
ContextLimits_default._maximumTextureFilterAnisotropy = defined_default(
textureFilterAnisotropic
) ? gl.getParameter(textureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 1;
let glCreateVertexArray;
let glBindVertexArray;
let glDeleteVertexArray;
let glDrawElementsInstanced;
let glDrawArraysInstanced;
let glVertexAttribDivisor;
let glDrawBuffers;
let vertexArrayObject;
let instancedArrays;
let drawBuffers;
if (webgl2) {
const that = this;
glCreateVertexArray = function() {
return that._gl.createVertexArray();
};
glBindVertexArray = function(vao) {
that._gl.bindVertexArray(vao);
};
glDeleteVertexArray = function(vao) {
that._gl.deleteVertexArray(vao);
};
glDrawElementsInstanced = function(mode2, count, type, offset2, instanceCount) {
gl.drawElementsInstanced(mode2, count, type, offset2, instanceCount);
};
glDrawArraysInstanced = function(mode2, first, count, instanceCount) {
gl.drawArraysInstanced(mode2, first, count, instanceCount);
};
glVertexAttribDivisor = function(index, divisor) {
gl.vertexAttribDivisor(index, divisor);
};
glDrawBuffers = function(buffers) {
gl.drawBuffers(buffers);
};
} else {
vertexArrayObject = getExtension(gl, ["OES_vertex_array_object"]);
if (defined_default(vertexArrayObject)) {
glCreateVertexArray = function() {
return vertexArrayObject.createVertexArrayOES();
};
glBindVertexArray = function(vertexArray) {
vertexArrayObject.bindVertexArrayOES(vertexArray);
};
glDeleteVertexArray = function(vertexArray) {
vertexArrayObject.deleteVertexArrayOES(vertexArray);
};
}
instancedArrays = getExtension(gl, ["ANGLE_instanced_arrays"]);
if (defined_default(instancedArrays)) {
glDrawElementsInstanced = function(mode2, count, type, offset2, instanceCount) {
instancedArrays.drawElementsInstancedANGLE(
mode2,
count,
type,
offset2,
instanceCount
);
};
glDrawArraysInstanced = function(mode2, first, count, instanceCount) {
instancedArrays.drawArraysInstancedANGLE(
mode2,
first,
count,
instanceCount
);
};
glVertexAttribDivisor = function(index, divisor) {
instancedArrays.vertexAttribDivisorANGLE(index, divisor);
};
}
drawBuffers = getExtension(gl, ["WEBGL_draw_buffers"]);
if (defined_default(drawBuffers)) {
glDrawBuffers = function(buffers) {
drawBuffers.drawBuffersWEBGL(buffers);
};
}
}
this.glCreateVertexArray = glCreateVertexArray;
this.glBindVertexArray = glBindVertexArray;
this.glDeleteVertexArray = glDeleteVertexArray;
this.glDrawElementsInstanced = glDrawElementsInstanced;
this.glDrawArraysInstanced = glDrawArraysInstanced;
this.glVertexAttribDivisor = glVertexAttribDivisor;
this.glDrawBuffers = glDrawBuffers;
this._vertexArrayObject = !!vertexArrayObject;
this._instancedArrays = !!instancedArrays;
this._drawBuffers = !!drawBuffers;
ContextLimits_default._maximumDrawBuffers = this.drawBuffers ? gl.getParameter(WebGLConstants_default.MAX_DRAW_BUFFERS) : 1;
ContextLimits_default._maximumColorAttachments = this.drawBuffers ? gl.getParameter(WebGLConstants_default.MAX_COLOR_ATTACHMENTS) : 1;
this._clearColor = new Color_default(0, 0, 0, 0);
this._clearDepth = 1;
this._clearStencil = 0;
const us = new UniformState_default();
const ps = new PassState_default(this);
const rs = RenderState_default.fromCache();
this._defaultPassState = ps;
this._defaultRenderState = rs;
this._defaultTexture = void 0;
this._defaultEmissiveTexture = void 0;
this._defaultNormalTexture = void 0;
this._defaultCubeMap = void 0;
this._us = us;
this._currentRenderState = rs;
this._currentPassState = ps;
this._currentFramebuffer = void 0;
this._maxFrameTextureUnitIndex = 0;
this._vertexAttribDivisors = [];
this._previousDrawInstanced = false;
for (let i = 0; i < ContextLimits_default._maximumVertexAttributes; i++) {
this._vertexAttribDivisors.push(0);
}
this._pickObjects = {};
this._nextPickColor = new Uint32Array(1);
this.options = {
getWebGLStub,
requestWebgl1,
webgl: webglOptions,
allowTextureFilterAnisotropic
};
this.cache = {};
RenderState_default.apply(gl, rs, ps);
}
function getWebGLContext(canvas, webglOptions, requestWebgl1) {
if (typeof WebGLRenderingContext === "undefined") {
throw new RuntimeError_default(
"The browser does not support WebGL. Visit http://get.webgl.org."
);
}
const webgl2Supported = typeof WebGL2RenderingContext !== "undefined";
if (!requestWebgl1 && !webgl2Supported) {
requestWebgl1 = true;
}
const contextType = requestWebgl1 ? "webgl" : "webgl2";
const glContext = canvas.getContext(contextType, webglOptions);
if (!defined_default(glContext)) {
throw new RuntimeError_default(
"The browser supports WebGL, but initialization failed."
);
}
return glContext;
}
function errorToString(gl, error) {
let message = "WebGL Error: ";
switch (error) {
case gl.INVALID_ENUM:
message += "INVALID_ENUM";
break;
case gl.INVALID_VALUE:
message += "INVALID_VALUE";
break;
case gl.INVALID_OPERATION:
message += "INVALID_OPERATION";
break;
case gl.OUT_OF_MEMORY:
message += "OUT_OF_MEMORY";
break;
case gl.CONTEXT_LOST_WEBGL:
message += "CONTEXT_LOST_WEBGL lost";
break;
default:
message += `Unknown (${error})`;
}
return message;
}
function createErrorMessage(gl, glFunc, glFuncArguments, error) {
let message = `${errorToString(gl, error)}: ${glFunc.name}(`;
for (let i = 0; i < glFuncArguments.length; ++i) {
if (i !== 0) {
message += ", ";
}
message += glFuncArguments[i];
}
message += ");";
return message;
}
function throwOnError(gl, glFunc, glFuncArguments) {
const error = gl.getError();
if (error !== gl.NO_ERROR) {
throw new RuntimeError_default(
createErrorMessage(gl, glFunc, glFuncArguments, error)
);
}
}
function makeGetterSetter(gl, propertyName, logFunction) {
return {
get: function() {
const value = gl[propertyName];
logFunction(gl, `get: ${propertyName}`, value);
return gl[propertyName];
},
set: function(value) {
gl[propertyName] = value;
logFunction(gl, `set: ${propertyName}`, value);
}
};
}
function wrapGL(gl, logFunction) {
if (!defined_default(logFunction)) {
return gl;
}
function wrapFunction2(property) {
return function() {
const result = property.apply(gl, arguments);
logFunction(gl, property, arguments);
return result;
};
}
const glWrapper = {};
for (const propertyName in gl) {
const property = gl[propertyName];
if (property instanceof Function) {
glWrapper[propertyName] = wrapFunction2(property);
} else {
Object.defineProperty(
glWrapper,
propertyName,
makeGetterSetter(gl, propertyName, logFunction)
);
}
}
return glWrapper;
}
function getExtension(gl, names) {
const length3 = names.length;
for (let i = 0; i < length3; ++i) {
const extension = gl.getExtension(names[i]);
if (extension) {
return extension;
}
}
return void 0;
}
var defaultFramebufferMarker = {};
Object.defineProperties(Context.prototype, {
id: {
get: function() {
return this._id;
}
},
webgl2: {
get: function() {
return this._webgl2;
}
},
canvas: {
get: function() {
return this._canvas;
}
},
shaderCache: {
get: function() {
return this._shaderCache;
}
},
textureCache: {
get: function() {
return this._textureCache;
}
},
uniformState: {
get: function() {
return this._us;
}
},
/**
* The number of stencil bits per pixel in the default bound framebuffer. The minimum is eight bits.
* @memberof Context.prototype
* @type {number}
* @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with STENCIL_BITS
.
*/
stencilBits: {
get: function() {
return this._stencilBits;
}
},
/**
* true
if the WebGL context supports stencil buffers.
* Stencil buffers are not supported by all systems.
* @memberof Context.prototype
* @type {boolean}
*/
stencilBuffer: {
get: function() {
return this._stencilBits >= 8;
}
},
/**
* true
if the WebGL context supports antialiasing. By default
* antialiasing is requested, but it is not supported by all systems.
* @memberof Context.prototype
* @type {boolean}
*/
antialias: {
get: function() {
return this._antialias;
}
},
/**
* true
if the WebGL context supports multisample antialiasing. Requires
* WebGL2.
* @memberof Context.prototype
* @type {boolean}
*/
msaa: {
get: function() {
return this._webgl2;
}
},
/**
* true
if the OES_standard_derivatives extension is supported. This
* extension provides access to dFdx
, dFdy
, and fwidth
* functions from GLSL. A shader using these functions still needs to explicitly enable the
* extension with #extension GL_OES_standard_derivatives : enable
.
* @memberof Context.prototype
* @type {boolean}
* @see {@link http://www.khronos.org/registry/gles/extensions/OES/OES_standard_derivatives.txt|OES_standard_derivatives}
*/
standardDerivatives: {
get: function() {
return this._standardDerivatives || this._webgl2;
}
},
/**
* true
if the EXT_float_blend extension is supported. This
* extension enables blending with 32-bit float values.
* @memberof Context.prototype
* @type {boolean}
* @see {@link https://www.khronos.org/registry/webgl/extensions/EXT_float_blend/}
*/
floatBlend: {
get: function() {
return this._floatBlend;
}
},
/**
* true
if the EXT_blend_minmax extension is supported. This
* extension extends blending capabilities by adding two new blend equations:
* the minimum or maximum color components of the source and destination colors.
* @memberof Context.prototype
* @type {boolean}
* @see {@link https://www.khronos.org/registry/webgl/extensions/EXT_blend_minmax/}
*/
blendMinmax: {
get: function() {
return this._blendMinmax || this._webgl2;
}
},
/**
* true
if the OES_element_index_uint extension is supported. This
* extension allows the use of unsigned int indices, which can improve performance by
* eliminating batch breaking caused by unsigned short indices.
* @memberof Context.prototype
* @type {boolean}
* @see {@link http://www.khronos.org/registry/webgl/extensions/OES_element_index_uint/|OES_element_index_uint}
*/
elementIndexUint: {
get: function() {
return this._elementIndexUint || this._webgl2;
}
},
/**
* true
if WEBGL_depth_texture is supported. This extension provides
* access to depth textures that, for example, can be attached to framebuffers for shadow mapping.
* @memberof Context.prototype
* @type {boolean}
* @see {@link http://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/|WEBGL_depth_texture}
*/
depthTexture: {
get: function() {
return this._depthTexture || this._webgl2;
}
},
/**
* true
if OES_texture_float is supported. This extension provides
* access to floating point textures that, for example, can be attached to framebuffers for high dynamic range.
* @memberof Context.prototype
* @type {boolean}
* @see {@link https://www.khronos.org/registry/webgl/extensions/OES_texture_float/}
*/
floatingPointTexture: {
get: function() {
return this._webgl2 || this._textureFloat;
}
},
/**
* true
if OES_texture_half_float is supported. This extension provides
* access to floating point textures that, for example, can be attached to framebuffers for high dynamic range.
* @memberof Context.prototype
* @type {boolean}
* @see {@link https://www.khronos.org/registry/webgl/extensions/OES_texture_half_float/}
*/
halfFloatingPointTexture: {
get: function() {
return this._webgl2 || this._textureHalfFloat;
}
},
/**
* true
if OES_texture_float_linear is supported. This extension provides
* access to linear sampling methods for minification and magnification filters of floating-point textures.
* @memberof Context.prototype
* @type {boolean}
* @see {@link https://www.khronos.org/registry/webgl/extensions/OES_texture_float_linear/}
*/
textureFloatLinear: {
get: function() {
return this._textureFloatLinear;
}
},
/**
* true
if OES_texture_half_float_linear is supported. This extension provides
* access to linear sampling methods for minification and magnification filters of half floating-point textures.
* @memberof Context.prototype
* @type {boolean}
* @see {@link https://www.khronos.org/registry/webgl/extensions/OES_texture_half_float_linear/}
*/
textureHalfFloatLinear: {
get: function() {
return this._webgl2 && this._textureFloatLinear || !this._webgl2 && this._textureHalfFloatLinear;
}
},
/**
* true
if EXT_texture_filter_anisotropic is supported. This extension provides
* access to anisotropic filtering for textured surfaces at an oblique angle from the viewer.
* @memberof Context.prototype
* @type {boolean}
* @see {@link https://www.khronos.org/registry/webgl/extensions/EXT_texture_filter_anisotropic/}
*/
textureFilterAnisotropic: {
get: function() {
return !!this._textureFilterAnisotropic;
}
},
/**
* true
if WEBGL_compressed_texture_s3tc is supported. This extension provides
* access to DXT compressed textures.
* @memberof Context.prototype
* @type {boolean}
* @see {@link https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_s3tc/}
*/
s3tc: {
get: function() {
return this._s3tc;
}
},
/**
* true
if WEBGL_compressed_texture_pvrtc is supported. This extension provides
* access to PVR compressed textures.
* @memberof Context.prototype
* @type {boolean}
* @see {@link https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_pvrtc/}
*/
pvrtc: {
get: function() {
return this._pvrtc;
}
},
/**
* true
if WEBGL_compressed_texture_astc is supported. This extension provides
* access to ASTC compressed textures.
* @memberof Context.prototype
* @type {boolean}
* @see {@link https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_astc/}
*/
astc: {
get: function() {
return this._astc;
}
},
/**
* true
if WEBGL_compressed_texture_etc is supported. This extension provides
* access to ETC compressed textures.
* @memberof Context.prototype
* @type {boolean}
* @see {@link https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_etc/}
*/
etc: {
get: function() {
return this._etc;
}
},
/**
* true
if WEBGL_compressed_texture_etc1 is supported. This extension provides
* access to ETC1 compressed textures.
* @memberof Context.prototype
* @type {boolean}
* @see {@link https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_etc1/}
*/
etc1: {
get: function() {
return this._etc1;
}
},
/**
* true
if EXT_texture_compression_bptc is supported. This extension provides
* access to BC7 compressed textures.
* @memberof Context.prototype
* @type {boolean}
* @see {@link https://www.khronos.org/registry/webgl/extensions/EXT_texture_compression_bptc/}
*/
bc7: {
get: function() {
return this._bc7;
}
},
/**
* true
if S3TC, PVRTC, ASTC, ETC, ETC1, or BC7 compression is supported.
* @memberof Context.prototype
* @type {boolean}
*/
supportsBasis: {
get: function() {
return this._s3tc || this._pvrtc || this._astc || this._etc || this._etc1 || this._bc7;
}
},
/**
* true
if the OES_vertex_array_object extension is supported. This
* extension can improve performance by reducing the overhead of switching vertex arrays.
* When enabled, this extension is automatically used by {@link VertexArray}.
* @memberof Context.prototype
* @type {boolean}
* @see {@link http://www.khronos.org/registry/webgl/extensions/OES_vertex_array_object/|OES_vertex_array_object}
*/
vertexArrayObject: {
get: function() {
return this._vertexArrayObject || this._webgl2;
}
},
/**
* true
if the EXT_frag_depth extension is supported. This
* extension provides access to the gl_FragDepthEXT
built-in output variable
* from GLSL fragment shaders. A shader using these functions still needs to explicitly enable the
* extension with #extension GL_EXT_frag_depth : enable
.
* @memberof Context.prototype
* @type {boolean}
* @see {@link http://www.khronos.org/registry/webgl/extensions/EXT_frag_depth/|EXT_frag_depth}
*/
fragmentDepth: {
get: function() {
return this._fragDepth || this._webgl2;
}
},
/**
* true
if the ANGLE_instanced_arrays extension is supported. This
* extension provides access to instanced rendering.
* @memberof Context.prototype
* @type {boolean}
* @see {@link https://www.khronos.org/registry/webgl/extensions/ANGLE_instanced_arrays}
*/
instancedArrays: {
get: function() {
return this._instancedArrays || this._webgl2;
}
},
/**
* true
if the EXT_color_buffer_float extension is supported. This
* extension makes the gl.RGBA32F format color renderable.
* @memberof Context.prototype
* @type {boolean}
* @see {@link https://www.khronos.org/registry/webgl/extensions/WEBGL_color_buffer_float/}
* @see {@link https://www.khronos.org/registry/webgl/extensions/EXT_color_buffer_float/}
*/
colorBufferFloat: {
get: function() {
return this._colorBufferFloat;
}
},
/**
* true
if the EXT_color_buffer_half_float extension is supported. This
* extension makes the format gl.RGBA16F format color renderable.
* @memberof Context.prototype
* @type {boolean}
* @see {@link https://www.khronos.org/registry/webgl/extensions/EXT_color_buffer_half_float/}
* @see {@link https://www.khronos.org/registry/webgl/extensions/EXT_color_buffer_float/}
*/
colorBufferHalfFloat: {
get: function() {
return this._webgl2 && this._colorBufferFloat || !this._webgl2 && this._colorBufferHalfFloat;
}
},
/**
* true
if the WEBGL_draw_buffers extension is supported. This
* extensions provides support for multiple render targets. The framebuffer object can have mutiple
* color attachments and the GLSL fragment shader can write to the built-in output array gl_FragData
.
* A shader using this feature needs to explicitly enable the extension with
* #extension GL_EXT_draw_buffers : enable
.
* @memberof Context.prototype
* @type {boolean}
* @see {@link http://www.khronos.org/registry/webgl/extensions/WEBGL_draw_buffers/|WEBGL_draw_buffers}
*/
drawBuffers: {
get: function() {
return this._drawBuffers || this._webgl2;
}
},
debugShaders: {
get: function() {
return this._debugShaders;
}
},
throwOnWebGLError: {
get: function() {
return this._throwOnWebGLError;
},
set: function(value) {
this._throwOnWebGLError = value;
this._gl = wrapGL(
this._originalGLContext,
value ? throwOnError : void 0
);
}
},
/**
* A 1x1 RGBA texture initialized to [255, 255, 255, 255]. This can
* be used as a placeholder texture while other textures are downloaded.
* @memberof Context.prototype
* @type {Texture}
*/
defaultTexture: {
get: function() {
if (this._defaultTexture === void 0) {
this._defaultTexture = new Texture_default({
context: this,
source: {
width: 1,
height: 1,
arrayBufferView: new Uint8Array([255, 255, 255, 255])
},
flipY: false
});
}
return this._defaultTexture;
}
},
/**
* A 1x1 RGB texture initialized to [0, 0, 0] representing a material that is
* not emissive. This can be used as a placeholder texture for emissive
* textures while other textures are downloaded.
* @memberof Context.prototype
* @type {Texture}
*/
defaultEmissiveTexture: {
get: function() {
if (this._defaultEmissiveTexture === void 0) {
this._defaultEmissiveTexture = new Texture_default({
context: this,
pixelFormat: PixelFormat_default.RGB,
source: {
width: 1,
height: 1,
arrayBufferView: new Uint8Array([0, 0, 0])
},
flipY: false
});
}
return this._defaultEmissiveTexture;
}
},
/**
* A 1x1 RGBA texture initialized to [128, 128, 255] to encode a tangent
* space normal pointing in the +z direction, i.e. (0, 0, 1). This can
* be used as a placeholder normal texture while other textures are
* downloaded.
* @memberof Context.prototype
* @type {Texture}
*/
defaultNormalTexture: {
get: function() {
if (this._defaultNormalTexture === void 0) {
this._defaultNormalTexture = new Texture_default({
context: this,
pixelFormat: PixelFormat_default.RGB,
source: {
width: 1,
height: 1,
arrayBufferView: new Uint8Array([128, 128, 255])
},
flipY: false
});
}
return this._defaultNormalTexture;
}
},
/**
* A cube map, where each face is a 1x1 RGBA texture initialized to
* [255, 255, 255, 255]. This can be used as a placeholder cube map while
* other cube maps are downloaded.
* @memberof Context.prototype
* @type {CubeMap}
*/
defaultCubeMap: {
get: function() {
if (this._defaultCubeMap === void 0) {
const face = {
width: 1,
height: 1,
arrayBufferView: new Uint8Array([255, 255, 255, 255])
};
this._defaultCubeMap = new CubeMap_default({
context: this,
source: {
positiveX: face,
negativeX: face,
positiveY: face,
negativeY: face,
positiveZ: face,
negativeZ: face
},
flipY: false
});
}
return this._defaultCubeMap;
}
},
/**
* The drawingBufferHeight of the underlying GL context.
* @memberof Context.prototype
* @type {number}
* @see {@link https://www.khronos.org/registry/webgl/specs/1.0/#DOM-WebGLRenderingContext-drawingBufferHeight|drawingBufferHeight}
*/
drawingBufferHeight: {
get: function() {
return this._gl.drawingBufferHeight;
}
},
/**
* The drawingBufferWidth of the underlying GL context.
* @memberof Context.prototype
* @type {number}
* @see {@link https://www.khronos.org/registry/webgl/specs/1.0/#DOM-WebGLRenderingContext-drawingBufferWidth|drawingBufferWidth}
*/
drawingBufferWidth: {
get: function() {
return this._gl.drawingBufferWidth;
}
},
/**
* Gets an object representing the currently bound framebuffer. While this instance is not an actual
* {@link Framebuffer}, it is used to represent the default framebuffer in calls to
* {@link Texture.fromFramebuffer}.
* @memberof Context.prototype
* @type {object}
*/
defaultFramebuffer: {
get: function() {
return defaultFramebufferMarker;
}
}
});
function validateFramebuffer(context) {
if (context.validateFramebuffer) {
const gl = context._gl;
const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
if (status !== gl.FRAMEBUFFER_COMPLETE) {
let message;
switch (status) {
case gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
message = "Framebuffer is not complete. Incomplete attachment: at least one attachment point with a renderbuffer or texture attached has its attached object no longer in existence or has an attached image with a width or height of zero, or the color attachment point has a non-color-renderable image attached, or the depth attachment point has a non-depth-renderable image attached, or the stencil attachment point has a non-stencil-renderable image attached. Color-renderable formats include GL_RGBA4, GL_RGB5_A1, and GL_RGB565. GL_DEPTH_COMPONENT16 is the only depth-renderable format. GL_STENCIL_INDEX8 is the only stencil-renderable format.";
break;
case gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:
message = "Framebuffer is not complete. Incomplete dimensions: not all attached images have the same width and height.";
break;
case gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
message = "Framebuffer is not complete. Missing attachment: no images are attached to the framebuffer.";
break;
case gl.FRAMEBUFFER_UNSUPPORTED:
message = "Framebuffer is not complete. Unsupported: the combination of internal formats of the attached images violates an implementation-dependent set of restrictions.";
break;
}
throw new DeveloperError_default(message);
}
}
}
function applyRenderState(context, renderState, passState, clear2) {
const previousRenderState = context._currentRenderState;
const previousPassState = context._currentPassState;
context._currentRenderState = renderState;
context._currentPassState = passState;
RenderState_default.partialApply(
context._gl,
previousRenderState,
renderState,
previousPassState,
passState,
clear2
);
}
var scratchBackBufferArray;
if (typeof WebGLRenderingContext !== "undefined") {
scratchBackBufferArray = [WebGLConstants_default.BACK];
}
function bindFramebuffer(context, framebuffer) {
if (framebuffer !== context._currentFramebuffer) {
context._currentFramebuffer = framebuffer;
let buffers = scratchBackBufferArray;
if (defined_default(framebuffer)) {
framebuffer._bind();
validateFramebuffer(context);
buffers = framebuffer._getActiveColorAttachments();
} else {
const gl = context._gl;
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
}
if (context.drawBuffers) {
context.glDrawBuffers(buffers);
}
}
}
var defaultClearCommand = new ClearCommand_default();
Context.prototype.clear = function(clearCommand, passState) {
clearCommand = defaultValue_default(clearCommand, defaultClearCommand);
passState = defaultValue_default(passState, this._defaultPassState);
const gl = this._gl;
let bitmask = 0;
const c = clearCommand.color;
const d = clearCommand.depth;
const s = clearCommand.stencil;
if (defined_default(c)) {
if (!Color_default.equals(this._clearColor, c)) {
Color_default.clone(c, this._clearColor);
gl.clearColor(c.red, c.green, c.blue, c.alpha);
}
bitmask |= gl.COLOR_BUFFER_BIT;
}
if (defined_default(d)) {
if (d !== this._clearDepth) {
this._clearDepth = d;
gl.clearDepth(d);
}
bitmask |= gl.DEPTH_BUFFER_BIT;
}
if (defined_default(s)) {
if (s !== this._clearStencil) {
this._clearStencil = s;
gl.clearStencil(s);
}
bitmask |= gl.STENCIL_BUFFER_BIT;
}
const rs = defaultValue_default(clearCommand.renderState, this._defaultRenderState);
applyRenderState(this, rs, passState, true);
const framebuffer = defaultValue_default(
clearCommand.framebuffer,
passState.framebuffer
);
bindFramebuffer(this, framebuffer);
gl.clear(bitmask);
};
function beginDraw(context, framebuffer, passState, shaderProgram, renderState) {
if (defined_default(framebuffer) && renderState.depthTest) {
if (renderState.depthTest.enabled && !framebuffer.hasDepthAttachment) {
throw new DeveloperError_default(
"The depth test can not be enabled (drawCommand.renderState.depthTest.enabled) because the framebuffer (drawCommand.framebuffer) does not have a depth or depth-stencil renderbuffer."
);
}
}
bindFramebuffer(context, framebuffer);
applyRenderState(context, renderState, passState, false);
shaderProgram._bind();
context._maxFrameTextureUnitIndex = Math.max(
context._maxFrameTextureUnitIndex,
shaderProgram.maximumTextureUnitIndex
);
}
function continueDraw(context, drawCommand, shaderProgram, uniformMap2) {
const primitiveType = drawCommand._primitiveType;
const va = drawCommand._vertexArray;
let offset2 = drawCommand._offset;
let count = drawCommand._count;
const instanceCount = drawCommand.instanceCount;
if (!PrimitiveType_default.validate(primitiveType)) {
throw new DeveloperError_default(
"drawCommand.primitiveType is required and must be valid."
);
}
Check_default.defined("drawCommand.vertexArray", va);
Check_default.typeOf.number.greaterThanOrEquals("drawCommand.offset", offset2, 0);
if (defined_default(count)) {
Check_default.typeOf.number.greaterThanOrEquals("drawCommand.count", count, 0);
}
Check_default.typeOf.number.greaterThanOrEquals(
"drawCommand.instanceCount",
instanceCount,
0
);
if (instanceCount > 0 && !context.instancedArrays) {
throw new DeveloperError_default("Instanced arrays extension is not supported");
}
context._us.model = defaultValue_default(drawCommand._modelMatrix, Matrix4_default.IDENTITY);
shaderProgram._setUniforms(
uniformMap2,
context._us,
context.validateShaderProgram
);
va._bind();
const indexBuffer = va.indexBuffer;
if (defined_default(indexBuffer)) {
offset2 = offset2 * indexBuffer.bytesPerIndex;
count = defaultValue_default(count, indexBuffer.numberOfIndices);
if (instanceCount === 0) {
context._gl.drawElements(
primitiveType,
count,
indexBuffer.indexDatatype,
offset2
);
} else {
context.glDrawElementsInstanced(
primitiveType,
count,
indexBuffer.indexDatatype,
offset2,
instanceCount
);
}
} else {
count = defaultValue_default(count, va.numberOfVertices);
if (instanceCount === 0) {
context._gl.drawArrays(primitiveType, offset2, count);
} else {
context.glDrawArraysInstanced(
primitiveType,
offset2,
count,
instanceCount
);
}
}
va._unBind();
}
Context.prototype.draw = function(drawCommand, passState, shaderProgram, uniformMap2) {
Check_default.defined("drawCommand", drawCommand);
Check_default.defined("drawCommand.shaderProgram", drawCommand._shaderProgram);
passState = defaultValue_default(passState, this._defaultPassState);
const framebuffer = defaultValue_default(
drawCommand._framebuffer,
passState.framebuffer
);
const renderState = defaultValue_default(
drawCommand._renderState,
this._defaultRenderState
);
shaderProgram = defaultValue_default(shaderProgram, drawCommand._shaderProgram);
uniformMap2 = defaultValue_default(uniformMap2, drawCommand._uniformMap);
beginDraw(this, framebuffer, passState, shaderProgram, renderState);
continueDraw(this, drawCommand, shaderProgram, uniformMap2);
};
Context.prototype.endFrame = function() {
const gl = this._gl;
gl.useProgram(null);
this._currentFramebuffer = void 0;
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
const buffers = scratchBackBufferArray;
if (this.drawBuffers) {
this.glDrawBuffers(buffers);
}
const length3 = this._maxFrameTextureUnitIndex;
this._maxFrameTextureUnitIndex = 0;
for (let i = 0; i < length3; ++i) {
gl.activeTexture(gl.TEXTURE0 + i);
gl.bindTexture(gl.TEXTURE_2D, null);
gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
}
};
Context.prototype.readPixels = function(readState) {
const gl = this._gl;
readState = defaultValue_default(readState, defaultValue_default.EMPTY_OBJECT);
const x = Math.max(defaultValue_default(readState.x, 0), 0);
const y = Math.max(defaultValue_default(readState.y, 0), 0);
const width = defaultValue_default(readState.width, gl.drawingBufferWidth);
const height = defaultValue_default(readState.height, gl.drawingBufferHeight);
const framebuffer = readState.framebuffer;
Check_default.typeOf.number.greaterThan("readState.width", width, 0);
Check_default.typeOf.number.greaterThan("readState.height", height, 0);
let pixelDatatype = PixelDatatype_default.UNSIGNED_BYTE;
if (defined_default(framebuffer) && framebuffer.numberOfColorAttachments > 0) {
pixelDatatype = framebuffer.getColorTexture(0).pixelDatatype;
}
const pixels = PixelFormat_default.createTypedArray(
PixelFormat_default.RGBA,
pixelDatatype,
width,
height
);
bindFramebuffer(this, framebuffer);
gl.readPixels(
x,
y,
width,
height,
PixelFormat_default.RGBA,
PixelDatatype_default.toWebGLConstant(pixelDatatype, this),
pixels
);
return pixels;
};
var viewportQuadAttributeLocations = {
position: 0,
textureCoordinates: 1
};
Context.prototype.getViewportQuadVertexArray = function() {
let vertexArray = this.cache.viewportQuad_vertexArray;
if (!defined_default(vertexArray)) {
const geometry = new Geometry_default({
attributes: {
position: new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 2,
values: [-1, -1, 1, -1, 1, 1, -1, 1]
}),
textureCoordinates: new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 2,
values: [0, 0, 1, 0, 1, 1, 0, 1]
})
},
// Workaround Internet Explorer 11.0.8 lack of TRIANGLE_FAN
indices: new Uint16Array([0, 1, 2, 0, 2, 3]),
primitiveType: PrimitiveType_default.TRIANGLES
});
vertexArray = VertexArray_default.fromGeometry({
context: this,
geometry,
attributeLocations: viewportQuadAttributeLocations,
bufferUsage: BufferUsage_default.STATIC_DRAW,
interleave: true
});
this.cache.viewportQuad_vertexArray = vertexArray;
}
return vertexArray;
};
Context.prototype.createViewportQuadCommand = function(fragmentShaderSource, overrides) {
overrides = defaultValue_default(overrides, defaultValue_default.EMPTY_OBJECT);
return new DrawCommand_default({
vertexArray: this.getViewportQuadVertexArray(),
primitiveType: PrimitiveType_default.TRIANGLES,
renderState: overrides.renderState,
shaderProgram: ShaderProgram_default.fromCache({
context: this,
vertexShaderSource: ViewportQuadVS_default,
fragmentShaderSource,
attributeLocations: viewportQuadAttributeLocations
}),
uniformMap: overrides.uniformMap,
owner: overrides.owner,
framebuffer: overrides.framebuffer,
pass: overrides.pass
});
};
Context.prototype.getObjectByPickColor = function(pickColor) {
Check_default.defined("pickColor", pickColor);
return this._pickObjects[pickColor.toRgba()];
};
function PickId(pickObjects, key, color) {
this._pickObjects = pickObjects;
this.key = key;
this.color = color;
}
Object.defineProperties(PickId.prototype, {
object: {
get: function() {
return this._pickObjects[this.key];
},
set: function(value) {
this._pickObjects[this.key] = value;
}
}
});
PickId.prototype.destroy = function() {
delete this._pickObjects[this.key];
return void 0;
};
Context.prototype.createPickId = function(object2) {
Check_default.defined("object", object2);
++this._nextPickColor[0];
const key = this._nextPickColor[0];
if (key === 0) {
throw new RuntimeError_default("Out of unique Pick IDs.");
}
this._pickObjects[key] = object2;
return new PickId(this._pickObjects, key, Color_default.fromRgba(key));
};
Context.prototype.isDestroyed = function() {
return false;
};
Context.prototype.destroy = function() {
const cache = this.cache;
for (const property in cache) {
if (cache.hasOwnProperty(property)) {
const propertyValue = cache[property];
if (defined_default(propertyValue.destroy)) {
propertyValue.destroy();
}
}
}
this._shaderCache = this._shaderCache.destroy();
this._textureCache = this._textureCache.destroy();
this._defaultTexture = this._defaultTexture && this._defaultTexture.destroy();
this._defaultEmissiveTexture = this._defaultEmissiveTexture && this._defaultEmissiveTexture.destroy();
this._defaultNormalTexture = this._defaultNormalTexture && this._defaultNormalTexture.destroy();
this._defaultCubeMap = this._defaultCubeMap && this._defaultCubeMap.destroy();
return destroyObject_default(this);
};
Context._deprecationWarning = deprecationWarning_default;
var Context_default = Context;
// packages/engine/Source/Renderer/MultisampleFramebuffer.js
function MultisampleFramebuffer(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const context = options.context;
const width = options.width;
const height = options.height;
Check_default.defined("options.context", context);
Check_default.defined("options.width", width);
Check_default.defined("options.height", height);
this._width = width;
this._height = height;
const colorRenderbuffers = options.colorRenderbuffers;
const colorTextures = options.colorTextures;
if (defined_default(colorRenderbuffers) !== defined_default(colorTextures)) {
throw new DeveloperError_default(
"Both color renderbuffer and texture attachments must be provided."
);
}
const depthStencilRenderbuffer = options.depthStencilRenderbuffer;
const depthStencilTexture = options.depthStencilTexture;
if (defined_default(depthStencilRenderbuffer) !== defined_default(depthStencilTexture)) {
throw new DeveloperError_default(
"Both depth-stencil renderbuffer and texture attachments must be provided."
);
}
this._renderFramebuffer = new Framebuffer_default({
context,
colorRenderbuffers,
depthStencilRenderbuffer,
destroyAttachments: options.destroyAttachments
});
this._colorFramebuffer = new Framebuffer_default({
context,
colorTextures,
depthStencilTexture,
destroyAttachments: options.destroyAttachments
});
}
MultisampleFramebuffer.prototype.getRenderFramebuffer = function() {
return this._renderFramebuffer;
};
MultisampleFramebuffer.prototype.getColorFramebuffer = function() {
return this._colorFramebuffer;
};
MultisampleFramebuffer.prototype.blitFramebuffers = function(context, blitStencil) {
this._renderFramebuffer.bindRead();
this._colorFramebuffer.bindDraw();
const gl = context._gl;
let mask = 0;
if (this._colorFramebuffer._colorTextures.length > 0) {
mask |= gl.COLOR_BUFFER_BIT;
}
if (defined_default(this._colorFramebuffer.depthStencilTexture)) {
mask |= gl.DEPTH_BUFFER_BIT | (blitStencil ? gl.STENCIL_BUFFER_BIT : 0);
}
gl.blitFramebuffer(
0,
0,
this._width,
this._height,
0,
0,
this._width,
this._height,
mask,
gl.NEAREST
);
gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
};
MultisampleFramebuffer.prototype.isDestroyed = function() {
return false;
};
MultisampleFramebuffer.prototype.destroy = function() {
this._renderFramebuffer.destroy();
this._colorFramebuffer.destroy();
return destroyObject_default(this);
};
var MultisampleFramebuffer_default = MultisampleFramebuffer;
// packages/engine/Source/Renderer/RenderbufferFormat.js
var RenderbufferFormat = {
RGBA4: WebGLConstants_default.RGBA4,
RGBA8: WebGLConstants_default.RGBA8,
RGBA16F: WebGLConstants_default.RGBA16F,
RGBA32F: WebGLConstants_default.RGBA32F,
RGB5_A1: WebGLConstants_default.RGB5_A1,
RGB565: WebGLConstants_default.RGB565,
DEPTH_COMPONENT16: WebGLConstants_default.DEPTH_COMPONENT16,
STENCIL_INDEX8: WebGLConstants_default.STENCIL_INDEX8,
DEPTH_STENCIL: WebGLConstants_default.DEPTH_STENCIL,
DEPTH24_STENCIL8: WebGLConstants_default.DEPTH24_STENCIL8,
validate: function(renderbufferFormat) {
return renderbufferFormat === RenderbufferFormat.RGBA4 || renderbufferFormat === RenderbufferFormat.RGBA8 || renderbufferFormat === RenderbufferFormat.RGBA16F || renderbufferFormat === RenderbufferFormat.RGBA32F || renderbufferFormat === RenderbufferFormat.RGB5_A1 || renderbufferFormat === RenderbufferFormat.RGB565 || renderbufferFormat === RenderbufferFormat.DEPTH_COMPONENT16 || renderbufferFormat === RenderbufferFormat.STENCIL_INDEX8 || renderbufferFormat === RenderbufferFormat.DEPTH_STENCIL || renderbufferFormat === RenderbufferFormat.DEPTH24_STENCIL8;
},
getColorFormat: function(datatype) {
if (datatype === WebGLConstants_default.FLOAT) {
return RenderbufferFormat.RGBA32F;
} else if (datatype === WebGLConstants_default.HALF_FLOAT_OES) {
return RenderbufferFormat.RGBA16F;
}
return RenderbufferFormat.RGBA8;
}
};
var RenderbufferFormat_default = Object.freeze(RenderbufferFormat);
// packages/engine/Source/Renderer/Renderbuffer.js
function Renderbuffer(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
Check_default.defined("options.context", options.context);
const context = options.context;
const gl = context._gl;
const maximumRenderbufferSize = ContextLimits_default.maximumRenderbufferSize;
const format = defaultValue_default(options.format, RenderbufferFormat_default.RGBA4);
const width = defined_default(options.width) ? options.width : gl.drawingBufferWidth;
const height = defined_default(options.height) ? options.height : gl.drawingBufferHeight;
const numSamples = defaultValue_default(options.numSamples, 1);
if (!RenderbufferFormat_default.validate(format)) {
throw new DeveloperError_default("Invalid format.");
}
Check_default.typeOf.number.greaterThan("width", width, 0);
if (width > maximumRenderbufferSize) {
throw new DeveloperError_default(
`Width must be less than or equal to the maximum renderbuffer size (${maximumRenderbufferSize}). Check maximumRenderbufferSize.`
);
}
Check_default.typeOf.number.greaterThan("height", height, 0);
if (height > maximumRenderbufferSize) {
throw new DeveloperError_default(
`Height must be less than or equal to the maximum renderbuffer size (${maximumRenderbufferSize}). Check maximumRenderbufferSize.`
);
}
this._gl = gl;
this._format = format;
this._width = width;
this._height = height;
this._renderbuffer = this._gl.createRenderbuffer();
gl.bindRenderbuffer(gl.RENDERBUFFER, this._renderbuffer);
if (numSamples > 1) {
gl.renderbufferStorageMultisample(
gl.RENDERBUFFER,
numSamples,
format,
width,
height
);
} else {
gl.renderbufferStorage(gl.RENDERBUFFER, format, width, height);
}
gl.bindRenderbuffer(gl.RENDERBUFFER, null);
}
Object.defineProperties(Renderbuffer.prototype, {
format: {
get: function() {
return this._format;
}
},
width: {
get: function() {
return this._width;
}
},
height: {
get: function() {
return this._height;
}
}
});
Renderbuffer.prototype._getRenderbuffer = function() {
return this._renderbuffer;
};
Renderbuffer.prototype.isDestroyed = function() {
return false;
};
Renderbuffer.prototype.destroy = function() {
this._gl.deleteRenderbuffer(this._renderbuffer);
return destroyObject_default(this);
};
var Renderbuffer_default = Renderbuffer;
// packages/engine/Source/Renderer/FramebufferManager.js
function FramebufferManager(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this._numSamples = defaultValue_default(options.numSamples, 1);
this._colorAttachmentsLength = defaultValue_default(
options.colorAttachmentsLength,
1
);
this._color = defaultValue_default(options.color, true);
this._depth = defaultValue_default(options.depth, false);
this._depthStencil = defaultValue_default(options.depthStencil, false);
this._supportsDepthTexture = defaultValue_default(
options.supportsDepthTexture,
false
);
if (!this._color && !this._depth && !this._depthStencil) {
throw new DeveloperError_default(
"Must enable at least one type of framebuffer attachment."
);
}
if (this._depth && this._depthStencil) {
throw new DeveloperError_default(
"Cannot have both a depth and depth-stencil attachment."
);
}
this._createColorAttachments = defaultValue_default(
options.createColorAttachments,
true
);
this._createDepthAttachments = defaultValue_default(
options.createDepthAttachments,
true
);
this._pixelDatatype = options.pixelDatatype;
this._pixelFormat = options.pixelFormat;
this._width = void 0;
this._height = void 0;
this._framebuffer = void 0;
this._multisampleFramebuffer = void 0;
this._colorTextures = void 0;
if (this._color) {
this._colorTextures = new Array(this._colorAttachmentsLength);
this._colorRenderbuffers = new Array(this._colorAttachmentsLength);
}
this._colorRenderbuffer = void 0;
this._depthStencilRenderbuffer = void 0;
this._depthStencilTexture = void 0;
this._depthRenderbuffer = void 0;
this._depthTexture = void 0;
this._attachmentsDirty = false;
}
Object.defineProperties(FramebufferManager.prototype, {
framebuffer: {
get: function() {
if (this._numSamples > 1) {
return this._multisampleFramebuffer.getRenderFramebuffer();
}
return this._framebuffer;
}
},
numSamples: {
get: function() {
return this._numSamples;
}
},
status: {
get: function() {
return this.framebuffer.status;
}
}
});
FramebufferManager.prototype.isDirty = function(width, height, numSamples, pixelDatatype, pixelFormat) {
numSamples = defaultValue_default(numSamples, 1);
const dimensionChanged = this._width !== width || this._height !== height;
const samplesChanged = this._numSamples !== numSamples;
const pixelChanged = defined_default(pixelDatatype) && this._pixelDatatype !== pixelDatatype || defined_default(pixelFormat) && this._pixelFormat !== pixelFormat;
const framebufferDefined = numSamples === 1 ? defined_default(this._framebuffer) : defined_default(this._multisampleFramebuffer);
return this._attachmentsDirty || dimensionChanged || samplesChanged || pixelChanged || !framebufferDefined || this._color && !defined_default(this._colorTextures[0]);
};
FramebufferManager.prototype.update = function(context, width, height, numSamples, pixelDatatype, pixelFormat) {
if (!defined_default(width) || !defined_default(height)) {
throw new DeveloperError_default("width and height must be defined.");
}
numSamples = context.msaa ? defaultValue_default(numSamples, 1) : 1;
pixelDatatype = defaultValue_default(
pixelDatatype,
this._color ? defaultValue_default(this._pixelDatatype, PixelDatatype_default.UNSIGNED_BYTE) : void 0
);
pixelFormat = defaultValue_default(
pixelFormat,
this._color ? defaultValue_default(this._pixelFormat, PixelFormat_default.RGBA) : void 0
);
if (this.isDirty(width, height, numSamples, pixelDatatype, pixelFormat)) {
this.destroy();
this._width = width;
this._height = height;
this._numSamples = numSamples;
this._pixelDatatype = pixelDatatype;
this._pixelFormat = pixelFormat;
this._attachmentsDirty = false;
if (this._color && this._createColorAttachments) {
for (let i = 0; i < this._colorAttachmentsLength; ++i) {
this._colorTextures[i] = new Texture_default({
context,
width,
height,
pixelFormat,
pixelDatatype,
sampler: Sampler_default.NEAREST
});
if (this._numSamples > 1) {
const format = RenderbufferFormat_default.getColorFormat(pixelDatatype);
this._colorRenderbuffers[i] = new Renderbuffer_default({
context,
width,
height,
format,
numSamples: this._numSamples
});
}
}
}
if (this._depthStencil && this._createDepthAttachments) {
if (this._supportsDepthTexture && context.depthTexture) {
this._depthStencilTexture = new Texture_default({
context,
width,
height,
pixelFormat: PixelFormat_default.DEPTH_STENCIL,
pixelDatatype: PixelDatatype_default.UNSIGNED_INT_24_8,
sampler: Sampler_default.NEAREST
});
if (this._numSamples > 1) {
this._depthStencilRenderbuffer = new Renderbuffer_default({
context,
width,
height,
format: RenderbufferFormat_default.DEPTH24_STENCIL8,
numSamples: this._numSamples
});
}
} else {
this._depthStencilRenderbuffer = new Renderbuffer_default({
context,
width,
height,
format: RenderbufferFormat_default.DEPTH_STENCIL
});
}
}
if (this._depth && this._createDepthAttachments) {
if (this._supportsDepthTexture && context.depthTexture) {
this._depthTexture = new Texture_default({
context,
width,
height,
pixelFormat: PixelFormat_default.DEPTH_COMPONENT,
pixelDatatype: PixelDatatype_default.UNSIGNED_INT,
sampler: Sampler_default.NEAREST
});
} else {
this._depthRenderbuffer = new Renderbuffer_default({
context,
width,
height,
format: RenderbufferFormat_default.DEPTH_COMPONENT16
});
}
}
if (this._numSamples > 1) {
this._multisampleFramebuffer = new MultisampleFramebuffer_default({
context,
width: this._width,
height: this._height,
colorTextures: this._colorTextures,
colorRenderbuffers: this._colorRenderbuffers,
depthStencilTexture: this._depthStencilTexture,
depthStencilRenderbuffer: this._depthStencilRenderbuffer,
destroyAttachments: false
});
} else {
this._framebuffer = new Framebuffer_default({
context,
colorTextures: this._colorTextures,
depthTexture: this._depthTexture,
depthRenderbuffer: this._depthRenderbuffer,
depthStencilTexture: this._depthStencilTexture,
depthStencilRenderbuffer: this._depthStencilRenderbuffer,
destroyAttachments: false
});
}
}
};
FramebufferManager.prototype.getColorTexture = function(index) {
index = defaultValue_default(index, 0);
if (index >= this._colorAttachmentsLength) {
throw new DeveloperError_default(
"index must be smaller than total number of color attachments."
);
}
return this._colorTextures[index];
};
FramebufferManager.prototype.setColorTexture = function(texture, index) {
index = defaultValue_default(index, 0);
if (this._createColorAttachments) {
throw new DeveloperError_default(
"createColorAttachments must be false if setColorTexture is called."
);
}
if (index >= this._colorAttachmentsLength) {
throw new DeveloperError_default(
"index must be smaller than total number of color attachments."
);
}
this._attachmentsDirty = texture !== this._colorTextures[index];
this._colorTextures[index] = texture;
};
FramebufferManager.prototype.getColorRenderbuffer = function(index) {
index = defaultValue_default(index, 0);
if (index >= this._colorAttachmentsLength) {
throw new DeveloperError_default(
"index must be smaller than total number of color attachments."
);
}
return this._colorRenderbuffers[index];
};
FramebufferManager.prototype.setColorRenderbuffer = function(renderbuffer, index) {
index = defaultValue_default(index, 0);
if (this._createColorAttachments) {
throw new DeveloperError_default(
"createColorAttachments must be false if setColorRenderbuffer is called."
);
}
if (index >= this._colorAttachmentsLength) {
throw new DeveloperError_default(
"index must be smaller than total number of color attachments."
);
}
this._attachmentsDirty = renderbuffer !== this._colorRenderbuffers[index];
this._colorRenderbuffers[index] = renderbuffer;
};
FramebufferManager.prototype.getDepthRenderbuffer = function() {
return this._depthRenderbuffer;
};
FramebufferManager.prototype.setDepthRenderbuffer = function(renderbuffer) {
if (this._createDepthAttachments) {
throw new DeveloperError_default(
"createDepthAttachments must be false if setDepthRenderbuffer is called."
);
}
this._attachmentsDirty = renderbuffer !== this._depthRenderbuffer;
this._depthRenderbuffer = renderbuffer;
};
FramebufferManager.prototype.getDepthTexture = function() {
return this._depthTexture;
};
FramebufferManager.prototype.setDepthTexture = function(texture) {
if (this._createDepthAttachments) {
throw new DeveloperError_default(
"createDepthAttachments must be false if setDepthTexture is called."
);
}
this._attachmentsDirty = texture !== this._depthTexture;
this._depthTexture = texture;
};
FramebufferManager.prototype.getDepthStencilRenderbuffer = function() {
return this._depthStencilRenderbuffer;
};
FramebufferManager.prototype.setDepthStencilRenderbuffer = function(renderbuffer) {
if (this._createDepthAttachments) {
throw new DeveloperError_default(
"createDepthAttachments must be false if setDepthStencilRenderbuffer is called."
);
}
this._attachmentsDirty = renderbuffer !== this._depthStencilRenderbuffer;
this._depthStencilRenderbuffer = renderbuffer;
};
FramebufferManager.prototype.getDepthStencilTexture = function() {
return this._depthStencilTexture;
};
FramebufferManager.prototype.setDepthStencilTexture = function(texture) {
if (this._createDepthAttachments) {
throw new DeveloperError_default(
"createDepthAttachments must be false if setDepthStencilTexture is called."
);
}
this._attachmentsDirty = texture !== this._depthStencilTexture;
this._depthStencilTexture = texture;
};
FramebufferManager.prototype.prepareTextures = function(context, blitStencil) {
if (this._numSamples > 1) {
this._multisampleFramebuffer.blitFramebuffers(context, blitStencil);
}
};
FramebufferManager.prototype.clear = function(context, clearCommand, passState) {
const framebuffer = clearCommand.framebuffer;
clearCommand.framebuffer = this.framebuffer;
clearCommand.execute(context, passState);
clearCommand.framebuffer = framebuffer;
};
FramebufferManager.prototype.destroyFramebuffer = function() {
this._framebuffer = this._framebuffer && this._framebuffer.destroy();
this._multisampleFramebuffer = this._multisampleFramebuffer && this._multisampleFramebuffer.destroy();
};
FramebufferManager.prototype.destroy = function() {
if (this._color) {
let i;
const length3 = this._colorTextures.length;
for (i = 0; i < length3; ++i) {
const texture = this._colorTextures[i];
if (this._createColorAttachments) {
if (defined_default(texture) && !texture.isDestroyed()) {
this._colorTextures[i].destroy();
this._colorTextures[i] = void 0;
}
}
if (defined_default(texture) && texture.isDestroyed()) {
this._colorTextures[i] = void 0;
}
const renderbuffer = this._colorRenderbuffers[i];
if (this._createColorAttachments) {
if (defined_default(renderbuffer) && !renderbuffer.isDestroyed()) {
this._colorRenderbuffers[i].destroy();
this._colorRenderbuffers[i] = void 0;
}
}
if (defined_default(renderbuffer) && renderbuffer.isDestroyed()) {
this._colorRenderbuffers[i] = void 0;
}
}
}
if (this._depthStencil) {
if (this._createDepthAttachments) {
this._depthStencilTexture = this._depthStencilTexture && this._depthStencilTexture.destroy();
this._depthStencilRenderbuffer = this._depthStencilRenderbuffer && this._depthStencilRenderbuffer.destroy();
}
if (defined_default(this._depthStencilTexture) && this._depthStencilTexture.isDestroyed()) {
this._depthStencilTexture = void 0;
}
if (defined_default(this._depthStencilRenderbuffer) && this._depthStencilRenderbuffer.isDestroyed()) {
this._depthStencilRenderbuffer = void 0;
}
}
if (this._depth) {
if (this._createDepthAttachments) {
this._depthTexture = this._depthTexture && this._depthTexture.destroy();
this._depthRenderbuffer = this._depthRenderbuffer && this._depthRenderbuffer.destroy();
}
if (defined_default(this._depthTexture) && this._depthTexture.isDestroyed()) {
this._depthTexture = void 0;
}
if (defined_default(this._depthRenderbuffer) && this._depthRenderbuffer.isDestroyed()) {
this._depthRenderbuffer = void 0;
}
}
this.destroyFramebuffer();
};
var FramebufferManager_default = FramebufferManager;
// packages/engine/Source/Renderer/ShaderDestination.js
var ShaderDestination = {
VERTEX: 0,
FRAGMENT: 1,
BOTH: 2
};
ShaderDestination.includesVertexShader = function(destination) {
Check_default.typeOf.number("destination", destination);
return destination === ShaderDestination.VERTEX || destination === ShaderDestination.BOTH;
};
ShaderDestination.includesFragmentShader = function(destination) {
Check_default.typeOf.number("destination", destination);
return destination === ShaderDestination.FRAGMENT || destination === ShaderDestination.BOTH;
};
var ShaderDestination_default = Object.freeze(ShaderDestination);
// packages/engine/Source/Renderer/ShaderStruct.js
function ShaderStruct(name) {
this.name = name;
this.fields = [];
}
ShaderStruct.prototype.addField = function(type, identifier) {
const field = ` ${type} ${identifier};`;
this.fields.push(field);
};
ShaderStruct.prototype.generateGlslLines = function() {
let fields = this.fields;
if (fields.length === 0) {
fields = [" float _empty;"];
}
return [].concat(`struct ${this.name}`, "{", fields, "};");
};
var ShaderStruct_default = ShaderStruct;
// packages/engine/Source/Renderer/ShaderFunction.js
function ShaderFunction(signature) {
this.signature = signature;
this.body = [];
}
ShaderFunction.prototype.addLines = function(lines) {
if (typeof lines !== "string" && !Array.isArray(lines)) {
throw new DeveloperError_default(
`Expected lines to be a string or an array of strings, actual value was ${lines}`
);
}
const body = this.body;
if (Array.isArray(lines)) {
const length3 = lines.length;
for (let i = 0; i < length3; i++) {
body.push(` ${lines[i]}`);
}
} else {
body.push(` ${lines}`);
}
};
ShaderFunction.prototype.generateGlslLines = function() {
return [].concat(this.signature, "{", this.body, "}");
};
var ShaderFunction_default = ShaderFunction;
// packages/engine/Source/Renderer/ShaderBuilder.js
function ShaderBuilder() {
this._positionAttributeLine = void 0;
this._nextAttributeLocation = 1;
this._attributeLocations = {};
this._attributeLines = [];
this._structs = {};
this._functions = {};
this._vertexShaderParts = {
defineLines: [],
uniformLines: [],
shaderLines: [],
varyingLines: [],
// identifiers of structs/functions to include, listed in insertion order
structIds: [],
functionIds: []
};
this._fragmentShaderParts = {
defineLines: [],
uniformLines: [],
shaderLines: [],
varyingLines: [],
// identifiers of structs/functions to include, listed in insertion order
structIds: [],
functionIds: []
};
}
Object.defineProperties(ShaderBuilder.prototype, {
/**
* Get a dictionary of attribute names to the integer location in
* the vertex shader.
*
* @memberof ShaderBuilder.prototype
* @type {Objecttrue
.
* @memberof ConstantProperty.prototype
*
* @type {boolean}
* @readonly
*/
isConstant: {
value: true
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* The definition is changed whenever setValue is called with data different
* than the current value.
* @memberof ConstantProperty.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function() {
return this._definitionChanged;
}
}
});
ConstantProperty.prototype.getValue = function(time, result) {
return this._hasClone ? this._value.clone(result) : this._value;
};
ConstantProperty.prototype.setValue = function(value) {
const oldValue2 = this._value;
if (oldValue2 !== value) {
const isDefined = defined_default(value);
const hasClone = isDefined && typeof value.clone === "function";
const hasEquals = isDefined && typeof value.equals === "function";
const changed = !hasEquals || !value.equals(oldValue2);
if (changed) {
this._hasClone = hasClone;
this._hasEquals = hasEquals;
this._value = !hasClone ? value : value.clone(this._value);
this._definitionChanged.raiseEvent(this);
}
}
};
ConstantProperty.prototype.equals = function(other) {
return this === other || //
other instanceof ConstantProperty && //
(!this._hasEquals && this._value === other._value || //
this._hasEquals && this._value.equals(other._value));
};
ConstantProperty.prototype.valueOf = function() {
return this._value;
};
ConstantProperty.prototype.toString = function() {
return String(this._value);
};
var ConstantProperty_default = ConstantProperty;
// packages/engine/Source/DataSources/createPropertyDescriptor.js
function createProperty(name, privateName, subscriptionName, configurable, createPropertyCallback) {
return {
configurable,
get: function() {
return this[privateName];
},
set: function(value) {
const oldValue2 = this[privateName];
const subscription = this[subscriptionName];
if (defined_default(subscription)) {
subscription();
this[subscriptionName] = void 0;
}
const hasValue = value !== void 0;
if (hasValue && (!defined_default(value) || !defined_default(value.getValue)) && defined_default(createPropertyCallback)) {
value = createPropertyCallback(value);
}
if (oldValue2 !== value) {
this[privateName] = value;
this._definitionChanged.raiseEvent(this, name, value, oldValue2);
}
if (defined_default(value) && defined_default(value.definitionChanged)) {
this[subscriptionName] = value.definitionChanged.addEventListener(
function() {
this._definitionChanged.raiseEvent(this, name, value, value);
},
this
);
}
}
};
}
function createConstantProperty(value) {
return new ConstantProperty_default(value);
}
function createPropertyDescriptor(name, configurable, createPropertyCallback) {
return createProperty(
name,
`_${name.toString()}`,
`_${name.toString()}Subscription`,
defaultValue_default(configurable, false),
defaultValue_default(createPropertyCallback, createConstantProperty)
);
}
var createPropertyDescriptor_default = createPropertyDescriptor;
// packages/engine/Source/DataSources/BillboardGraphics.js
function BillboardGraphics(options) {
this._definitionChanged = new Event_default();
this._show = void 0;
this._showSubscription = void 0;
this._image = void 0;
this._imageSubscription = void 0;
this._scale = void 0;
this._scaleSubscription = void 0;
this._pixelOffset = void 0;
this._pixelOffsetSubscription = void 0;
this._eyeOffset = void 0;
this._eyeOffsetSubscription = void 0;
this._horizontalOrigin = void 0;
this._horizontalOriginSubscription = void 0;
this._verticalOrigin = void 0;
this._verticalOriginSubscription = void 0;
this._heightReference = void 0;
this._heightReferenceSubscription = void 0;
this._color = void 0;
this._colorSubscription = void 0;
this._rotation = void 0;
this._rotationSubscription = void 0;
this._alignedAxis = void 0;
this._alignedAxisSubscription = void 0;
this._sizeInMeters = void 0;
this._sizeInMetersSubscription = void 0;
this._width = void 0;
this._widthSubscription = void 0;
this._height = void 0;
this._heightSubscription = void 0;
this._scaleByDistance = void 0;
this._scaleByDistanceSubscription = void 0;
this._translucencyByDistance = void 0;
this._translucencyByDistanceSubscription = void 0;
this._pixelOffsetScaleByDistance = void 0;
this._pixelOffsetScaleByDistanceSubscription = void 0;
this._imageSubRegion = void 0;
this._imageSubRegionSubscription = void 0;
this._distanceDisplayCondition = void 0;
this._distanceDisplayConditionSubscription = void 0;
this._disableDepthTestDistance = void 0;
this._disableDepthTestDistanceSubscription = void 0;
this.merge(defaultValue_default(options, defaultValue_default.EMPTY_OBJECT));
}
Object.defineProperties(BillboardGraphics.prototype, {
/**
* Gets the event that is raised whenever a property or sub-property is changed or modified.
* @memberof BillboardGraphics.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
/**
* Gets or sets the boolean Property specifying the visibility of the billboard.
* @memberof BillboardGraphics.prototype
* @type {Property|undefined}
* @default true
*/
show: createPropertyDescriptor_default("show"),
/**
* Gets or sets the Property specifying the Image, URI, or Canvas to use for the billboard.
* @memberof BillboardGraphics.prototype
* @type {Property|undefined}
*/
image: createPropertyDescriptor_default("image"),
/**
* Gets or sets the numeric Property specifying the uniform scale to apply to the image.
* A scale greater than 1.0
enlarges the billboard while a scale less than 1.0
shrinks it.
*
* From left to right in the above image, the scales are 0.5
, 1.0
, and 2.0
.
*
x
increases from left to right, and y
increases from top to bottom.
* *
default ![]() |
* b.pixeloffset = new Cartesian2(50, 25); ![]() |
*
x
points towards the viewer's
* right, y
points up, and z
points into the screen.
* * An eye offset is commonly used to arrange multiple billboards or objects at the same position, e.g., to * arrange a billboard above its corresponding 3D model. *
* Below, the billboard is positioned at the center of the Earth but an eye offset makes it always * appear on top of the Earth regardless of the viewer's or Earth's orientation. **
![]() |
* ![]() |
*
b.eyeOffset = new Cartesian3(0.0, 8000000.0, 0.0);
* image
.
* This has two common use cases. First, the same white texture may be used by many different billboards,
* each with a different color, to create colored billboards. Second, the color's alpha component can be
* used to make the billboard translucent as shown below. An alpha of 0.0
makes the billboard
* transparent, and 1.0
makes the billboard opaque.
* *
default ![]() |
* alpha : 0.5 ![]() |
*
alignedAxis
.
* @memberof BillboardGraphics.prototype
* @type {Property|undefined}
* @default 0
*/
rotation: createPropertyDescriptor_default("rotation"),
/**
* Gets or sets the {@link Cartesian3} Property specifying the unit vector axis of rotation
* in the fixed frame. When set to Cartesian3.ZERO the rotation is from the top of the screen.
* @memberof BillboardGraphics.prototype
* @type {Property|undefined}
* @default Cartesian3.ZERO
*/
alignedAxis: createPropertyDescriptor_default("alignedAxis"),
/**
* Gets or sets the boolean Property specifying if this billboard's size will be measured in meters.
* @memberof BillboardGraphics.prototype
* @type {Property|undefined}
* @default false
*/
sizeInMeters: createPropertyDescriptor_default("sizeInMeters"),
/**
* Gets or sets the numeric Property specifying the width of the billboard in pixels.
* When undefined, the native width is used.
* @memberof BillboardGraphics.prototype
* @type {Property|undefined}
*/
width: createPropertyDescriptor_default("width"),
/**
* Gets or sets the numeric Property specifying the height of the billboard in pixels.
* When undefined, the native height is used.
* @memberof BillboardGraphics.prototype
* @type {Property|undefined}
*/
height: createPropertyDescriptor_default("height"),
/**
* Gets or sets {@link NearFarScalar} Property specifying the scale of the billboard based on the distance from the camera.
* A billboard's scale will interpolate between the {@link NearFarScalar#nearValue} and
* {@link NearFarScalar#farValue} while the camera distance falls within the lower and upper bounds
* of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}.
* Outside of these ranges the billboard's scale remains clamped to the nearest bound.
* @memberof BillboardGraphics.prototype
* @type {Property|undefined}
*/
scaleByDistance: createPropertyDescriptor_default("scaleByDistance"),
/**
* Gets or sets {@link NearFarScalar} Property specifying the translucency of the billboard based on the distance from the camera.
* A billboard's translucency will interpolate between the {@link NearFarScalar#nearValue} and
* {@link NearFarScalar#farValue} while the camera distance falls within the lower and upper bounds
* of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}.
* Outside of these ranges the billboard's translucency remains clamped to the nearest bound.
* @memberof BillboardGraphics.prototype
* @type {Property|undefined}
*/
translucencyByDistance: createPropertyDescriptor_default("translucencyByDistance"),
/**
* Gets or sets {@link NearFarScalar} Property specifying the pixel offset of the billboard based on the distance from the camera.
* A billboard's pixel offset will interpolate between the {@link NearFarScalar#nearValue} and
* {@link NearFarScalar#farValue} while the camera distance falls within the lower and upper bounds
* of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}.
* Outside of these ranges the billboard's pixel offset remains clamped to the nearest bound.
* @memberof BillboardGraphics.prototype
* @type {Property|undefined}
*/
pixelOffsetScaleByDistance: createPropertyDescriptor_default(
"pixelOffsetScaleByDistance"
),
/**
* Gets or sets the Property specifying a {@link BoundingRectangle} that defines a
* sub-region of the image
to use for the billboard, rather than the entire image,
* measured in pixels from the bottom-left.
* @memberof BillboardGraphics.prototype
* @type {Property|undefined}
*/
imageSubRegion: createPropertyDescriptor_default("imageSubRegion"),
/**
* Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this billboard will be displayed.
* @memberof BillboardGraphics.prototype
* @type {Property|undefined}
*/
distanceDisplayCondition: createPropertyDescriptor_default(
"distanceDisplayCondition"
),
/**
* Gets or sets the distance from the camera at which to disable the depth test to, for example, prevent clipping against terrain.
* When set to zero, the depth test is always applied. When set to Number.POSITIVE_INFINITY, the depth test is never applied.
* @memberof BillboardGraphics.prototype
* @type {Property|undefined}
*/
disableDepthTestDistance: createPropertyDescriptor_default(
"disableDepthTestDistance"
)
});
BillboardGraphics.prototype.clone = function(result) {
if (!defined_default(result)) {
return new BillboardGraphics(this);
}
result.show = this._show;
result.image = this._image;
result.scale = this._scale;
result.pixelOffset = this._pixelOffset;
result.eyeOffset = this._eyeOffset;
result.horizontalOrigin = this._horizontalOrigin;
result.verticalOrigin = this._verticalOrigin;
result.heightReference = this._heightReference;
result.color = this._color;
result.rotation = this._rotation;
result.alignedAxis = this._alignedAxis;
result.sizeInMeters = this._sizeInMeters;
result.width = this._width;
result.height = this._height;
result.scaleByDistance = this._scaleByDistance;
result.translucencyByDistance = this._translucencyByDistance;
result.pixelOffsetScaleByDistance = this._pixelOffsetScaleByDistance;
result.imageSubRegion = this._imageSubRegion;
result.distanceDisplayCondition = this._distanceDisplayCondition;
result.disableDepthTestDistance = this._disableDepthTestDistance;
return result;
};
BillboardGraphics.prototype.merge = function(source) {
if (!defined_default(source)) {
throw new DeveloperError_default("source is required.");
}
this.show = defaultValue_default(this._show, source.show);
this.image = defaultValue_default(this._image, source.image);
this.scale = defaultValue_default(this._scale, source.scale);
this.pixelOffset = defaultValue_default(this._pixelOffset, source.pixelOffset);
this.eyeOffset = defaultValue_default(this._eyeOffset, source.eyeOffset);
this.horizontalOrigin = defaultValue_default(
this._horizontalOrigin,
source.horizontalOrigin
);
this.verticalOrigin = defaultValue_default(
this._verticalOrigin,
source.verticalOrigin
);
this.heightReference = defaultValue_default(
this._heightReference,
source.heightReference
);
this.color = defaultValue_default(this._color, source.color);
this.rotation = defaultValue_default(this._rotation, source.rotation);
this.alignedAxis = defaultValue_default(this._alignedAxis, source.alignedAxis);
this.sizeInMeters = defaultValue_default(this._sizeInMeters, source.sizeInMeters);
this.width = defaultValue_default(this._width, source.width);
this.height = defaultValue_default(this._height, source.height);
this.scaleByDistance = defaultValue_default(
this._scaleByDistance,
source.scaleByDistance
);
this.translucencyByDistance = defaultValue_default(
this._translucencyByDistance,
source.translucencyByDistance
);
this.pixelOffsetScaleByDistance = defaultValue_default(
this._pixelOffsetScaleByDistance,
source.pixelOffsetScaleByDistance
);
this.imageSubRegion = defaultValue_default(
this._imageSubRegion,
source.imageSubRegion
);
this.distanceDisplayCondition = defaultValue_default(
this._distanceDisplayCondition,
source.distanceDisplayCondition
);
this.disableDepthTestDistance = defaultValue_default(
this._disableDepthTestDistance,
source.disableDepthTestDistance
);
};
var BillboardGraphics_default = BillboardGraphics;
// packages/engine/Source/Core/AssociativeArray.js
function AssociativeArray() {
this._array = [];
this._hash = {};
}
Object.defineProperties(AssociativeArray.prototype, {
/**
* Gets the number of items in the collection.
* @memberof AssociativeArray.prototype
*
* @type {number}
*/
length: {
get: function() {
return this._array.length;
}
},
/**
* Gets an unordered array of all values in the collection.
* This is a live array that will automatically reflect the values in the collection,
* it should not be modified directly.
* @memberof AssociativeArray.prototype
*
* @type {Array}
*/
values: {
get: function() {
return this._array;
}
}
});
AssociativeArray.prototype.contains = function(key) {
if (typeof key !== "string" && typeof key !== "number") {
throw new DeveloperError_default("key is required to be a string or number.");
}
return defined_default(this._hash[key]);
};
AssociativeArray.prototype.set = function(key, value) {
if (typeof key !== "string" && typeof key !== "number") {
throw new DeveloperError_default("key is required to be a string or number.");
}
const oldValue2 = this._hash[key];
if (value !== oldValue2) {
this.remove(key);
this._hash[key] = value;
this._array.push(value);
}
};
AssociativeArray.prototype.get = function(key) {
if (typeof key !== "string" && typeof key !== "number") {
throw new DeveloperError_default("key is required to be a string or number.");
}
return this._hash[key];
};
AssociativeArray.prototype.remove = function(key) {
if (defined_default(key) && typeof key !== "string" && typeof key !== "number") {
throw new DeveloperError_default("key is required to be a string or number.");
}
const value = this._hash[key];
const hasValue = defined_default(value);
if (hasValue) {
const array = this._array;
array.splice(array.indexOf(value), 1);
delete this._hash[key];
}
return hasValue;
};
AssociativeArray.prototype.removeAll = function() {
const array = this._array;
if (array.length > 0) {
this._hash = {};
array.length = 0;
}
};
var AssociativeArray_default = AssociativeArray;
// packages/engine/Source/Core/DistanceDisplayCondition.js
function DistanceDisplayCondition(near, far) {
near = defaultValue_default(near, 0);
this._near = near;
far = defaultValue_default(far, Number.MAX_VALUE);
this._far = far;
}
Object.defineProperties(DistanceDisplayCondition.prototype, {
/**
* The smallest distance in the interval where the object is visible.
* @memberof DistanceDisplayCondition.prototype
* @type {number}
* @default 0.0
*/
near: {
get: function() {
return this._near;
},
set: function(value) {
this._near = value;
}
},
/**
* The largest distance in the interval where the object is visible.
* @memberof DistanceDisplayCondition.prototype
* @type {number}
* @default Number.MAX_VALUE
*/
far: {
get: function() {
return this._far;
},
set: function(value) {
this._far = value;
}
}
});
DistanceDisplayCondition.packedLength = 2;
DistanceDisplayCondition.pack = function(value, array, startingIndex) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required");
}
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
array[startingIndex++] = value.near;
array[startingIndex] = value.far;
return array;
};
DistanceDisplayCondition.unpack = function(array, startingIndex, result) {
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
if (!defined_default(result)) {
result = new DistanceDisplayCondition();
}
result.near = array[startingIndex++];
result.far = array[startingIndex];
return result;
};
DistanceDisplayCondition.equals = function(left, right) {
return left === right || defined_default(left) && defined_default(right) && left.near === right.near && left.far === right.far;
};
DistanceDisplayCondition.clone = function(value, result) {
if (!defined_default(value)) {
return void 0;
}
if (!defined_default(result)) {
result = new DistanceDisplayCondition();
}
result.near = value.near;
result.far = value.far;
return result;
};
DistanceDisplayCondition.prototype.clone = function(result) {
return DistanceDisplayCondition.clone(this, result);
};
DistanceDisplayCondition.prototype.equals = function(other) {
return DistanceDisplayCondition.equals(this, other);
};
var DistanceDisplayCondition_default = DistanceDisplayCondition;
// packages/engine/Source/Core/NearFarScalar.js
function NearFarScalar(near, nearValue, far, farValue) {
this.near = defaultValue_default(near, 0);
this.nearValue = defaultValue_default(nearValue, 0);
this.far = defaultValue_default(far, 1);
this.farValue = defaultValue_default(farValue, 0);
}
NearFarScalar.clone = function(nearFarScalar, result) {
if (!defined_default(nearFarScalar)) {
return void 0;
}
if (!defined_default(result)) {
return new NearFarScalar(
nearFarScalar.near,
nearFarScalar.nearValue,
nearFarScalar.far,
nearFarScalar.farValue
);
}
result.near = nearFarScalar.near;
result.nearValue = nearFarScalar.nearValue;
result.far = nearFarScalar.far;
result.farValue = nearFarScalar.farValue;
return result;
};
NearFarScalar.packedLength = 4;
NearFarScalar.pack = function(value, array, startingIndex) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required");
}
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
array[startingIndex++] = value.near;
array[startingIndex++] = value.nearValue;
array[startingIndex++] = value.far;
array[startingIndex] = value.farValue;
return array;
};
NearFarScalar.unpack = function(array, startingIndex, result) {
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
if (!defined_default(result)) {
result = new NearFarScalar();
}
result.near = array[startingIndex++];
result.nearValue = array[startingIndex++];
result.far = array[startingIndex++];
result.farValue = array[startingIndex];
return result;
};
NearFarScalar.equals = function(left, right) {
return left === right || defined_default(left) && defined_default(right) && left.near === right.near && left.nearValue === right.nearValue && left.far === right.far && left.farValue === right.farValue;
};
NearFarScalar.prototype.clone = function(result) {
return NearFarScalar.clone(this, result);
};
NearFarScalar.prototype.equals = function(right) {
return NearFarScalar.equals(this, right);
};
var NearFarScalar_default = NearFarScalar;
// packages/engine/Source/Scene/HeightReference.js
var HeightReference = {
/**
* The position is absolute.
* @type {number}
* @constant
*/
NONE: 0,
/**
* The position is clamped to the terrain.
* @type {number}
* @constant
*/
CLAMP_TO_GROUND: 1,
/**
* The position height is the height above the terrain.
* @type {number}
* @constant
*/
RELATIVE_TO_GROUND: 2
};
var HeightReference_default = Object.freeze(HeightReference);
// packages/engine/Source/Scene/HorizontalOrigin.js
var HorizontalOrigin = {
/**
* The origin is at the horizontal center of the object.
*
* @type {number}
* @constant
*/
CENTER: 0,
/**
* The origin is on the left side of the object.
*
* @type {number}
* @constant
*/
LEFT: 1,
/**
* The origin is on the right side of the object.
*
* @type {number}
* @constant
*/
RIGHT: -1
};
var HorizontalOrigin_default = Object.freeze(HorizontalOrigin);
// packages/engine/Source/Scene/VerticalOrigin.js
var VerticalOrigin = {
/**
* The origin is at the vertical center between BASELINE
and TOP
.
*
* @type {number}
* @constant
*/
CENTER: 0,
/**
* The origin is at the bottom of the object.
*
* @type {number}
* @constant
*/
BOTTOM: 1,
/**
* If the object contains text, the origin is at the baseline of the text, else the origin is at the bottom of the object.
*
* @type {number}
* @constant
*/
BASELINE: 2,
/**
* The origin is at the top of the object.
*
* @type {number}
* @constant
*/
TOP: -1
};
var VerticalOrigin_default = Object.freeze(VerticalOrigin);
// packages/engine/Source/DataSources/BoundingSphereState.js
var BoundingSphereState = {
/**
* The BoundingSphere has been computed.
* @type BoundingSphereState
* @constant
*/
DONE: 0,
/**
* The BoundingSphere is still being computed.
* @type BoundingSphereState
* @constant
*/
PENDING: 1,
/**
* The BoundingSphere does not exist.
* @type BoundingSphereState
* @constant
*/
FAILED: 2
};
var BoundingSphereState_default = Object.freeze(BoundingSphereState);
// packages/engine/Source/DataSources/Property.js
function Property() {
DeveloperError_default.throwInstantiationError();
}
Object.defineProperties(Property.prototype, {
/**
* Gets a value indicating if this property is constant. A property is considered
* constant if getValue always returns the same result for the current definition.
* @memberof Property.prototype
*
* @type {boolean}
* @readonly
*/
isConstant: {
get: DeveloperError_default.throwInstantiationError
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* The definition is considered to have changed if a call to getValue would return
* a different result for the same time.
* @memberof Property.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: DeveloperError_default.throwInstantiationError
}
});
Property.prototype.getValue = DeveloperError_default.throwInstantiationError;
Property.prototype.equals = DeveloperError_default.throwInstantiationError;
Property.equals = function(left, right) {
return left === right || defined_default(left) && left.equals(right);
};
Property.arrayEquals = function(left, right) {
if (left === right) {
return true;
}
if (!defined_default(left) || !defined_default(right) || left.length !== right.length) {
return false;
}
const length3 = left.length;
for (let i = 0; i < length3; i++) {
if (!Property.equals(left[i], right[i])) {
return false;
}
}
return true;
};
Property.isConstant = function(property) {
return !defined_default(property) || property.isConstant;
};
Property.getValueOrUndefined = function(property, time, result) {
return defined_default(property) ? property.getValue(time, result) : void 0;
};
Property.getValueOrDefault = function(property, time, valueDefault, result) {
return defined_default(property) ? defaultValue_default(property.getValue(time, result), valueDefault) : valueDefault;
};
Property.getValueOrClonedDefault = function(property, time, valueDefault, result) {
let value;
if (defined_default(property)) {
value = property.getValue(time, result);
}
if (!defined_default(value)) {
value = valueDefault.clone(value);
}
return value;
};
var Property_default = Property;
// packages/engine/Source/DataSources/BillboardVisualizer.js
var defaultColor = Color_default.WHITE;
var defaultEyeOffset = Cartesian3_default.ZERO;
var defaultHeightReference = HeightReference_default.NONE;
var defaultPixelOffset = Cartesian2_default.ZERO;
var defaultScale = 1;
var defaultRotation = 0;
var defaultAlignedAxis = Cartesian3_default.ZERO;
var defaultHorizontalOrigin = HorizontalOrigin_default.CENTER;
var defaultVerticalOrigin = VerticalOrigin_default.CENTER;
var defaultSizeInMeters = false;
var positionScratch = new Cartesian3_default();
var colorScratch = new Color_default();
var eyeOffsetScratch = new Cartesian3_default();
var pixelOffsetScratch = new Cartesian2_default();
var scaleByDistanceScratch = new NearFarScalar_default();
var translucencyByDistanceScratch = new NearFarScalar_default();
var pixelOffsetScaleByDistanceScratch = new NearFarScalar_default();
var boundingRectangleScratch = new BoundingRectangle_default();
var distanceDisplayConditionScratch = new DistanceDisplayCondition_default();
function EntityData(entity) {
this.entity = entity;
this.billboard = void 0;
this.textureValue = void 0;
}
function BillboardVisualizer(entityCluster, entityCollection) {
if (!defined_default(entityCluster)) {
throw new DeveloperError_default("entityCluster is required.");
}
if (!defined_default(entityCollection)) {
throw new DeveloperError_default("entityCollection is required.");
}
entityCollection.collectionChanged.addEventListener(
BillboardVisualizer.prototype._onCollectionChanged,
this
);
this._cluster = entityCluster;
this._entityCollection = entityCollection;
this._items = new AssociativeArray_default();
this._onCollectionChanged(entityCollection, entityCollection.values, [], []);
}
BillboardVisualizer.prototype.update = function(time) {
if (!defined_default(time)) {
throw new DeveloperError_default("time is required.");
}
const items = this._items.values;
const cluster = this._cluster;
for (let i = 0, len = items.length; i < len; i++) {
const item = items[i];
const entity = item.entity;
const billboardGraphics = entity._billboard;
let textureValue;
let billboard = item.billboard;
let show = entity.isShowing && entity.isAvailable(time) && Property_default.getValueOrDefault(billboardGraphics._show, time, true);
let position;
if (show) {
position = Property_default.getValueOrUndefined(
entity._position,
time,
positionScratch
);
textureValue = Property_default.getValueOrUndefined(
billboardGraphics._image,
time
);
show = defined_default(position) && defined_default(textureValue);
}
if (!show) {
returnPrimitive(item, entity, cluster);
continue;
}
if (!Property_default.isConstant(entity._position)) {
cluster._clusterDirty = true;
}
if (!defined_default(billboard)) {
billboard = cluster.getBillboard(entity);
billboard.id = entity;
billboard.image = void 0;
item.billboard = billboard;
}
billboard.show = show;
if (!defined_default(billboard.image) || item.textureValue !== textureValue) {
billboard.image = textureValue;
item.textureValue = textureValue;
}
billboard.position = position;
billboard.color = Property_default.getValueOrDefault(
billboardGraphics._color,
time,
defaultColor,
colorScratch
);
billboard.eyeOffset = Property_default.getValueOrDefault(
billboardGraphics._eyeOffset,
time,
defaultEyeOffset,
eyeOffsetScratch
);
billboard.heightReference = Property_default.getValueOrDefault(
billboardGraphics._heightReference,
time,
defaultHeightReference
);
billboard.pixelOffset = Property_default.getValueOrDefault(
billboardGraphics._pixelOffset,
time,
defaultPixelOffset,
pixelOffsetScratch
);
billboard.scale = Property_default.getValueOrDefault(
billboardGraphics._scale,
time,
defaultScale
);
billboard.rotation = Property_default.getValueOrDefault(
billboardGraphics._rotation,
time,
defaultRotation
);
billboard.alignedAxis = Property_default.getValueOrDefault(
billboardGraphics._alignedAxis,
time,
defaultAlignedAxis
);
billboard.horizontalOrigin = Property_default.getValueOrDefault(
billboardGraphics._horizontalOrigin,
time,
defaultHorizontalOrigin
);
billboard.verticalOrigin = Property_default.getValueOrDefault(
billboardGraphics._verticalOrigin,
time,
defaultVerticalOrigin
);
billboard.width = Property_default.getValueOrUndefined(
billboardGraphics._width,
time
);
billboard.height = Property_default.getValueOrUndefined(
billboardGraphics._height,
time
);
billboard.scaleByDistance = Property_default.getValueOrUndefined(
billboardGraphics._scaleByDistance,
time,
scaleByDistanceScratch
);
billboard.translucencyByDistance = Property_default.getValueOrUndefined(
billboardGraphics._translucencyByDistance,
time,
translucencyByDistanceScratch
);
billboard.pixelOffsetScaleByDistance = Property_default.getValueOrUndefined(
billboardGraphics._pixelOffsetScaleByDistance,
time,
pixelOffsetScaleByDistanceScratch
);
billboard.sizeInMeters = Property_default.getValueOrDefault(
billboardGraphics._sizeInMeters,
time,
defaultSizeInMeters
);
billboard.distanceDisplayCondition = Property_default.getValueOrUndefined(
billboardGraphics._distanceDisplayCondition,
time,
distanceDisplayConditionScratch
);
billboard.disableDepthTestDistance = Property_default.getValueOrUndefined(
billboardGraphics._disableDepthTestDistance,
time
);
const subRegion = Property_default.getValueOrUndefined(
billboardGraphics._imageSubRegion,
time,
boundingRectangleScratch
);
if (defined_default(subRegion)) {
billboard.setImageSubRegion(billboard._imageId, subRegion);
}
}
return true;
};
BillboardVisualizer.prototype.getBoundingSphere = function(entity, result) {
if (!defined_default(entity)) {
throw new DeveloperError_default("entity is required.");
}
if (!defined_default(result)) {
throw new DeveloperError_default("result is required.");
}
const item = this._items.get(entity.id);
if (!defined_default(item) || !defined_default(item.billboard)) {
return BoundingSphereState_default.FAILED;
}
const billboard = item.billboard;
if (billboard.heightReference === HeightReference_default.NONE) {
result.center = Cartesian3_default.clone(billboard.position, result.center);
} else {
if (!defined_default(billboard._clampedPosition)) {
return BoundingSphereState_default.PENDING;
}
result.center = Cartesian3_default.clone(billboard._clampedPosition, result.center);
}
result.radius = 0;
return BoundingSphereState_default.DONE;
};
BillboardVisualizer.prototype.isDestroyed = function() {
return false;
};
BillboardVisualizer.prototype.destroy = function() {
this._entityCollection.collectionChanged.removeEventListener(
BillboardVisualizer.prototype._onCollectionChanged,
this
);
const entities = this._entityCollection.values;
for (let i = 0; i < entities.length; i++) {
this._cluster.removeBillboard(entities[i]);
}
return destroyObject_default(this);
};
BillboardVisualizer.prototype._onCollectionChanged = function(entityCollection, added, removed, changed) {
let i;
let entity;
const items = this._items;
const cluster = this._cluster;
for (i = added.length - 1; i > -1; i--) {
entity = added[i];
if (defined_default(entity._billboard) && defined_default(entity._position)) {
items.set(entity.id, new EntityData(entity));
}
}
for (i = changed.length - 1; i > -1; i--) {
entity = changed[i];
if (defined_default(entity._billboard) && defined_default(entity._position)) {
if (!items.contains(entity.id)) {
items.set(entity.id, new EntityData(entity));
}
} else {
returnPrimitive(items.get(entity.id), entity, cluster);
items.remove(entity.id);
}
}
for (i = removed.length - 1; i > -1; i--) {
entity = removed[i];
returnPrimitive(items.get(entity.id), entity, cluster);
items.remove(entity.id);
}
};
function returnPrimitive(item, entity, cluster) {
if (defined_default(item)) {
item.billboard = void 0;
cluster.removeBillboard(entity);
}
}
var BillboardVisualizer_default = BillboardVisualizer;
// packages/engine/Source/Core/Interval.js
function Interval(start, stop2) {
this.start = defaultValue_default(start, 0);
this.stop = defaultValue_default(stop2, 0);
}
var Interval_default = Interval;
// packages/engine/Source/Core/BoundingSphere.js
function BoundingSphere(center, radius) {
this.center = Cartesian3_default.clone(defaultValue_default(center, Cartesian3_default.ZERO));
this.radius = defaultValue_default(radius, 0);
}
var fromPointsXMin = new Cartesian3_default();
var fromPointsYMin = new Cartesian3_default();
var fromPointsZMin = new Cartesian3_default();
var fromPointsXMax = new Cartesian3_default();
var fromPointsYMax = new Cartesian3_default();
var fromPointsZMax = new Cartesian3_default();
var fromPointsCurrentPos = new Cartesian3_default();
var fromPointsScratch = new Cartesian3_default();
var fromPointsRitterCenter = new Cartesian3_default();
var fromPointsMinBoxPt = new Cartesian3_default();
var fromPointsMaxBoxPt = new Cartesian3_default();
var fromPointsNaiveCenterScratch = new Cartesian3_default();
var volumeConstant = 4 / 3 * Math_default.PI;
BoundingSphere.fromPoints = function(positions, result) {
if (!defined_default(result)) {
result = new BoundingSphere();
}
if (!defined_default(positions) || positions.length === 0) {
result.center = Cartesian3_default.clone(Cartesian3_default.ZERO, result.center);
result.radius = 0;
return result;
}
const currentPos = Cartesian3_default.clone(positions[0], fromPointsCurrentPos);
const xMin = Cartesian3_default.clone(currentPos, fromPointsXMin);
const yMin = Cartesian3_default.clone(currentPos, fromPointsYMin);
const zMin = Cartesian3_default.clone(currentPos, fromPointsZMin);
const xMax = Cartesian3_default.clone(currentPos, fromPointsXMax);
const yMax = Cartesian3_default.clone(currentPos, fromPointsYMax);
const zMax = Cartesian3_default.clone(currentPos, fromPointsZMax);
const numPositions = positions.length;
let i;
for (i = 1; i < numPositions; i++) {
Cartesian3_default.clone(positions[i], currentPos);
const x = currentPos.x;
const y = currentPos.y;
const z = currentPos.z;
if (x < xMin.x) {
Cartesian3_default.clone(currentPos, xMin);
}
if (x > xMax.x) {
Cartesian3_default.clone(currentPos, xMax);
}
if (y < yMin.y) {
Cartesian3_default.clone(currentPos, yMin);
}
if (y > yMax.y) {
Cartesian3_default.clone(currentPos, yMax);
}
if (z < zMin.z) {
Cartesian3_default.clone(currentPos, zMin);
}
if (z > zMax.z) {
Cartesian3_default.clone(currentPos, zMax);
}
}
const xSpan = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(xMax, xMin, fromPointsScratch)
);
const ySpan = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(yMax, yMin, fromPointsScratch)
);
const zSpan = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(zMax, zMin, fromPointsScratch)
);
let diameter1 = xMin;
let diameter2 = xMax;
let maxSpan = xSpan;
if (ySpan > maxSpan) {
maxSpan = ySpan;
diameter1 = yMin;
diameter2 = yMax;
}
if (zSpan > maxSpan) {
maxSpan = zSpan;
diameter1 = zMin;
diameter2 = zMax;
}
const ritterCenter = fromPointsRitterCenter;
ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
let radiusSquared = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(diameter2, ritterCenter, fromPointsScratch)
);
let ritterRadius = Math.sqrt(radiusSquared);
const minBoxPt = fromPointsMinBoxPt;
minBoxPt.x = xMin.x;
minBoxPt.y = yMin.y;
minBoxPt.z = zMin.z;
const maxBoxPt = fromPointsMaxBoxPt;
maxBoxPt.x = xMax.x;
maxBoxPt.y = yMax.y;
maxBoxPt.z = zMax.z;
const naiveCenter = Cartesian3_default.midpoint(
minBoxPt,
maxBoxPt,
fromPointsNaiveCenterScratch
);
let naiveRadius = 0;
for (i = 0; i < numPositions; i++) {
Cartesian3_default.clone(positions[i], currentPos);
const r = Cartesian3_default.magnitude(
Cartesian3_default.subtract(currentPos, naiveCenter, fromPointsScratch)
);
if (r > naiveRadius) {
naiveRadius = r;
}
const oldCenterToPointSquared = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(currentPos, ritterCenter, fromPointsScratch)
);
if (oldCenterToPointSquared > radiusSquared) {
const oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
radiusSquared = ritterRadius * ritterRadius;
const oldToNew = oldCenterToPoint - ritterRadius;
ritterCenter.x = (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) / oldCenterToPoint;
ritterCenter.y = (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) / oldCenterToPoint;
ritterCenter.z = (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) / oldCenterToPoint;
}
}
if (ritterRadius < naiveRadius) {
Cartesian3_default.clone(ritterCenter, result.center);
result.radius = ritterRadius;
} else {
Cartesian3_default.clone(naiveCenter, result.center);
result.radius = naiveRadius;
}
return result;
};
var defaultProjection2 = new GeographicProjection_default();
var fromRectangle2DLowerLeft = new Cartesian3_default();
var fromRectangle2DUpperRight = new Cartesian3_default();
var fromRectangle2DSouthwest = new Cartographic_default();
var fromRectangle2DNortheast = new Cartographic_default();
BoundingSphere.fromRectangle2D = function(rectangle, projection, result) {
return BoundingSphere.fromRectangleWithHeights2D(
rectangle,
projection,
0,
0,
result
);
};
BoundingSphere.fromRectangleWithHeights2D = function(rectangle, projection, minimumHeight, maximumHeight, result) {
if (!defined_default(result)) {
result = new BoundingSphere();
}
if (!defined_default(rectangle)) {
result.center = Cartesian3_default.clone(Cartesian3_default.ZERO, result.center);
result.radius = 0;
return result;
}
projection = defaultValue_default(projection, defaultProjection2);
Rectangle_default.southwest(rectangle, fromRectangle2DSouthwest);
fromRectangle2DSouthwest.height = minimumHeight;
Rectangle_default.northeast(rectangle, fromRectangle2DNortheast);
fromRectangle2DNortheast.height = maximumHeight;
const lowerLeft = projection.project(
fromRectangle2DSouthwest,
fromRectangle2DLowerLeft
);
const upperRight = projection.project(
fromRectangle2DNortheast,
fromRectangle2DUpperRight
);
const width = upperRight.x - lowerLeft.x;
const height = upperRight.y - lowerLeft.y;
const elevation = upperRight.z - lowerLeft.z;
result.radius = Math.sqrt(width * width + height * height + elevation * elevation) * 0.5;
const center = result.center;
center.x = lowerLeft.x + width * 0.5;
center.y = lowerLeft.y + height * 0.5;
center.z = lowerLeft.z + elevation * 0.5;
return result;
};
var fromRectangle3DScratch = [];
BoundingSphere.fromRectangle3D = function(rectangle, ellipsoid, surfaceHeight, result) {
ellipsoid = defaultValue_default(ellipsoid, Ellipsoid_default.WGS84);
surfaceHeight = defaultValue_default(surfaceHeight, 0);
if (!defined_default(result)) {
result = new BoundingSphere();
}
if (!defined_default(rectangle)) {
result.center = Cartesian3_default.clone(Cartesian3_default.ZERO, result.center);
result.radius = 0;
return result;
}
const positions = Rectangle_default.subsample(
rectangle,
ellipsoid,
surfaceHeight,
fromRectangle3DScratch
);
return BoundingSphere.fromPoints(positions, result);
};
BoundingSphere.fromVertices = function(positions, center, stride, result) {
if (!defined_default(result)) {
result = new BoundingSphere();
}
if (!defined_default(positions) || positions.length === 0) {
result.center = Cartesian3_default.clone(Cartesian3_default.ZERO, result.center);
result.radius = 0;
return result;
}
center = defaultValue_default(center, Cartesian3_default.ZERO);
stride = defaultValue_default(stride, 3);
Check_default.typeOf.number.greaterThanOrEquals("stride", stride, 3);
const currentPos = fromPointsCurrentPos;
currentPos.x = positions[0] + center.x;
currentPos.y = positions[1] + center.y;
currentPos.z = positions[2] + center.z;
const xMin = Cartesian3_default.clone(currentPos, fromPointsXMin);
const yMin = Cartesian3_default.clone(currentPos, fromPointsYMin);
const zMin = Cartesian3_default.clone(currentPos, fromPointsZMin);
const xMax = Cartesian3_default.clone(currentPos, fromPointsXMax);
const yMax = Cartesian3_default.clone(currentPos, fromPointsYMax);
const zMax = Cartesian3_default.clone(currentPos, fromPointsZMax);
const numElements = positions.length;
let i;
for (i = 0; i < numElements; i += stride) {
const x = positions[i] + center.x;
const y = positions[i + 1] + center.y;
const z = positions[i + 2] + center.z;
currentPos.x = x;
currentPos.y = y;
currentPos.z = z;
if (x < xMin.x) {
Cartesian3_default.clone(currentPos, xMin);
}
if (x > xMax.x) {
Cartesian3_default.clone(currentPos, xMax);
}
if (y < yMin.y) {
Cartesian3_default.clone(currentPos, yMin);
}
if (y > yMax.y) {
Cartesian3_default.clone(currentPos, yMax);
}
if (z < zMin.z) {
Cartesian3_default.clone(currentPos, zMin);
}
if (z > zMax.z) {
Cartesian3_default.clone(currentPos, zMax);
}
}
const xSpan = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(xMax, xMin, fromPointsScratch)
);
const ySpan = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(yMax, yMin, fromPointsScratch)
);
const zSpan = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(zMax, zMin, fromPointsScratch)
);
let diameter1 = xMin;
let diameter2 = xMax;
let maxSpan = xSpan;
if (ySpan > maxSpan) {
maxSpan = ySpan;
diameter1 = yMin;
diameter2 = yMax;
}
if (zSpan > maxSpan) {
maxSpan = zSpan;
diameter1 = zMin;
diameter2 = zMax;
}
const ritterCenter = fromPointsRitterCenter;
ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
let radiusSquared = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(diameter2, ritterCenter, fromPointsScratch)
);
let ritterRadius = Math.sqrt(radiusSquared);
const minBoxPt = fromPointsMinBoxPt;
minBoxPt.x = xMin.x;
minBoxPt.y = yMin.y;
minBoxPt.z = zMin.z;
const maxBoxPt = fromPointsMaxBoxPt;
maxBoxPt.x = xMax.x;
maxBoxPt.y = yMax.y;
maxBoxPt.z = zMax.z;
const naiveCenter = Cartesian3_default.midpoint(
minBoxPt,
maxBoxPt,
fromPointsNaiveCenterScratch
);
let naiveRadius = 0;
for (i = 0; i < numElements; i += stride) {
currentPos.x = positions[i] + center.x;
currentPos.y = positions[i + 1] + center.y;
currentPos.z = positions[i + 2] + center.z;
const r = Cartesian3_default.magnitude(
Cartesian3_default.subtract(currentPos, naiveCenter, fromPointsScratch)
);
if (r > naiveRadius) {
naiveRadius = r;
}
const oldCenterToPointSquared = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(currentPos, ritterCenter, fromPointsScratch)
);
if (oldCenterToPointSquared > radiusSquared) {
const oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
radiusSquared = ritterRadius * ritterRadius;
const oldToNew = oldCenterToPoint - ritterRadius;
ritterCenter.x = (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) / oldCenterToPoint;
ritterCenter.y = (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) / oldCenterToPoint;
ritterCenter.z = (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) / oldCenterToPoint;
}
}
if (ritterRadius < naiveRadius) {
Cartesian3_default.clone(ritterCenter, result.center);
result.radius = ritterRadius;
} else {
Cartesian3_default.clone(naiveCenter, result.center);
result.radius = naiveRadius;
}
return result;
};
BoundingSphere.fromEncodedCartesianVertices = function(positionsHigh, positionsLow, result) {
if (!defined_default(result)) {
result = new BoundingSphere();
}
if (!defined_default(positionsHigh) || !defined_default(positionsLow) || positionsHigh.length !== positionsLow.length || positionsHigh.length === 0) {
result.center = Cartesian3_default.clone(Cartesian3_default.ZERO, result.center);
result.radius = 0;
return result;
}
const currentPos = fromPointsCurrentPos;
currentPos.x = positionsHigh[0] + positionsLow[0];
currentPos.y = positionsHigh[1] + positionsLow[1];
currentPos.z = positionsHigh[2] + positionsLow[2];
const xMin = Cartesian3_default.clone(currentPos, fromPointsXMin);
const yMin = Cartesian3_default.clone(currentPos, fromPointsYMin);
const zMin = Cartesian3_default.clone(currentPos, fromPointsZMin);
const xMax = Cartesian3_default.clone(currentPos, fromPointsXMax);
const yMax = Cartesian3_default.clone(currentPos, fromPointsYMax);
const zMax = Cartesian3_default.clone(currentPos, fromPointsZMax);
const numElements = positionsHigh.length;
let i;
for (i = 0; i < numElements; i += 3) {
const x = positionsHigh[i] + positionsLow[i];
const y = positionsHigh[i + 1] + positionsLow[i + 1];
const z = positionsHigh[i + 2] + positionsLow[i + 2];
currentPos.x = x;
currentPos.y = y;
currentPos.z = z;
if (x < xMin.x) {
Cartesian3_default.clone(currentPos, xMin);
}
if (x > xMax.x) {
Cartesian3_default.clone(currentPos, xMax);
}
if (y < yMin.y) {
Cartesian3_default.clone(currentPos, yMin);
}
if (y > yMax.y) {
Cartesian3_default.clone(currentPos, yMax);
}
if (z < zMin.z) {
Cartesian3_default.clone(currentPos, zMin);
}
if (z > zMax.z) {
Cartesian3_default.clone(currentPos, zMax);
}
}
const xSpan = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(xMax, xMin, fromPointsScratch)
);
const ySpan = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(yMax, yMin, fromPointsScratch)
);
const zSpan = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(zMax, zMin, fromPointsScratch)
);
let diameter1 = xMin;
let diameter2 = xMax;
let maxSpan = xSpan;
if (ySpan > maxSpan) {
maxSpan = ySpan;
diameter1 = yMin;
diameter2 = yMax;
}
if (zSpan > maxSpan) {
maxSpan = zSpan;
diameter1 = zMin;
diameter2 = zMax;
}
const ritterCenter = fromPointsRitterCenter;
ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
let radiusSquared = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(diameter2, ritterCenter, fromPointsScratch)
);
let ritterRadius = Math.sqrt(radiusSquared);
const minBoxPt = fromPointsMinBoxPt;
minBoxPt.x = xMin.x;
minBoxPt.y = yMin.y;
minBoxPt.z = zMin.z;
const maxBoxPt = fromPointsMaxBoxPt;
maxBoxPt.x = xMax.x;
maxBoxPt.y = yMax.y;
maxBoxPt.z = zMax.z;
const naiveCenter = Cartesian3_default.midpoint(
minBoxPt,
maxBoxPt,
fromPointsNaiveCenterScratch
);
let naiveRadius = 0;
for (i = 0; i < numElements; i += 3) {
currentPos.x = positionsHigh[i] + positionsLow[i];
currentPos.y = positionsHigh[i + 1] + positionsLow[i + 1];
currentPos.z = positionsHigh[i + 2] + positionsLow[i + 2];
const r = Cartesian3_default.magnitude(
Cartesian3_default.subtract(currentPos, naiveCenter, fromPointsScratch)
);
if (r > naiveRadius) {
naiveRadius = r;
}
const oldCenterToPointSquared = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(currentPos, ritterCenter, fromPointsScratch)
);
if (oldCenterToPointSquared > radiusSquared) {
const oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
radiusSquared = ritterRadius * ritterRadius;
const oldToNew = oldCenterToPoint - ritterRadius;
ritterCenter.x = (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) / oldCenterToPoint;
ritterCenter.y = (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) / oldCenterToPoint;
ritterCenter.z = (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) / oldCenterToPoint;
}
}
if (ritterRadius < naiveRadius) {
Cartesian3_default.clone(ritterCenter, result.center);
result.radius = ritterRadius;
} else {
Cartesian3_default.clone(naiveCenter, result.center);
result.radius = naiveRadius;
}
return result;
};
BoundingSphere.fromCornerPoints = function(corner, oppositeCorner, result) {
Check_default.typeOf.object("corner", corner);
Check_default.typeOf.object("oppositeCorner", oppositeCorner);
if (!defined_default(result)) {
result = new BoundingSphere();
}
const center = Cartesian3_default.midpoint(corner, oppositeCorner, result.center);
result.radius = Cartesian3_default.distance(center, oppositeCorner);
return result;
};
BoundingSphere.fromEllipsoid = function(ellipsoid, result) {
Check_default.typeOf.object("ellipsoid", ellipsoid);
if (!defined_default(result)) {
result = new BoundingSphere();
}
Cartesian3_default.clone(Cartesian3_default.ZERO, result.center);
result.radius = ellipsoid.maximumRadius;
return result;
};
var fromBoundingSpheresScratch = new Cartesian3_default();
BoundingSphere.fromBoundingSpheres = function(boundingSpheres, result) {
if (!defined_default(result)) {
result = new BoundingSphere();
}
if (!defined_default(boundingSpheres) || boundingSpheres.length === 0) {
result.center = Cartesian3_default.clone(Cartesian3_default.ZERO, result.center);
result.radius = 0;
return result;
}
const length3 = boundingSpheres.length;
if (length3 === 1) {
return BoundingSphere.clone(boundingSpheres[0], result);
}
if (length3 === 2) {
return BoundingSphere.union(boundingSpheres[0], boundingSpheres[1], result);
}
const positions = [];
let i;
for (i = 0; i < length3; i++) {
positions.push(boundingSpheres[i].center);
}
result = BoundingSphere.fromPoints(positions, result);
const center = result.center;
let radius = result.radius;
for (i = 0; i < length3; i++) {
const tmp2 = boundingSpheres[i];
radius = Math.max(
radius,
Cartesian3_default.distance(center, tmp2.center, fromBoundingSpheresScratch) + tmp2.radius
);
}
result.radius = radius;
return result;
};
var fromOrientedBoundingBoxScratchU = new Cartesian3_default();
var fromOrientedBoundingBoxScratchV = new Cartesian3_default();
var fromOrientedBoundingBoxScratchW = new Cartesian3_default();
BoundingSphere.fromOrientedBoundingBox = function(orientedBoundingBox, result) {
Check_default.defined("orientedBoundingBox", orientedBoundingBox);
if (!defined_default(result)) {
result = new BoundingSphere();
}
const halfAxes = orientedBoundingBox.halfAxes;
const u3 = Matrix3_default.getColumn(halfAxes, 0, fromOrientedBoundingBoxScratchU);
const v7 = Matrix3_default.getColumn(halfAxes, 1, fromOrientedBoundingBoxScratchV);
const w = Matrix3_default.getColumn(halfAxes, 2, fromOrientedBoundingBoxScratchW);
Cartesian3_default.add(u3, v7, u3);
Cartesian3_default.add(u3, w, u3);
result.center = Cartesian3_default.clone(orientedBoundingBox.center, result.center);
result.radius = Cartesian3_default.magnitude(u3);
return result;
};
var scratchFromTransformationCenter = new Cartesian3_default();
var scratchFromTransformationScale = new Cartesian3_default();
BoundingSphere.fromTransformation = function(transformation, result) {
Check_default.typeOf.object("transformation", transformation);
if (!defined_default(result)) {
result = new BoundingSphere();
}
const center = Matrix4_default.getTranslation(
transformation,
scratchFromTransformationCenter
);
const scale = Matrix4_default.getScale(
transformation,
scratchFromTransformationScale
);
const radius = 0.5 * Cartesian3_default.magnitude(scale);
result.center = Cartesian3_default.clone(center, result.center);
result.radius = radius;
return result;
};
BoundingSphere.clone = function(sphere, result) {
if (!defined_default(sphere)) {
return void 0;
}
if (!defined_default(result)) {
return new BoundingSphere(sphere.center, sphere.radius);
}
result.center = Cartesian3_default.clone(sphere.center, result.center);
result.radius = sphere.radius;
return result;
};
BoundingSphere.packedLength = 4;
BoundingSphere.pack = function(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
const center = value.center;
array[startingIndex++] = center.x;
array[startingIndex++] = center.y;
array[startingIndex++] = center.z;
array[startingIndex] = value.radius;
return array;
};
BoundingSphere.unpack = function(array, startingIndex, result) {
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
if (!defined_default(result)) {
result = new BoundingSphere();
}
const center = result.center;
center.x = array[startingIndex++];
center.y = array[startingIndex++];
center.z = array[startingIndex++];
result.radius = array[startingIndex];
return result;
};
var unionScratch = new Cartesian3_default();
var unionScratchCenter = new Cartesian3_default();
BoundingSphere.union = function(left, right, result) {
Check_default.typeOf.object("left", left);
Check_default.typeOf.object("right", right);
if (!defined_default(result)) {
result = new BoundingSphere();
}
const leftCenter = left.center;
const leftRadius = left.radius;
const rightCenter = right.center;
const rightRadius = right.radius;
const toRightCenter = Cartesian3_default.subtract(
rightCenter,
leftCenter,
unionScratch
);
const centerSeparation = Cartesian3_default.magnitude(toRightCenter);
if (leftRadius >= centerSeparation + rightRadius) {
left.clone(result);
return result;
}
if (rightRadius >= centerSeparation + leftRadius) {
right.clone(result);
return result;
}
const halfDistanceBetweenTangentPoints = (leftRadius + centerSeparation + rightRadius) * 0.5;
const center = Cartesian3_default.multiplyByScalar(
toRightCenter,
(-leftRadius + halfDistanceBetweenTangentPoints) / centerSeparation,
unionScratchCenter
);
Cartesian3_default.add(center, leftCenter, center);
Cartesian3_default.clone(center, result.center);
result.radius = halfDistanceBetweenTangentPoints;
return result;
};
var expandScratch = new Cartesian3_default();
BoundingSphere.expand = function(sphere, point, result) {
Check_default.typeOf.object("sphere", sphere);
Check_default.typeOf.object("point", point);
result = BoundingSphere.clone(sphere, result);
const radius = Cartesian3_default.magnitude(
Cartesian3_default.subtract(point, result.center, expandScratch)
);
if (radius > result.radius) {
result.radius = radius;
}
return result;
};
BoundingSphere.intersectPlane = function(sphere, plane) {
Check_default.typeOf.object("sphere", sphere);
Check_default.typeOf.object("plane", plane);
const center = sphere.center;
const radius = sphere.radius;
const normal2 = plane.normal;
const distanceToPlane = Cartesian3_default.dot(normal2, center) + plane.distance;
if (distanceToPlane < -radius) {
return Intersect_default.OUTSIDE;
} else if (distanceToPlane < radius) {
return Intersect_default.INTERSECTING;
}
return Intersect_default.INSIDE;
};
BoundingSphere.transform = function(sphere, transform3, result) {
Check_default.typeOf.object("sphere", sphere);
Check_default.typeOf.object("transform", transform3);
if (!defined_default(result)) {
result = new BoundingSphere();
}
result.center = Matrix4_default.multiplyByPoint(
transform3,
sphere.center,
result.center
);
result.radius = Matrix4_default.getMaximumScale(transform3) * sphere.radius;
return result;
};
var distanceSquaredToScratch = new Cartesian3_default();
BoundingSphere.distanceSquaredTo = function(sphere, cartesian11) {
Check_default.typeOf.object("sphere", sphere);
Check_default.typeOf.object("cartesian", cartesian11);
const diff = Cartesian3_default.subtract(
sphere.center,
cartesian11,
distanceSquaredToScratch
);
const distance2 = Cartesian3_default.magnitude(diff) - sphere.radius;
if (distance2 <= 0) {
return 0;
}
return distance2 * distance2;
};
BoundingSphere.transformWithoutScale = function(sphere, transform3, result) {
Check_default.typeOf.object("sphere", sphere);
Check_default.typeOf.object("transform", transform3);
if (!defined_default(result)) {
result = new BoundingSphere();
}
result.center = Matrix4_default.multiplyByPoint(
transform3,
sphere.center,
result.center
);
result.radius = sphere.radius;
return result;
};
var scratchCartesian3 = new Cartesian3_default();
BoundingSphere.computePlaneDistances = function(sphere, position, direction2, result) {
Check_default.typeOf.object("sphere", sphere);
Check_default.typeOf.object("position", position);
Check_default.typeOf.object("direction", direction2);
if (!defined_default(result)) {
result = new Interval_default();
}
const toCenter = Cartesian3_default.subtract(
sphere.center,
position,
scratchCartesian3
);
const mag = Cartesian3_default.dot(direction2, toCenter);
result.start = mag - sphere.radius;
result.stop = mag + sphere.radius;
return result;
};
var projectTo2DNormalScratch = new Cartesian3_default();
var projectTo2DEastScratch = new Cartesian3_default();
var projectTo2DNorthScratch = new Cartesian3_default();
var projectTo2DWestScratch = new Cartesian3_default();
var projectTo2DSouthScratch = new Cartesian3_default();
var projectTo2DCartographicScratch = new Cartographic_default();
var projectTo2DPositionsScratch = new Array(8);
for (let n = 0; n < 8; ++n) {
projectTo2DPositionsScratch[n] = new Cartesian3_default();
}
var projectTo2DProjection = new GeographicProjection_default();
BoundingSphere.projectTo2D = function(sphere, projection, result) {
Check_default.typeOf.object("sphere", sphere);
projection = defaultValue_default(projection, projectTo2DProjection);
const ellipsoid = projection.ellipsoid;
let center = sphere.center;
const radius = sphere.radius;
let normal2;
if (Cartesian3_default.equals(center, Cartesian3_default.ZERO)) {
normal2 = Cartesian3_default.clone(Cartesian3_default.UNIT_X, projectTo2DNormalScratch);
} else {
normal2 = ellipsoid.geodeticSurfaceNormal(center, projectTo2DNormalScratch);
}
const east = Cartesian3_default.cross(
Cartesian3_default.UNIT_Z,
normal2,
projectTo2DEastScratch
);
Cartesian3_default.normalize(east, east);
const north = Cartesian3_default.cross(normal2, east, projectTo2DNorthScratch);
Cartesian3_default.normalize(north, north);
Cartesian3_default.multiplyByScalar(normal2, radius, normal2);
Cartesian3_default.multiplyByScalar(north, radius, north);
Cartesian3_default.multiplyByScalar(east, radius, east);
const south = Cartesian3_default.negate(north, projectTo2DSouthScratch);
const west = Cartesian3_default.negate(east, projectTo2DWestScratch);
const positions = projectTo2DPositionsScratch;
let corner = positions[0];
Cartesian3_default.add(normal2, north, corner);
Cartesian3_default.add(corner, east, corner);
corner = positions[1];
Cartesian3_default.add(normal2, north, corner);
Cartesian3_default.add(corner, west, corner);
corner = positions[2];
Cartesian3_default.add(normal2, south, corner);
Cartesian3_default.add(corner, west, corner);
corner = positions[3];
Cartesian3_default.add(normal2, south, corner);
Cartesian3_default.add(corner, east, corner);
Cartesian3_default.negate(normal2, normal2);
corner = positions[4];
Cartesian3_default.add(normal2, north, corner);
Cartesian3_default.add(corner, east, corner);
corner = positions[5];
Cartesian3_default.add(normal2, north, corner);
Cartesian3_default.add(corner, west, corner);
corner = positions[6];
Cartesian3_default.add(normal2, south, corner);
Cartesian3_default.add(corner, west, corner);
corner = positions[7];
Cartesian3_default.add(normal2, south, corner);
Cartesian3_default.add(corner, east, corner);
const length3 = positions.length;
for (let i = 0; i < length3; ++i) {
const position = positions[i];
Cartesian3_default.add(center, position, position);
const cartographic2 = ellipsoid.cartesianToCartographic(
position,
projectTo2DCartographicScratch
);
projection.project(cartographic2, position);
}
result = BoundingSphere.fromPoints(positions, result);
center = result.center;
const x = center.x;
const y = center.y;
const z = center.z;
center.x = z;
center.y = x;
center.z = y;
return result;
};
BoundingSphere.isOccluded = function(sphere, occluder) {
Check_default.typeOf.object("sphere", sphere);
Check_default.typeOf.object("occluder", occluder);
return !occluder.isBoundingSphereVisible(sphere);
};
BoundingSphere.equals = function(left, right) {
return left === right || defined_default(left) && defined_default(right) && Cartesian3_default.equals(left.center, right.center) && left.radius === right.radius;
};
BoundingSphere.prototype.intersectPlane = function(plane) {
return BoundingSphere.intersectPlane(this, plane);
};
BoundingSphere.prototype.distanceSquaredTo = function(cartesian11) {
return BoundingSphere.distanceSquaredTo(this, cartesian11);
};
BoundingSphere.prototype.computePlaneDistances = function(position, direction2, result) {
return BoundingSphere.computePlaneDistances(
this,
position,
direction2,
result
);
};
BoundingSphere.prototype.isOccluded = function(occluder) {
return BoundingSphere.isOccluded(this, occluder);
};
BoundingSphere.prototype.equals = function(right) {
return BoundingSphere.equals(this, right);
};
BoundingSphere.prototype.clone = function(result) {
return BoundingSphere.clone(this, result);
};
BoundingSphere.prototype.volume = function() {
const radius = this.radius;
return volumeConstant * radius * radius * radius;
};
var BoundingSphere_default = BoundingSphere;
// packages/engine/Source/Core/GeometryAttributes.js
function GeometryAttributes(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this.position = options.position;
this.normal = options.normal;
this.st = options.st;
this.bitangent = options.bitangent;
this.tangent = options.tangent;
this.color = options.color;
}
var GeometryAttributes_default = GeometryAttributes;
// packages/engine/Source/Core/GeometryOffsetAttribute.js
var GeometryOffsetAttribute = {
NONE: 0,
TOP: 1,
ALL: 2
};
var GeometryOffsetAttribute_default = Object.freeze(GeometryOffsetAttribute);
// packages/engine/Source/Core/VertexFormat.js
function VertexFormat(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this.position = defaultValue_default(options.position, false);
this.normal = defaultValue_default(options.normal, false);
this.st = defaultValue_default(options.st, false);
this.bitangent = defaultValue_default(options.bitangent, false);
this.tangent = defaultValue_default(options.tangent, false);
this.color = defaultValue_default(options.color, false);
}
VertexFormat.POSITION_ONLY = Object.freeze(
new VertexFormat({
position: true
})
);
VertexFormat.POSITION_AND_NORMAL = Object.freeze(
new VertexFormat({
position: true,
normal: true
})
);
VertexFormat.POSITION_NORMAL_AND_ST = Object.freeze(
new VertexFormat({
position: true,
normal: true,
st: true
})
);
VertexFormat.POSITION_AND_ST = Object.freeze(
new VertexFormat({
position: true,
st: true
})
);
VertexFormat.POSITION_AND_COLOR = Object.freeze(
new VertexFormat({
position: true,
color: true
})
);
VertexFormat.ALL = Object.freeze(
new VertexFormat({
position: true,
normal: true,
st: true,
tangent: true,
bitangent: true
})
);
VertexFormat.DEFAULT = VertexFormat.POSITION_NORMAL_AND_ST;
VertexFormat.packedLength = 6;
VertexFormat.pack = function(value, array, startingIndex) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required");
}
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
array[startingIndex++] = value.position ? 1 : 0;
array[startingIndex++] = value.normal ? 1 : 0;
array[startingIndex++] = value.st ? 1 : 0;
array[startingIndex++] = value.tangent ? 1 : 0;
array[startingIndex++] = value.bitangent ? 1 : 0;
array[startingIndex] = value.color ? 1 : 0;
return array;
};
VertexFormat.unpack = function(array, startingIndex, result) {
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
if (!defined_default(result)) {
result = new VertexFormat();
}
result.position = array[startingIndex++] === 1;
result.normal = array[startingIndex++] === 1;
result.st = array[startingIndex++] === 1;
result.tangent = array[startingIndex++] === 1;
result.bitangent = array[startingIndex++] === 1;
result.color = array[startingIndex] === 1;
return result;
};
VertexFormat.clone = function(vertexFormat, result) {
if (!defined_default(vertexFormat)) {
return void 0;
}
if (!defined_default(result)) {
result = new VertexFormat();
}
result.position = vertexFormat.position;
result.normal = vertexFormat.normal;
result.st = vertexFormat.st;
result.tangent = vertexFormat.tangent;
result.bitangent = vertexFormat.bitangent;
result.color = vertexFormat.color;
return result;
};
var VertexFormat_default = VertexFormat;
// packages/engine/Source/Core/BoxGeometry.js
var diffScratch = new Cartesian3_default();
function BoxGeometry(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const min3 = options.minimum;
const max3 = options.maximum;
Check_default.typeOf.object("min", min3);
Check_default.typeOf.object("max", max3);
if (defined_default(options.offsetAttribute) && options.offsetAttribute === GeometryOffsetAttribute_default.TOP) {
throw new DeveloperError_default(
"GeometryOffsetAttribute.TOP is not a supported options.offsetAttribute for this geometry."
);
}
const vertexFormat = defaultValue_default(options.vertexFormat, VertexFormat_default.DEFAULT);
this._minimum = Cartesian3_default.clone(min3);
this._maximum = Cartesian3_default.clone(max3);
this._vertexFormat = vertexFormat;
this._offsetAttribute = options.offsetAttribute;
this._workerName = "createBoxGeometry";
}
BoxGeometry.fromDimensions = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const dimensions = options.dimensions;
Check_default.typeOf.object("dimensions", dimensions);
Check_default.typeOf.number.greaterThanOrEquals("dimensions.x", dimensions.x, 0);
Check_default.typeOf.number.greaterThanOrEquals("dimensions.y", dimensions.y, 0);
Check_default.typeOf.number.greaterThanOrEquals("dimensions.z", dimensions.z, 0);
const corner = Cartesian3_default.multiplyByScalar(dimensions, 0.5, new Cartesian3_default());
return new BoxGeometry({
minimum: Cartesian3_default.negate(corner, new Cartesian3_default()),
maximum: corner,
vertexFormat: options.vertexFormat,
offsetAttribute: options.offsetAttribute
});
};
BoxGeometry.fromAxisAlignedBoundingBox = function(boundingBox) {
Check_default.typeOf.object("boundingBox", boundingBox);
return new BoxGeometry({
minimum: boundingBox.minimum,
maximum: boundingBox.maximum
});
};
BoxGeometry.packedLength = 2 * Cartesian3_default.packedLength + VertexFormat_default.packedLength + 1;
BoxGeometry.pack = function(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
Cartesian3_default.pack(value._minimum, array, startingIndex);
Cartesian3_default.pack(
value._maximum,
array,
startingIndex + Cartesian3_default.packedLength
);
VertexFormat_default.pack(
value._vertexFormat,
array,
startingIndex + 2 * Cartesian3_default.packedLength
);
array[startingIndex + 2 * Cartesian3_default.packedLength + VertexFormat_default.packedLength] = defaultValue_default(value._offsetAttribute, -1);
return array;
};
var scratchMin = new Cartesian3_default();
var scratchMax = new Cartesian3_default();
var scratchVertexFormat = new VertexFormat_default();
var scratchOptions = {
minimum: scratchMin,
maximum: scratchMax,
vertexFormat: scratchVertexFormat,
offsetAttribute: void 0
};
BoxGeometry.unpack = function(array, startingIndex, result) {
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
const min3 = Cartesian3_default.unpack(array, startingIndex, scratchMin);
const max3 = Cartesian3_default.unpack(
array,
startingIndex + Cartesian3_default.packedLength,
scratchMax
);
const vertexFormat = VertexFormat_default.unpack(
array,
startingIndex + 2 * Cartesian3_default.packedLength,
scratchVertexFormat
);
const offsetAttribute = array[startingIndex + 2 * Cartesian3_default.packedLength + VertexFormat_default.packedLength];
if (!defined_default(result)) {
scratchOptions.offsetAttribute = offsetAttribute === -1 ? void 0 : offsetAttribute;
return new BoxGeometry(scratchOptions);
}
result._minimum = Cartesian3_default.clone(min3, result._minimum);
result._maximum = Cartesian3_default.clone(max3, result._maximum);
result._vertexFormat = VertexFormat_default.clone(vertexFormat, result._vertexFormat);
result._offsetAttribute = offsetAttribute === -1 ? void 0 : offsetAttribute;
return result;
};
BoxGeometry.createGeometry = function(boxGeometry) {
const min3 = boxGeometry._minimum;
const max3 = boxGeometry._maximum;
const vertexFormat = boxGeometry._vertexFormat;
if (Cartesian3_default.equals(min3, max3)) {
return;
}
const attributes = new GeometryAttributes_default();
let indices2;
let positions;
if (vertexFormat.position && (vertexFormat.st || vertexFormat.normal || vertexFormat.tangent || vertexFormat.bitangent)) {
if (vertexFormat.position) {
positions = new Float64Array(6 * 4 * 3);
positions[0] = min3.x;
positions[1] = min3.y;
positions[2] = max3.z;
positions[3] = max3.x;
positions[4] = min3.y;
positions[5] = max3.z;
positions[6] = max3.x;
positions[7] = max3.y;
positions[8] = max3.z;
positions[9] = min3.x;
positions[10] = max3.y;
positions[11] = max3.z;
positions[12] = min3.x;
positions[13] = min3.y;
positions[14] = min3.z;
positions[15] = max3.x;
positions[16] = min3.y;
positions[17] = min3.z;
positions[18] = max3.x;
positions[19] = max3.y;
positions[20] = min3.z;
positions[21] = min3.x;
positions[22] = max3.y;
positions[23] = min3.z;
positions[24] = max3.x;
positions[25] = min3.y;
positions[26] = min3.z;
positions[27] = max3.x;
positions[28] = max3.y;
positions[29] = min3.z;
positions[30] = max3.x;
positions[31] = max3.y;
positions[32] = max3.z;
positions[33] = max3.x;
positions[34] = min3.y;
positions[35] = max3.z;
positions[36] = min3.x;
positions[37] = min3.y;
positions[38] = min3.z;
positions[39] = min3.x;
positions[40] = max3.y;
positions[41] = min3.z;
positions[42] = min3.x;
positions[43] = max3.y;
positions[44] = max3.z;
positions[45] = min3.x;
positions[46] = min3.y;
positions[47] = max3.z;
positions[48] = min3.x;
positions[49] = max3.y;
positions[50] = min3.z;
positions[51] = max3.x;
positions[52] = max3.y;
positions[53] = min3.z;
positions[54] = max3.x;
positions[55] = max3.y;
positions[56] = max3.z;
positions[57] = min3.x;
positions[58] = max3.y;
positions[59] = max3.z;
positions[60] = min3.x;
positions[61] = min3.y;
positions[62] = min3.z;
positions[63] = max3.x;
positions[64] = min3.y;
positions[65] = min3.z;
positions[66] = max3.x;
positions[67] = min3.y;
positions[68] = max3.z;
positions[69] = min3.x;
positions[70] = min3.y;
positions[71] = max3.z;
attributes.position = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: positions
});
}
if (vertexFormat.normal) {
const normals = new Float32Array(6 * 4 * 3);
normals[0] = 0;
normals[1] = 0;
normals[2] = 1;
normals[3] = 0;
normals[4] = 0;
normals[5] = 1;
normals[6] = 0;
normals[7] = 0;
normals[8] = 1;
normals[9] = 0;
normals[10] = 0;
normals[11] = 1;
normals[12] = 0;
normals[13] = 0;
normals[14] = -1;
normals[15] = 0;
normals[16] = 0;
normals[17] = -1;
normals[18] = 0;
normals[19] = 0;
normals[20] = -1;
normals[21] = 0;
normals[22] = 0;
normals[23] = -1;
normals[24] = 1;
normals[25] = 0;
normals[26] = 0;
normals[27] = 1;
normals[28] = 0;
normals[29] = 0;
normals[30] = 1;
normals[31] = 0;
normals[32] = 0;
normals[33] = 1;
normals[34] = 0;
normals[35] = 0;
normals[36] = -1;
normals[37] = 0;
normals[38] = 0;
normals[39] = -1;
normals[40] = 0;
normals[41] = 0;
normals[42] = -1;
normals[43] = 0;
normals[44] = 0;
normals[45] = -1;
normals[46] = 0;
normals[47] = 0;
normals[48] = 0;
normals[49] = 1;
normals[50] = 0;
normals[51] = 0;
normals[52] = 1;
normals[53] = 0;
normals[54] = 0;
normals[55] = 1;
normals[56] = 0;
normals[57] = 0;
normals[58] = 1;
normals[59] = 0;
normals[60] = 0;
normals[61] = -1;
normals[62] = 0;
normals[63] = 0;
normals[64] = -1;
normals[65] = 0;
normals[66] = 0;
normals[67] = -1;
normals[68] = 0;
normals[69] = 0;
normals[70] = -1;
normals[71] = 0;
attributes.normal = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: normals
});
}
if (vertexFormat.st) {
const texCoords = new Float32Array(6 * 4 * 2);
texCoords[0] = 0;
texCoords[1] = 0;
texCoords[2] = 1;
texCoords[3] = 0;
texCoords[4] = 1;
texCoords[5] = 1;
texCoords[6] = 0;
texCoords[7] = 1;
texCoords[8] = 1;
texCoords[9] = 0;
texCoords[10] = 0;
texCoords[11] = 0;
texCoords[12] = 0;
texCoords[13] = 1;
texCoords[14] = 1;
texCoords[15] = 1;
texCoords[16] = 0;
texCoords[17] = 0;
texCoords[18] = 1;
texCoords[19] = 0;
texCoords[20] = 1;
texCoords[21] = 1;
texCoords[22] = 0;
texCoords[23] = 1;
texCoords[24] = 1;
texCoords[25] = 0;
texCoords[26] = 0;
texCoords[27] = 0;
texCoords[28] = 0;
texCoords[29] = 1;
texCoords[30] = 1;
texCoords[31] = 1;
texCoords[32] = 1;
texCoords[33] = 0;
texCoords[34] = 0;
texCoords[35] = 0;
texCoords[36] = 0;
texCoords[37] = 1;
texCoords[38] = 1;
texCoords[39] = 1;
texCoords[40] = 0;
texCoords[41] = 0;
texCoords[42] = 1;
texCoords[43] = 0;
texCoords[44] = 1;
texCoords[45] = 1;
texCoords[46] = 0;
texCoords[47] = 1;
attributes.st = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 2,
values: texCoords
});
}
if (vertexFormat.tangent) {
const tangents = new Float32Array(6 * 4 * 3);
tangents[0] = 1;
tangents[1] = 0;
tangents[2] = 0;
tangents[3] = 1;
tangents[4] = 0;
tangents[5] = 0;
tangents[6] = 1;
tangents[7] = 0;
tangents[8] = 0;
tangents[9] = 1;
tangents[10] = 0;
tangents[11] = 0;
tangents[12] = -1;
tangents[13] = 0;
tangents[14] = 0;
tangents[15] = -1;
tangents[16] = 0;
tangents[17] = 0;
tangents[18] = -1;
tangents[19] = 0;
tangents[20] = 0;
tangents[21] = -1;
tangents[22] = 0;
tangents[23] = 0;
tangents[24] = 0;
tangents[25] = 1;
tangents[26] = 0;
tangents[27] = 0;
tangents[28] = 1;
tangents[29] = 0;
tangents[30] = 0;
tangents[31] = 1;
tangents[32] = 0;
tangents[33] = 0;
tangents[34] = 1;
tangents[35] = 0;
tangents[36] = 0;
tangents[37] = -1;
tangents[38] = 0;
tangents[39] = 0;
tangents[40] = -1;
tangents[41] = 0;
tangents[42] = 0;
tangents[43] = -1;
tangents[44] = 0;
tangents[45] = 0;
tangents[46] = -1;
tangents[47] = 0;
tangents[48] = -1;
tangents[49] = 0;
tangents[50] = 0;
tangents[51] = -1;
tangents[52] = 0;
tangents[53] = 0;
tangents[54] = -1;
tangents[55] = 0;
tangents[56] = 0;
tangents[57] = -1;
tangents[58] = 0;
tangents[59] = 0;
tangents[60] = 1;
tangents[61] = 0;
tangents[62] = 0;
tangents[63] = 1;
tangents[64] = 0;
tangents[65] = 0;
tangents[66] = 1;
tangents[67] = 0;
tangents[68] = 0;
tangents[69] = 1;
tangents[70] = 0;
tangents[71] = 0;
attributes.tangent = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: tangents
});
}
if (vertexFormat.bitangent) {
const bitangents = new Float32Array(6 * 4 * 3);
bitangents[0] = 0;
bitangents[1] = 1;
bitangents[2] = 0;
bitangents[3] = 0;
bitangents[4] = 1;
bitangents[5] = 0;
bitangents[6] = 0;
bitangents[7] = 1;
bitangents[8] = 0;
bitangents[9] = 0;
bitangents[10] = 1;
bitangents[11] = 0;
bitangents[12] = 0;
bitangents[13] = 1;
bitangents[14] = 0;
bitangents[15] = 0;
bitangents[16] = 1;
bitangents[17] = 0;
bitangents[18] = 0;
bitangents[19] = 1;
bitangents[20] = 0;
bitangents[21] = 0;
bitangents[22] = 1;
bitangents[23] = 0;
bitangents[24] = 0;
bitangents[25] = 0;
bitangents[26] = 1;
bitangents[27] = 0;
bitangents[28] = 0;
bitangents[29] = 1;
bitangents[30] = 0;
bitangents[31] = 0;
bitangents[32] = 1;
bitangents[33] = 0;
bitangents[34] = 0;
bitangents[35] = 1;
bitangents[36] = 0;
bitangents[37] = 0;
bitangents[38] = 1;
bitangents[39] = 0;
bitangents[40] = 0;
bitangents[41] = 1;
bitangents[42] = 0;
bitangents[43] = 0;
bitangents[44] = 1;
bitangents[45] = 0;
bitangents[46] = 0;
bitangents[47] = 1;
bitangents[48] = 0;
bitangents[49] = 0;
bitangents[50] = 1;
bitangents[51] = 0;
bitangents[52] = 0;
bitangents[53] = 1;
bitangents[54] = 0;
bitangents[55] = 0;
bitangents[56] = 1;
bitangents[57] = 0;
bitangents[58] = 0;
bitangents[59] = 1;
bitangents[60] = 0;
bitangents[61] = 0;
bitangents[62] = 1;
bitangents[63] = 0;
bitangents[64] = 0;
bitangents[65] = 1;
bitangents[66] = 0;
bitangents[67] = 0;
bitangents[68] = 1;
bitangents[69] = 0;
bitangents[70] = 0;
bitangents[71] = 1;
attributes.bitangent = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: bitangents
});
}
indices2 = new Uint16Array(6 * 2 * 3);
indices2[0] = 0;
indices2[1] = 1;
indices2[2] = 2;
indices2[3] = 0;
indices2[4] = 2;
indices2[5] = 3;
indices2[6] = 4 + 2;
indices2[7] = 4 + 1;
indices2[8] = 4 + 0;
indices2[9] = 4 + 3;
indices2[10] = 4 + 2;
indices2[11] = 4 + 0;
indices2[12] = 8 + 0;
indices2[13] = 8 + 1;
indices2[14] = 8 + 2;
indices2[15] = 8 + 0;
indices2[16] = 8 + 2;
indices2[17] = 8 + 3;
indices2[18] = 12 + 2;
indices2[19] = 12 + 1;
indices2[20] = 12 + 0;
indices2[21] = 12 + 3;
indices2[22] = 12 + 2;
indices2[23] = 12 + 0;
indices2[24] = 16 + 2;
indices2[25] = 16 + 1;
indices2[26] = 16 + 0;
indices2[27] = 16 + 3;
indices2[28] = 16 + 2;
indices2[29] = 16 + 0;
indices2[30] = 20 + 0;
indices2[31] = 20 + 1;
indices2[32] = 20 + 2;
indices2[33] = 20 + 0;
indices2[34] = 20 + 2;
indices2[35] = 20 + 3;
} else {
positions = new Float64Array(8 * 3);
positions[0] = min3.x;
positions[1] = min3.y;
positions[2] = min3.z;
positions[3] = max3.x;
positions[4] = min3.y;
positions[5] = min3.z;
positions[6] = max3.x;
positions[7] = max3.y;
positions[8] = min3.z;
positions[9] = min3.x;
positions[10] = max3.y;
positions[11] = min3.z;
positions[12] = min3.x;
positions[13] = min3.y;
positions[14] = max3.z;
positions[15] = max3.x;
positions[16] = min3.y;
positions[17] = max3.z;
positions[18] = max3.x;
positions[19] = max3.y;
positions[20] = max3.z;
positions[21] = min3.x;
positions[22] = max3.y;
positions[23] = max3.z;
attributes.position = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: positions
});
indices2 = new Uint16Array(6 * 2 * 3);
indices2[0] = 4;
indices2[1] = 5;
indices2[2] = 6;
indices2[3] = 4;
indices2[4] = 6;
indices2[5] = 7;
indices2[6] = 1;
indices2[7] = 0;
indices2[8] = 3;
indices2[9] = 1;
indices2[10] = 3;
indices2[11] = 2;
indices2[12] = 1;
indices2[13] = 6;
indices2[14] = 5;
indices2[15] = 1;
indices2[16] = 2;
indices2[17] = 6;
indices2[18] = 2;
indices2[19] = 3;
indices2[20] = 7;
indices2[21] = 2;
indices2[22] = 7;
indices2[23] = 6;
indices2[24] = 3;
indices2[25] = 0;
indices2[26] = 4;
indices2[27] = 3;
indices2[28] = 4;
indices2[29] = 7;
indices2[30] = 0;
indices2[31] = 1;
indices2[32] = 5;
indices2[33] = 0;
indices2[34] = 5;
indices2[35] = 4;
}
const diff = Cartesian3_default.subtract(max3, min3, diffScratch);
const radius = Cartesian3_default.magnitude(diff) * 0.5;
if (defined_default(boxGeometry._offsetAttribute)) {
const length3 = positions.length;
const offsetValue = boxGeometry._offsetAttribute === GeometryOffsetAttribute_default.NONE ? 0 : 1;
const applyOffset = new Uint8Array(length3 / 3).fill(offsetValue);
attributes.applyOffset = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentsPerAttribute: 1,
values: applyOffset
});
}
return new Geometry_default({
attributes,
indices: indices2,
primitiveType: PrimitiveType_default.TRIANGLES,
boundingSphere: new BoundingSphere_default(Cartesian3_default.ZERO, radius),
offsetAttribute: boxGeometry._offsetAttribute
});
};
var unitBoxGeometry;
BoxGeometry.getUnitBox = function() {
if (!defined_default(unitBoxGeometry)) {
unitBoxGeometry = BoxGeometry.createGeometry(
BoxGeometry.fromDimensions({
dimensions: new Cartesian3_default(1, 1, 1),
vertexFormat: VertexFormat_default.POSITION_ONLY
})
);
}
return unitBoxGeometry;
};
var BoxGeometry_default = BoxGeometry;
// packages/engine/Source/Core/BoxOutlineGeometry.js
var diffScratch2 = new Cartesian3_default();
function BoxOutlineGeometry(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const min3 = options.minimum;
const max3 = options.maximum;
Check_default.typeOf.object("min", min3);
Check_default.typeOf.object("max", max3);
if (defined_default(options.offsetAttribute) && options.offsetAttribute === GeometryOffsetAttribute_default.TOP) {
throw new DeveloperError_default(
"GeometryOffsetAttribute.TOP is not a supported options.offsetAttribute for this geometry."
);
}
this._min = Cartesian3_default.clone(min3);
this._max = Cartesian3_default.clone(max3);
this._offsetAttribute = options.offsetAttribute;
this._workerName = "createBoxOutlineGeometry";
}
BoxOutlineGeometry.fromDimensions = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const dimensions = options.dimensions;
Check_default.typeOf.object("dimensions", dimensions);
Check_default.typeOf.number.greaterThanOrEquals("dimensions.x", dimensions.x, 0);
Check_default.typeOf.number.greaterThanOrEquals("dimensions.y", dimensions.y, 0);
Check_default.typeOf.number.greaterThanOrEquals("dimensions.z", dimensions.z, 0);
const corner = Cartesian3_default.multiplyByScalar(dimensions, 0.5, new Cartesian3_default());
return new BoxOutlineGeometry({
minimum: Cartesian3_default.negate(corner, new Cartesian3_default()),
maximum: corner,
offsetAttribute: options.offsetAttribute
});
};
BoxOutlineGeometry.fromAxisAlignedBoundingBox = function(boundingBox) {
Check_default.typeOf.object("boundindBox", boundingBox);
return new BoxOutlineGeometry({
minimum: boundingBox.minimum,
maximum: boundingBox.maximum
});
};
BoxOutlineGeometry.packedLength = 2 * Cartesian3_default.packedLength + 1;
BoxOutlineGeometry.pack = function(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
Cartesian3_default.pack(value._min, array, startingIndex);
Cartesian3_default.pack(value._max, array, startingIndex + Cartesian3_default.packedLength);
array[startingIndex + Cartesian3_default.packedLength * 2] = defaultValue_default(
value._offsetAttribute,
-1
);
return array;
};
var scratchMin2 = new Cartesian3_default();
var scratchMax2 = new Cartesian3_default();
var scratchOptions2 = {
minimum: scratchMin2,
maximum: scratchMax2,
offsetAttribute: void 0
};
BoxOutlineGeometry.unpack = function(array, startingIndex, result) {
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
const min3 = Cartesian3_default.unpack(array, startingIndex, scratchMin2);
const max3 = Cartesian3_default.unpack(
array,
startingIndex + Cartesian3_default.packedLength,
scratchMax2
);
const offsetAttribute = array[startingIndex + Cartesian3_default.packedLength * 2];
if (!defined_default(result)) {
scratchOptions2.offsetAttribute = offsetAttribute === -1 ? void 0 : offsetAttribute;
return new BoxOutlineGeometry(scratchOptions2);
}
result._min = Cartesian3_default.clone(min3, result._min);
result._max = Cartesian3_default.clone(max3, result._max);
result._offsetAttribute = offsetAttribute === -1 ? void 0 : offsetAttribute;
return result;
};
BoxOutlineGeometry.createGeometry = function(boxGeometry) {
const min3 = boxGeometry._min;
const max3 = boxGeometry._max;
if (Cartesian3_default.equals(min3, max3)) {
return;
}
const attributes = new GeometryAttributes_default();
const indices2 = new Uint16Array(12 * 2);
const positions = new Float64Array(8 * 3);
positions[0] = min3.x;
positions[1] = min3.y;
positions[2] = min3.z;
positions[3] = max3.x;
positions[4] = min3.y;
positions[5] = min3.z;
positions[6] = max3.x;
positions[7] = max3.y;
positions[8] = min3.z;
positions[9] = min3.x;
positions[10] = max3.y;
positions[11] = min3.z;
positions[12] = min3.x;
positions[13] = min3.y;
positions[14] = max3.z;
positions[15] = max3.x;
positions[16] = min3.y;
positions[17] = max3.z;
positions[18] = max3.x;
positions[19] = max3.y;
positions[20] = max3.z;
positions[21] = min3.x;
positions[22] = max3.y;
positions[23] = max3.z;
attributes.position = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: positions
});
indices2[0] = 4;
indices2[1] = 5;
indices2[2] = 5;
indices2[3] = 6;
indices2[4] = 6;
indices2[5] = 7;
indices2[6] = 7;
indices2[7] = 4;
indices2[8] = 0;
indices2[9] = 1;
indices2[10] = 1;
indices2[11] = 2;
indices2[12] = 2;
indices2[13] = 3;
indices2[14] = 3;
indices2[15] = 0;
indices2[16] = 0;
indices2[17] = 4;
indices2[18] = 1;
indices2[19] = 5;
indices2[20] = 2;
indices2[21] = 6;
indices2[22] = 3;
indices2[23] = 7;
const diff = Cartesian3_default.subtract(max3, min3, diffScratch2);
const radius = Cartesian3_default.magnitude(diff) * 0.5;
if (defined_default(boxGeometry._offsetAttribute)) {
const length3 = positions.length;
const offsetValue = boxGeometry._offsetAttribute === GeometryOffsetAttribute_default.NONE ? 0 : 1;
const applyOffset = new Uint8Array(length3 / 3).fill(offsetValue);
attributes.applyOffset = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentsPerAttribute: 1,
values: applyOffset
});
}
return new Geometry_default({
attributes,
indices: indices2,
primitiveType: PrimitiveType_default.LINES,
boundingSphere: new BoundingSphere_default(Cartesian3_default.ZERO, radius),
offsetAttribute: boxGeometry._offsetAttribute
});
};
var BoxOutlineGeometry_default = BoxOutlineGeometry;
// packages/engine/Source/Core/ColorGeometryInstanceAttribute.js
function ColorGeometryInstanceAttribute(red, green, blue, alpha) {
red = defaultValue_default(red, 1);
green = defaultValue_default(green, 1);
blue = defaultValue_default(blue, 1);
alpha = defaultValue_default(alpha, 1);
this.value = new Uint8Array([
Color_default.floatToByte(red),
Color_default.floatToByte(green),
Color_default.floatToByte(blue),
Color_default.floatToByte(alpha)
]);
}
Object.defineProperties(ColorGeometryInstanceAttribute.prototype, {
/**
* The datatype of each component in the attribute, e.g., individual elements in
* {@link ColorGeometryInstanceAttribute#value}.
*
* @memberof ColorGeometryInstanceAttribute.prototype
*
* @type {ComponentDatatype}
* @readonly
*
* @default {@link ComponentDatatype.UNSIGNED_BYTE}
*/
componentDatatype: {
get: function() {
return ComponentDatatype_default.UNSIGNED_BYTE;
}
},
/**
* The number of components in the attributes, i.e., {@link ColorGeometryInstanceAttribute#value}.
*
* @memberof ColorGeometryInstanceAttribute.prototype
*
* @type {number}
* @readonly
*
* @default 4
*/
componentsPerAttribute: {
get: function() {
return 4;
}
},
/**
* When true
and componentDatatype
is an integer format,
* indicate that the components should be mapped to the range [0, 1] (unsigned)
* or [-1, 1] (signed) when they are accessed as floating-point for rendering.
*
* @memberof ColorGeometryInstanceAttribute.prototype
*
* @type {boolean}
* @readonly
*
* @default true
*/
normalize: {
get: function() {
return true;
}
}
});
ColorGeometryInstanceAttribute.fromColor = function(color) {
if (!defined_default(color)) {
throw new DeveloperError_default("color is required.");
}
return new ColorGeometryInstanceAttribute(
color.red,
color.green,
color.blue,
color.alpha
);
};
ColorGeometryInstanceAttribute.toValue = function(color, result) {
if (!defined_default(color)) {
throw new DeveloperError_default("color is required.");
}
if (!defined_default(result)) {
return new Uint8Array(color.toBytes());
}
return color.toBytes(result);
};
ColorGeometryInstanceAttribute.equals = function(left, right) {
return left === right || defined_default(left) && defined_default(right) && left.value[0] === right.value[0] && left.value[1] === right.value[1] && left.value[2] === right.value[2] && left.value[3] === right.value[3];
};
var ColorGeometryInstanceAttribute_default = ColorGeometryInstanceAttribute;
// packages/engine/Source/Core/DistanceDisplayConditionGeometryInstanceAttribute.js
function DistanceDisplayConditionGeometryInstanceAttribute(near, far) {
near = defaultValue_default(near, 0);
far = defaultValue_default(far, Number.MAX_VALUE);
if (far <= near) {
throw new DeveloperError_default(
"far distance must be greater than near distance."
);
}
this.value = new Float32Array([near, far]);
}
Object.defineProperties(
DistanceDisplayConditionGeometryInstanceAttribute.prototype,
{
/**
* The datatype of each component in the attribute, e.g., individual elements in
* {@link DistanceDisplayConditionGeometryInstanceAttribute#value}.
*
* @memberof DistanceDisplayConditionGeometryInstanceAttribute.prototype
*
* @type {ComponentDatatype}
* @readonly
*
* @default {@link ComponentDatatype.FLOAT}
*/
componentDatatype: {
get: function() {
return ComponentDatatype_default.FLOAT;
}
},
/**
* The number of components in the attributes, i.e., {@link DistanceDisplayConditionGeometryInstanceAttribute#value}.
*
* @memberof DistanceDisplayConditionGeometryInstanceAttribute.prototype
*
* @type {number}
* @readonly
*
* @default 3
*/
componentsPerAttribute: {
get: function() {
return 2;
}
},
/**
* When true
and componentDatatype
is an integer format,
* indicate that the components should be mapped to the range [0, 1] (unsigned)
* or [-1, 1] (signed) when they are accessed as floating-point for rendering.
*
* @memberof DistanceDisplayConditionGeometryInstanceAttribute.prototype
*
* @type {boolean}
* @readonly
*
* @default false
*/
normalize: {
get: function() {
return false;
}
}
}
);
DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition = function(distanceDisplayCondition) {
if (!defined_default(distanceDisplayCondition)) {
throw new DeveloperError_default("distanceDisplayCondition is required.");
}
if (distanceDisplayCondition.far <= distanceDisplayCondition.near) {
throw new DeveloperError_default(
"distanceDisplayCondition.far distance must be greater than distanceDisplayCondition.near distance."
);
}
return new DistanceDisplayConditionGeometryInstanceAttribute(
distanceDisplayCondition.near,
distanceDisplayCondition.far
);
};
DistanceDisplayConditionGeometryInstanceAttribute.toValue = function(distanceDisplayCondition, result) {
if (!defined_default(distanceDisplayCondition)) {
throw new DeveloperError_default("distanceDisplayCondition is required.");
}
if (!defined_default(result)) {
return new Float32Array([
distanceDisplayCondition.near,
distanceDisplayCondition.far
]);
}
result[0] = distanceDisplayCondition.near;
result[1] = distanceDisplayCondition.far;
return result;
};
var DistanceDisplayConditionGeometryInstanceAttribute_default = DistanceDisplayConditionGeometryInstanceAttribute;
// packages/engine/Source/Core/GeometryInstance.js
function GeometryInstance(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
if (!defined_default(options.geometry)) {
throw new DeveloperError_default("options.geometry is required.");
}
this.geometry = options.geometry;
this.modelMatrix = Matrix4_default.clone(
defaultValue_default(options.modelMatrix, Matrix4_default.IDENTITY)
);
this.id = options.id;
this.pickPrimitive = options.pickPrimitive;
this.attributes = defaultValue_default(options.attributes, {});
this.westHemisphereGeometry = void 0;
this.eastHemisphereGeometry = void 0;
}
var GeometryInstance_default = GeometryInstance;
// packages/engine/Source/Core/TimeInterval.js
function TimeInterval(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this.start = defined_default(options.start) ? JulianDate_default.clone(options.start) : new JulianDate_default();
this.stop = defined_default(options.stop) ? JulianDate_default.clone(options.stop) : new JulianDate_default();
this.data = options.data;
this.isStartIncluded = defaultValue_default(options.isStartIncluded, true);
this.isStopIncluded = defaultValue_default(options.isStopIncluded, true);
}
Object.defineProperties(TimeInterval.prototype, {
/**
* Gets whether or not this interval is empty.
* @memberof TimeInterval.prototype
* @type {boolean}
* @readonly
*/
isEmpty: {
get: function() {
const stopComparedToStart = JulianDate_default.compare(this.stop, this.start);
return stopComparedToStart < 0 || stopComparedToStart === 0 && (!this.isStartIncluded || !this.isStopIncluded);
}
}
});
var scratchInterval = {
start: void 0,
stop: void 0,
isStartIncluded: void 0,
isStopIncluded: void 0,
data: void 0
};
TimeInterval.fromIso8601 = function(options, result) {
Check_default.typeOf.object("options", options);
Check_default.typeOf.string("options.iso8601", options.iso8601);
const dates = options.iso8601.split("/");
if (dates.length !== 2) {
throw new DeveloperError_default(
"options.iso8601 is an invalid ISO 8601 interval."
);
}
const start = JulianDate_default.fromIso8601(dates[0]);
const stop2 = JulianDate_default.fromIso8601(dates[1]);
const isStartIncluded = defaultValue_default(options.isStartIncluded, true);
const isStopIncluded = defaultValue_default(options.isStopIncluded, true);
const data = options.data;
if (!defined_default(result)) {
scratchInterval.start = start;
scratchInterval.stop = stop2;
scratchInterval.isStartIncluded = isStartIncluded;
scratchInterval.isStopIncluded = isStopIncluded;
scratchInterval.data = data;
return new TimeInterval(scratchInterval);
}
result.start = start;
result.stop = stop2;
result.isStartIncluded = isStartIncluded;
result.isStopIncluded = isStopIncluded;
result.data = data;
return result;
};
TimeInterval.toIso8601 = function(timeInterval, precision) {
Check_default.typeOf.object("timeInterval", timeInterval);
return `${JulianDate_default.toIso8601(
timeInterval.start,
precision
)}/${JulianDate_default.toIso8601(timeInterval.stop, precision)}`;
};
TimeInterval.clone = function(timeInterval, result) {
if (!defined_default(timeInterval)) {
return void 0;
}
if (!defined_default(result)) {
return new TimeInterval(timeInterval);
}
result.start = timeInterval.start;
result.stop = timeInterval.stop;
result.isStartIncluded = timeInterval.isStartIncluded;
result.isStopIncluded = timeInterval.isStopIncluded;
result.data = timeInterval.data;
return result;
};
TimeInterval.equals = function(left, right, dataComparer) {
return left === right || defined_default(left) && defined_default(right) && (left.isEmpty && right.isEmpty || left.isStartIncluded === right.isStartIncluded && left.isStopIncluded === right.isStopIncluded && JulianDate_default.equals(left.start, right.start) && JulianDate_default.equals(left.stop, right.stop) && (left.data === right.data || defined_default(dataComparer) && dataComparer(left.data, right.data)));
};
TimeInterval.equalsEpsilon = function(left, right, epsilon, dataComparer) {
epsilon = defaultValue_default(epsilon, 0);
return left === right || defined_default(left) && defined_default(right) && (left.isEmpty && right.isEmpty || left.isStartIncluded === right.isStartIncluded && left.isStopIncluded === right.isStopIncluded && JulianDate_default.equalsEpsilon(left.start, right.start, epsilon) && JulianDate_default.equalsEpsilon(left.stop, right.stop, epsilon) && (left.data === right.data || defined_default(dataComparer) && dataComparer(left.data, right.data)));
};
TimeInterval.intersect = function(left, right, result, mergeCallback) {
Check_default.typeOf.object("left", left);
if (!defined_default(right)) {
return TimeInterval.clone(TimeInterval.EMPTY, result);
}
const leftStart = left.start;
const leftStop = left.stop;
const rightStart = right.start;
const rightStop = right.stop;
const intersectsStartRight = JulianDate_default.greaterThanOrEquals(rightStart, leftStart) && JulianDate_default.greaterThanOrEquals(leftStop, rightStart);
const intersectsStartLeft = !intersectsStartRight && JulianDate_default.lessThanOrEquals(rightStart, leftStart) && JulianDate_default.lessThanOrEquals(leftStart, rightStop);
if (!intersectsStartRight && !intersectsStartLeft) {
return TimeInterval.clone(TimeInterval.EMPTY, result);
}
const leftIsStartIncluded = left.isStartIncluded;
const leftIsStopIncluded = left.isStopIncluded;
const rightIsStartIncluded = right.isStartIncluded;
const rightIsStopIncluded = right.isStopIncluded;
const leftLessThanRight = JulianDate_default.lessThan(leftStop, rightStop);
if (!defined_default(result)) {
result = new TimeInterval();
}
result.start = intersectsStartRight ? rightStart : leftStart;
result.isStartIncluded = leftIsStartIncluded && rightIsStartIncluded || !JulianDate_default.equals(rightStart, leftStart) && (intersectsStartRight && rightIsStartIncluded || intersectsStartLeft && leftIsStartIncluded);
result.stop = leftLessThanRight ? leftStop : rightStop;
result.isStopIncluded = leftLessThanRight ? leftIsStopIncluded : leftIsStopIncluded && rightIsStopIncluded || !JulianDate_default.equals(rightStop, leftStop) && rightIsStopIncluded;
result.data = defined_default(mergeCallback) ? mergeCallback(left.data, right.data) : left.data;
return result;
};
TimeInterval.contains = function(timeInterval, julianDate) {
Check_default.typeOf.object("timeInterval", timeInterval);
Check_default.typeOf.object("julianDate", julianDate);
if (timeInterval.isEmpty) {
return false;
}
const startComparedToDate = JulianDate_default.compare(
timeInterval.start,
julianDate
);
if (startComparedToDate === 0) {
return timeInterval.isStartIncluded;
}
const dateComparedToStop = JulianDate_default.compare(julianDate, timeInterval.stop);
if (dateComparedToStop === 0) {
return timeInterval.isStopIncluded;
}
return startComparedToDate < 0 && dateComparedToStop < 0;
};
TimeInterval.prototype.clone = function(result) {
return TimeInterval.clone(this, result);
};
TimeInterval.prototype.equals = function(right, dataComparer) {
return TimeInterval.equals(this, right, dataComparer);
};
TimeInterval.prototype.equalsEpsilon = function(right, epsilon, dataComparer) {
return TimeInterval.equalsEpsilon(this, right, epsilon, dataComparer);
};
TimeInterval.prototype.toString = function() {
return TimeInterval.toIso8601(this);
};
TimeInterval.EMPTY = Object.freeze(
new TimeInterval({
start: new JulianDate_default(),
stop: new JulianDate_default(),
isStartIncluded: false,
isStopIncluded: false
})
);
var TimeInterval_default = TimeInterval;
// packages/engine/Source/Core/Iso8601.js
var MINIMUM_VALUE = Object.freeze(
JulianDate_default.fromIso8601("0000-01-01T00:00:00Z")
);
var MAXIMUM_VALUE = Object.freeze(
JulianDate_default.fromIso8601("9999-12-31T24:00:00Z")
);
var MAXIMUM_INTERVAL = Object.freeze(
new TimeInterval_default({
start: MINIMUM_VALUE,
stop: MAXIMUM_VALUE
})
);
var Iso8601 = {
/**
* A {@link JulianDate} representing the earliest time representable by an ISO8601 date.
* This is equivalent to the date string '0000-01-01T00:00:00Z'
*
* @type {JulianDate}
* @constant
*/
MINIMUM_VALUE,
/**
* A {@link JulianDate} representing the latest time representable by an ISO8601 date.
* This is equivalent to the date string '9999-12-31T24:00:00Z'
*
* @type {JulianDate}
* @constant
*/
MAXIMUM_VALUE,
/**
* A {@link TimeInterval} representing the largest interval representable by an ISO8601 interval.
* This is equivalent to the interval string '0000-01-01T00:00:00Z/9999-12-31T24:00:00Z'
*
* @type {TimeInterval}
* @constant
*/
MAXIMUM_INTERVAL
};
var Iso8601_default = Iso8601;
// packages/engine/Source/Core/OffsetGeometryInstanceAttribute.js
function OffsetGeometryInstanceAttribute(x, y, z) {
x = defaultValue_default(x, 0);
y = defaultValue_default(y, 0);
z = defaultValue_default(z, 0);
this.value = new Float32Array([x, y, z]);
}
Object.defineProperties(OffsetGeometryInstanceAttribute.prototype, {
/**
* The datatype of each component in the attribute, e.g., individual elements in
* {@link OffsetGeometryInstanceAttribute#value}.
*
* @memberof OffsetGeometryInstanceAttribute.prototype
*
* @type {ComponentDatatype}
* @readonly
*
* @default {@link ComponentDatatype.FLOAT}
*/
componentDatatype: {
get: function() {
return ComponentDatatype_default.FLOAT;
}
},
/**
* The number of components in the attributes, i.e., {@link OffsetGeometryInstanceAttribute#value}.
*
* @memberof OffsetGeometryInstanceAttribute.prototype
*
* @type {number}
* @readonly
*
* @default 3
*/
componentsPerAttribute: {
get: function() {
return 3;
}
},
/**
* When true
and componentDatatype
is an integer format,
* indicate that the components should be mapped to the range [0, 1] (unsigned)
* or [-1, 1] (signed) when they are accessed as floating-point for rendering.
*
* @memberof OffsetGeometryInstanceAttribute.prototype
*
* @type {boolean}
* @readonly
*
* @default false
*/
normalize: {
get: function() {
return false;
}
}
});
OffsetGeometryInstanceAttribute.fromCartesian3 = function(offset2) {
Check_default.defined("offset", offset2);
return new OffsetGeometryInstanceAttribute(offset2.x, offset2.y, offset2.z);
};
OffsetGeometryInstanceAttribute.toValue = function(offset2, result) {
Check_default.defined("offset", offset2);
if (!defined_default(result)) {
result = new Float32Array([offset2.x, offset2.y, offset2.z]);
}
result[0] = offset2.x;
result[1] = offset2.y;
result[2] = offset2.z;
return result;
};
var OffsetGeometryInstanceAttribute_default = OffsetGeometryInstanceAttribute;
// packages/engine/Source/Core/ShowGeometryInstanceAttribute.js
function ShowGeometryInstanceAttribute(show) {
show = defaultValue_default(show, true);
this.value = ShowGeometryInstanceAttribute.toValue(show);
}
Object.defineProperties(ShowGeometryInstanceAttribute.prototype, {
/**
* The datatype of each component in the attribute, e.g., individual elements in
* {@link ColorGeometryInstanceAttribute#value}.
*
* @memberof ShowGeometryInstanceAttribute.prototype
*
* @type {ComponentDatatype}
* @readonly
*
* @default {@link ComponentDatatype.UNSIGNED_BYTE}
*/
componentDatatype: {
get: function() {
return ComponentDatatype_default.UNSIGNED_BYTE;
}
},
/**
* The number of components in the attributes, i.e., {@link ColorGeometryInstanceAttribute#value}.
*
* @memberof ShowGeometryInstanceAttribute.prototype
*
* @type {number}
* @readonly
*
* @default 1
*/
componentsPerAttribute: {
get: function() {
return 1;
}
},
/**
* When true
and componentDatatype
is an integer format,
* indicate that the components should be mapped to the range [0, 1] (unsigned)
* or [-1, 1] (signed) when they are accessed as floating-point for rendering.
*
* @memberof ShowGeometryInstanceAttribute.prototype
*
* @type {boolean}
* @readonly
*
* @default true
*/
normalize: {
get: function() {
return false;
}
}
});
ShowGeometryInstanceAttribute.toValue = function(show, result) {
if (!defined_default(show)) {
throw new DeveloperError_default("show is required.");
}
if (!defined_default(result)) {
return new Uint8Array([show]);
}
result[0] = show;
return result;
};
var ShowGeometryInstanceAttribute_default = ShowGeometryInstanceAttribute;
// packages/engine/Source/Shaders/Appearances/AllMaterialAppearanceFS.js
var AllMaterialAppearanceFS_default = "in vec3 v_positionEC;\nin vec3 v_normalEC;\nin vec3 v_tangentEC;\nin vec3 v_bitangentEC;\nin vec2 v_st;\n\nvoid main()\n{\n vec3 positionToEyeEC = -v_positionEC;\n mat3 tangentToEyeMatrix = czm_tangentToEyeSpaceMatrix(v_normalEC, v_tangentEC, v_bitangentEC);\n\n vec3 normalEC = normalize(v_normalEC);\n#ifdef FACE_FORWARD\n normalEC = faceforward(normalEC, vec3(0.0, 0.0, 1.0), -normalEC);\n#endif\n\n czm_materialInput materialInput;\n materialInput.normalEC = normalEC;\n materialInput.tangentToEyeMatrix = tangentToEyeMatrix;\n materialInput.positionToEyeEC = positionToEyeEC;\n materialInput.st = v_st;\n czm_material material = czm_getMaterial(materialInput);\n\n#ifdef FLAT\n out_FragColor = vec4(material.diffuse + material.emission, material.alpha);\n#else\n out_FragColor = czm_phong(normalize(positionToEyeEC), material, czm_lightDirectionEC);\n#endif\n}\n";
// packages/engine/Source/Shaders/Appearances/AllMaterialAppearanceVS.js
var AllMaterialAppearanceVS_default = "in vec3 position3DHigh;\nin vec3 position3DLow;\nin vec3 normal;\nin vec3 tangent;\nin vec3 bitangent;\nin vec2 st;\nin float batchId;\n\nout vec3 v_positionEC;\nout vec3 v_normalEC;\nout vec3 v_tangentEC;\nout vec3 v_bitangentEC;\nout vec2 v_st;\n\nvoid main()\n{\n vec4 p = czm_computePosition();\n\n v_positionEC = (czm_modelViewRelativeToEye * p).xyz; // position in eye coordinates\n v_normalEC = czm_normal * normal; // normal in eye coordinates\n v_tangentEC = czm_normal * tangent; // tangent in eye coordinates\n v_bitangentEC = czm_normal * bitangent; // bitangent in eye coordinates\n v_st = st;\n\n gl_Position = czm_modelViewProjectionRelativeToEye * p;\n}\n";
// packages/engine/Source/Shaders/Appearances/BasicMaterialAppearanceFS.js
var BasicMaterialAppearanceFS_default = "in vec3 v_positionEC;\nin vec3 v_normalEC;\n\nvoid main()\n{\n vec3 positionToEyeEC = -v_positionEC;\n\n vec3 normalEC = normalize(v_normalEC);\n#ifdef FACE_FORWARD\n normalEC = faceforward(normalEC, vec3(0.0, 0.0, 1.0), -normalEC);\n#endif\n\n czm_materialInput materialInput;\n materialInput.normalEC = normalEC;\n materialInput.positionToEyeEC = positionToEyeEC;\n czm_material material = czm_getMaterial(materialInput);\n\n#ifdef FLAT\n out_FragColor = vec4(material.diffuse + material.emission, material.alpha);\n#else\n out_FragColor = czm_phong(normalize(positionToEyeEC), material, czm_lightDirectionEC);\n#endif\n}\n";
// packages/engine/Source/Shaders/Appearances/BasicMaterialAppearanceVS.js
var BasicMaterialAppearanceVS_default = "in vec3 position3DHigh;\nin vec3 position3DLow;\nin vec3 normal;\nin float batchId;\n\nout vec3 v_positionEC;\nout vec3 v_normalEC;\n\nvoid main()\n{\n vec4 p = czm_computePosition();\n\n v_positionEC = (czm_modelViewRelativeToEye * p).xyz; // position in eye coordinates\n v_normalEC = czm_normal * normal; // normal in eye coordinates\n\n gl_Position = czm_modelViewProjectionRelativeToEye * p;\n}\n";
// packages/engine/Source/Shaders/Appearances/TexturedMaterialAppearanceFS.js
var TexturedMaterialAppearanceFS_default = "in vec3 v_positionEC;\nin vec3 v_normalEC;\nin vec2 v_st;\n\nvoid main()\n{\n vec3 positionToEyeEC = -v_positionEC;\n\n vec3 normalEC = normalize(v_normalEC);\n#ifdef FACE_FORWARD\n normalEC = faceforward(normalEC, vec3(0.0, 0.0, 1.0), -normalEC);\n#endif\n\n czm_materialInput materialInput;\n materialInput.normalEC = normalEC;\n materialInput.positionToEyeEC = positionToEyeEC;\n materialInput.st = v_st;\n czm_material material = czm_getMaterial(materialInput);\n\n#ifdef FLAT\n out_FragColor = vec4(material.diffuse + material.emission, material.alpha);\n#else\n out_FragColor = czm_phong(normalize(positionToEyeEC), material, czm_lightDirectionEC);\n#endif\n}\n";
// packages/engine/Source/Shaders/Appearances/TexturedMaterialAppearanceVS.js
var TexturedMaterialAppearanceVS_default = "in vec3 position3DHigh;\nin vec3 position3DLow;\nin vec3 normal;\nin vec2 st;\nin float batchId;\n\nout vec3 v_positionEC;\nout vec3 v_normalEC;\nout vec2 v_st;\n\nvoid main()\n{\n vec4 p = czm_computePosition();\n\n v_positionEC = (czm_modelViewRelativeToEye * p).xyz; // position in eye coordinates\n v_normalEC = czm_normal * normal; // normal in eye coordinates\n v_st = st;\n\n gl_Position = czm_modelViewProjectionRelativeToEye * p;\n}\n";
// packages/engine/Source/Scene/BlendEquation.js
var BlendEquation = {
/**
* Pixel values are added componentwise. This is used in additive blending for translucency.
*
* @type {number}
* @constant
*/
ADD: WebGLConstants_default.FUNC_ADD,
/**
* Pixel values are subtracted componentwise (source - destination). This is used in alpha blending for translucency.
*
* @type {number}
* @constant
*/
SUBTRACT: WebGLConstants_default.FUNC_SUBTRACT,
/**
* Pixel values are subtracted componentwise (destination - source).
*
* @type {number}
* @constant
*/
REVERSE_SUBTRACT: WebGLConstants_default.FUNC_REVERSE_SUBTRACT,
/**
* Pixel values are given to the minimum function (min(source, destination)).
*
* This equation operates on each pixel color component.
*
* @type {number}
* @constant
*/
MIN: WebGLConstants_default.MIN,
/**
* Pixel values are given to the maximum function (max(source, destination)).
*
* This equation operates on each pixel color component.
*
* @type {number}
* @constant
*/
MAX: WebGLConstants_default.MAX
};
var BlendEquation_default = Object.freeze(BlendEquation);
// packages/engine/Source/Scene/BlendFunction.js
var BlendFunction = {
/**
* The blend factor is zero.
*
* @type {number}
* @constant
*/
ZERO: WebGLConstants_default.ZERO,
/**
* The blend factor is one.
*
* @type {number}
* @constant
*/
ONE: WebGLConstants_default.ONE,
/**
* The blend factor is the source color.
*
* @type {number}
* @constant
*/
SOURCE_COLOR: WebGLConstants_default.SRC_COLOR,
/**
* The blend factor is one minus the source color.
*
* @type {number}
* @constant
*/
ONE_MINUS_SOURCE_COLOR: WebGLConstants_default.ONE_MINUS_SRC_COLOR,
/**
* The blend factor is the destination color.
*
* @type {number}
* @constant
*/
DESTINATION_COLOR: WebGLConstants_default.DST_COLOR,
/**
* The blend factor is one minus the destination color.
*
* @type {number}
* @constant
*/
ONE_MINUS_DESTINATION_COLOR: WebGLConstants_default.ONE_MINUS_DST_COLOR,
/**
* The blend factor is the source alpha.
*
* @type {number}
* @constant
*/
SOURCE_ALPHA: WebGLConstants_default.SRC_ALPHA,
/**
* The blend factor is one minus the source alpha.
*
* @type {number}
* @constant
*/
ONE_MINUS_SOURCE_ALPHA: WebGLConstants_default.ONE_MINUS_SRC_ALPHA,
/**
* The blend factor is the destination alpha.
*
* @type {number}
* @constant
*/
DESTINATION_ALPHA: WebGLConstants_default.DST_ALPHA,
/**
* The blend factor is one minus the destination alpha.
*
* @type {number}
* @constant
*/
ONE_MINUS_DESTINATION_ALPHA: WebGLConstants_default.ONE_MINUS_DST_ALPHA,
/**
* The blend factor is the constant color.
*
* @type {number}
* @constant
*/
CONSTANT_COLOR: WebGLConstants_default.CONSTANT_COLOR,
/**
* The blend factor is one minus the constant color.
*
* @type {number}
* @constant
*/
ONE_MINUS_CONSTANT_COLOR: WebGLConstants_default.ONE_MINUS_CONSTANT_COLOR,
/**
* The blend factor is the constant alpha.
*
* @type {number}
* @constant
*/
CONSTANT_ALPHA: WebGLConstants_default.CONSTANT_ALPHA,
/**
* The blend factor is one minus the constant alpha.
*
* @type {number}
* @constant
*/
ONE_MINUS_CONSTANT_ALPHA: WebGLConstants_default.ONE_MINUS_CONSTANT_ALPHA,
/**
* The blend factor is the saturated source alpha.
*
* @type {number}
* @constant
*/
SOURCE_ALPHA_SATURATE: WebGLConstants_default.SRC_ALPHA_SATURATE
};
var BlendFunction_default = Object.freeze(BlendFunction);
// packages/engine/Source/Scene/BlendingState.js
var BlendingState = {
/**
* Blending is disabled.
*
* @type {object}
* @constant
*/
DISABLED: Object.freeze({
enabled: false
}),
/**
* Blending is enabled using alpha blending, source(source.alpha) + destination(1 - source.alpha)
.
*
* @type {object}
* @constant
*/
ALPHA_BLEND: Object.freeze({
enabled: true,
equationRgb: BlendEquation_default.ADD,
equationAlpha: BlendEquation_default.ADD,
functionSourceRgb: BlendFunction_default.SOURCE_ALPHA,
functionSourceAlpha: BlendFunction_default.ONE,
functionDestinationRgb: BlendFunction_default.ONE_MINUS_SOURCE_ALPHA,
functionDestinationAlpha: BlendFunction_default.ONE_MINUS_SOURCE_ALPHA
}),
/**
* Blending is enabled using alpha blending with premultiplied alpha, source + destination(1 - source.alpha)
.
*
* @type {object}
* @constant
*/
PRE_MULTIPLIED_ALPHA_BLEND: Object.freeze({
enabled: true,
equationRgb: BlendEquation_default.ADD,
equationAlpha: BlendEquation_default.ADD,
functionSourceRgb: BlendFunction_default.ONE,
functionSourceAlpha: BlendFunction_default.ONE,
functionDestinationRgb: BlendFunction_default.ONE_MINUS_SOURCE_ALPHA,
functionDestinationAlpha: BlendFunction_default.ONE_MINUS_SOURCE_ALPHA
}),
/**
* Blending is enabled using additive blending, source(source.alpha) + destination
.
*
* @type {object}
* @constant
*/
ADDITIVE_BLEND: Object.freeze({
enabled: true,
equationRgb: BlendEquation_default.ADD,
equationAlpha: BlendEquation_default.ADD,
functionSourceRgb: BlendFunction_default.SOURCE_ALPHA,
functionSourceAlpha: BlendFunction_default.ONE,
functionDestinationRgb: BlendFunction_default.ONE,
functionDestinationAlpha: BlendFunction_default.ONE
})
};
var BlendingState_default = Object.freeze(BlendingState);
// packages/engine/Source/Scene/CullFace.js
var CullFace = {
/**
* Front-facing triangles are culled.
*
* @type {number}
* @constant
*/
FRONT: WebGLConstants_default.FRONT,
/**
* Back-facing triangles are culled.
*
* @type {number}
* @constant
*/
BACK: WebGLConstants_default.BACK,
/**
* Both front-facing and back-facing triangles are culled.
*
* @type {number}
* @constant
*/
FRONT_AND_BACK: WebGLConstants_default.FRONT_AND_BACK
};
var CullFace_default = Object.freeze(CullFace);
// packages/engine/Source/Scene/Appearance.js
function Appearance(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this.material = options.material;
this.translucent = defaultValue_default(options.translucent, true);
this._vertexShaderSource = options.vertexShaderSource;
this._fragmentShaderSource = options.fragmentShaderSource;
this._renderState = options.renderState;
this._closed = defaultValue_default(options.closed, false);
}
Object.defineProperties(Appearance.prototype, {
/**
* The GLSL source code for the vertex shader.
*
* @memberof Appearance.prototype
*
* @type {string}
* @readonly
*/
vertexShaderSource: {
get: function() {
return this._vertexShaderSource;
}
},
/**
* The GLSL source code for the fragment shader. The full fragment shader
* source is built procedurally taking into account the {@link Appearance#material}.
* Use {@link Appearance#getFragmentShaderSource} to get the full source.
*
* @memberof Appearance.prototype
*
* @type {string}
* @readonly
*/
fragmentShaderSource: {
get: function() {
return this._fragmentShaderSource;
}
},
/**
* The WebGL fixed-function state to use when rendering the geometry.
*
* @memberof Appearance.prototype
*
* @type {object}
* @readonly
*/
renderState: {
get: function() {
return this._renderState;
}
},
/**
* When true
, the geometry is expected to be closed.
*
* @memberof Appearance.prototype
*
* @type {boolean}
* @readonly
*
* @default false
*/
closed: {
get: function() {
return this._closed;
}
}
});
Appearance.prototype.getFragmentShaderSource = function() {
const parts = [];
if (this.flat) {
parts.push("#define FLAT");
}
if (this.faceForward) {
parts.push("#define FACE_FORWARD");
}
if (defined_default(this.material)) {
parts.push(this.material.shaderSource);
}
parts.push(this.fragmentShaderSource);
return parts.join("\n");
};
Appearance.prototype.isTranslucent = function() {
return defined_default(this.material) && this.material.isTranslucent() || !defined_default(this.material) && this.translucent;
};
Appearance.prototype.getRenderState = function() {
const translucent = this.isTranslucent();
const rs = clone_default(this.renderState, false);
if (translucent) {
rs.depthMask = false;
rs.blending = BlendingState_default.ALPHA_BLEND;
} else {
rs.depthMask = true;
}
return rs;
};
Appearance.getDefaultRenderState = function(translucent, closed, existing) {
let rs = {
depthTest: {
enabled: true
}
};
if (translucent) {
rs.depthMask = false;
rs.blending = BlendingState_default.ALPHA_BLEND;
}
if (closed) {
rs.cull = {
enabled: true,
face: CullFace_default.BACK
};
}
if (defined_default(existing)) {
rs = combine_default(existing, rs, true);
}
return rs;
};
var Appearance_default = Appearance;
// packages/engine/Source/Shaders/Materials/AspectRampMaterial.js
var AspectRampMaterial_default = "uniform sampler2D image;\n\nczm_material czm_getMaterial(czm_materialInput materialInput)\n{\n czm_material material = czm_getDefaultMaterial(materialInput);\n vec4 rampColor = texture(image, vec2(materialInput.aspect / (2.0 * czm_pi), 0.5));\n rampColor = czm_gammaCorrect(rampColor);\n material.diffuse = rampColor.rgb;\n material.alpha = rampColor.a;\n return material;\n}\n";
// packages/engine/Source/Shaders/Materials/BumpMapMaterial.js
var BumpMapMaterial_default = "uniform sampler2D image;\nuniform float strength;\nuniform vec2 repeat;\n\nczm_material czm_getMaterial(czm_materialInput materialInput)\n{\n czm_material material = czm_getDefaultMaterial(materialInput);\n\n vec2 st = materialInput.st;\n\n vec2 centerPixel = fract(repeat * st);\n float centerBump = texture(image, centerPixel).channel;\n\n float imageWidth = float(imageDimensions.x);\n vec2 rightPixel = fract(repeat * (st + vec2(1.0 / imageWidth, 0.0)));\n float rightBump = texture(image, rightPixel).channel;\n\n float imageHeight = float(imageDimensions.y);\n vec2 leftPixel = fract(repeat * (st + vec2(0.0, 1.0 / imageHeight)));\n float topBump = texture(image, leftPixel).channel;\n\n vec3 normalTangentSpace = normalize(vec3(centerBump - rightBump, centerBump - topBump, clamp(1.0 - strength, 0.1, 1.0)));\n vec3 normalEC = materialInput.tangentToEyeMatrix * normalTangentSpace;\n\n material.normal = normalEC;\n material.diffuse = vec3(0.01);\n\n return material;\n}\n";
// packages/engine/Source/Shaders/Materials/CheckerboardMaterial.js
var CheckerboardMaterial_default = "uniform vec4 lightColor;\nuniform vec4 darkColor;\nuniform vec2 repeat;\n\nczm_material czm_getMaterial(czm_materialInput materialInput)\n{\n czm_material material = czm_getDefaultMaterial(materialInput);\n\n vec2 st = materialInput.st;\n\n // From Stefan Gustavson's Procedural Textures in GLSL in OpenGL Insights\n float b = mod(floor(repeat.s * st.s) + floor(repeat.t * st.t), 2.0); // 0.0 or 1.0\n\n // Find the distance from the closest separator (region between two colors)\n float scaledWidth = fract(repeat.s * st.s);\n scaledWidth = abs(scaledWidth - floor(scaledWidth + 0.5));\n float scaledHeight = fract(repeat.t * st.t);\n scaledHeight = abs(scaledHeight - floor(scaledHeight + 0.5));\n float value = min(scaledWidth, scaledHeight);\n\n vec4 currentColor = mix(lightColor, darkColor, b);\n vec4 color = czm_antialias(lightColor, darkColor, currentColor, value, 0.03);\n\n color = czm_gammaCorrect(color);\n material.diffuse = color.rgb;\n material.alpha = color.a;\n\n return material;\n}\n";
// packages/engine/Source/Shaders/Materials/DotMaterial.js
var DotMaterial_default = "uniform vec4 lightColor;\nuniform vec4 darkColor;\nuniform vec2 repeat;\n\nczm_material czm_getMaterial(czm_materialInput materialInput)\n{\n czm_material material = czm_getDefaultMaterial(materialInput);\n\n // From Stefan Gustavson's Procedural Textures in GLSL in OpenGL Insights\n float b = smoothstep(0.3, 0.32, length(fract(repeat * materialInput.st) - 0.5)); // 0.0 or 1.0\n\n vec4 color = mix(lightColor, darkColor, b);\n color = czm_gammaCorrect(color);\n material.diffuse = color.rgb;\n material.alpha = color.a;\n\n return material;\n}\n";
// packages/engine/Source/Shaders/Materials/ElevationBandMaterial.js
var ElevationBandMaterial_default = "uniform sampler2D heights;\nuniform sampler2D colors;\n\n// This material expects heights to be sorted from lowest to highest.\n\nfloat getHeight(int idx, float invTexSize)\n{\n vec2 uv = vec2((float(idx) + 0.5) * invTexSize, 0.5);\n#ifdef OES_texture_float\n return texture(heights, uv).x;\n#else\n return czm_unpackFloat(texture(heights, uv));\n#endif\n}\n\nczm_material czm_getMaterial(czm_materialInput materialInput)\n{\n czm_material material = czm_getDefaultMaterial(materialInput);\n\n float height = materialInput.height;\n float invTexSize = 1.0 / float(heightsDimensions.x);\n\n float minHeight = getHeight(0, invTexSize);\n float maxHeight = getHeight(heightsDimensions.x - 1, invTexSize);\n\n // early-out when outside the height range\n if (height < minHeight || height > maxHeight) {\n material.diffuse = vec3(0.0);\n material.alpha = 0.0;\n return material;\n }\n\n // Binary search to find heights above and below.\n int idxBelow = 0;\n int idxAbove = heightsDimensions.x;\n float heightBelow = minHeight;\n float heightAbove = maxHeight;\n\n // while loop not allowed, so use for loop with max iterations.\n // maxIterations of 16 supports a texture size up to 65536 (2^16).\n const int maxIterations = 16;\n for (int i = 0; i < maxIterations; i++) {\n if (idxBelow >= idxAbove - 1) {\n break;\n }\n\n int idxMid = (idxBelow + idxAbove) / 2;\n float heightTex = getHeight(idxMid, invTexSize);\n\n if (height > heightTex) {\n idxBelow = idxMid;\n heightBelow = heightTex;\n } else {\n idxAbove = idxMid;\n heightAbove = heightTex;\n }\n }\n\n float lerper = heightBelow == heightAbove ? 1.0 : (height - heightBelow) / (heightAbove - heightBelow);\n vec2 colorUv = vec2(invTexSize * (float(idxBelow) + 0.5 + lerper), 0.5);\n vec4 color = texture(colors, colorUv);\n\n // undo preumultiplied alpha\n if (color.a > 0.0) \n {\n color.rgb /= color.a;\n }\n \n color.rgb = czm_gammaCorrect(color.rgb);\n\n material.diffuse = color.rgb;\n material.alpha = color.a;\n return material;\n}\n";
// packages/engine/Source/Shaders/Materials/ElevationContourMaterial.js
var ElevationContourMaterial_default = "#ifdef GL_OES_standard_derivatives\n #extension GL_OES_standard_derivatives : enable\n#endif\n\nuniform vec4 color;\nuniform float spacing;\nuniform float width;\n\nczm_material czm_getMaterial(czm_materialInput materialInput)\n{\n czm_material material = czm_getDefaultMaterial(materialInput);\n\n float distanceToContour = mod(materialInput.height, spacing);\n\n#if (__VERSION__ == 300 || defined(GL_OES_standard_derivatives))\n float dxc = abs(dFdx(materialInput.height));\n float dyc = abs(dFdy(materialInput.height));\n float dF = max(dxc, dyc) * czm_pixelRatio * width;\n float alpha = (distanceToContour < dF) ? 1.0 : 0.0;\n#else\n // If no derivatives available (IE 10?), use pixel ratio\n float alpha = (distanceToContour < (czm_pixelRatio * width)) ? 1.0 : 0.0;\n#endif\n\n vec4 outColor = czm_gammaCorrect(vec4(color.rgb, alpha * color.a));\n material.diffuse = outColor.rgb;\n material.alpha = outColor.a;\n\n return material;\n}\n";
// packages/engine/Source/Shaders/Materials/ElevationRampMaterial.js
var ElevationRampMaterial_default = "uniform sampler2D image;\nuniform float minimumHeight;\nuniform float maximumHeight;\n\nczm_material czm_getMaterial(czm_materialInput materialInput)\n{\n czm_material material = czm_getDefaultMaterial(materialInput);\n float scaledHeight = clamp((materialInput.height - minimumHeight) / (maximumHeight - minimumHeight), 0.0, 1.0);\n vec4 rampColor = texture(image, vec2(scaledHeight, 0.5));\n rampColor = czm_gammaCorrect(rampColor);\n material.diffuse = rampColor.rgb;\n material.alpha = rampColor.a;\n return material;\n}\n";
// packages/engine/Source/Shaders/Materials/FadeMaterial.js
var FadeMaterial_default = "uniform vec4 fadeInColor;\nuniform vec4 fadeOutColor;\nuniform float maximumDistance;\nuniform bool repeat;\nuniform vec2 fadeDirection;\nuniform vec2 time;\n\nfloat getTime(float t, float coord)\n{\n float scalar = 1.0 / maximumDistance;\n float q = distance(t, coord) * scalar;\n if (repeat)\n {\n float r = distance(t, coord + 1.0) * scalar;\n float s = distance(t, coord - 1.0) * scalar;\n q = min(min(r, s), q);\n }\n return clamp(q, 0.0, 1.0);\n}\n\nczm_material czm_getMaterial(czm_materialInput materialInput)\n{\n czm_material material = czm_getDefaultMaterial(materialInput);\n\n vec2 st = materialInput.st;\n float s = getTime(time.x, st.s) * fadeDirection.s;\n float t = getTime(time.y, st.t) * fadeDirection.t;\n\n float u = length(vec2(s, t));\n vec4 color = mix(fadeInColor, fadeOutColor, u);\n\n color = czm_gammaCorrect(color);\n material.emission = color.rgb;\n material.alpha = color.a;\n\n return material;\n}\n";
// packages/engine/Source/Shaders/Materials/GridMaterial.js
var GridMaterial_default = '#ifdef GL_OES_standard_derivatives\n #extension GL_OES_standard_derivatives : enable\n#endif\n\nuniform vec4 color;\nuniform float cellAlpha;\nuniform vec2 lineCount;\nuniform vec2 lineThickness;\nuniform vec2 lineOffset;\n\nczm_material czm_getMaterial(czm_materialInput materialInput)\n{\n czm_material material = czm_getDefaultMaterial(materialInput);\n\n vec2 st = materialInput.st;\n\n float scaledWidth = fract(lineCount.s * st.s - lineOffset.s);\n scaledWidth = abs(scaledWidth - floor(scaledWidth + 0.5));\n float scaledHeight = fract(lineCount.t * st.t - lineOffset.t);\n scaledHeight = abs(scaledHeight - floor(scaledHeight + 0.5));\n\n float value;\n\n // Fuzz Factor - Controls blurriness of lines\n#if (__VERSION__ == 300 || defined(GL_OES_standard_derivatives))\n const float fuzz = 1.2;\n vec2 thickness = (lineThickness * czm_pixelRatio) - 1.0;\n\n // From "3D Engine Design for Virtual Globes" by Cozzi and Ring, Listing 4.13.\n vec2 dx = abs(dFdx(st));\n vec2 dy = abs(dFdy(st));\n vec2 dF = vec2(max(dx.s, dy.s), max(dx.t, dy.t)) * lineCount;\n value = min(\n smoothstep(dF.s * thickness.s, dF.s * (fuzz + thickness.s), scaledWidth),\n smoothstep(dF.t * thickness.t, dF.t * (fuzz + thickness.t), scaledHeight));\n#else\n // If no derivatives available (IE 10?), revert to view-dependent fuzz\n const float fuzz = 0.05;\n\n vec2 range = 0.5 - (lineThickness * 0.05);\n value = min(\n 1.0 - smoothstep(range.s, range.s + fuzz, scaledWidth),\n 1.0 - smoothstep(range.t, range.t + fuzz, scaledHeight));\n#endif\n\n // Edges taken from RimLightingMaterial.glsl\n // See http://www.fundza.com/rman_shaders/surface/fake_rim/fake_rim1.html\n float dRim = 1.0 - abs(dot(materialInput.normalEC, normalize(materialInput.positionToEyeEC)));\n float sRim = smoothstep(0.8, 1.0, dRim);\n value *= (1.0 - sRim);\n\n vec4 halfColor;\n halfColor.rgb = color.rgb * 0.5;\n halfColor.a = color.a * (1.0 - ((1.0 - cellAlpha) * value));\n halfColor = czm_gammaCorrect(halfColor);\n material.diffuse = halfColor.rgb;\n material.emission = halfColor.rgb;\n material.alpha = halfColor.a;\n\n return material;\n}\n';
// packages/engine/Source/Shaders/Materials/NormalMapMaterial.js
var NormalMapMaterial_default = "uniform sampler2D image;\nuniform float strength;\nuniform vec2 repeat;\n\nczm_material czm_getMaterial(czm_materialInput materialInput)\n{\n czm_material material = czm_getDefaultMaterial(materialInput);\n \n vec4 textureValue = texture(image, fract(repeat * materialInput.st));\n vec3 normalTangentSpace = textureValue.channels;\n normalTangentSpace.xy = normalTangentSpace.xy * 2.0 - 1.0;\n normalTangentSpace.z = clamp(1.0 - strength, 0.1, 1.0);\n normalTangentSpace = normalize(normalTangentSpace);\n vec3 normalEC = materialInput.tangentToEyeMatrix * normalTangentSpace;\n \n material.normal = normalEC;\n \n return material;\n}\n";
// packages/engine/Source/Shaders/Materials/PolylineArrowMaterial.js
var PolylineArrowMaterial_default = "#ifdef GL_OES_standard_derivatives\n#extension GL_OES_standard_derivatives : enable\n#endif\n\nuniform vec4 color;\n\nfloat getPointOnLine(vec2 p0, vec2 p1, float x)\n{\n float slope = (p0.y - p1.y) / (p0.x - p1.x);\n return slope * (x - p0.x) + p0.y;\n}\n\nczm_material czm_getMaterial(czm_materialInput materialInput)\n{\n czm_material material = czm_getDefaultMaterial(materialInput);\n\n vec2 st = materialInput.st;\n\n#if (__VERSION__ == 300 || defined(GL_OES_standard_derivatives))\n float base = 1.0 - abs(fwidth(st.s)) * 10.0 * czm_pixelRatio;\n#else\n // If no derivatives available (IE 10?), 2.5% of the line will be the arrow head\n float base = 0.975;\n#endif\n\n vec2 center = vec2(1.0, 0.5);\n float ptOnUpperLine = getPointOnLine(vec2(base, 1.0), center, st.s);\n float ptOnLowerLine = getPointOnLine(vec2(base, 0.0), center, st.s);\n\n float halfWidth = 0.15;\n float s = step(0.5 - halfWidth, st.t);\n s *= 1.0 - step(0.5 + halfWidth, st.t);\n s *= 1.0 - step(base, st.s);\n\n float t = step(base, materialInput.st.s);\n t *= 1.0 - step(ptOnUpperLine, st.t);\n t *= step(ptOnLowerLine, st.t);\n\n // Find the distance from the closest separator (region between two colors)\n float dist;\n if (st.s < base)\n {\n float d1 = abs(st.t - (0.5 - halfWidth));\n float d2 = abs(st.t - (0.5 + halfWidth));\n dist = min(d1, d2);\n }\n else\n {\n float d1 = czm_infinity;\n if (st.t < 0.5 - halfWidth && st.t > 0.5 + halfWidth)\n {\n d1 = abs(st.s - base);\n }\n float d2 = abs(st.t - ptOnUpperLine);\n float d3 = abs(st.t - ptOnLowerLine);\n dist = min(min(d1, d2), d3);\n }\n\n vec4 outsideColor = vec4(0.0);\n vec4 currentColor = mix(outsideColor, color, clamp(s + t, 0.0, 1.0));\n vec4 outColor = czm_antialias(outsideColor, color, currentColor, dist);\n\n outColor = czm_gammaCorrect(outColor);\n material.diffuse = outColor.rgb;\n material.alpha = outColor.a;\n return material;\n}\n";
// packages/engine/Source/Shaders/Materials/PolylineDashMaterial.js
var PolylineDashMaterial_default = "uniform vec4 color;\nuniform vec4 gapColor;\nuniform float dashLength;\nuniform float dashPattern;\nin float v_polylineAngle;\n\nconst float maskLength = 16.0;\n\nmat2 rotate(float rad) {\n float c = cos(rad);\n float s = sin(rad);\n return mat2(\n c, s,\n -s, c\n );\n}\n\nczm_material czm_getMaterial(czm_materialInput materialInput)\n{\n czm_material material = czm_getDefaultMaterial(materialInput);\n\n vec2 pos = rotate(v_polylineAngle) * gl_FragCoord.xy;\n\n // Get the relative position within the dash from 0 to 1\n float dashPosition = fract(pos.x / (dashLength * czm_pixelRatio));\n // Figure out the mask index.\n float maskIndex = floor(dashPosition * maskLength);\n // Test the bit mask.\n float maskTest = floor(dashPattern / pow(2.0, maskIndex));\n vec4 fragColor = (mod(maskTest, 2.0) < 1.0) ? gapColor : color;\n if (fragColor.a < 0.005) { // matches 0/255 and 1/255\n discard;\n }\n\n fragColor = czm_gammaCorrect(fragColor);\n material.emission = fragColor.rgb;\n material.alpha = fragColor.a;\n return material;\n}\n";
// packages/engine/Source/Shaders/Materials/PolylineGlowMaterial.js
var PolylineGlowMaterial_default = "uniform vec4 color;\nuniform float glowPower;\nuniform float taperPower;\n\nczm_material czm_getMaterial(czm_materialInput materialInput)\n{\n czm_material material = czm_getDefaultMaterial(materialInput);\n\n vec2 st = materialInput.st;\n float glow = glowPower / abs(st.t - 0.5) - (glowPower / 0.5);\n\n if (taperPower <= 0.99999) {\n glow *= min(1.0, taperPower / (0.5 - st.s * 0.5) - (taperPower / 0.5));\n }\n\n vec4 fragColor;\n fragColor.rgb = max(vec3(glow - 1.0 + color.rgb), color.rgb);\n fragColor.a = clamp(0.0, 1.0, glow) * color.a;\n fragColor = czm_gammaCorrect(fragColor);\n\n material.emission = fragColor.rgb;\n material.alpha = fragColor.a;\n\n return material;\n}\n";
// packages/engine/Source/Shaders/Materials/PolylineOutlineMaterial.js
var PolylineOutlineMaterial_default = "uniform vec4 color;\nuniform vec4 outlineColor;\nuniform float outlineWidth;\n\nin float v_width;\n\nczm_material czm_getMaterial(czm_materialInput materialInput)\n{\n czm_material material = czm_getDefaultMaterial(materialInput);\n\n vec2 st = materialInput.st;\n float halfInteriorWidth = 0.5 * (v_width - outlineWidth) / v_width;\n float b = step(0.5 - halfInteriorWidth, st.t);\n b *= 1.0 - step(0.5 + halfInteriorWidth, st.t);\n\n // Find the distance from the closest separator (region between two colors)\n float d1 = abs(st.t - (0.5 - halfInteriorWidth));\n float d2 = abs(st.t - (0.5 + halfInteriorWidth));\n float dist = min(d1, d2);\n\n vec4 currentColor = mix(outlineColor, color, b);\n vec4 outColor = czm_antialias(outlineColor, color, currentColor, dist);\n outColor = czm_gammaCorrect(outColor);\n\n material.diffuse = outColor.rgb;\n material.alpha = outColor.a;\n\n return material;\n}\n";
// packages/engine/Source/Shaders/Materials/RimLightingMaterial.js
var RimLightingMaterial_default = "uniform vec4 color;\nuniform vec4 rimColor;\nuniform float width;\n\nczm_material czm_getMaterial(czm_materialInput materialInput)\n{\n czm_material material = czm_getDefaultMaterial(materialInput);\n\n // See http://www.fundza.com/rman_shaders/surface/fake_rim/fake_rim1.html\n float d = 1.0 - dot(materialInput.normalEC, normalize(materialInput.positionToEyeEC));\n float s = smoothstep(1.0 - width, 1.0, d);\n\n vec4 outColor = czm_gammaCorrect(color);\n vec4 outRimColor = czm_gammaCorrect(rimColor);\n\n material.diffuse = outColor.rgb;\n material.emission = outRimColor.rgb * s;\n material.alpha = mix(outColor.a, outRimColor.a, s);\n\n return material;\n}\n";
// packages/engine/Source/Shaders/Materials/SlopeRampMaterial.js
var SlopeRampMaterial_default = "uniform sampler2D image;\n\nczm_material czm_getMaterial(czm_materialInput materialInput)\n{\n czm_material material = czm_getDefaultMaterial(materialInput);\n vec4 rampColor = texture(image, vec2(materialInput.slope / (czm_pi / 2.0), 0.5));\n rampColor = czm_gammaCorrect(rampColor);\n material.diffuse = rampColor.rgb;\n material.alpha = rampColor.a;\n return material;\n}\n";
// packages/engine/Source/Shaders/Materials/StripeMaterial.js
var StripeMaterial_default = "uniform vec4 evenColor;\nuniform vec4 oddColor;\nuniform float offset;\nuniform float repeat;\nuniform bool horizontal;\n\nczm_material czm_getMaterial(czm_materialInput materialInput)\n{\n czm_material material = czm_getDefaultMaterial(materialInput);\n\n // Based on the Stripes Fragment Shader in the Orange Book (11.1.2)\n float coord = mix(materialInput.st.s, materialInput.st.t, float(horizontal));\n float value = fract((coord - offset) * (repeat * 0.5));\n float dist = min(value, min(abs(value - 0.5), 1.0 - value));\n\n vec4 currentColor = mix(evenColor, oddColor, step(0.5, value));\n vec4 color = czm_antialias(evenColor, oddColor, currentColor, dist);\n color = czm_gammaCorrect(color);\n\n material.diffuse = color.rgb;\n material.alpha = color.a;\n\n return material;\n}\n";
// packages/engine/Source/Shaders/Materials/Water.js
var Water_default = "// Thanks for the contribution Jonas\n// http://29a.ch/2012/7/19/webgl-terrain-rendering-water-fog\n\nuniform sampler2D specularMap;\nuniform sampler2D normalMap;\nuniform vec4 baseWaterColor;\nuniform vec4 blendColor;\nuniform float frequency;\nuniform float animationSpeed;\nuniform float amplitude;\nuniform float specularIntensity;\nuniform float fadeFactor;\n\nczm_material czm_getMaterial(czm_materialInput materialInput)\n{\n czm_material material = czm_getDefaultMaterial(materialInput);\n\n float time = czm_frameNumber * animationSpeed;\n\n // fade is a function of the distance from the fragment and the frequency of the waves\n float fade = max(1.0, (length(materialInput.positionToEyeEC) / 10000000000.0) * frequency * fadeFactor);\n\n float specularMapValue = texture(specularMap, materialInput.st).r;\n\n // note: not using directional motion at this time, just set the angle to 0.0;\n vec4 noise = czm_getWaterNoise(normalMap, materialInput.st * frequency, time, 0.0);\n vec3 normalTangentSpace = noise.xyz * vec3(1.0, 1.0, (1.0 / amplitude));\n\n // fade out the normal perturbation as we move further from the water surface\n normalTangentSpace.xy /= fade;\n\n // attempt to fade out the normal perturbation as we approach non water areas (low specular map value)\n normalTangentSpace = mix(vec3(0.0, 0.0, 50.0), normalTangentSpace, specularMapValue);\n\n normalTangentSpace = normalize(normalTangentSpace);\n\n // get ratios for alignment of the new normal vector with a vector perpendicular to the tangent plane\n float tsPerturbationRatio = clamp(dot(normalTangentSpace, vec3(0.0, 0.0, 1.0)), 0.0, 1.0);\n\n // fade out water effect as specular map value decreases\n material.alpha = mix(blendColor.a, baseWaterColor.a, specularMapValue) * specularMapValue;\n\n // base color is a blend of the water and non-water color based on the value from the specular map\n // may need a uniform blend factor to better control this\n material.diffuse = mix(blendColor.rgb, baseWaterColor.rgb, specularMapValue);\n\n // diffuse highlights are based on how perturbed the normal is\n material.diffuse += (0.1 * tsPerturbationRatio);\n\n material.diffuse = material.diffuse;\n\n material.normal = normalize(materialInput.tangentToEyeMatrix * normalTangentSpace);\n\n material.specular = specularIntensity;\n material.shininess = 10.0;\n\n return material;\n}\n";
// packages/engine/Source/Scene/Material.js
function Material(options) {
this.type = void 0;
this.shaderSource = void 0;
this.materials = void 0;
this.uniforms = void 0;
this._uniforms = void 0;
this.translucent = void 0;
this._minificationFilter = defaultValue_default(
options.minificationFilter,
TextureMinificationFilter_default.LINEAR
);
this._magnificationFilter = defaultValue_default(
options.magnificationFilter,
TextureMagnificationFilter_default.LINEAR
);
this._strict = void 0;
this._template = void 0;
this._count = void 0;
this._texturePaths = {};
this._loadedImages = [];
this._loadedCubeMaps = [];
this._textures = {};
this._updateFunctions = [];
this._defaultTexture = void 0;
initializeMaterial(options, this);
Object.defineProperties(this, {
type: {
value: this.type,
writable: false
}
});
if (!defined_default(Material._uniformList[this.type])) {
Material._uniformList[this.type] = Object.keys(this._uniforms);
}
}
Material._uniformList = {};
Material.fromType = function(type, uniforms) {
if (!defined_default(Material._materialCache.getMaterial(type))) {
throw new DeveloperError_default(`material with type '${type}' does not exist.`);
}
const material = new Material({
fabric: {
type
}
});
if (defined_default(uniforms)) {
for (const name in uniforms) {
if (uniforms.hasOwnProperty(name)) {
material.uniforms[name] = uniforms[name];
}
}
}
return material;
};
Material.prototype.isTranslucent = function() {
if (defined_default(this.translucent)) {
if (typeof this.translucent === "function") {
return this.translucent();
}
return this.translucent;
}
let translucent = true;
const funcs = this._translucentFunctions;
const length3 = funcs.length;
for (let i = 0; i < length3; ++i) {
const func = funcs[i];
if (typeof func === "function") {
translucent = translucent && func();
} else {
translucent = translucent && func;
}
if (!translucent) {
break;
}
}
return translucent;
};
Material.prototype.update = function(context) {
this._defaultTexture = context.defaultTexture;
let i;
let uniformId;
const loadedImages = this._loadedImages;
let length3 = loadedImages.length;
for (i = 0; i < length3; ++i) {
const loadedImage = loadedImages[i];
uniformId = loadedImage.id;
let image = loadedImage.image;
let mipLevels;
if (Array.isArray(image)) {
mipLevels = image.slice(1, image.length).map(function(mipLevel) {
return mipLevel.bufferView;
});
image = image[0];
}
const sampler = new Sampler_default({
minificationFilter: this._minificationFilter,
magnificationFilter: this._magnificationFilter
});
let texture;
if (defined_default(image.internalFormat)) {
texture = new Texture_default({
context,
pixelFormat: image.internalFormat,
width: image.width,
height: image.height,
source: {
arrayBufferView: image.bufferView,
mipLevels
},
sampler
});
} else {
texture = new Texture_default({
context,
source: image,
sampler
});
}
const oldTexture = this._textures[uniformId];
if (defined_default(oldTexture) && oldTexture !== this._defaultTexture) {
oldTexture.destroy();
}
this._textures[uniformId] = texture;
const uniformDimensionsName = `${uniformId}Dimensions`;
if (this.uniforms.hasOwnProperty(uniformDimensionsName)) {
const uniformDimensions = this.uniforms[uniformDimensionsName];
uniformDimensions.x = texture._width;
uniformDimensions.y = texture._height;
}
}
loadedImages.length = 0;
const loadedCubeMaps = this._loadedCubeMaps;
length3 = loadedCubeMaps.length;
for (i = 0; i < length3; ++i) {
const loadedCubeMap = loadedCubeMaps[i];
uniformId = loadedCubeMap.id;
const images = loadedCubeMap.images;
const cubeMap = new CubeMap_default({
context,
source: {
positiveX: images[0],
negativeX: images[1],
positiveY: images[2],
negativeY: images[3],
positiveZ: images[4],
negativeZ: images[5]
},
sampler: new Sampler_default({
minificationFilter: this._minificationFilter,
magnificationFilter: this._magnificationFilter
})
});
this._textures[uniformId] = cubeMap;
}
loadedCubeMaps.length = 0;
const updateFunctions2 = this._updateFunctions;
length3 = updateFunctions2.length;
for (i = 0; i < length3; ++i) {
updateFunctions2[i](this, context);
}
const subMaterials = this.materials;
for (const name in subMaterials) {
if (subMaterials.hasOwnProperty(name)) {
subMaterials[name].update(context);
}
}
};
Material.prototype.isDestroyed = function() {
return false;
};
Material.prototype.destroy = function() {
const textures = this._textures;
for (const texture in textures) {
if (textures.hasOwnProperty(texture)) {
const instance = textures[texture];
if (instance !== this._defaultTexture) {
instance.destroy();
}
}
}
const materials = this.materials;
for (const material in materials) {
if (materials.hasOwnProperty(material)) {
materials[material].destroy();
}
}
return destroyObject_default(this);
};
function initializeMaterial(options, result) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
result._strict = defaultValue_default(options.strict, false);
result._count = defaultValue_default(options.count, 0);
result._template = clone_default(
defaultValue_default(options.fabric, defaultValue_default.EMPTY_OBJECT)
);
result._template.uniforms = clone_default(
defaultValue_default(result._template.uniforms, defaultValue_default.EMPTY_OBJECT)
);
result._template.materials = clone_default(
defaultValue_default(result._template.materials, defaultValue_default.EMPTY_OBJECT)
);
result.type = defined_default(result._template.type) ? result._template.type : createGuid_default();
result.shaderSource = "";
result.materials = {};
result.uniforms = {};
result._uniforms = {};
result._translucentFunctions = [];
let translucent;
const cachedMaterial = Material._materialCache.getMaterial(result.type);
if (defined_default(cachedMaterial)) {
const template = clone_default(cachedMaterial.fabric, true);
result._template = combine_default(result._template, template, true);
translucent = cachedMaterial.translucent;
}
checkForTemplateErrors(result);
if (!defined_default(cachedMaterial)) {
Material._materialCache.addMaterial(result.type, result);
}
createMethodDefinition(result);
createUniforms(result);
createSubMaterials(result);
const defaultTranslucent = result._translucentFunctions.length === 0 ? true : void 0;
translucent = defaultValue_default(translucent, defaultTranslucent);
translucent = defaultValue_default(options.translucent, translucent);
if (defined_default(translucent)) {
if (typeof translucent === "function") {
const wrappedTranslucent = function() {
return translucent(result);
};
result._translucentFunctions.push(wrappedTranslucent);
} else {
result._translucentFunctions.push(translucent);
}
}
}
function checkForValidProperties(object2, properties, result, throwNotFound) {
if (defined_default(object2)) {
for (const property in object2) {
if (object2.hasOwnProperty(property)) {
const hasProperty = properties.indexOf(property) !== -1;
if (throwNotFound && !hasProperty || !throwNotFound && hasProperty) {
result(property, properties);
}
}
}
}
}
function invalidNameError(property, properties) {
let errorString = `fabric: property name '${property}' is not valid. It should be `;
for (let i = 0; i < properties.length; i++) {
const propertyName = `'${properties[i]}'`;
errorString += i === properties.length - 1 ? `or ${propertyName}.` : `${propertyName}, `;
}
throw new DeveloperError_default(errorString);
}
function duplicateNameError(property, properties) {
const errorString = `fabric: uniforms and materials cannot share the same property '${property}'`;
throw new DeveloperError_default(errorString);
}
var templateProperties = [
"type",
"materials",
"uniforms",
"components",
"source"
];
var componentProperties = [
"diffuse",
"specular",
"shininess",
"normal",
"emission",
"alpha"
];
function checkForTemplateErrors(material) {
const template = material._template;
const uniforms = template.uniforms;
const materials = template.materials;
const components = template.components;
if (defined_default(components) && defined_default(template.source)) {
throw new DeveloperError_default(
"fabric: cannot have source and components in the same template."
);
}
checkForValidProperties(template, templateProperties, invalidNameError, true);
checkForValidProperties(
components,
componentProperties,
invalidNameError,
true
);
const materialNames = [];
for (const property in materials) {
if (materials.hasOwnProperty(property)) {
materialNames.push(property);
}
}
checkForValidProperties(uniforms, materialNames, duplicateNameError, false);
}
function isMaterialFused(shaderComponent, material) {
const materials = material._template.materials;
for (const subMaterialId in materials) {
if (materials.hasOwnProperty(subMaterialId)) {
if (shaderComponent.indexOf(subMaterialId) > -1) {
return true;
}
}
}
return false;
}
function createMethodDefinition(material) {
const components = material._template.components;
const source = material._template.source;
if (defined_default(source)) {
material.shaderSource += `${source}
`;
} else {
material.shaderSource += "czm_material czm_getMaterial(czm_materialInput materialInput)\n{\n";
material.shaderSource += "czm_material material = czm_getDefaultMaterial(materialInput);\n";
if (defined_default(components)) {
const isMultiMaterial = Object.keys(material._template.materials).length > 0;
for (const component in components) {
if (components.hasOwnProperty(component)) {
if (component === "diffuse" || component === "emission") {
const isFusion = isMultiMaterial && isMaterialFused(components[component], material);
const componentSource = isFusion ? components[component] : `czm_gammaCorrect(${components[component]})`;
material.shaderSource += `material.${component} = ${componentSource};
`;
} else if (component === "alpha") {
material.shaderSource += `material.alpha = ${components.alpha};
`;
} else {
material.shaderSource += `material.${component} = ${components[component]};
`;
}
}
}
}
material.shaderSource += "return material;\n}\n";
}
}
var matrixMap = {
mat2: Matrix2_default,
mat3: Matrix3_default,
mat4: Matrix4_default
};
var ktx2Regex = /\.ktx2$/i;
function createTexture2DUpdateFunction(uniformId) {
let oldUniformValue;
return function(material, context) {
const uniforms = material.uniforms;
const uniformValue = uniforms[uniformId];
const uniformChanged = oldUniformValue !== uniformValue;
const uniformValueIsDefaultImage = !defined_default(uniformValue) || uniformValue === Material.DefaultImageId;
oldUniformValue = uniformValue;
let texture = material._textures[uniformId];
let uniformDimensionsName;
let uniformDimensions;
if (uniformValue instanceof HTMLVideoElement) {
if (uniformValue.readyState >= 2) {
if (uniformChanged && defined_default(texture)) {
if (texture !== context.defaultTexture) {
texture.destroy();
}
texture = void 0;
}
if (!defined_default(texture) || texture === context.defaultTexture) {
const sampler = new Sampler_default({
minificationFilter: material._minificationFilter,
magnificationFilter: material._magnificationFilter
});
texture = new Texture_default({
context,
source: uniformValue,
sampler
});
material._textures[uniformId] = texture;
return;
}
texture.copyFrom({
source: uniformValue
});
} else if (!defined_default(texture)) {
material._textures[uniformId] = context.defaultTexture;
}
return;
}
if (uniformValue instanceof Texture_default && uniformValue !== texture) {
material._texturePaths[uniformId] = void 0;
const tmp2 = material._textures[uniformId];
if (defined_default(tmp2) && tmp2 !== material._defaultTexture) {
tmp2.destroy();
}
material._textures[uniformId] = uniformValue;
uniformDimensionsName = `${uniformId}Dimensions`;
if (uniforms.hasOwnProperty(uniformDimensionsName)) {
uniformDimensions = uniforms[uniformDimensionsName];
uniformDimensions.x = uniformValue._width;
uniformDimensions.y = uniformValue._height;
}
return;
}
if (uniformChanged && defined_default(texture) && uniformValueIsDefaultImage) {
if (texture !== material._defaultTexture) {
texture.destroy();
}
texture = void 0;
}
if (!defined_default(texture)) {
material._texturePaths[uniformId] = void 0;
texture = material._textures[uniformId] = material._defaultTexture;
uniformDimensionsName = `${uniformId}Dimensions`;
if (uniforms.hasOwnProperty(uniformDimensionsName)) {
uniformDimensions = uniforms[uniformDimensionsName];
uniformDimensions.x = texture._width;
uniformDimensions.y = texture._height;
}
}
if (uniformValueIsDefaultImage) {
return;
}
const isResource = uniformValue instanceof Resource_default;
if (!defined_default(material._texturePaths[uniformId]) || isResource && uniformValue.url !== material._texturePaths[uniformId].url || !isResource && uniformValue !== material._texturePaths[uniformId]) {
if (typeof uniformValue === "string" || isResource) {
const resource = isResource ? uniformValue : Resource_default.createIfNeeded(uniformValue);
let promise;
if (ktx2Regex.test(resource.url)) {
promise = loadKTX2_default(resource.url);
} else {
promise = resource.fetchImage();
}
Promise.resolve(promise).then(function(image) {
material._loadedImages.push({
id: uniformId,
image
});
}).catch(function() {
if (defined_default(texture) && texture !== material._defaultTexture) {
texture.destroy();
}
material._textures[uniformId] = material._defaultTexture;
});
} else if (uniformValue instanceof HTMLCanvasElement || uniformValue instanceof HTMLImageElement) {
material._loadedImages.push({
id: uniformId,
image: uniformValue
});
}
material._texturePaths[uniformId] = uniformValue;
}
};
}
function createCubeMapUpdateFunction(uniformId) {
return function(material, context) {
const uniformValue = material.uniforms[uniformId];
if (uniformValue instanceof CubeMap_default) {
const tmp2 = material._textures[uniformId];
if (tmp2 !== material._defaultTexture) {
tmp2.destroy();
}
material._texturePaths[uniformId] = void 0;
material._textures[uniformId] = uniformValue;
return;
}
if (!defined_default(material._textures[uniformId])) {
material._texturePaths[uniformId] = void 0;
material._textures[uniformId] = context.defaultCubeMap;
}
if (uniformValue === Material.DefaultCubeMapId) {
return;
}
const path = uniformValue.positiveX + uniformValue.negativeX + uniformValue.positiveY + uniformValue.negativeY + uniformValue.positiveZ + uniformValue.negativeZ;
if (path !== material._texturePaths[uniformId]) {
const promises = [
Resource_default.createIfNeeded(uniformValue.positiveX).fetchImage(),
Resource_default.createIfNeeded(uniformValue.negativeX).fetchImage(),
Resource_default.createIfNeeded(uniformValue.positiveY).fetchImage(),
Resource_default.createIfNeeded(uniformValue.negativeY).fetchImage(),
Resource_default.createIfNeeded(uniformValue.positiveZ).fetchImage(),
Resource_default.createIfNeeded(uniformValue.negativeZ).fetchImage()
];
Promise.all(promises).then(function(images) {
material._loadedCubeMaps.push({
id: uniformId,
images
});
});
material._texturePaths[uniformId] = path;
}
};
}
function createUniforms(material) {
const uniforms = material._template.uniforms;
for (const uniformId in uniforms) {
if (uniforms.hasOwnProperty(uniformId)) {
createUniform2(material, uniformId);
}
}
}
function createUniform2(material, uniformId) {
const strict = material._strict;
const materialUniforms = material._template.uniforms;
const uniformValue = materialUniforms[uniformId];
const uniformType = getUniformType(uniformValue);
if (!defined_default(uniformType)) {
throw new DeveloperError_default(
`fabric: uniform '${uniformId}' has invalid type.`
);
}
let replacedTokenCount;
if (uniformType === "channels") {
replacedTokenCount = replaceToken(material, uniformId, uniformValue, false);
if (replacedTokenCount === 0 && strict) {
throw new DeveloperError_default(
`strict: shader source does not use channels '${uniformId}'.`
);
}
} else {
if (uniformType === "sampler2D") {
const imageDimensionsUniformName = `${uniformId}Dimensions`;
if (getNumberOfTokens(material, imageDimensionsUniformName) > 0) {
materialUniforms[imageDimensionsUniformName] = {
type: "ivec3",
x: 1,
y: 1
};
createUniform2(material, imageDimensionsUniformName);
}
}
const uniformDeclarationRegex = new RegExp(
`uniform\\s+${uniformType}\\s+${uniformId}\\s*;`
);
if (!uniformDeclarationRegex.test(material.shaderSource)) {
const uniformDeclaration = `uniform ${uniformType} ${uniformId};`;
material.shaderSource = uniformDeclaration + material.shaderSource;
}
const newUniformId = `${uniformId}_${material._count++}`;
replacedTokenCount = replaceToken(material, uniformId, newUniformId);
if (replacedTokenCount === 1 && strict) {
throw new DeveloperError_default(
`strict: shader source does not use uniform '${uniformId}'.`
);
}
material.uniforms[uniformId] = uniformValue;
if (uniformType === "sampler2D") {
material._uniforms[newUniformId] = function() {
return material._textures[uniformId];
};
material._updateFunctions.push(createTexture2DUpdateFunction(uniformId));
} else if (uniformType === "samplerCube") {
material._uniforms[newUniformId] = function() {
return material._textures[uniformId];
};
material._updateFunctions.push(createCubeMapUpdateFunction(uniformId));
} else if (uniformType.indexOf("mat") !== -1) {
const scratchMatrix7 = new matrixMap[uniformType]();
material._uniforms[newUniformId] = function() {
return matrixMap[uniformType].fromColumnMajorArray(
material.uniforms[uniformId],
scratchMatrix7
);
};
} else {
material._uniforms[newUniformId] = function() {
return material.uniforms[uniformId];
};
}
}
}
function getUniformType(uniformValue) {
let uniformType = uniformValue.type;
if (!defined_default(uniformType)) {
const type = typeof uniformValue;
if (type === "number") {
uniformType = "float";
} else if (type === "boolean") {
uniformType = "bool";
} else if (type === "string" || uniformValue instanceof Resource_default || uniformValue instanceof HTMLCanvasElement || uniformValue instanceof HTMLImageElement) {
if (/^([rgba]){1,4}$/i.test(uniformValue)) {
uniformType = "channels";
} else if (uniformValue === Material.DefaultCubeMapId) {
uniformType = "samplerCube";
} else {
uniformType = "sampler2D";
}
} else if (type === "object") {
if (Array.isArray(uniformValue)) {
if (uniformValue.length === 4 || uniformValue.length === 9 || uniformValue.length === 16) {
uniformType = `mat${Math.sqrt(uniformValue.length)}`;
}
} else {
let numAttributes = 0;
for (const attribute in uniformValue) {
if (uniformValue.hasOwnProperty(attribute)) {
numAttributes += 1;
}
}
if (numAttributes >= 2 && numAttributes <= 4) {
uniformType = `vec${numAttributes}`;
} else if (numAttributes === 6) {
uniformType = "samplerCube";
}
}
}
}
return uniformType;
}
function createSubMaterials(material) {
const strict = material._strict;
const subMaterialTemplates = material._template.materials;
for (const subMaterialId in subMaterialTemplates) {
if (subMaterialTemplates.hasOwnProperty(subMaterialId)) {
const subMaterial = new Material({
strict,
fabric: subMaterialTemplates[subMaterialId],
count: material._count
});
material._count = subMaterial._count;
material._uniforms = combine_default(
material._uniforms,
subMaterial._uniforms,
true
);
material.materials[subMaterialId] = subMaterial;
material._translucentFunctions = material._translucentFunctions.concat(
subMaterial._translucentFunctions
);
const originalMethodName = "czm_getMaterial";
const newMethodName = `${originalMethodName}_${material._count++}`;
replaceToken(subMaterial, originalMethodName, newMethodName);
material.shaderSource = subMaterial.shaderSource + material.shaderSource;
const materialMethodCall = `${newMethodName}(materialInput)`;
const tokensReplacedCount = replaceToken(
material,
subMaterialId,
materialMethodCall
);
if (tokensReplacedCount === 0 && strict) {
throw new DeveloperError_default(
`strict: shader source does not use material '${subMaterialId}'.`
);
}
}
}
}
function replaceToken(material, token, newToken, excludePeriod) {
excludePeriod = defaultValue_default(excludePeriod, true);
let count = 0;
const suffixChars = "([\\w])?";
const prefixChars = `([\\w${excludePeriod ? "." : ""}])?`;
const regExp = new RegExp(prefixChars + token + suffixChars, "g");
material.shaderSource = material.shaderSource.replace(regExp, function($0, $1, $2) {
if ($1 || $2) {
return $0;
}
count += 1;
return newToken;
});
return count;
}
function getNumberOfTokens(material, token, excludePeriod) {
return replaceToken(material, token, token, excludePeriod);
}
Material._materialCache = {
_materials: {},
addMaterial: function(type, materialTemplate) {
this._materials[type] = materialTemplate;
},
getMaterial: function(type) {
return this._materials[type];
}
};
Material.DefaultImageId = "czm_defaultImage";
Material.DefaultCubeMapId = "czm_defaultCubeMap";
Material.ColorType = "Color";
Material._materialCache.addMaterial(Material.ColorType, {
fabric: {
type: Material.ColorType,
uniforms: {
color: new Color_default(1, 0, 0, 0.5)
},
components: {
diffuse: "color.rgb",
alpha: "color.a"
}
},
translucent: function(material) {
return material.uniforms.color.alpha < 1;
}
});
Material.ImageType = "Image";
Material._materialCache.addMaterial(Material.ImageType, {
fabric: {
type: Material.ImageType,
uniforms: {
image: Material.DefaultImageId,
repeat: new Cartesian2_default(1, 1),
color: new Color_default(1, 1, 1, 1)
},
components: {
diffuse: "texture(image, fract(repeat * materialInput.st)).rgb * color.rgb",
alpha: "texture(image, fract(repeat * materialInput.st)).a * color.a"
}
},
translucent: function(material) {
return material.uniforms.color.alpha < 1;
}
});
Material.DiffuseMapType = "DiffuseMap";
Material._materialCache.addMaterial(Material.DiffuseMapType, {
fabric: {
type: Material.DiffuseMapType,
uniforms: {
image: Material.DefaultImageId,
channels: "rgb",
repeat: new Cartesian2_default(1, 1)
},
components: {
diffuse: "texture(image, fract(repeat * materialInput.st)).channels"
}
},
translucent: false
});
Material.AlphaMapType = "AlphaMap";
Material._materialCache.addMaterial(Material.AlphaMapType, {
fabric: {
type: Material.AlphaMapType,
uniforms: {
image: Material.DefaultImageId,
channel: "a",
repeat: new Cartesian2_default(1, 1)
},
components: {
alpha: "texture(image, fract(repeat * materialInput.st)).channel"
}
},
translucent: true
});
Material.SpecularMapType = "SpecularMap";
Material._materialCache.addMaterial(Material.SpecularMapType, {
fabric: {
type: Material.SpecularMapType,
uniforms: {
image: Material.DefaultImageId,
channel: "r",
repeat: new Cartesian2_default(1, 1)
},
components: {
specular: "texture(image, fract(repeat * materialInput.st)).channel"
}
},
translucent: false
});
Material.EmissionMapType = "EmissionMap";
Material._materialCache.addMaterial(Material.EmissionMapType, {
fabric: {
type: Material.EmissionMapType,
uniforms: {
image: Material.DefaultImageId,
channels: "rgb",
repeat: new Cartesian2_default(1, 1)
},
components: {
emission: "texture(image, fract(repeat * materialInput.st)).channels"
}
},
translucent: false
});
Material.BumpMapType = "BumpMap";
Material._materialCache.addMaterial(Material.BumpMapType, {
fabric: {
type: Material.BumpMapType,
uniforms: {
image: Material.DefaultImageId,
channel: "r",
strength: 0.8,
repeat: new Cartesian2_default(1, 1)
},
source: BumpMapMaterial_default
},
translucent: false
});
Material.NormalMapType = "NormalMap";
Material._materialCache.addMaterial(Material.NormalMapType, {
fabric: {
type: Material.NormalMapType,
uniforms: {
image: Material.DefaultImageId,
channels: "rgb",
strength: 0.8,
repeat: new Cartesian2_default(1, 1)
},
source: NormalMapMaterial_default
},
translucent: false
});
Material.GridType = "Grid";
Material._materialCache.addMaterial(Material.GridType, {
fabric: {
type: Material.GridType,
uniforms: {
color: new Color_default(0, 1, 0, 1),
cellAlpha: 0.1,
lineCount: new Cartesian2_default(8, 8),
lineThickness: new Cartesian2_default(1, 1),
lineOffset: new Cartesian2_default(0, 0)
},
source: GridMaterial_default
},
translucent: function(material) {
const uniforms = material.uniforms;
return uniforms.color.alpha < 1 || uniforms.cellAlpha < 1;
}
});
Material.StripeType = "Stripe";
Material._materialCache.addMaterial(Material.StripeType, {
fabric: {
type: Material.StripeType,
uniforms: {
horizontal: true,
evenColor: new Color_default(1, 1, 1, 0.5),
oddColor: new Color_default(0, 0, 1, 0.5),
offset: 0,
repeat: 5
},
source: StripeMaterial_default
},
translucent: function(material) {
const uniforms = material.uniforms;
return uniforms.evenColor.alpha < 1 || uniforms.oddColor.alpha < 1;
}
});
Material.CheckerboardType = "Checkerboard";
Material._materialCache.addMaterial(Material.CheckerboardType, {
fabric: {
type: Material.CheckerboardType,
uniforms: {
lightColor: new Color_default(1, 1, 1, 0.5),
darkColor: new Color_default(0, 0, 0, 0.5),
repeat: new Cartesian2_default(5, 5)
},
source: CheckerboardMaterial_default
},
translucent: function(material) {
const uniforms = material.uniforms;
return uniforms.lightColor.alpha < 1 || uniforms.darkColor.alpha < 1;
}
});
Material.DotType = "Dot";
Material._materialCache.addMaterial(Material.DotType, {
fabric: {
type: Material.DotType,
uniforms: {
lightColor: new Color_default(1, 1, 0, 0.75),
darkColor: new Color_default(0, 1, 1, 0.75),
repeat: new Cartesian2_default(5, 5)
},
source: DotMaterial_default
},
translucent: function(material) {
const uniforms = material.uniforms;
return uniforms.lightColor.alpha < 1 || uniforms.darkColor.alpha < 1;
}
});
Material.WaterType = "Water";
Material._materialCache.addMaterial(Material.WaterType, {
fabric: {
type: Material.WaterType,
uniforms: {
baseWaterColor: new Color_default(0.2, 0.3, 0.6, 1),
blendColor: new Color_default(0, 1, 0.699, 1),
specularMap: Material.DefaultImageId,
normalMap: Material.DefaultImageId,
frequency: 10,
animationSpeed: 0.01,
amplitude: 1,
specularIntensity: 0.5,
fadeFactor: 1
},
source: Water_default
},
translucent: function(material) {
const uniforms = material.uniforms;
return uniforms.baseWaterColor.alpha < 1 || uniforms.blendColor.alpha < 1;
}
});
Material.RimLightingType = "RimLighting";
Material._materialCache.addMaterial(Material.RimLightingType, {
fabric: {
type: Material.RimLightingType,
uniforms: {
color: new Color_default(1, 0, 0, 0.7),
rimColor: new Color_default(1, 1, 1, 0.4),
width: 0.3
},
source: RimLightingMaterial_default
},
translucent: function(material) {
const uniforms = material.uniforms;
return uniforms.color.alpha < 1 || uniforms.rimColor.alpha < 1;
}
});
Material.FadeType = "Fade";
Material._materialCache.addMaterial(Material.FadeType, {
fabric: {
type: Material.FadeType,
uniforms: {
fadeInColor: new Color_default(1, 0, 0, 1),
fadeOutColor: new Color_default(0, 0, 0, 0),
maximumDistance: 0.5,
repeat: true,
fadeDirection: {
x: true,
y: true
},
time: new Cartesian2_default(0.5, 0.5)
},
source: FadeMaterial_default
},
translucent: function(material) {
const uniforms = material.uniforms;
return uniforms.fadeInColor.alpha < 1 || uniforms.fadeOutColor.alpha < 1;
}
});
Material.PolylineArrowType = "PolylineArrow";
Material._materialCache.addMaterial(Material.PolylineArrowType, {
fabric: {
type: Material.PolylineArrowType,
uniforms: {
color: new Color_default(1, 1, 1, 1)
},
source: PolylineArrowMaterial_default
},
translucent: true
});
Material.PolylineDashType = "PolylineDash";
Material._materialCache.addMaterial(Material.PolylineDashType, {
fabric: {
type: Material.PolylineDashType,
uniforms: {
color: new Color_default(1, 0, 1, 1),
gapColor: new Color_default(0, 0, 0, 0),
dashLength: 16,
dashPattern: 255
},
source: PolylineDashMaterial_default
},
translucent: true
});
Material.PolylineGlowType = "PolylineGlow";
Material._materialCache.addMaterial(Material.PolylineGlowType, {
fabric: {
type: Material.PolylineGlowType,
uniforms: {
color: new Color_default(0, 0.5, 1, 1),
glowPower: 0.25,
taperPower: 1
},
source: PolylineGlowMaterial_default
},
translucent: true
});
Material.PolylineOutlineType = "PolylineOutline";
Material._materialCache.addMaterial(Material.PolylineOutlineType, {
fabric: {
type: Material.PolylineOutlineType,
uniforms: {
color: new Color_default(1, 1, 1, 1),
outlineColor: new Color_default(1, 0, 0, 1),
outlineWidth: 1
},
source: PolylineOutlineMaterial_default
},
translucent: function(material) {
const uniforms = material.uniforms;
return uniforms.color.alpha < 1 || uniforms.outlineColor.alpha < 1;
}
});
Material.ElevationContourType = "ElevationContour";
Material._materialCache.addMaterial(Material.ElevationContourType, {
fabric: {
type: Material.ElevationContourType,
uniforms: {
spacing: 100,
color: new Color_default(1, 0, 0, 1),
width: 1
},
source: ElevationContourMaterial_default
},
translucent: false
});
Material.ElevationRampType = "ElevationRamp";
Material._materialCache.addMaterial(Material.ElevationRampType, {
fabric: {
type: Material.ElevationRampType,
uniforms: {
image: Material.DefaultImageId,
minimumHeight: 0,
maximumHeight: 1e4
},
source: ElevationRampMaterial_default
},
translucent: false
});
Material.SlopeRampMaterialType = "SlopeRamp";
Material._materialCache.addMaterial(Material.SlopeRampMaterialType, {
fabric: {
type: Material.SlopeRampMaterialType,
uniforms: {
image: Material.DefaultImageId
},
source: SlopeRampMaterial_default
},
translucent: false
});
Material.AspectRampMaterialType = "AspectRamp";
Material._materialCache.addMaterial(Material.AspectRampMaterialType, {
fabric: {
type: Material.AspectRampMaterialType,
uniforms: {
image: Material.DefaultImageId
},
source: AspectRampMaterial_default
},
translucent: false
});
Material.ElevationBandType = "ElevationBand";
Material._materialCache.addMaterial(Material.ElevationBandType, {
fabric: {
type: Material.ElevationBandType,
uniforms: {
heights: Material.DefaultImageId,
colors: Material.DefaultImageId
},
source: ElevationBandMaterial_default
},
translucent: true
});
var Material_default = Material;
// packages/engine/Source/Scene/MaterialAppearance.js
function MaterialAppearance(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const translucent = defaultValue_default(options.translucent, true);
const closed = defaultValue_default(options.closed, false);
const materialSupport = defaultValue_default(
options.materialSupport,
MaterialAppearance.MaterialSupport.TEXTURED
);
this.material = defined_default(options.material) ? options.material : Material_default.fromType(Material_default.ColorType);
this.translucent = translucent;
this._vertexShaderSource = defaultValue_default(
options.vertexShaderSource,
materialSupport.vertexShaderSource
);
this._fragmentShaderSource = defaultValue_default(
options.fragmentShaderSource,
materialSupport.fragmentShaderSource
);
this._renderState = Appearance_default.getDefaultRenderState(
translucent,
closed,
options.renderState
);
this._closed = closed;
this._materialSupport = materialSupport;
this._vertexFormat = materialSupport.vertexFormat;
this._flat = defaultValue_default(options.flat, false);
this._faceForward = defaultValue_default(options.faceForward, !closed);
}
Object.defineProperties(MaterialAppearance.prototype, {
/**
* The GLSL source code for the vertex shader.
*
* @memberof MaterialAppearance.prototype
*
* @type {string}
* @readonly
*/
vertexShaderSource: {
get: function() {
return this._vertexShaderSource;
}
},
/**
* The GLSL source code for the fragment shader. The full fragment shader
* source is built procedurally taking into account {@link MaterialAppearance#material},
* {@link MaterialAppearance#flat}, and {@link MaterialAppearance#faceForward}.
* Use {@link MaterialAppearance#getFragmentShaderSource} to get the full source.
*
* @memberof MaterialAppearance.prototype
*
* @type {string}
* @readonly
*/
fragmentShaderSource: {
get: function() {
return this._fragmentShaderSource;
}
},
/**
* The WebGL fixed-function state to use when rendering the geometry.
* * The render state can be explicitly defined when constructing a {@link MaterialAppearance} * instance, or it is set implicitly via {@link MaterialAppearance#translucent} * and {@link MaterialAppearance#closed}. *
* * @memberof MaterialAppearance.prototype * * @type {object} * @readonly */ renderState: { get: function() { return this._renderState; } }, /** * Whentrue
, the geometry is expected to be closed so
* {@link MaterialAppearance#renderState} has backface culling enabled.
* If the viewer enters the geometry, it will not be visible.
*
* @memberof MaterialAppearance.prototype
*
* @type {boolean}
* @readonly
*
* @default false
*/
closed: {
get: function() {
return this._closed;
}
},
/**
* The type of materials supported by this instance. This impacts the required
* {@link VertexFormat} and the complexity of the vertex and fragment shaders.
*
* @memberof MaterialAppearance.prototype
*
* @type {MaterialAppearance.MaterialSupportType}
* @readonly
*
* @default {@link MaterialAppearance.MaterialSupport.TEXTURED}
*/
materialSupport: {
get: function() {
return this._materialSupport;
}
},
/**
* The {@link VertexFormat} that this appearance instance is compatible with.
* A geometry can have more vertex attributes and still be compatible - at a
* potential performance cost - but it can't have less.
*
* @memberof MaterialAppearance.prototype
*
* @type VertexFormat
* @readonly
*
* @default {@link MaterialAppearance.MaterialSupport.TEXTURED.vertexFormat}
*/
vertexFormat: {
get: function() {
return this._vertexFormat;
}
},
/**
* When true
, flat shading is used in the fragment shader,
* which means lighting is not taking into account.
*
* @memberof MaterialAppearance.prototype
*
* @type {boolean}
* @readonly
*
* @default false
*/
flat: {
get: function() {
return this._flat;
}
},
/**
* When true
, the fragment shader flips the surface normal
* as needed to ensure that the normal faces the viewer to avoid
* dark spots. This is useful when both sides of a geometry should be
* shaded like {@link WallGeometry}.
*
* @memberof MaterialAppearance.prototype
*
* @type {boolean}
* @readonly
*
* @default true
*/
faceForward: {
get: function() {
return this._faceForward;
}
}
});
MaterialAppearance.prototype.getFragmentShaderSource = Appearance_default.prototype.getFragmentShaderSource;
MaterialAppearance.prototype.isTranslucent = Appearance_default.prototype.isTranslucent;
MaterialAppearance.prototype.getRenderState = Appearance_default.prototype.getRenderState;
MaterialAppearance.MaterialSupport = {
/**
* Only basic materials, which require just position
and
* normal
vertex attributes, are supported.
*
* @type {MaterialAppearance.MaterialSupportType}
* @constant
*/
BASIC: Object.freeze({
vertexFormat: VertexFormat_default.POSITION_AND_NORMAL,
vertexShaderSource: BasicMaterialAppearanceVS_default,
fragmentShaderSource: BasicMaterialAppearanceFS_default
}),
/**
* Materials with textures, which require position
,
* normal
, and st
vertex attributes,
* are supported. The vast majority of materials fall into this category.
*
* @type {MaterialAppearance.MaterialSupportType}
* @constant
*/
TEXTURED: Object.freeze({
vertexFormat: VertexFormat_default.POSITION_NORMAL_AND_ST,
vertexShaderSource: TexturedMaterialAppearanceVS_default,
fragmentShaderSource: TexturedMaterialAppearanceFS_default
}),
/**
* All materials, including those that work in tangent space, are supported.
* This requires position
, normal
, st
,
* tangent
, and bitangent
vertex attributes.
*
* @type {MaterialAppearance.MaterialSupportType}
* @constant
*/
ALL: Object.freeze({
vertexFormat: VertexFormat_default.ALL,
vertexShaderSource: AllMaterialAppearanceVS_default,
fragmentShaderSource: AllMaterialAppearanceFS_default
})
};
var MaterialAppearance_default = MaterialAppearance;
// packages/engine/Source/Shaders/Appearances/PerInstanceColorAppearanceFS.js
var PerInstanceColorAppearanceFS_default = "in vec3 v_positionEC;\nin vec3 v_normalEC;\nin vec4 v_color;\n\nvoid main()\n{\n vec3 positionToEyeEC = -v_positionEC;\n\n vec3 normalEC = normalize(v_normalEC);\n#ifdef FACE_FORWARD\n normalEC = faceforward(normalEC, vec3(0.0, 0.0, 1.0), -normalEC);\n#endif\n\n vec4 color = czm_gammaCorrect(v_color);\n\n czm_materialInput materialInput;\n materialInput.normalEC = normalEC;\n materialInput.positionToEyeEC = positionToEyeEC;\n czm_material material = czm_getDefaultMaterial(materialInput);\n material.diffuse = color.rgb;\n material.alpha = color.a;\n\n out_FragColor = czm_phong(normalize(positionToEyeEC), material, czm_lightDirectionEC);\n}\n";
// packages/engine/Source/Shaders/Appearances/PerInstanceColorAppearanceVS.js
var PerInstanceColorAppearanceVS_default = "in vec3 position3DHigh;\nin vec3 position3DLow;\nin vec3 normal;\nin vec4 color;\nin float batchId;\n\nout vec3 v_positionEC;\nout vec3 v_normalEC;\nout vec4 v_color;\n\nvoid main()\n{\n vec4 p = czm_computePosition();\n\n v_positionEC = (czm_modelViewRelativeToEye * p).xyz; // position in eye coordinates\n v_normalEC = czm_normal * normal; // normal in eye coordinates\n v_color = color;\n\n gl_Position = czm_modelViewProjectionRelativeToEye * p;\n}\n";
// packages/engine/Source/Shaders/Appearances/PerInstanceFlatColorAppearanceFS.js
var PerInstanceFlatColorAppearanceFS_default = "in vec4 v_color;\n\nvoid main()\n{\n out_FragColor = czm_gammaCorrect(v_color);\n}\n";
// packages/engine/Source/Shaders/Appearances/PerInstanceFlatColorAppearanceVS.js
var PerInstanceFlatColorAppearanceVS_default = "in vec3 position3DHigh;\nin vec3 position3DLow;\nin vec4 color;\nin float batchId;\n\nout vec4 v_color;\n\nvoid main()\n{\n vec4 p = czm_computePosition();\n\n v_color = color;\n\n gl_Position = czm_modelViewProjectionRelativeToEye * p;\n}\n";
// packages/engine/Source/Scene/PerInstanceColorAppearance.js
function PerInstanceColorAppearance(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const translucent = defaultValue_default(options.translucent, true);
const closed = defaultValue_default(options.closed, false);
const flat = defaultValue_default(options.flat, false);
const vs = flat ? PerInstanceFlatColorAppearanceVS_default : PerInstanceColorAppearanceVS_default;
const fs = flat ? PerInstanceFlatColorAppearanceFS_default : PerInstanceColorAppearanceFS_default;
const vertexFormat = flat ? PerInstanceColorAppearance.FLAT_VERTEX_FORMAT : PerInstanceColorAppearance.VERTEX_FORMAT;
this.material = void 0;
this.translucent = translucent;
this._vertexShaderSource = defaultValue_default(options.vertexShaderSource, vs);
this._fragmentShaderSource = defaultValue_default(options.fragmentShaderSource, fs);
this._renderState = Appearance_default.getDefaultRenderState(
translucent,
closed,
options.renderState
);
this._closed = closed;
this._vertexFormat = vertexFormat;
this._flat = flat;
this._faceForward = defaultValue_default(options.faceForward, !closed);
}
Object.defineProperties(PerInstanceColorAppearance.prototype, {
/**
* The GLSL source code for the vertex shader.
*
* @memberof PerInstanceColorAppearance.prototype
*
* @type {string}
* @readonly
*/
vertexShaderSource: {
get: function() {
return this._vertexShaderSource;
}
},
/**
* The GLSL source code for the fragment shader.
*
* @memberof PerInstanceColorAppearance.prototype
*
* @type {string}
* @readonly
*/
fragmentShaderSource: {
get: function() {
return this._fragmentShaderSource;
}
},
/**
* The WebGL fixed-function state to use when rendering the geometry.
* * The render state can be explicitly defined when constructing a {@link PerInstanceColorAppearance} * instance, or it is set implicitly via {@link PerInstanceColorAppearance#translucent} * and {@link PerInstanceColorAppearance#closed}. *
* * @memberof PerInstanceColorAppearance.prototype * * @type {object} * @readonly */ renderState: { get: function() { return this._renderState; } }, /** * Whentrue
, the geometry is expected to be closed so
* {@link PerInstanceColorAppearance#renderState} has backface culling enabled.
* If the viewer enters the geometry, it will not be visible.
*
* @memberof PerInstanceColorAppearance.prototype
*
* @type {boolean}
* @readonly
*
* @default false
*/
closed: {
get: function() {
return this._closed;
}
},
/**
* The {@link VertexFormat} that this appearance instance is compatible with.
* A geometry can have more vertex attributes and still be compatible - at a
* potential performance cost - but it can't have less.
*
* @memberof PerInstanceColorAppearance.prototype
*
* @type VertexFormat
* @readonly
*/
vertexFormat: {
get: function() {
return this._vertexFormat;
}
},
/**
* When true
, flat shading is used in the fragment shader,
* which means lighting is not taking into account.
*
* @memberof PerInstanceColorAppearance.prototype
*
* @type {boolean}
* @readonly
*
* @default false
*/
flat: {
get: function() {
return this._flat;
}
},
/**
* When true
, the fragment shader flips the surface normal
* as needed to ensure that the normal faces the viewer to avoid
* dark spots. This is useful when both sides of a geometry should be
* shaded like {@link WallGeometry}.
*
* @memberof PerInstanceColorAppearance.prototype
*
* @type {boolean}
* @readonly
*
* @default true
*/
faceForward: {
get: function() {
return this._faceForward;
}
}
});
PerInstanceColorAppearance.VERTEX_FORMAT = VertexFormat_default.POSITION_AND_NORMAL;
PerInstanceColorAppearance.FLAT_VERTEX_FORMAT = VertexFormat_default.POSITION_ONLY;
PerInstanceColorAppearance.prototype.getFragmentShaderSource = Appearance_default.prototype.getFragmentShaderSource;
PerInstanceColorAppearance.prototype.isTranslucent = Appearance_default.prototype.isTranslucent;
PerInstanceColorAppearance.prototype.getRenderState = Appearance_default.prototype.getRenderState;
var PerInstanceColorAppearance_default = PerInstanceColorAppearance;
// packages/engine/Source/DataSources/ColorMaterialProperty.js
function ColorMaterialProperty(color) {
this._definitionChanged = new Event_default();
this._color = void 0;
this._colorSubscription = void 0;
this.color = color;
}
Object.defineProperties(ColorMaterialProperty.prototype, {
/**
* Gets a value indicating if this property is constant. A property is considered
* constant if getValue always returns the same result for the current definition.
* @memberof ColorMaterialProperty.prototype
*
* @type {boolean}
* @readonly
*/
isConstant: {
get: function() {
return Property_default.isConstant(this._color);
}
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* The definition is considered to have changed if a call to getValue would return
* a different result for the same time.
* @memberof ColorMaterialProperty.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
/**
* Gets or sets the {@link Color} {@link Property}.
* @memberof ColorMaterialProperty.prototype
* @type {Property|undefined}
* @default Color.WHITE
*/
color: createPropertyDescriptor_default("color")
});
ColorMaterialProperty.prototype.getType = function(time) {
return "Color";
};
ColorMaterialProperty.prototype.getValue = function(time, result) {
if (!defined_default(result)) {
result = {};
}
result.color = Property_default.getValueOrClonedDefault(
this._color,
time,
Color_default.WHITE,
result.color
);
return result;
};
ColorMaterialProperty.prototype.equals = function(other) {
return this === other || //
other instanceof ColorMaterialProperty && //
Property_default.equals(this._color, other._color);
};
var ColorMaterialProperty_default = ColorMaterialProperty;
// packages/engine/Source/Core/GeographicTilingScheme.js
function GeographicTilingScheme(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this._ellipsoid = defaultValue_default(options.ellipsoid, Ellipsoid_default.WGS84);
this._rectangle = defaultValue_default(options.rectangle, Rectangle_default.MAX_VALUE);
this._projection = new GeographicProjection_default(this._ellipsoid);
this._numberOfLevelZeroTilesX = defaultValue_default(
options.numberOfLevelZeroTilesX,
2
);
this._numberOfLevelZeroTilesY = defaultValue_default(
options.numberOfLevelZeroTilesY,
1
);
}
Object.defineProperties(GeographicTilingScheme.prototype, {
/**
* Gets the ellipsoid that is tiled by this tiling scheme.
* @memberof GeographicTilingScheme.prototype
* @type {Ellipsoid}
*/
ellipsoid: {
get: function() {
return this._ellipsoid;
}
},
/**
* Gets the rectangle, in radians, covered by this tiling scheme.
* @memberof GeographicTilingScheme.prototype
* @type {Rectangle}
*/
rectangle: {
get: function() {
return this._rectangle;
}
},
/**
* Gets the map projection used by this tiling scheme.
* @memberof GeographicTilingScheme.prototype
* @type {MapProjection}
*/
projection: {
get: function() {
return this._projection;
}
}
});
GeographicTilingScheme.prototype.getNumberOfXTilesAtLevel = function(level) {
return this._numberOfLevelZeroTilesX << level;
};
GeographicTilingScheme.prototype.getNumberOfYTilesAtLevel = function(level) {
return this._numberOfLevelZeroTilesY << level;
};
GeographicTilingScheme.prototype.rectangleToNativeRectangle = function(rectangle, result) {
Check_default.defined("rectangle", rectangle);
const west = Math_default.toDegrees(rectangle.west);
const south = Math_default.toDegrees(rectangle.south);
const east = Math_default.toDegrees(rectangle.east);
const north = Math_default.toDegrees(rectangle.north);
if (!defined_default(result)) {
return new Rectangle_default(west, south, east, north);
}
result.west = west;
result.south = south;
result.east = east;
result.north = north;
return result;
};
GeographicTilingScheme.prototype.tileXYToNativeRectangle = function(x, y, level, result) {
const rectangleRadians = this.tileXYToRectangle(x, y, level, result);
rectangleRadians.west = Math_default.toDegrees(rectangleRadians.west);
rectangleRadians.south = Math_default.toDegrees(rectangleRadians.south);
rectangleRadians.east = Math_default.toDegrees(rectangleRadians.east);
rectangleRadians.north = Math_default.toDegrees(rectangleRadians.north);
return rectangleRadians;
};
GeographicTilingScheme.prototype.tileXYToRectangle = function(x, y, level, result) {
const rectangle = this._rectangle;
const xTiles = this.getNumberOfXTilesAtLevel(level);
const yTiles = this.getNumberOfYTilesAtLevel(level);
const xTileWidth = rectangle.width / xTiles;
const west = x * xTileWidth + rectangle.west;
const east = (x + 1) * xTileWidth + rectangle.west;
const yTileHeight = rectangle.height / yTiles;
const north = rectangle.north - y * yTileHeight;
const south = rectangle.north - (y + 1) * yTileHeight;
if (!defined_default(result)) {
result = new Rectangle_default(west, south, east, north);
}
result.west = west;
result.south = south;
result.east = east;
result.north = north;
return result;
};
GeographicTilingScheme.prototype.positionToTileXY = function(position, level, result) {
const rectangle = this._rectangle;
if (!Rectangle_default.contains(rectangle, position)) {
return void 0;
}
const xTiles = this.getNumberOfXTilesAtLevel(level);
const yTiles = this.getNumberOfYTilesAtLevel(level);
const xTileWidth = rectangle.width / xTiles;
const yTileHeight = rectangle.height / yTiles;
let longitude = position.longitude;
if (rectangle.east < rectangle.west) {
longitude += Math_default.TWO_PI;
}
let xTileCoordinate = (longitude - rectangle.west) / xTileWidth | 0;
if (xTileCoordinate >= xTiles) {
xTileCoordinate = xTiles - 1;
}
let yTileCoordinate = (rectangle.north - position.latitude) / yTileHeight | 0;
if (yTileCoordinate >= yTiles) {
yTileCoordinate = yTiles - 1;
}
if (!defined_default(result)) {
return new Cartesian2_default(xTileCoordinate, yTileCoordinate);
}
result.x = xTileCoordinate;
result.y = yTileCoordinate;
return result;
};
var GeographicTilingScheme_default = GeographicTilingScheme;
// packages/engine/Source/Core/ApproximateTerrainHeights.js
var scratchDiagonalCartesianNE = new Cartesian3_default();
var scratchDiagonalCartesianSW = new Cartesian3_default();
var scratchDiagonalCartographic = new Cartographic_default();
var scratchCenterCartesian = new Cartesian3_default();
var scratchSurfaceCartesian = new Cartesian3_default();
var scratchBoundingSphere = new BoundingSphere_default();
var tilingScheme = new GeographicTilingScheme_default();
var scratchCorners = [
new Cartographic_default(),
new Cartographic_default(),
new Cartographic_default(),
new Cartographic_default()
];
var scratchTileXY = new Cartesian2_default();
var ApproximateTerrainHeights = {};
ApproximateTerrainHeights.initialize = function() {
let initPromise = ApproximateTerrainHeights._initPromise;
if (defined_default(initPromise)) {
return initPromise;
}
initPromise = Resource_default.fetchJson(
buildModuleUrl_default("Assets/approximateTerrainHeights.json")
).then(function(json) {
ApproximateTerrainHeights._terrainHeights = json;
});
ApproximateTerrainHeights._initPromise = initPromise;
return initPromise;
};
ApproximateTerrainHeights.getMinimumMaximumHeights = function(rectangle, ellipsoid) {
Check_default.defined("rectangle", rectangle);
if (!defined_default(ApproximateTerrainHeights._terrainHeights)) {
throw new DeveloperError_default(
"You must call ApproximateTerrainHeights.initialize and wait for the promise to resolve before using this function"
);
}
ellipsoid = defaultValue_default(ellipsoid, Ellipsoid_default.WGS84);
const xyLevel = getTileXYLevel(rectangle);
let minTerrainHeight = ApproximateTerrainHeights._defaultMinTerrainHeight;
let maxTerrainHeight = ApproximateTerrainHeights._defaultMaxTerrainHeight;
if (defined_default(xyLevel)) {
const key = `${xyLevel.level}-${xyLevel.x}-${xyLevel.y}`;
const heights = ApproximateTerrainHeights._terrainHeights[key];
if (defined_default(heights)) {
minTerrainHeight = heights[0];
maxTerrainHeight = heights[1];
}
ellipsoid.cartographicToCartesian(
Rectangle_default.northeast(rectangle, scratchDiagonalCartographic),
scratchDiagonalCartesianNE
);
ellipsoid.cartographicToCartesian(
Rectangle_default.southwest(rectangle, scratchDiagonalCartographic),
scratchDiagonalCartesianSW
);
Cartesian3_default.midpoint(
scratchDiagonalCartesianSW,
scratchDiagonalCartesianNE,
scratchCenterCartesian
);
const surfacePosition = ellipsoid.scaleToGeodeticSurface(
scratchCenterCartesian,
scratchSurfaceCartesian
);
if (defined_default(surfacePosition)) {
const distance2 = Cartesian3_default.distance(
scratchCenterCartesian,
surfacePosition
);
minTerrainHeight = Math.min(minTerrainHeight, -distance2);
} else {
minTerrainHeight = ApproximateTerrainHeights._defaultMinTerrainHeight;
}
}
minTerrainHeight = Math.max(
ApproximateTerrainHeights._defaultMinTerrainHeight,
minTerrainHeight
);
return {
minimumTerrainHeight: minTerrainHeight,
maximumTerrainHeight: maxTerrainHeight
};
};
ApproximateTerrainHeights.getBoundingSphere = function(rectangle, ellipsoid) {
Check_default.defined("rectangle", rectangle);
if (!defined_default(ApproximateTerrainHeights._terrainHeights)) {
throw new DeveloperError_default(
"You must call ApproximateTerrainHeights.initialize and wait for the promise to resolve before using this function"
);
}
ellipsoid = defaultValue_default(ellipsoid, Ellipsoid_default.WGS84);
const xyLevel = getTileXYLevel(rectangle);
let maxTerrainHeight = ApproximateTerrainHeights._defaultMaxTerrainHeight;
if (defined_default(xyLevel)) {
const key = `${xyLevel.level}-${xyLevel.x}-${xyLevel.y}`;
const heights = ApproximateTerrainHeights._terrainHeights[key];
if (defined_default(heights)) {
maxTerrainHeight = heights[1];
}
}
const result = BoundingSphere_default.fromRectangle3D(rectangle, ellipsoid, 0);
BoundingSphere_default.fromRectangle3D(
rectangle,
ellipsoid,
maxTerrainHeight,
scratchBoundingSphere
);
return BoundingSphere_default.union(result, scratchBoundingSphere, result);
};
function getTileXYLevel(rectangle) {
Cartographic_default.fromRadians(
rectangle.east,
rectangle.north,
0,
scratchCorners[0]
);
Cartographic_default.fromRadians(
rectangle.west,
rectangle.north,
0,
scratchCorners[1]
);
Cartographic_default.fromRadians(
rectangle.east,
rectangle.south,
0,
scratchCorners[2]
);
Cartographic_default.fromRadians(
rectangle.west,
rectangle.south,
0,
scratchCorners[3]
);
let lastLevelX = 0, lastLevelY = 0;
let currentX = 0, currentY = 0;
const maxLevel = ApproximateTerrainHeights._terrainHeightsMaxLevel;
let i;
for (i = 0; i <= maxLevel; ++i) {
let failed = false;
for (let j = 0; j < 4; ++j) {
const corner = scratchCorners[j];
tilingScheme.positionToTileXY(corner, i, scratchTileXY);
if (j === 0) {
currentX = scratchTileXY.x;
currentY = scratchTileXY.y;
} else if (currentX !== scratchTileXY.x || currentY !== scratchTileXY.y) {
failed = true;
break;
}
}
if (failed) {
break;
}
lastLevelX = currentX;
lastLevelY = currentY;
}
if (i === 0) {
return void 0;
}
return {
x: lastLevelX,
y: lastLevelY,
level: i > maxLevel ? maxLevel : i - 1
};
}
ApproximateTerrainHeights._terrainHeightsMaxLevel = 6;
ApproximateTerrainHeights._defaultMaxTerrainHeight = 9e3;
ApproximateTerrainHeights._defaultMinTerrainHeight = -1e5;
ApproximateTerrainHeights._terrainHeights = void 0;
ApproximateTerrainHeights._initPromise = void 0;
Object.defineProperties(ApproximateTerrainHeights, {
/**
* Determines if the terrain heights are initialized and ready to use. To initialize the terrain heights,
* call {@link ApproximateTerrainHeights#initialize} and wait for the returned promise to resolve.
* @type {boolean}
* @readonly
* @memberof ApproximateTerrainHeights
*/
initialized: {
get: function() {
return defined_default(ApproximateTerrainHeights._terrainHeights);
}
}
});
var ApproximateTerrainHeights_default = ApproximateTerrainHeights;
// packages/engine/Source/Core/AxisAlignedBoundingBox.js
function AxisAlignedBoundingBox(minimum, maximum, center) {
this.minimum = Cartesian3_default.clone(defaultValue_default(minimum, Cartesian3_default.ZERO));
this.maximum = Cartesian3_default.clone(defaultValue_default(maximum, Cartesian3_default.ZERO));
if (!defined_default(center)) {
center = Cartesian3_default.midpoint(this.minimum, this.maximum, new Cartesian3_default());
} else {
center = Cartesian3_default.clone(center);
}
this.center = center;
}
AxisAlignedBoundingBox.fromCorners = function(minimum, maximum, result) {
Check_default.defined("minimum", minimum);
Check_default.defined("maximum", maximum);
if (!defined_default(result)) {
result = new AxisAlignedBoundingBox();
}
result.minimum = Cartesian3_default.clone(minimum, result.minimum);
result.maximum = Cartesian3_default.clone(maximum, result.maximum);
result.center = Cartesian3_default.midpoint(minimum, maximum, result.center);
return result;
};
AxisAlignedBoundingBox.fromPoints = function(positions, result) {
if (!defined_default(result)) {
result = new AxisAlignedBoundingBox();
}
if (!defined_default(positions) || positions.length === 0) {
result.minimum = Cartesian3_default.clone(Cartesian3_default.ZERO, result.minimum);
result.maximum = Cartesian3_default.clone(Cartesian3_default.ZERO, result.maximum);
result.center = Cartesian3_default.clone(Cartesian3_default.ZERO, result.center);
return result;
}
let minimumX = positions[0].x;
let minimumY = positions[0].y;
let minimumZ = positions[0].z;
let maximumX = positions[0].x;
let maximumY = positions[0].y;
let maximumZ = positions[0].z;
const length3 = positions.length;
for (let i = 1; i < length3; i++) {
const p = positions[i];
const x = p.x;
const y = p.y;
const z = p.z;
minimumX = Math.min(x, minimumX);
maximumX = Math.max(x, maximumX);
minimumY = Math.min(y, minimumY);
maximumY = Math.max(y, maximumY);
minimumZ = Math.min(z, minimumZ);
maximumZ = Math.max(z, maximumZ);
}
const minimum = result.minimum;
minimum.x = minimumX;
minimum.y = minimumY;
minimum.z = minimumZ;
const maximum = result.maximum;
maximum.x = maximumX;
maximum.y = maximumY;
maximum.z = maximumZ;
result.center = Cartesian3_default.midpoint(minimum, maximum, result.center);
return result;
};
AxisAlignedBoundingBox.clone = function(box, result) {
if (!defined_default(box)) {
return void 0;
}
if (!defined_default(result)) {
return new AxisAlignedBoundingBox(box.minimum, box.maximum, box.center);
}
result.minimum = Cartesian3_default.clone(box.minimum, result.minimum);
result.maximum = Cartesian3_default.clone(box.maximum, result.maximum);
result.center = Cartesian3_default.clone(box.center, result.center);
return result;
};
AxisAlignedBoundingBox.equals = function(left, right) {
return left === right || defined_default(left) && defined_default(right) && Cartesian3_default.equals(left.center, right.center) && Cartesian3_default.equals(left.minimum, right.minimum) && Cartesian3_default.equals(left.maximum, right.maximum);
};
var intersectScratch = new Cartesian3_default();
AxisAlignedBoundingBox.intersectPlane = function(box, plane) {
Check_default.defined("box", box);
Check_default.defined("plane", plane);
intersectScratch = Cartesian3_default.subtract(
box.maximum,
box.minimum,
intersectScratch
);
const h = Cartesian3_default.multiplyByScalar(
intersectScratch,
0.5,
intersectScratch
);
const normal2 = plane.normal;
const e = h.x * Math.abs(normal2.x) + h.y * Math.abs(normal2.y) + h.z * Math.abs(normal2.z);
const s = Cartesian3_default.dot(box.center, normal2) + plane.distance;
if (s - e > 0) {
return Intersect_default.INSIDE;
}
if (s + e < 0) {
return Intersect_default.OUTSIDE;
}
return Intersect_default.INTERSECTING;
};
AxisAlignedBoundingBox.prototype.clone = function(result) {
return AxisAlignedBoundingBox.clone(this, result);
};
AxisAlignedBoundingBox.prototype.intersectPlane = function(plane) {
return AxisAlignedBoundingBox.intersectPlane(this, plane);
};
AxisAlignedBoundingBox.prototype.equals = function(right) {
return AxisAlignedBoundingBox.equals(this, right);
};
var AxisAlignedBoundingBox_default = AxisAlignedBoundingBox;
// packages/engine/Source/Core/QuadraticRealPolynomial.js
var QuadraticRealPolynomial = {};
QuadraticRealPolynomial.computeDiscriminant = function(a3, b, c) {
if (typeof a3 !== "number") {
throw new DeveloperError_default("a is a required number.");
}
if (typeof b !== "number") {
throw new DeveloperError_default("b is a required number.");
}
if (typeof c !== "number") {
throw new DeveloperError_default("c is a required number.");
}
const discriminant = b * b - 4 * a3 * c;
return discriminant;
};
function addWithCancellationCheck(left, right, tolerance) {
const difference = left + right;
if (Math_default.sign(left) !== Math_default.sign(right) && Math.abs(difference / Math.max(Math.abs(left), Math.abs(right))) < tolerance) {
return 0;
}
return difference;
}
QuadraticRealPolynomial.computeRealRoots = function(a3, b, c) {
if (typeof a3 !== "number") {
throw new DeveloperError_default("a is a required number.");
}
if (typeof b !== "number") {
throw new DeveloperError_default("b is a required number.");
}
if (typeof c !== "number") {
throw new DeveloperError_default("c is a required number.");
}
let ratio;
if (a3 === 0) {
if (b === 0) {
return [];
}
return [-c / b];
} else if (b === 0) {
if (c === 0) {
return [0, 0];
}
const cMagnitude = Math.abs(c);
const aMagnitude = Math.abs(a3);
if (cMagnitude < aMagnitude && cMagnitude / aMagnitude < Math_default.EPSILON14) {
return [0, 0];
} else if (cMagnitude > aMagnitude && aMagnitude / cMagnitude < Math_default.EPSILON14) {
return [];
}
ratio = -c / a3;
if (ratio < 0) {
return [];
}
const root = Math.sqrt(ratio);
return [-root, root];
} else if (c === 0) {
ratio = -b / a3;
if (ratio < 0) {
return [ratio, 0];
}
return [0, ratio];
}
const b2 = b * b;
const four_ac = 4 * a3 * c;
const radicand = addWithCancellationCheck(b2, -four_ac, Math_default.EPSILON14);
if (radicand < 0) {
return [];
}
const q = -0.5 * addWithCancellationCheck(
b,
Math_default.sign(b) * Math.sqrt(radicand),
Math_default.EPSILON14
);
if (b > 0) {
return [q / a3, c / q];
}
return [c / q, q / a3];
};
var QuadraticRealPolynomial_default = QuadraticRealPolynomial;
// packages/engine/Source/Core/CubicRealPolynomial.js
var CubicRealPolynomial = {};
CubicRealPolynomial.computeDiscriminant = function(a3, b, c, d) {
if (typeof a3 !== "number") {
throw new DeveloperError_default("a is a required number.");
}
if (typeof b !== "number") {
throw new DeveloperError_default("b is a required number.");
}
if (typeof c !== "number") {
throw new DeveloperError_default("c is a required number.");
}
if (typeof d !== "number") {
throw new DeveloperError_default("d is a required number.");
}
const a22 = a3 * a3;
const b2 = b * b;
const c22 = c * c;
const d2 = d * d;
const discriminant = 18 * a3 * b * c * d + b2 * c22 - 27 * a22 * d2 - 4 * (a3 * c22 * c + b2 * b * d);
return discriminant;
};
function computeRealRoots(a3, b, c, d) {
const A = a3;
const B = b / 3;
const C = c / 3;
const D = d;
const AC = A * C;
const BD = B * D;
const B2 = B * B;
const C2 = C * C;
const delta1 = A * C - B2;
const delta2 = A * D - B * C;
const delta3 = B * D - C2;
const discriminant = 4 * delta1 * delta3 - delta2 * delta2;
let temp;
let temp1;
if (discriminant < 0) {
let ABar;
let CBar;
let DBar;
if (B2 * BD >= AC * C2) {
ABar = A;
CBar = delta1;
DBar = -2 * B * delta1 + A * delta2;
} else {
ABar = D;
CBar = delta3;
DBar = -D * delta2 + 2 * C * delta3;
}
const s = DBar < 0 ? -1 : 1;
const temp0 = -s * Math.abs(ABar) * Math.sqrt(-discriminant);
temp1 = -DBar + temp0;
const x = temp1 / 2;
const p = x < 0 ? -Math.pow(-x, 1 / 3) : Math.pow(x, 1 / 3);
const q = temp1 === temp0 ? -p : -CBar / p;
temp = CBar <= 0 ? p + q : -DBar / (p * p + q * q + CBar);
if (B2 * BD >= AC * C2) {
return [(temp - B) / A];
}
return [-D / (temp + C)];
}
const CBarA = delta1;
const DBarA = -2 * B * delta1 + A * delta2;
const CBarD = delta3;
const DBarD = -D * delta2 + 2 * C * delta3;
const squareRootOfDiscriminant = Math.sqrt(discriminant);
const halfSquareRootOf3 = Math.sqrt(3) / 2;
let theta = Math.abs(Math.atan2(A * squareRootOfDiscriminant, -DBarA) / 3);
temp = 2 * Math.sqrt(-CBarA);
let cosine = Math.cos(theta);
temp1 = temp * cosine;
let temp3 = temp * (-cosine / 2 - halfSquareRootOf3 * Math.sin(theta));
const numeratorLarge = temp1 + temp3 > 2 * B ? temp1 - B : temp3 - B;
const denominatorLarge = A;
const root1 = numeratorLarge / denominatorLarge;
theta = Math.abs(Math.atan2(D * squareRootOfDiscriminant, -DBarD) / 3);
temp = 2 * Math.sqrt(-CBarD);
cosine = Math.cos(theta);
temp1 = temp * cosine;
temp3 = temp * (-cosine / 2 - halfSquareRootOf3 * Math.sin(theta));
const numeratorSmall = -D;
const denominatorSmall = temp1 + temp3 < 2 * C ? temp1 + C : temp3 + C;
const root3 = numeratorSmall / denominatorSmall;
const E = denominatorLarge * denominatorSmall;
const F = -numeratorLarge * denominatorSmall - denominatorLarge * numeratorSmall;
const G = numeratorLarge * numeratorSmall;
const root2 = (C * F - B * G) / (-B * F + C * E);
if (root1 <= root2) {
if (root1 <= root3) {
if (root2 <= root3) {
return [root1, root2, root3];
}
return [root1, root3, root2];
}
return [root3, root1, root2];
}
if (root1 <= root3) {
return [root2, root1, root3];
}
if (root2 <= root3) {
return [root2, root3, root1];
}
return [root3, root2, root1];
}
CubicRealPolynomial.computeRealRoots = function(a3, b, c, d) {
if (typeof a3 !== "number") {
throw new DeveloperError_default("a is a required number.");
}
if (typeof b !== "number") {
throw new DeveloperError_default("b is a required number.");
}
if (typeof c !== "number") {
throw new DeveloperError_default("c is a required number.");
}
if (typeof d !== "number") {
throw new DeveloperError_default("d is a required number.");
}
let roots;
let ratio;
if (a3 === 0) {
return QuadraticRealPolynomial_default.computeRealRoots(b, c, d);
} else if (b === 0) {
if (c === 0) {
if (d === 0) {
return [0, 0, 0];
}
ratio = -d / a3;
const root = ratio < 0 ? -Math.pow(-ratio, 1 / 3) : Math.pow(ratio, 1 / 3);
return [root, root, root];
} else if (d === 0) {
roots = QuadraticRealPolynomial_default.computeRealRoots(a3, 0, c);
if (roots.Length === 0) {
return [0];
}
return [roots[0], 0, roots[1]];
}
return computeRealRoots(a3, 0, c, d);
} else if (c === 0) {
if (d === 0) {
ratio = -b / a3;
if (ratio < 0) {
return [ratio, 0, 0];
}
return [0, 0, ratio];
}
return computeRealRoots(a3, b, 0, d);
} else if (d === 0) {
roots = QuadraticRealPolynomial_default.computeRealRoots(a3, b, c);
if (roots.length === 0) {
return [0];
} else if (roots[1] <= 0) {
return [roots[0], roots[1], 0];
} else if (roots[0] >= 0) {
return [0, roots[0], roots[1]];
}
return [roots[0], 0, roots[1]];
}
return computeRealRoots(a3, b, c, d);
};
var CubicRealPolynomial_default = CubicRealPolynomial;
// packages/engine/Source/Core/QuarticRealPolynomial.js
var QuarticRealPolynomial = {};
QuarticRealPolynomial.computeDiscriminant = function(a3, b, c, d, e) {
if (typeof a3 !== "number") {
throw new DeveloperError_default("a is a required number.");
}
if (typeof b !== "number") {
throw new DeveloperError_default("b is a required number.");
}
if (typeof c !== "number") {
throw new DeveloperError_default("c is a required number.");
}
if (typeof d !== "number") {
throw new DeveloperError_default("d is a required number.");
}
if (typeof e !== "number") {
throw new DeveloperError_default("e is a required number.");
}
const a22 = a3 * a3;
const a32 = a22 * a3;
const b2 = b * b;
const b3 = b2 * b;
const c22 = c * c;
const c33 = c22 * c;
const d2 = d * d;
const d3 = d2 * d;
const e2 = e * e;
const e3 = e2 * e;
const discriminant = b2 * c22 * d2 - 4 * b3 * d3 - 4 * a3 * c33 * d2 + 18 * a3 * b * c * d3 - 27 * a22 * d2 * d2 + 256 * a32 * e3 + e * (18 * b3 * c * d - 4 * b2 * c33 + 16 * a3 * c22 * c22 - 80 * a3 * b * c22 * d - 6 * a3 * b2 * d2 + 144 * a22 * c * d2) + e2 * (144 * a3 * b2 * c - 27 * b2 * b2 - 128 * a22 * c22 - 192 * a22 * b * d);
return discriminant;
};
function original(a3, a22, a1, a0) {
const a3Squared = a3 * a3;
const p = a22 - 3 * a3Squared / 8;
const q = a1 - a22 * a3 / 2 + a3Squared * a3 / 8;
const r = a0 - a1 * a3 / 4 + a22 * a3Squared / 16 - 3 * a3Squared * a3Squared / 256;
const cubicRoots = CubicRealPolynomial_default.computeRealRoots(
1,
2 * p,
p * p - 4 * r,
-q * q
);
if (cubicRoots.length > 0) {
const temp = -a3 / 4;
const hSquared = cubicRoots[cubicRoots.length - 1];
if (Math.abs(hSquared) < Math_default.EPSILON14) {
const roots = QuadraticRealPolynomial_default.computeRealRoots(1, p, r);
if (roots.length === 2) {
const root0 = roots[0];
const root1 = roots[1];
let y;
if (root0 >= 0 && root1 >= 0) {
const y0 = Math.sqrt(root0);
const y1 = Math.sqrt(root1);
return [temp - y1, temp - y0, temp + y0, temp + y1];
} else if (root0 >= 0 && root1 < 0) {
y = Math.sqrt(root0);
return [temp - y, temp + y];
} else if (root0 < 0 && root1 >= 0) {
y = Math.sqrt(root1);
return [temp - y, temp + y];
}
}
return [];
} else if (hSquared > 0) {
const h = Math.sqrt(hSquared);
const m = (p + hSquared - q / h) / 2;
const n = (p + hSquared + q / h) / 2;
const roots1 = QuadraticRealPolynomial_default.computeRealRoots(1, h, m);
const roots2 = QuadraticRealPolynomial_default.computeRealRoots(1, -h, n);
if (roots1.length !== 0) {
roots1[0] += temp;
roots1[1] += temp;
if (roots2.length !== 0) {
roots2[0] += temp;
roots2[1] += temp;
if (roots1[1] <= roots2[0]) {
return [roots1[0], roots1[1], roots2[0], roots2[1]];
} else if (roots2[1] <= roots1[0]) {
return [roots2[0], roots2[1], roots1[0], roots1[1]];
} else if (roots1[0] >= roots2[0] && roots1[1] <= roots2[1]) {
return [roots2[0], roots1[0], roots1[1], roots2[1]];
} else if (roots2[0] >= roots1[0] && roots2[1] <= roots1[1]) {
return [roots1[0], roots2[0], roots2[1], roots1[1]];
} else if (roots1[0] > roots2[0] && roots1[0] < roots2[1]) {
return [roots2[0], roots1[0], roots2[1], roots1[1]];
}
return [roots1[0], roots2[0], roots1[1], roots2[1]];
}
return roots1;
}
if (roots2.length !== 0) {
roots2[0] += temp;
roots2[1] += temp;
return roots2;
}
return [];
}
}
return [];
}
function neumark(a3, a22, a1, a0) {
const a1Squared = a1 * a1;
const a2Squared = a22 * a22;
const a3Squared = a3 * a3;
const p = -2 * a22;
const q = a1 * a3 + a2Squared - 4 * a0;
const r = a3Squared * a0 - a1 * a22 * a3 + a1Squared;
const cubicRoots = CubicRealPolynomial_default.computeRealRoots(1, p, q, r);
if (cubicRoots.length > 0) {
const y = cubicRoots[0];
const temp = a22 - y;
const tempSquared = temp * temp;
const g1 = a3 / 2;
const h1 = temp / 2;
const m = tempSquared - 4 * a0;
const mError = tempSquared + 4 * Math.abs(a0);
const n = a3Squared - 4 * y;
const nError = a3Squared + 4 * Math.abs(y);
let g2;
let h2;
if (y < 0 || m * nError < n * mError) {
const squareRootOfN = Math.sqrt(n);
g2 = squareRootOfN / 2;
h2 = squareRootOfN === 0 ? 0 : (a3 * h1 - a1) / squareRootOfN;
} else {
const squareRootOfM = Math.sqrt(m);
g2 = squareRootOfM === 0 ? 0 : (a3 * h1 - a1) / squareRootOfM;
h2 = squareRootOfM / 2;
}
let G;
let g;
if (g1 === 0 && g2 === 0) {
G = 0;
g = 0;
} else if (Math_default.sign(g1) === Math_default.sign(g2)) {
G = g1 + g2;
g = y / G;
} else {
g = g1 - g2;
G = y / g;
}
let H;
let h;
if (h1 === 0 && h2 === 0) {
H = 0;
h = 0;
} else if (Math_default.sign(h1) === Math_default.sign(h2)) {
H = h1 + h2;
h = a0 / H;
} else {
h = h1 - h2;
H = a0 / h;
}
const roots1 = QuadraticRealPolynomial_default.computeRealRoots(1, G, H);
const roots2 = QuadraticRealPolynomial_default.computeRealRoots(1, g, h);
if (roots1.length !== 0) {
if (roots2.length !== 0) {
if (roots1[1] <= roots2[0]) {
return [roots1[0], roots1[1], roots2[0], roots2[1]];
} else if (roots2[1] <= roots1[0]) {
return [roots2[0], roots2[1], roots1[0], roots1[1]];
} else if (roots1[0] >= roots2[0] && roots1[1] <= roots2[1]) {
return [roots2[0], roots1[0], roots1[1], roots2[1]];
} else if (roots2[0] >= roots1[0] && roots2[1] <= roots1[1]) {
return [roots1[0], roots2[0], roots2[1], roots1[1]];
} else if (roots1[0] > roots2[0] && roots1[0] < roots2[1]) {
return [roots2[0], roots1[0], roots2[1], roots1[1]];
}
return [roots1[0], roots2[0], roots1[1], roots2[1]];
}
return roots1;
}
if (roots2.length !== 0) {
return roots2;
}
}
return [];
}
QuarticRealPolynomial.computeRealRoots = function(a3, b, c, d, e) {
if (typeof a3 !== "number") {
throw new DeveloperError_default("a is a required number.");
}
if (typeof b !== "number") {
throw new DeveloperError_default("b is a required number.");
}
if (typeof c !== "number") {
throw new DeveloperError_default("c is a required number.");
}
if (typeof d !== "number") {
throw new DeveloperError_default("d is a required number.");
}
if (typeof e !== "number") {
throw new DeveloperError_default("e is a required number.");
}
if (Math.abs(a3) < Math_default.EPSILON15) {
return CubicRealPolynomial_default.computeRealRoots(b, c, d, e);
}
const a32 = b / a3;
const a22 = c / a3;
const a1 = d / a3;
const a0 = e / a3;
let k = a32 < 0 ? 1 : 0;
k += a22 < 0 ? k + 1 : k;
k += a1 < 0 ? k + 1 : k;
k += a0 < 0 ? k + 1 : k;
switch (k) {
case 0:
return original(a32, a22, a1, a0);
case 1:
return neumark(a32, a22, a1, a0);
case 2:
return neumark(a32, a22, a1, a0);
case 3:
return original(a32, a22, a1, a0);
case 4:
return original(a32, a22, a1, a0);
case 5:
return neumark(a32, a22, a1, a0);
case 6:
return original(a32, a22, a1, a0);
case 7:
return original(a32, a22, a1, a0);
case 8:
return neumark(a32, a22, a1, a0);
case 9:
return original(a32, a22, a1, a0);
case 10:
return original(a32, a22, a1, a0);
case 11:
return neumark(a32, a22, a1, a0);
case 12:
return original(a32, a22, a1, a0);
case 13:
return original(a32, a22, a1, a0);
case 14:
return original(a32, a22, a1, a0);
case 15:
return original(a32, a22, a1, a0);
default:
return void 0;
}
};
var QuarticRealPolynomial_default = QuarticRealPolynomial;
// packages/engine/Source/Core/Ray.js
function Ray(origin, direction2) {
direction2 = Cartesian3_default.clone(defaultValue_default(direction2, Cartesian3_default.ZERO));
if (!Cartesian3_default.equals(direction2, Cartesian3_default.ZERO)) {
Cartesian3_default.normalize(direction2, direction2);
}
this.origin = Cartesian3_default.clone(defaultValue_default(origin, Cartesian3_default.ZERO));
this.direction = direction2;
}
Ray.clone = function(ray, result) {
if (!defined_default(ray)) {
return void 0;
}
if (!defined_default(result)) {
return new Ray(ray.origin, ray.direction);
}
result.origin = Cartesian3_default.clone(ray.origin);
result.direction = Cartesian3_default.clone(ray.direction);
return result;
};
Ray.getPoint = function(ray, t, result) {
Check_default.typeOf.object("ray", ray);
Check_default.typeOf.number("t", t);
if (!defined_default(result)) {
result = new Cartesian3_default();
}
result = Cartesian3_default.multiplyByScalar(ray.direction, t, result);
return Cartesian3_default.add(ray.origin, result, result);
};
var Ray_default = Ray;
// packages/engine/Source/Core/IntersectionTests.js
var IntersectionTests = {};
IntersectionTests.rayPlane = function(ray, plane, result) {
if (!defined_default(ray)) {
throw new DeveloperError_default("ray is required.");
}
if (!defined_default(plane)) {
throw new DeveloperError_default("plane is required.");
}
if (!defined_default(result)) {
result = new Cartesian3_default();
}
const origin = ray.origin;
const direction2 = ray.direction;
const normal2 = plane.normal;
const denominator = Cartesian3_default.dot(normal2, direction2);
if (Math.abs(denominator) < Math_default.EPSILON15) {
return void 0;
}
const t = (-plane.distance - Cartesian3_default.dot(normal2, origin)) / denominator;
if (t < 0) {
return void 0;
}
result = Cartesian3_default.multiplyByScalar(direction2, t, result);
return Cartesian3_default.add(origin, result, result);
};
var scratchEdge0 = new Cartesian3_default();
var scratchEdge1 = new Cartesian3_default();
var scratchPVec = new Cartesian3_default();
var scratchTVec = new Cartesian3_default();
var scratchQVec = new Cartesian3_default();
IntersectionTests.rayTriangleParametric = function(ray, p0, p1, p2, cullBackFaces) {
if (!defined_default(ray)) {
throw new DeveloperError_default("ray is required.");
}
if (!defined_default(p0)) {
throw new DeveloperError_default("p0 is required.");
}
if (!defined_default(p1)) {
throw new DeveloperError_default("p1 is required.");
}
if (!defined_default(p2)) {
throw new DeveloperError_default("p2 is required.");
}
cullBackFaces = defaultValue_default(cullBackFaces, false);
const origin = ray.origin;
const direction2 = ray.direction;
const edge0 = Cartesian3_default.subtract(p1, p0, scratchEdge0);
const edge1 = Cartesian3_default.subtract(p2, p0, scratchEdge1);
const p = Cartesian3_default.cross(direction2, edge1, scratchPVec);
const det = Cartesian3_default.dot(edge0, p);
let tvec;
let q;
let u3;
let v7;
let t;
if (cullBackFaces) {
if (det < Math_default.EPSILON6) {
return void 0;
}
tvec = Cartesian3_default.subtract(origin, p0, scratchTVec);
u3 = Cartesian3_default.dot(tvec, p);
if (u3 < 0 || u3 > det) {
return void 0;
}
q = Cartesian3_default.cross(tvec, edge0, scratchQVec);
v7 = Cartesian3_default.dot(direction2, q);
if (v7 < 0 || u3 + v7 > det) {
return void 0;
}
t = Cartesian3_default.dot(edge1, q) / det;
} else {
if (Math.abs(det) < Math_default.EPSILON6) {
return void 0;
}
const invDet = 1 / det;
tvec = Cartesian3_default.subtract(origin, p0, scratchTVec);
u3 = Cartesian3_default.dot(tvec, p) * invDet;
if (u3 < 0 || u3 > 1) {
return void 0;
}
q = Cartesian3_default.cross(tvec, edge0, scratchQVec);
v7 = Cartesian3_default.dot(direction2, q) * invDet;
if (v7 < 0 || u3 + v7 > 1) {
return void 0;
}
t = Cartesian3_default.dot(edge1, q) * invDet;
}
return t;
};
IntersectionTests.rayTriangle = function(ray, p0, p1, p2, cullBackFaces, result) {
const t = IntersectionTests.rayTriangleParametric(
ray,
p0,
p1,
p2,
cullBackFaces
);
if (!defined_default(t) || t < 0) {
return void 0;
}
if (!defined_default(result)) {
result = new Cartesian3_default();
}
Cartesian3_default.multiplyByScalar(ray.direction, t, result);
return Cartesian3_default.add(ray.origin, result, result);
};
var scratchLineSegmentTriangleRay = new Ray_default();
IntersectionTests.lineSegmentTriangle = function(v02, v13, p0, p1, p2, cullBackFaces, result) {
if (!defined_default(v02)) {
throw new DeveloperError_default("v0 is required.");
}
if (!defined_default(v13)) {
throw new DeveloperError_default("v1 is required.");
}
if (!defined_default(p0)) {
throw new DeveloperError_default("p0 is required.");
}
if (!defined_default(p1)) {
throw new DeveloperError_default("p1 is required.");
}
if (!defined_default(p2)) {
throw new DeveloperError_default("p2 is required.");
}
const ray = scratchLineSegmentTriangleRay;
Cartesian3_default.clone(v02, ray.origin);
Cartesian3_default.subtract(v13, v02, ray.direction);
Cartesian3_default.normalize(ray.direction, ray.direction);
const t = IntersectionTests.rayTriangleParametric(
ray,
p0,
p1,
p2,
cullBackFaces
);
if (!defined_default(t) || t < 0 || t > Cartesian3_default.distance(v02, v13)) {
return void 0;
}
if (!defined_default(result)) {
result = new Cartesian3_default();
}
Cartesian3_default.multiplyByScalar(ray.direction, t, result);
return Cartesian3_default.add(ray.origin, result, result);
};
function solveQuadratic(a3, b, c, result) {
const det = b * b - 4 * a3 * c;
if (det < 0) {
return void 0;
} else if (det > 0) {
const denom = 1 / (2 * a3);
const disc = Math.sqrt(det);
const root0 = (-b + disc) * denom;
const root1 = (-b - disc) * denom;
if (root0 < root1) {
result.root0 = root0;
result.root1 = root1;
} else {
result.root0 = root1;
result.root1 = root0;
}
return result;
}
const root = -b / (2 * a3);
if (root === 0) {
return void 0;
}
result.root0 = result.root1 = root;
return result;
}
var raySphereRoots = {
root0: 0,
root1: 0
};
function raySphere(ray, sphere, result) {
if (!defined_default(result)) {
result = new Interval_default();
}
const origin = ray.origin;
const direction2 = ray.direction;
const center = sphere.center;
const radiusSquared = sphere.radius * sphere.radius;
const diff = Cartesian3_default.subtract(origin, center, scratchPVec);
const a3 = Cartesian3_default.dot(direction2, direction2);
const b = 2 * Cartesian3_default.dot(direction2, diff);
const c = Cartesian3_default.magnitudeSquared(diff) - radiusSquared;
const roots = solveQuadratic(a3, b, c, raySphereRoots);
if (!defined_default(roots)) {
return void 0;
}
result.start = roots.root0;
result.stop = roots.root1;
return result;
}
IntersectionTests.raySphere = function(ray, sphere, result) {
if (!defined_default(ray)) {
throw new DeveloperError_default("ray is required.");
}
if (!defined_default(sphere)) {
throw new DeveloperError_default("sphere is required.");
}
result = raySphere(ray, sphere, result);
if (!defined_default(result) || result.stop < 0) {
return void 0;
}
result.start = Math.max(result.start, 0);
return result;
};
var scratchLineSegmentRay = new Ray_default();
IntersectionTests.lineSegmentSphere = function(p0, p1, sphere, result) {
if (!defined_default(p0)) {
throw new DeveloperError_default("p0 is required.");
}
if (!defined_default(p1)) {
throw new DeveloperError_default("p1 is required.");
}
if (!defined_default(sphere)) {
throw new DeveloperError_default("sphere is required.");
}
const ray = scratchLineSegmentRay;
Cartesian3_default.clone(p0, ray.origin);
const direction2 = Cartesian3_default.subtract(p1, p0, ray.direction);
const maxT = Cartesian3_default.magnitude(direction2);
Cartesian3_default.normalize(direction2, direction2);
result = raySphere(ray, sphere, result);
if (!defined_default(result) || result.stop < 0 || result.start > maxT) {
return void 0;
}
result.start = Math.max(result.start, 0);
result.stop = Math.min(result.stop, maxT);
return result;
};
var scratchQ = new Cartesian3_default();
var scratchW = new Cartesian3_default();
IntersectionTests.rayEllipsoid = function(ray, ellipsoid) {
if (!defined_default(ray)) {
throw new DeveloperError_default("ray is required.");
}
if (!defined_default(ellipsoid)) {
throw new DeveloperError_default("ellipsoid is required.");
}
const inverseRadii = ellipsoid.oneOverRadii;
const q = Cartesian3_default.multiplyComponents(inverseRadii, ray.origin, scratchQ);
const w = Cartesian3_default.multiplyComponents(
inverseRadii,
ray.direction,
scratchW
);
const q22 = Cartesian3_default.magnitudeSquared(q);
const qw = Cartesian3_default.dot(q, w);
let difference, w2, product, discriminant, temp;
if (q22 > 1) {
if (qw >= 0) {
return void 0;
}
const qw2 = qw * qw;
difference = q22 - 1;
w2 = Cartesian3_default.magnitudeSquared(w);
product = w2 * difference;
if (qw2 < product) {
return void 0;
} else if (qw2 > product) {
discriminant = qw * qw - product;
temp = -qw + Math.sqrt(discriminant);
const root0 = temp / w2;
const root1 = difference / temp;
if (root0 < root1) {
return new Interval_default(root0, root1);
}
return {
start: root1,
stop: root0
};
}
const root = Math.sqrt(difference / w2);
return new Interval_default(root, root);
} else if (q22 < 1) {
difference = q22 - 1;
w2 = Cartesian3_default.magnitudeSquared(w);
product = w2 * difference;
discriminant = qw * qw - product;
temp = -qw + Math.sqrt(discriminant);
return new Interval_default(0, temp / w2);
}
if (qw < 0) {
w2 = Cartesian3_default.magnitudeSquared(w);
return new Interval_default(0, -qw / w2);
}
return void 0;
};
function addWithCancellationCheck2(left, right, tolerance) {
const difference = left + right;
if (Math_default.sign(left) !== Math_default.sign(right) && Math.abs(difference / Math.max(Math.abs(left), Math.abs(right))) < tolerance) {
return 0;
}
return difference;
}
function quadraticVectorExpression(A, b, c, x, w) {
const xSquared = x * x;
const wSquared = w * w;
const l2 = (A[Matrix3_default.COLUMN1ROW1] - A[Matrix3_default.COLUMN2ROW2]) * wSquared;
const l1 = w * (x * addWithCancellationCheck2(
A[Matrix3_default.COLUMN1ROW0],
A[Matrix3_default.COLUMN0ROW1],
Math_default.EPSILON15
) + b.y);
const l0 = A[Matrix3_default.COLUMN0ROW0] * xSquared + A[Matrix3_default.COLUMN2ROW2] * wSquared + x * b.x + c;
const r1 = wSquared * addWithCancellationCheck2(
A[Matrix3_default.COLUMN2ROW1],
A[Matrix3_default.COLUMN1ROW2],
Math_default.EPSILON15
);
const r0 = w * (x * addWithCancellationCheck2(A[Matrix3_default.COLUMN2ROW0], A[Matrix3_default.COLUMN0ROW2]) + b.z);
let cosines;
const solutions = [];
if (r0 === 0 && r1 === 0) {
cosines = QuadraticRealPolynomial_default.computeRealRoots(l2, l1, l0);
if (cosines.length === 0) {
return solutions;
}
const cosine0 = cosines[0];
const sine0 = Math.sqrt(Math.max(1 - cosine0 * cosine0, 0));
solutions.push(new Cartesian3_default(x, w * cosine0, w * -sine0));
solutions.push(new Cartesian3_default(x, w * cosine0, w * sine0));
if (cosines.length === 2) {
const cosine1 = cosines[1];
const sine1 = Math.sqrt(Math.max(1 - cosine1 * cosine1, 0));
solutions.push(new Cartesian3_default(x, w * cosine1, w * -sine1));
solutions.push(new Cartesian3_default(x, w * cosine1, w * sine1));
}
return solutions;
}
const r0Squared = r0 * r0;
const r1Squared = r1 * r1;
const l2Squared = l2 * l2;
const r0r1 = r0 * r1;
const c42 = l2Squared + r1Squared;
const c33 = 2 * (l1 * l2 + r0r1);
const c22 = 2 * l0 * l2 + l1 * l1 - r1Squared + r0Squared;
const c14 = 2 * (l0 * l1 - r0r1);
const c0 = l0 * l0 - r0Squared;
if (c42 === 0 && c33 === 0 && c22 === 0 && c14 === 0) {
return solutions;
}
cosines = QuarticRealPolynomial_default.computeRealRoots(c42, c33, c22, c14, c0);
const length3 = cosines.length;
if (length3 === 0) {
return solutions;
}
for (let i = 0; i < length3; ++i) {
const cosine = cosines[i];
const cosineSquared = cosine * cosine;
const sineSquared = Math.max(1 - cosineSquared, 0);
const sine = Math.sqrt(sineSquared);
let left;
if (Math_default.sign(l2) === Math_default.sign(l0)) {
left = addWithCancellationCheck2(
l2 * cosineSquared + l0,
l1 * cosine,
Math_default.EPSILON12
);
} else if (Math_default.sign(l0) === Math_default.sign(l1 * cosine)) {
left = addWithCancellationCheck2(
l2 * cosineSquared,
l1 * cosine + l0,
Math_default.EPSILON12
);
} else {
left = addWithCancellationCheck2(
l2 * cosineSquared + l1 * cosine,
l0,
Math_default.EPSILON12
);
}
const right = addWithCancellationCheck2(
r1 * cosine,
r0,
Math_default.EPSILON15
);
const product = left * right;
if (product < 0) {
solutions.push(new Cartesian3_default(x, w * cosine, w * sine));
} else if (product > 0) {
solutions.push(new Cartesian3_default(x, w * cosine, w * -sine));
} else if (sine !== 0) {
solutions.push(new Cartesian3_default(x, w * cosine, w * -sine));
solutions.push(new Cartesian3_default(x, w * cosine, w * sine));
++i;
} else {
solutions.push(new Cartesian3_default(x, w * cosine, w * sine));
}
}
return solutions;
}
var firstAxisScratch = new Cartesian3_default();
var secondAxisScratch = new Cartesian3_default();
var thirdAxisScratch = new Cartesian3_default();
var referenceScratch = new Cartesian3_default();
var bCart = new Cartesian3_default();
var bScratch = new Matrix3_default();
var btScratch = new Matrix3_default();
var diScratch = new Matrix3_default();
var dScratch = new Matrix3_default();
var cScratch = new Matrix3_default();
var tempMatrix = new Matrix3_default();
var aScratch = new Matrix3_default();
var sScratch = new Cartesian3_default();
var closestScratch = new Cartesian3_default();
var surfPointScratch = new Cartographic_default();
IntersectionTests.grazingAltitudeLocation = function(ray, ellipsoid) {
if (!defined_default(ray)) {
throw new DeveloperError_default("ray is required.");
}
if (!defined_default(ellipsoid)) {
throw new DeveloperError_default("ellipsoid is required.");
}
const position = ray.origin;
const direction2 = ray.direction;
if (!Cartesian3_default.equals(position, Cartesian3_default.ZERO)) {
const normal2 = ellipsoid.geodeticSurfaceNormal(position, firstAxisScratch);
if (Cartesian3_default.dot(direction2, normal2) >= 0) {
return position;
}
}
const intersects = defined_default(this.rayEllipsoid(ray, ellipsoid));
const f = ellipsoid.transformPositionToScaledSpace(
direction2,
firstAxisScratch
);
const firstAxis = Cartesian3_default.normalize(f, f);
const reference = Cartesian3_default.mostOrthogonalAxis(f, referenceScratch);
const secondAxis = Cartesian3_default.normalize(
Cartesian3_default.cross(reference, firstAxis, secondAxisScratch),
secondAxisScratch
);
const thirdAxis = Cartesian3_default.normalize(
Cartesian3_default.cross(firstAxis, secondAxis, thirdAxisScratch),
thirdAxisScratch
);
const B = bScratch;
B[0] = firstAxis.x;
B[1] = firstAxis.y;
B[2] = firstAxis.z;
B[3] = secondAxis.x;
B[4] = secondAxis.y;
B[5] = secondAxis.z;
B[6] = thirdAxis.x;
B[7] = thirdAxis.y;
B[8] = thirdAxis.z;
const B_T = Matrix3_default.transpose(B, btScratch);
const D_I = Matrix3_default.fromScale(ellipsoid.radii, diScratch);
const D = Matrix3_default.fromScale(ellipsoid.oneOverRadii, dScratch);
const C = cScratch;
C[0] = 0;
C[1] = -direction2.z;
C[2] = direction2.y;
C[3] = direction2.z;
C[4] = 0;
C[5] = -direction2.x;
C[6] = -direction2.y;
C[7] = direction2.x;
C[8] = 0;
const temp = Matrix3_default.multiply(
Matrix3_default.multiply(B_T, D, tempMatrix),
C,
tempMatrix
);
const A = Matrix3_default.multiply(
Matrix3_default.multiply(temp, D_I, aScratch),
B,
aScratch
);
const b = Matrix3_default.multiplyByVector(temp, position, bCart);
const solutions = quadraticVectorExpression(
A,
Cartesian3_default.negate(b, firstAxisScratch),
0,
0,
1
);
let s;
let altitude;
const length3 = solutions.length;
if (length3 > 0) {
let closest = Cartesian3_default.clone(Cartesian3_default.ZERO, closestScratch);
let maximumValue = Number.NEGATIVE_INFINITY;
for (let i = 0; i < length3; ++i) {
s = Matrix3_default.multiplyByVector(
D_I,
Matrix3_default.multiplyByVector(B, solutions[i], sScratch),
sScratch
);
const v7 = Cartesian3_default.normalize(
Cartesian3_default.subtract(s, position, referenceScratch),
referenceScratch
);
const dotProduct = Cartesian3_default.dot(v7, direction2);
if (dotProduct > maximumValue) {
maximumValue = dotProduct;
closest = Cartesian3_default.clone(s, closest);
}
}
const surfacePoint = ellipsoid.cartesianToCartographic(
closest,
surfPointScratch
);
maximumValue = Math_default.clamp(maximumValue, 0, 1);
altitude = Cartesian3_default.magnitude(
Cartesian3_default.subtract(closest, position, referenceScratch)
) * Math.sqrt(1 - maximumValue * maximumValue);
altitude = intersects ? -altitude : altitude;
surfacePoint.height = altitude;
return ellipsoid.cartographicToCartesian(surfacePoint, new Cartesian3_default());
}
return void 0;
};
var lineSegmentPlaneDifference = new Cartesian3_default();
IntersectionTests.lineSegmentPlane = function(endPoint0, endPoint1, plane, result) {
if (!defined_default(endPoint0)) {
throw new DeveloperError_default("endPoint0 is required.");
}
if (!defined_default(endPoint1)) {
throw new DeveloperError_default("endPoint1 is required.");
}
if (!defined_default(plane)) {
throw new DeveloperError_default("plane is required.");
}
if (!defined_default(result)) {
result = new Cartesian3_default();
}
const difference = Cartesian3_default.subtract(
endPoint1,
endPoint0,
lineSegmentPlaneDifference
);
const normal2 = plane.normal;
const nDotDiff = Cartesian3_default.dot(normal2, difference);
if (Math.abs(nDotDiff) < Math_default.EPSILON6) {
return void 0;
}
const nDotP0 = Cartesian3_default.dot(normal2, endPoint0);
const t = -(plane.distance + nDotP0) / nDotDiff;
if (t < 0 || t > 1) {
return void 0;
}
Cartesian3_default.multiplyByScalar(difference, t, result);
Cartesian3_default.add(endPoint0, result, result);
return result;
};
IntersectionTests.trianglePlaneIntersection = function(p0, p1, p2, plane) {
if (!defined_default(p0) || !defined_default(p1) || !defined_default(p2) || !defined_default(plane)) {
throw new DeveloperError_default("p0, p1, p2, and plane are required.");
}
const planeNormal = plane.normal;
const planeD = plane.distance;
const p0Behind = Cartesian3_default.dot(planeNormal, p0) + planeD < 0;
const p1Behind = Cartesian3_default.dot(planeNormal, p1) + planeD < 0;
const p2Behind = Cartesian3_default.dot(planeNormal, p2) + planeD < 0;
let numBehind = 0;
numBehind += p0Behind ? 1 : 0;
numBehind += p1Behind ? 1 : 0;
numBehind += p2Behind ? 1 : 0;
let u12, u22;
if (numBehind === 1 || numBehind === 2) {
u12 = new Cartesian3_default();
u22 = new Cartesian3_default();
}
if (numBehind === 1) {
if (p0Behind) {
IntersectionTests.lineSegmentPlane(p0, p1, plane, u12);
IntersectionTests.lineSegmentPlane(p0, p2, plane, u22);
return {
positions: [p0, p1, p2, u12, u22],
indices: [
// Behind
0,
3,
4,
// In front
1,
2,
4,
1,
4,
3
]
};
} else if (p1Behind) {
IntersectionTests.lineSegmentPlane(p1, p2, plane, u12);
IntersectionTests.lineSegmentPlane(p1, p0, plane, u22);
return {
positions: [p0, p1, p2, u12, u22],
indices: [
// Behind
1,
3,
4,
// In front
2,
0,
4,
2,
4,
3
]
};
} else if (p2Behind) {
IntersectionTests.lineSegmentPlane(p2, p0, plane, u12);
IntersectionTests.lineSegmentPlane(p2, p1, plane, u22);
return {
positions: [p0, p1, p2, u12, u22],
indices: [
// Behind
2,
3,
4,
// In front
0,
1,
4,
0,
4,
3
]
};
}
} else if (numBehind === 2) {
if (!p0Behind) {
IntersectionTests.lineSegmentPlane(p1, p0, plane, u12);
IntersectionTests.lineSegmentPlane(p2, p0, plane, u22);
return {
positions: [p0, p1, p2, u12, u22],
indices: [
// Behind
1,
2,
4,
1,
4,
3,
// In front
0,
3,
4
]
};
} else if (!p1Behind) {
IntersectionTests.lineSegmentPlane(p2, p1, plane, u12);
IntersectionTests.lineSegmentPlane(p0, p1, plane, u22);
return {
positions: [p0, p1, p2, u12, u22],
indices: [
// Behind
2,
0,
4,
2,
4,
3,
// In front
1,
3,
4
]
};
} else if (!p2Behind) {
IntersectionTests.lineSegmentPlane(p0, p2, plane, u12);
IntersectionTests.lineSegmentPlane(p1, p2, plane, u22);
return {
positions: [p0, p1, p2, u12, u22],
indices: [
// Behind
0,
1,
4,
0,
4,
3,
// In front
2,
3,
4
]
};
}
}
return void 0;
};
var IntersectionTests_default = IntersectionTests;
// packages/engine/Source/Core/EllipsoidTangentPlane.js
var scratchCart4 = new Cartesian4_default();
function EllipsoidTangentPlane(origin, ellipsoid) {
Check_default.defined("origin", origin);
ellipsoid = defaultValue_default(ellipsoid, Ellipsoid_default.WGS84);
origin = ellipsoid.scaleToGeodeticSurface(origin);
if (!defined_default(origin)) {
throw new DeveloperError_default(
"origin must not be at the center of the ellipsoid."
);
}
const eastNorthUp = Transforms_default.eastNorthUpToFixedFrame(origin, ellipsoid);
this._ellipsoid = ellipsoid;
this._origin = origin;
this._xAxis = Cartesian3_default.fromCartesian4(
Matrix4_default.getColumn(eastNorthUp, 0, scratchCart4)
);
this._yAxis = Cartesian3_default.fromCartesian4(
Matrix4_default.getColumn(eastNorthUp, 1, scratchCart4)
);
const normal2 = Cartesian3_default.fromCartesian4(
Matrix4_default.getColumn(eastNorthUp, 2, scratchCart4)
);
this._plane = Plane_default.fromPointNormal(origin, normal2);
}
Object.defineProperties(EllipsoidTangentPlane.prototype, {
/**
* Gets the ellipsoid.
* @memberof EllipsoidTangentPlane.prototype
* @type {Ellipsoid}
*/
ellipsoid: {
get: function() {
return this._ellipsoid;
}
},
/**
* Gets the origin.
* @memberof EllipsoidTangentPlane.prototype
* @type {Cartesian3}
*/
origin: {
get: function() {
return this._origin;
}
},
/**
* Gets the plane which is tangent to the ellipsoid.
* @memberof EllipsoidTangentPlane.prototype
* @readonly
* @type {Plane}
*/
plane: {
get: function() {
return this._plane;
}
},
/**
* Gets the local X-axis (east) of the tangent plane.
* @memberof EllipsoidTangentPlane.prototype
* @readonly
* @type {Cartesian3}
*/
xAxis: {
get: function() {
return this._xAxis;
}
},
/**
* Gets the local Y-axis (north) of the tangent plane.
* @memberof EllipsoidTangentPlane.prototype
* @readonly
* @type {Cartesian3}
*/
yAxis: {
get: function() {
return this._yAxis;
}
},
/**
* Gets the local Z-axis (up) of the tangent plane.
* @memberof EllipsoidTangentPlane.prototype
* @readonly
* @type {Cartesian3}
*/
zAxis: {
get: function() {
return this._plane.normal;
}
}
});
var tmp = new AxisAlignedBoundingBox_default();
EllipsoidTangentPlane.fromPoints = function(cartesians, ellipsoid) {
Check_default.defined("cartesians", cartesians);
const box = AxisAlignedBoundingBox_default.fromPoints(cartesians, tmp);
return new EllipsoidTangentPlane(box.center, ellipsoid);
};
var scratchProjectPointOntoPlaneRay = new Ray_default();
var scratchProjectPointOntoPlaneCartesian3 = new Cartesian3_default();
EllipsoidTangentPlane.prototype.projectPointOntoPlane = function(cartesian11, result) {
Check_default.defined("cartesian", cartesian11);
const ray = scratchProjectPointOntoPlaneRay;
ray.origin = cartesian11;
Cartesian3_default.normalize(cartesian11, ray.direction);
let intersectionPoint = IntersectionTests_default.rayPlane(
ray,
this._plane,
scratchProjectPointOntoPlaneCartesian3
);
if (!defined_default(intersectionPoint)) {
Cartesian3_default.negate(ray.direction, ray.direction);
intersectionPoint = IntersectionTests_default.rayPlane(
ray,
this._plane,
scratchProjectPointOntoPlaneCartesian3
);
}
if (defined_default(intersectionPoint)) {
const v7 = Cartesian3_default.subtract(
intersectionPoint,
this._origin,
intersectionPoint
);
const x = Cartesian3_default.dot(this._xAxis, v7);
const y = Cartesian3_default.dot(this._yAxis, v7);
if (!defined_default(result)) {
return new Cartesian2_default(x, y);
}
result.x = x;
result.y = y;
return result;
}
return void 0;
};
EllipsoidTangentPlane.prototype.projectPointsOntoPlane = function(cartesians, result) {
Check_default.defined("cartesians", cartesians);
if (!defined_default(result)) {
result = [];
}
let count = 0;
const length3 = cartesians.length;
for (let i = 0; i < length3; i++) {
const p = this.projectPointOntoPlane(cartesians[i], result[count]);
if (defined_default(p)) {
result[count] = p;
count++;
}
}
result.length = count;
return result;
};
EllipsoidTangentPlane.prototype.projectPointToNearestOnPlane = function(cartesian11, result) {
Check_default.defined("cartesian", cartesian11);
if (!defined_default(result)) {
result = new Cartesian2_default();
}
const ray = scratchProjectPointOntoPlaneRay;
ray.origin = cartesian11;
Cartesian3_default.clone(this._plane.normal, ray.direction);
let intersectionPoint = IntersectionTests_default.rayPlane(
ray,
this._plane,
scratchProjectPointOntoPlaneCartesian3
);
if (!defined_default(intersectionPoint)) {
Cartesian3_default.negate(ray.direction, ray.direction);
intersectionPoint = IntersectionTests_default.rayPlane(
ray,
this._plane,
scratchProjectPointOntoPlaneCartesian3
);
}
const v7 = Cartesian3_default.subtract(
intersectionPoint,
this._origin,
intersectionPoint
);
const x = Cartesian3_default.dot(this._xAxis, v7);
const y = Cartesian3_default.dot(this._yAxis, v7);
result.x = x;
result.y = y;
return result;
};
EllipsoidTangentPlane.prototype.projectPointsToNearestOnPlane = function(cartesians, result) {
Check_default.defined("cartesians", cartesians);
if (!defined_default(result)) {
result = [];
}
const length3 = cartesians.length;
result.length = length3;
for (let i = 0; i < length3; i++) {
result[i] = this.projectPointToNearestOnPlane(cartesians[i], result[i]);
}
return result;
};
var projectPointsOntoEllipsoidScratch = new Cartesian3_default();
EllipsoidTangentPlane.prototype.projectPointOntoEllipsoid = function(cartesian11, result) {
Check_default.defined("cartesian", cartesian11);
if (!defined_default(result)) {
result = new Cartesian3_default();
}
const ellipsoid = this._ellipsoid;
const origin = this._origin;
const xAxis = this._xAxis;
const yAxis = this._yAxis;
const tmp2 = projectPointsOntoEllipsoidScratch;
Cartesian3_default.multiplyByScalar(xAxis, cartesian11.x, tmp2);
result = Cartesian3_default.add(origin, tmp2, result);
Cartesian3_default.multiplyByScalar(yAxis, cartesian11.y, tmp2);
Cartesian3_default.add(result, tmp2, result);
ellipsoid.scaleToGeocentricSurface(result, result);
return result;
};
EllipsoidTangentPlane.prototype.projectPointsOntoEllipsoid = function(cartesians, result) {
Check_default.defined("cartesians", cartesians);
const length3 = cartesians.length;
if (!defined_default(result)) {
result = new Array(length3);
} else {
result.length = length3;
}
for (let i = 0; i < length3; ++i) {
result[i] = this.projectPointOntoEllipsoid(cartesians[i], result[i]);
}
return result;
};
var EllipsoidTangentPlane_default = EllipsoidTangentPlane;
// packages/engine/Source/Core/OrientedBoundingBox.js
function OrientedBoundingBox(center, halfAxes) {
this.center = Cartesian3_default.clone(defaultValue_default(center, Cartesian3_default.ZERO));
this.halfAxes = Matrix3_default.clone(defaultValue_default(halfAxes, Matrix3_default.ZERO));
}
OrientedBoundingBox.packedLength = Cartesian3_default.packedLength + Matrix3_default.packedLength;
OrientedBoundingBox.pack = function(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
Cartesian3_default.pack(value.center, array, startingIndex);
Matrix3_default.pack(value.halfAxes, array, startingIndex + Cartesian3_default.packedLength);
return array;
};
OrientedBoundingBox.unpack = function(array, startingIndex, result) {
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
if (!defined_default(result)) {
result = new OrientedBoundingBox();
}
Cartesian3_default.unpack(array, startingIndex, result.center);
Matrix3_default.unpack(
array,
startingIndex + Cartesian3_default.packedLength,
result.halfAxes
);
return result;
};
var scratchCartesian1 = new Cartesian3_default();
var scratchCartesian2 = new Cartesian3_default();
var scratchCartesian32 = new Cartesian3_default();
var scratchCartesian4 = new Cartesian3_default();
var scratchCartesian5 = new Cartesian3_default();
var scratchCartesian6 = new Cartesian3_default();
var scratchCovarianceResult = new Matrix3_default();
var scratchEigenResult = {
unitary: new Matrix3_default(),
diagonal: new Matrix3_default()
};
OrientedBoundingBox.fromPoints = function(positions, result) {
if (!defined_default(result)) {
result = new OrientedBoundingBox();
}
if (!defined_default(positions) || positions.length === 0) {
result.halfAxes = Matrix3_default.ZERO;
result.center = Cartesian3_default.ZERO;
return result;
}
let i;
const length3 = positions.length;
const meanPoint = Cartesian3_default.clone(positions[0], scratchCartesian1);
for (i = 1; i < length3; i++) {
Cartesian3_default.add(meanPoint, positions[i], meanPoint);
}
const invLength = 1 / length3;
Cartesian3_default.multiplyByScalar(meanPoint, invLength, meanPoint);
let exx = 0;
let exy = 0;
let exz = 0;
let eyy = 0;
let eyz = 0;
let ezz = 0;
let p;
for (i = 0; i < length3; i++) {
p = Cartesian3_default.subtract(positions[i], meanPoint, scratchCartesian2);
exx += p.x * p.x;
exy += p.x * p.y;
exz += p.x * p.z;
eyy += p.y * p.y;
eyz += p.y * p.z;
ezz += p.z * p.z;
}
exx *= invLength;
exy *= invLength;
exz *= invLength;
eyy *= invLength;
eyz *= invLength;
ezz *= invLength;
const covarianceMatrix = scratchCovarianceResult;
covarianceMatrix[0] = exx;
covarianceMatrix[1] = exy;
covarianceMatrix[2] = exz;
covarianceMatrix[3] = exy;
covarianceMatrix[4] = eyy;
covarianceMatrix[5] = eyz;
covarianceMatrix[6] = exz;
covarianceMatrix[7] = eyz;
covarianceMatrix[8] = ezz;
const eigenDecomposition = Matrix3_default.computeEigenDecomposition(
covarianceMatrix,
scratchEigenResult
);
const rotation = Matrix3_default.clone(eigenDecomposition.unitary, result.halfAxes);
let v13 = Matrix3_default.getColumn(rotation, 0, scratchCartesian4);
let v23 = Matrix3_default.getColumn(rotation, 1, scratchCartesian5);
let v32 = Matrix3_default.getColumn(rotation, 2, scratchCartesian6);
let u12 = -Number.MAX_VALUE;
let u22 = -Number.MAX_VALUE;
let u3 = -Number.MAX_VALUE;
let l1 = Number.MAX_VALUE;
let l2 = Number.MAX_VALUE;
let l3 = Number.MAX_VALUE;
for (i = 0; i < length3; i++) {
p = positions[i];
u12 = Math.max(Cartesian3_default.dot(v13, p), u12);
u22 = Math.max(Cartesian3_default.dot(v23, p), u22);
u3 = Math.max(Cartesian3_default.dot(v32, p), u3);
l1 = Math.min(Cartesian3_default.dot(v13, p), l1);
l2 = Math.min(Cartesian3_default.dot(v23, p), l2);
l3 = Math.min(Cartesian3_default.dot(v32, p), l3);
}
v13 = Cartesian3_default.multiplyByScalar(v13, 0.5 * (l1 + u12), v13);
v23 = Cartesian3_default.multiplyByScalar(v23, 0.5 * (l2 + u22), v23);
v32 = Cartesian3_default.multiplyByScalar(v32, 0.5 * (l3 + u3), v32);
const center = Cartesian3_default.add(v13, v23, result.center);
Cartesian3_default.add(center, v32, center);
const scale = scratchCartesian32;
scale.x = u12 - l1;
scale.y = u22 - l2;
scale.z = u3 - l3;
Cartesian3_default.multiplyByScalar(scale, 0.5, scale);
Matrix3_default.multiplyByScale(result.halfAxes, scale, result.halfAxes);
return result;
};
var scratchOffset = new Cartesian3_default();
var scratchScale2 = new Cartesian3_default();
function fromPlaneExtents(planeOrigin, planeXAxis, planeYAxis, planeZAxis, minimumX, maximumX, minimumY, maximumY, minimumZ, maximumZ, result) {
if (!defined_default(minimumX) || !defined_default(maximumX) || !defined_default(minimumY) || !defined_default(maximumY) || !defined_default(minimumZ) || !defined_default(maximumZ)) {
throw new DeveloperError_default(
"all extents (minimum/maximum X/Y/Z) are required."
);
}
if (!defined_default(result)) {
result = new OrientedBoundingBox();
}
const halfAxes = result.halfAxes;
Matrix3_default.setColumn(halfAxes, 0, planeXAxis, halfAxes);
Matrix3_default.setColumn(halfAxes, 1, planeYAxis, halfAxes);
Matrix3_default.setColumn(halfAxes, 2, planeZAxis, halfAxes);
let centerOffset = scratchOffset;
centerOffset.x = (minimumX + maximumX) / 2;
centerOffset.y = (minimumY + maximumY) / 2;
centerOffset.z = (minimumZ + maximumZ) / 2;
const scale = scratchScale2;
scale.x = (maximumX - minimumX) / 2;
scale.y = (maximumY - minimumY) / 2;
scale.z = (maximumZ - minimumZ) / 2;
const center = result.center;
centerOffset = Matrix3_default.multiplyByVector(halfAxes, centerOffset, centerOffset);
Cartesian3_default.add(planeOrigin, centerOffset, center);
Matrix3_default.multiplyByScale(halfAxes, scale, halfAxes);
return result;
}
var scratchRectangleCenterCartographic = new Cartographic_default();
var scratchRectangleCenter = new Cartesian3_default();
var scratchPerimeterCartographicNC = new Cartographic_default();
var scratchPerimeterCartographicNW = new Cartographic_default();
var scratchPerimeterCartographicCW = new Cartographic_default();
var scratchPerimeterCartographicSW = new Cartographic_default();
var scratchPerimeterCartographicSC = new Cartographic_default();
var scratchPerimeterCartesianNC = new Cartesian3_default();
var scratchPerimeterCartesianNW = new Cartesian3_default();
var scratchPerimeterCartesianCW = new Cartesian3_default();
var scratchPerimeterCartesianSW = new Cartesian3_default();
var scratchPerimeterCartesianSC = new Cartesian3_default();
var scratchPerimeterProjectedNC = new Cartesian2_default();
var scratchPerimeterProjectedNW = new Cartesian2_default();
var scratchPerimeterProjectedCW = new Cartesian2_default();
var scratchPerimeterProjectedSW = new Cartesian2_default();
var scratchPerimeterProjectedSC = new Cartesian2_default();
var scratchPlaneOrigin = new Cartesian3_default();
var scratchPlaneNormal2 = new Cartesian3_default();
var scratchPlaneXAxis = new Cartesian3_default();
var scratchHorizonCartesian = new Cartesian3_default();
var scratchHorizonProjected = new Cartesian2_default();
var scratchMaxY = new Cartesian3_default();
var scratchMinY = new Cartesian3_default();
var scratchZ = new Cartesian3_default();
var scratchPlane2 = new Plane_default(Cartesian3_default.UNIT_X, 0);
OrientedBoundingBox.fromRectangle = function(rectangle, minimumHeight, maximumHeight, ellipsoid, result) {
if (!defined_default(rectangle)) {
throw new DeveloperError_default("rectangle is required");
}
if (rectangle.width < 0 || rectangle.width > Math_default.TWO_PI) {
throw new DeveloperError_default("Rectangle width must be between 0 and 2 * pi");
}
if (rectangle.height < 0 || rectangle.height > Math_default.PI) {
throw new DeveloperError_default("Rectangle height must be between 0 and pi");
}
if (defined_default(ellipsoid) && !Math_default.equalsEpsilon(
ellipsoid.radii.x,
ellipsoid.radii.y,
Math_default.EPSILON15
)) {
throw new DeveloperError_default(
"Ellipsoid must be an ellipsoid of revolution (radii.x == radii.y)"
);
}
minimumHeight = defaultValue_default(minimumHeight, 0);
maximumHeight = defaultValue_default(maximumHeight, 0);
ellipsoid = defaultValue_default(ellipsoid, Ellipsoid_default.WGS84);
let minX, maxX, minY, maxY, minZ, maxZ, plane;
if (rectangle.width <= Math_default.PI) {
const tangentPointCartographic = Rectangle_default.center(
rectangle,
scratchRectangleCenterCartographic
);
const tangentPoint = ellipsoid.cartographicToCartesian(
tangentPointCartographic,
scratchRectangleCenter
);
const tangentPlane = new EllipsoidTangentPlane_default(tangentPoint, ellipsoid);
plane = tangentPlane.plane;
const lonCenter = tangentPointCartographic.longitude;
const latCenter = rectangle.south < 0 && rectangle.north > 0 ? 0 : tangentPointCartographic.latitude;
const perimeterCartographicNC = Cartographic_default.fromRadians(
lonCenter,
rectangle.north,
maximumHeight,
scratchPerimeterCartographicNC
);
const perimeterCartographicNW = Cartographic_default.fromRadians(
rectangle.west,
rectangle.north,
maximumHeight,
scratchPerimeterCartographicNW
);
const perimeterCartographicCW = Cartographic_default.fromRadians(
rectangle.west,
latCenter,
maximumHeight,
scratchPerimeterCartographicCW
);
const perimeterCartographicSW = Cartographic_default.fromRadians(
rectangle.west,
rectangle.south,
maximumHeight,
scratchPerimeterCartographicSW
);
const perimeterCartographicSC = Cartographic_default.fromRadians(
lonCenter,
rectangle.south,
maximumHeight,
scratchPerimeterCartographicSC
);
const perimeterCartesianNC = ellipsoid.cartographicToCartesian(
perimeterCartographicNC,
scratchPerimeterCartesianNC
);
let perimeterCartesianNW = ellipsoid.cartographicToCartesian(
perimeterCartographicNW,
scratchPerimeterCartesianNW
);
const perimeterCartesianCW = ellipsoid.cartographicToCartesian(
perimeterCartographicCW,
scratchPerimeterCartesianCW
);
let perimeterCartesianSW = ellipsoid.cartographicToCartesian(
perimeterCartographicSW,
scratchPerimeterCartesianSW
);
const perimeterCartesianSC = ellipsoid.cartographicToCartesian(
perimeterCartographicSC,
scratchPerimeterCartesianSC
);
const perimeterProjectedNC = tangentPlane.projectPointToNearestOnPlane(
perimeterCartesianNC,
scratchPerimeterProjectedNC
);
const perimeterProjectedNW = tangentPlane.projectPointToNearestOnPlane(
perimeterCartesianNW,
scratchPerimeterProjectedNW
);
const perimeterProjectedCW = tangentPlane.projectPointToNearestOnPlane(
perimeterCartesianCW,
scratchPerimeterProjectedCW
);
const perimeterProjectedSW = tangentPlane.projectPointToNearestOnPlane(
perimeterCartesianSW,
scratchPerimeterProjectedSW
);
const perimeterProjectedSC = tangentPlane.projectPointToNearestOnPlane(
perimeterCartesianSC,
scratchPerimeterProjectedSC
);
minX = Math.min(
perimeterProjectedNW.x,
perimeterProjectedCW.x,
perimeterProjectedSW.x
);
maxX = -minX;
maxY = Math.max(perimeterProjectedNW.y, perimeterProjectedNC.y);
minY = Math.min(perimeterProjectedSW.y, perimeterProjectedSC.y);
perimeterCartographicNW.height = perimeterCartographicSW.height = minimumHeight;
perimeterCartesianNW = ellipsoid.cartographicToCartesian(
perimeterCartographicNW,
scratchPerimeterCartesianNW
);
perimeterCartesianSW = ellipsoid.cartographicToCartesian(
perimeterCartographicSW,
scratchPerimeterCartesianSW
);
minZ = Math.min(
Plane_default.getPointDistance(plane, perimeterCartesianNW),
Plane_default.getPointDistance(plane, perimeterCartesianSW)
);
maxZ = maximumHeight;
return fromPlaneExtents(
tangentPlane.origin,
tangentPlane.xAxis,
tangentPlane.yAxis,
tangentPlane.zAxis,
minX,
maxX,
minY,
maxY,
minZ,
maxZ,
result
);
}
const fullyAboveEquator = rectangle.south > 0;
const fullyBelowEquator = rectangle.north < 0;
const latitudeNearestToEquator = fullyAboveEquator ? rectangle.south : fullyBelowEquator ? rectangle.north : 0;
const centerLongitude = Rectangle_default.center(
rectangle,
scratchRectangleCenterCartographic
).longitude;
const planeOrigin = Cartesian3_default.fromRadians(
centerLongitude,
latitudeNearestToEquator,
maximumHeight,
ellipsoid,
scratchPlaneOrigin
);
planeOrigin.z = 0;
const isPole = Math.abs(planeOrigin.x) < Math_default.EPSILON10 && Math.abs(planeOrigin.y) < Math_default.EPSILON10;
const planeNormal = !isPole ? Cartesian3_default.normalize(planeOrigin, scratchPlaneNormal2) : Cartesian3_default.UNIT_X;
const planeYAxis = Cartesian3_default.UNIT_Z;
const planeXAxis = Cartesian3_default.cross(
planeNormal,
planeYAxis,
scratchPlaneXAxis
);
plane = Plane_default.fromPointNormal(planeOrigin, planeNormal, scratchPlane2);
const horizonCartesian = Cartesian3_default.fromRadians(
centerLongitude + Math_default.PI_OVER_TWO,
latitudeNearestToEquator,
maximumHeight,
ellipsoid,
scratchHorizonCartesian
);
maxX = Cartesian3_default.dot(
Plane_default.projectPointOntoPlane(
plane,
horizonCartesian,
scratchHorizonProjected
),
planeXAxis
);
minX = -maxX;
maxY = Cartesian3_default.fromRadians(
0,
rectangle.north,
fullyBelowEquator ? minimumHeight : maximumHeight,
ellipsoid,
scratchMaxY
).z;
minY = Cartesian3_default.fromRadians(
0,
rectangle.south,
fullyAboveEquator ? minimumHeight : maximumHeight,
ellipsoid,
scratchMinY
).z;
const farZ = Cartesian3_default.fromRadians(
rectangle.east,
latitudeNearestToEquator,
maximumHeight,
ellipsoid,
scratchZ
);
minZ = Plane_default.getPointDistance(plane, farZ);
maxZ = 0;
return fromPlaneExtents(
planeOrigin,
planeXAxis,
planeYAxis,
planeNormal,
minX,
maxX,
minY,
maxY,
minZ,
maxZ,
result
);
};
OrientedBoundingBox.fromTransformation = function(transformation, result) {
Check_default.typeOf.object("transformation", transformation);
if (!defined_default(result)) {
result = new OrientedBoundingBox();
}
result.center = Matrix4_default.getTranslation(transformation, result.center);
result.halfAxes = Matrix4_default.getMatrix3(transformation, result.halfAxes);
result.halfAxes = Matrix3_default.multiplyByScalar(
result.halfAxes,
0.5,
result.halfAxes
);
return result;
};
OrientedBoundingBox.clone = function(box, result) {
if (!defined_default(box)) {
return void 0;
}
if (!defined_default(result)) {
return new OrientedBoundingBox(box.center, box.halfAxes);
}
Cartesian3_default.clone(box.center, result.center);
Matrix3_default.clone(box.halfAxes, result.halfAxes);
return result;
};
OrientedBoundingBox.intersectPlane = function(box, plane) {
if (!defined_default(box)) {
throw new DeveloperError_default("box is required.");
}
if (!defined_default(plane)) {
throw new DeveloperError_default("plane is required.");
}
const center = box.center;
const normal2 = plane.normal;
const halfAxes = box.halfAxes;
const normalX = normal2.x, normalY = normal2.y, normalZ = normal2.z;
const radEffective = Math.abs(
normalX * halfAxes[Matrix3_default.COLUMN0ROW0] + normalY * halfAxes[Matrix3_default.COLUMN0ROW1] + normalZ * halfAxes[Matrix3_default.COLUMN0ROW2]
) + Math.abs(
normalX * halfAxes[Matrix3_default.COLUMN1ROW0] + normalY * halfAxes[Matrix3_default.COLUMN1ROW1] + normalZ * halfAxes[Matrix3_default.COLUMN1ROW2]
) + Math.abs(
normalX * halfAxes[Matrix3_default.COLUMN2ROW0] + normalY * halfAxes[Matrix3_default.COLUMN2ROW1] + normalZ * halfAxes[Matrix3_default.COLUMN2ROW2]
);
const distanceToPlane = Cartesian3_default.dot(normal2, center) + plane.distance;
if (distanceToPlane <= -radEffective) {
return Intersect_default.OUTSIDE;
} else if (distanceToPlane >= radEffective) {
return Intersect_default.INSIDE;
}
return Intersect_default.INTERSECTING;
};
var scratchCartesianU = new Cartesian3_default();
var scratchCartesianV = new Cartesian3_default();
var scratchCartesianW = new Cartesian3_default();
var scratchValidAxis2 = new Cartesian3_default();
var scratchValidAxis3 = new Cartesian3_default();
var scratchPPrime = new Cartesian3_default();
OrientedBoundingBox.distanceSquaredTo = function(box, cartesian11) {
if (!defined_default(box)) {
throw new DeveloperError_default("box is required.");
}
if (!defined_default(cartesian11)) {
throw new DeveloperError_default("cartesian is required.");
}
const offset2 = Cartesian3_default.subtract(cartesian11, box.center, scratchOffset);
const halfAxes = box.halfAxes;
let u3 = Matrix3_default.getColumn(halfAxes, 0, scratchCartesianU);
let v7 = Matrix3_default.getColumn(halfAxes, 1, scratchCartesianV);
let w = Matrix3_default.getColumn(halfAxes, 2, scratchCartesianW);
const uHalf = Cartesian3_default.magnitude(u3);
const vHalf = Cartesian3_default.magnitude(v7);
const wHalf = Cartesian3_default.magnitude(w);
let uValid = true;
let vValid = true;
let wValid = true;
if (uHalf > 0) {
Cartesian3_default.divideByScalar(u3, uHalf, u3);
} else {
uValid = false;
}
if (vHalf > 0) {
Cartesian3_default.divideByScalar(v7, vHalf, v7);
} else {
vValid = false;
}
if (wHalf > 0) {
Cartesian3_default.divideByScalar(w, wHalf, w);
} else {
wValid = false;
}
const numberOfDegenerateAxes = !uValid + !vValid + !wValid;
let validAxis1;
let validAxis2;
let validAxis3;
if (numberOfDegenerateAxes === 1) {
let degenerateAxis = u3;
validAxis1 = v7;
validAxis2 = w;
if (!vValid) {
degenerateAxis = v7;
validAxis1 = u3;
} else if (!wValid) {
degenerateAxis = w;
validAxis2 = u3;
}
validAxis3 = Cartesian3_default.cross(validAxis1, validAxis2, scratchValidAxis3);
if (degenerateAxis === u3) {
u3 = validAxis3;
} else if (degenerateAxis === v7) {
v7 = validAxis3;
} else if (degenerateAxis === w) {
w = validAxis3;
}
} else if (numberOfDegenerateAxes === 2) {
validAxis1 = u3;
if (vValid) {
validAxis1 = v7;
} else if (wValid) {
validAxis1 = w;
}
let crossVector = Cartesian3_default.UNIT_Y;
if (crossVector.equalsEpsilon(validAxis1, Math_default.EPSILON3)) {
crossVector = Cartesian3_default.UNIT_X;
}
validAxis2 = Cartesian3_default.cross(validAxis1, crossVector, scratchValidAxis2);
Cartesian3_default.normalize(validAxis2, validAxis2);
validAxis3 = Cartesian3_default.cross(validAxis1, validAxis2, scratchValidAxis3);
Cartesian3_default.normalize(validAxis3, validAxis3);
if (validAxis1 === u3) {
v7 = validAxis2;
w = validAxis3;
} else if (validAxis1 === v7) {
w = validAxis2;
u3 = validAxis3;
} else if (validAxis1 === w) {
u3 = validAxis2;
v7 = validAxis3;
}
} else if (numberOfDegenerateAxes === 3) {
u3 = Cartesian3_default.UNIT_X;
v7 = Cartesian3_default.UNIT_Y;
w = Cartesian3_default.UNIT_Z;
}
const pPrime = scratchPPrime;
pPrime.x = Cartesian3_default.dot(offset2, u3);
pPrime.y = Cartesian3_default.dot(offset2, v7);
pPrime.z = Cartesian3_default.dot(offset2, w);
let distanceSquared = 0;
let d;
if (pPrime.x < -uHalf) {
d = pPrime.x + uHalf;
distanceSquared += d * d;
} else if (pPrime.x > uHalf) {
d = pPrime.x - uHalf;
distanceSquared += d * d;
}
if (pPrime.y < -vHalf) {
d = pPrime.y + vHalf;
distanceSquared += d * d;
} else if (pPrime.y > vHalf) {
d = pPrime.y - vHalf;
distanceSquared += d * d;
}
if (pPrime.z < -wHalf) {
d = pPrime.z + wHalf;
distanceSquared += d * d;
} else if (pPrime.z > wHalf) {
d = pPrime.z - wHalf;
distanceSquared += d * d;
}
return distanceSquared;
};
var scratchCorner = new Cartesian3_default();
var scratchToCenter = new Cartesian3_default();
OrientedBoundingBox.computePlaneDistances = function(box, position, direction2, result) {
if (!defined_default(box)) {
throw new DeveloperError_default("box is required.");
}
if (!defined_default(position)) {
throw new DeveloperError_default("position is required.");
}
if (!defined_default(direction2)) {
throw new DeveloperError_default("direction is required.");
}
if (!defined_default(result)) {
result = new Interval_default();
}
let minDist = Number.POSITIVE_INFINITY;
let maxDist = Number.NEGATIVE_INFINITY;
const center = box.center;
const halfAxes = box.halfAxes;
const u3 = Matrix3_default.getColumn(halfAxes, 0, scratchCartesianU);
const v7 = Matrix3_default.getColumn(halfAxes, 1, scratchCartesianV);
const w = Matrix3_default.getColumn(halfAxes, 2, scratchCartesianW);
const corner = Cartesian3_default.add(u3, v7, scratchCorner);
Cartesian3_default.add(corner, w, corner);
Cartesian3_default.add(corner, center, corner);
const toCenter = Cartesian3_default.subtract(corner, position, scratchToCenter);
let mag = Cartesian3_default.dot(direction2, toCenter);
minDist = Math.min(mag, minDist);
maxDist = Math.max(mag, maxDist);
Cartesian3_default.add(center, u3, corner);
Cartesian3_default.add(corner, v7, corner);
Cartesian3_default.subtract(corner, w, corner);
Cartesian3_default.subtract(corner, position, toCenter);
mag = Cartesian3_default.dot(direction2, toCenter);
minDist = Math.min(mag, minDist);
maxDist = Math.max(mag, maxDist);
Cartesian3_default.add(center, u3, corner);
Cartesian3_default.subtract(corner, v7, corner);
Cartesian3_default.add(corner, w, corner);
Cartesian3_default.subtract(corner, position, toCenter);
mag = Cartesian3_default.dot(direction2, toCenter);
minDist = Math.min(mag, minDist);
maxDist = Math.max(mag, maxDist);
Cartesian3_default.add(center, u3, corner);
Cartesian3_default.subtract(corner, v7, corner);
Cartesian3_default.subtract(corner, w, corner);
Cartesian3_default.subtract(corner, position, toCenter);
mag = Cartesian3_default.dot(direction2, toCenter);
minDist = Math.min(mag, minDist);
maxDist = Math.max(mag, maxDist);
Cartesian3_default.subtract(center, u3, corner);
Cartesian3_default.add(corner, v7, corner);
Cartesian3_default.add(corner, w, corner);
Cartesian3_default.subtract(corner, position, toCenter);
mag = Cartesian3_default.dot(direction2, toCenter);
minDist = Math.min(mag, minDist);
maxDist = Math.max(mag, maxDist);
Cartesian3_default.subtract(center, u3, corner);
Cartesian3_default.add(corner, v7, corner);
Cartesian3_default.subtract(corner, w, corner);
Cartesian3_default.subtract(corner, position, toCenter);
mag = Cartesian3_default.dot(direction2, toCenter);
minDist = Math.min(mag, minDist);
maxDist = Math.max(mag, maxDist);
Cartesian3_default.subtract(center, u3, corner);
Cartesian3_default.subtract(corner, v7, corner);
Cartesian3_default.add(corner, w, corner);
Cartesian3_default.subtract(corner, position, toCenter);
mag = Cartesian3_default.dot(direction2, toCenter);
minDist = Math.min(mag, minDist);
maxDist = Math.max(mag, maxDist);
Cartesian3_default.subtract(center, u3, corner);
Cartesian3_default.subtract(corner, v7, corner);
Cartesian3_default.subtract(corner, w, corner);
Cartesian3_default.subtract(corner, position, toCenter);
mag = Cartesian3_default.dot(direction2, toCenter);
minDist = Math.min(mag, minDist);
maxDist = Math.max(mag, maxDist);
result.start = minDist;
result.stop = maxDist;
return result;
};
var scratchXAxis = new Cartesian3_default();
var scratchYAxis = new Cartesian3_default();
var scratchZAxis = new Cartesian3_default();
OrientedBoundingBox.computeCorners = function(box, result) {
Check_default.typeOf.object("box", box);
if (!defined_default(result)) {
result = [
new Cartesian3_default(),
new Cartesian3_default(),
new Cartesian3_default(),
new Cartesian3_default(),
new Cartesian3_default(),
new Cartesian3_default(),
new Cartesian3_default(),
new Cartesian3_default()
];
}
const center = box.center;
const halfAxes = box.halfAxes;
const xAxis = Matrix3_default.getColumn(halfAxes, 0, scratchXAxis);
const yAxis = Matrix3_default.getColumn(halfAxes, 1, scratchYAxis);
const zAxis = Matrix3_default.getColumn(halfAxes, 2, scratchZAxis);
Cartesian3_default.clone(center, result[0]);
Cartesian3_default.subtract(result[0], xAxis, result[0]);
Cartesian3_default.subtract(result[0], yAxis, result[0]);
Cartesian3_default.subtract(result[0], zAxis, result[0]);
Cartesian3_default.clone(center, result[1]);
Cartesian3_default.subtract(result[1], xAxis, result[1]);
Cartesian3_default.subtract(result[1], yAxis, result[1]);
Cartesian3_default.add(result[1], zAxis, result[1]);
Cartesian3_default.clone(center, result[2]);
Cartesian3_default.subtract(result[2], xAxis, result[2]);
Cartesian3_default.add(result[2], yAxis, result[2]);
Cartesian3_default.subtract(result[2], zAxis, result[2]);
Cartesian3_default.clone(center, result[3]);
Cartesian3_default.subtract(result[3], xAxis, result[3]);
Cartesian3_default.add(result[3], yAxis, result[3]);
Cartesian3_default.add(result[3], zAxis, result[3]);
Cartesian3_default.clone(center, result[4]);
Cartesian3_default.add(result[4], xAxis, result[4]);
Cartesian3_default.subtract(result[4], yAxis, result[4]);
Cartesian3_default.subtract(result[4], zAxis, result[4]);
Cartesian3_default.clone(center, result[5]);
Cartesian3_default.add(result[5], xAxis, result[5]);
Cartesian3_default.subtract(result[5], yAxis, result[5]);
Cartesian3_default.add(result[5], zAxis, result[5]);
Cartesian3_default.clone(center, result[6]);
Cartesian3_default.add(result[6], xAxis, result[6]);
Cartesian3_default.add(result[6], yAxis, result[6]);
Cartesian3_default.subtract(result[6], zAxis, result[6]);
Cartesian3_default.clone(center, result[7]);
Cartesian3_default.add(result[7], xAxis, result[7]);
Cartesian3_default.add(result[7], yAxis, result[7]);
Cartesian3_default.add(result[7], zAxis, result[7]);
return result;
};
var scratchRotationScale = new Matrix3_default();
OrientedBoundingBox.computeTransformation = function(box, result) {
Check_default.typeOf.object("box", box);
if (!defined_default(result)) {
result = new Matrix4_default();
}
const translation3 = box.center;
const rotationScale = Matrix3_default.multiplyByUniformScale(
box.halfAxes,
2,
scratchRotationScale
);
return Matrix4_default.fromRotationTranslation(rotationScale, translation3, result);
};
var scratchBoundingSphere2 = new BoundingSphere_default();
OrientedBoundingBox.isOccluded = function(box, occluder) {
if (!defined_default(box)) {
throw new DeveloperError_default("box is required.");
}
if (!defined_default(occluder)) {
throw new DeveloperError_default("occluder is required.");
}
const sphere = BoundingSphere_default.fromOrientedBoundingBox(
box,
scratchBoundingSphere2
);
return !occluder.isBoundingSphereVisible(sphere);
};
OrientedBoundingBox.prototype.intersectPlane = function(plane) {
return OrientedBoundingBox.intersectPlane(this, plane);
};
OrientedBoundingBox.prototype.distanceSquaredTo = function(cartesian11) {
return OrientedBoundingBox.distanceSquaredTo(this, cartesian11);
};
OrientedBoundingBox.prototype.computePlaneDistances = function(position, direction2, result) {
return OrientedBoundingBox.computePlaneDistances(
this,
position,
direction2,
result
);
};
OrientedBoundingBox.prototype.computeCorners = function(result) {
return OrientedBoundingBox.computeCorners(this, result);
};
OrientedBoundingBox.prototype.computeTransformation = function(result) {
return OrientedBoundingBox.computeTransformation(this, result);
};
OrientedBoundingBox.prototype.isOccluded = function(occluder) {
return OrientedBoundingBox.isOccluded(this, occluder);
};
OrientedBoundingBox.equals = function(left, right) {
return left === right || defined_default(left) && defined_default(right) && Cartesian3_default.equals(left.center, right.center) && Matrix3_default.equals(left.halfAxes, right.halfAxes);
};
OrientedBoundingBox.prototype.clone = function(result) {
return OrientedBoundingBox.clone(this, result);
};
OrientedBoundingBox.prototype.equals = function(right) {
return OrientedBoundingBox.equals(this, right);
};
var OrientedBoundingBox_default = OrientedBoundingBox;
// packages/engine/Source/Core/TerrainExaggeration.js
var TerrainExaggeration = {};
TerrainExaggeration.getHeight = function(height, scale, relativeHeight) {
return (height - relativeHeight) * scale + relativeHeight;
};
var scratchCartographic2 = new Cartesian3_default();
TerrainExaggeration.getPosition = function(position, ellipsoid, terrainExaggeration, terrainExaggerationRelativeHeight, result) {
const cartographic2 = ellipsoid.cartesianToCartographic(
position,
scratchCartographic2
);
const newHeight = TerrainExaggeration.getHeight(
cartographic2.height,
terrainExaggeration,
terrainExaggerationRelativeHeight
);
return Cartesian3_default.fromRadians(
cartographic2.longitude,
cartographic2.latitude,
newHeight,
ellipsoid,
result
);
};
var TerrainExaggeration_default = TerrainExaggeration;
// packages/engine/Source/Shaders/ShadowVolumeAppearanceVS.js
var ShadowVolumeAppearanceVS_default = 'in vec3 position3DHigh;\nin vec3 position3DLow;\nin float batchId;\n\n#ifdef EXTRUDED_GEOMETRY\nin vec3 extrudeDirection;\n\nuniform float u_globeMinimumAltitude;\n#endif // EXTRUDED_GEOMETRY\n\n#ifdef PER_INSTANCE_COLOR\nout vec4 v_color;\n#endif // PER_INSTANCE_COLOR\n\n#ifdef TEXTURE_COORDINATES\n#ifdef SPHERICAL\nout vec4 v_sphericalExtents;\n#else // SPHERICAL\nout vec2 v_inversePlaneExtents;\nout vec4 v_westPlane;\nout vec4 v_southPlane;\n#endif // SPHERICAL\nout vec3 v_uvMinAndSphericalLongitudeRotation;\nout vec3 v_uMaxAndInverseDistance;\nout vec3 v_vMaxAndInverseDistance;\n#endif // TEXTURE_COORDINATES\n\nvoid main()\n{\n vec4 position = czm_computePosition();\n\n#ifdef EXTRUDED_GEOMETRY\n float delta = min(u_globeMinimumAltitude, czm_geometricToleranceOverMeter * length(position.xyz));\n delta *= czm_sceneMode == czm_sceneMode3D ? 1.0 : 0.0;\n\n //extrudeDirection is zero for the top layer\n position = position + vec4(extrudeDirection * delta, 0.0);\n#endif\n\n#ifdef TEXTURE_COORDINATES\n#ifdef SPHERICAL\n v_sphericalExtents = czm_batchTable_sphericalExtents(batchId);\n v_uvMinAndSphericalLongitudeRotation.z = czm_batchTable_longitudeRotation(batchId);\n#else // SPHERICAL\n#ifdef COLUMBUS_VIEW_2D\n vec4 planes2D_high = czm_batchTable_planes2D_HIGH(batchId);\n vec4 planes2D_low = czm_batchTable_planes2D_LOW(batchId);\n\n // If the primitive is split across the IDL (planes2D_high.x > planes2D_high.w):\n // - If this vertex is on the east side of the IDL (position3DLow.y > 0.0, comparison with position3DHigh may produce artifacts)\n // - existing "east" is on the wrong side of the world, far away (planes2D_high/low.w)\n // - so set "east" as beyond the eastmost extent of the projection (idlSplitNewPlaneHiLow)\n vec2 idlSplitNewPlaneHiLow = vec2(EAST_MOST_X_HIGH - (WEST_MOST_X_HIGH - planes2D_high.w), EAST_MOST_X_LOW - (WEST_MOST_X_LOW - planes2D_low.w));\n bool idlSplit = planes2D_high.x > planes2D_high.w && position3DLow.y > 0.0;\n planes2D_high.w = czm_branchFreeTernary(idlSplit, idlSplitNewPlaneHiLow.x, planes2D_high.w);\n planes2D_low.w = czm_branchFreeTernary(idlSplit, idlSplitNewPlaneHiLow.y, planes2D_low.w);\n\n // - else, if this vertex is on the west side of the IDL (position3DLow.y < 0.0)\n // - existing "west" is on the wrong side of the world, far away (planes2D_high/low.x)\n // - so set "west" as beyond the westmost extent of the projection (idlSplitNewPlaneHiLow)\n idlSplit = planes2D_high.x > planes2D_high.w && position3DLow.y < 0.0;\n idlSplitNewPlaneHiLow = vec2(WEST_MOST_X_HIGH - (EAST_MOST_X_HIGH - planes2D_high.x), WEST_MOST_X_LOW - (EAST_MOST_X_LOW - planes2D_low.x));\n planes2D_high.x = czm_branchFreeTernary(idlSplit, idlSplitNewPlaneHiLow.x, planes2D_high.x);\n planes2D_low.x = czm_branchFreeTernary(idlSplit, idlSplitNewPlaneHiLow.y, planes2D_low.x);\n\n vec3 southWestCorner = (czm_modelViewRelativeToEye * czm_translateRelativeToEye(vec3(0.0, planes2D_high.xy), vec3(0.0, planes2D_low.xy))).xyz;\n vec3 northWestCorner = (czm_modelViewRelativeToEye * czm_translateRelativeToEye(vec3(0.0, planes2D_high.x, planes2D_high.z), vec3(0.0, planes2D_low.x, planes2D_low.z))).xyz;\n vec3 southEastCorner = (czm_modelViewRelativeToEye * czm_translateRelativeToEye(vec3(0.0, planes2D_high.w, planes2D_high.y), vec3(0.0, planes2D_low.w, planes2D_low.y))).xyz;\n#else // COLUMBUS_VIEW_2D\n // 3D case has smaller "plane extents," so planes encoded as a 64 bit position and 2 vec3s for distances/direction\n vec3 southWestCorner = (czm_modelViewRelativeToEye * czm_translateRelativeToEye(czm_batchTable_southWest_HIGH(batchId), czm_batchTable_southWest_LOW(batchId))).xyz;\n vec3 northWestCorner = czm_normal * czm_batchTable_northward(batchId) + southWestCorner;\n vec3 southEastCorner = czm_normal * czm_batchTable_eastward(batchId) + southWestCorner;\n#endif // COLUMBUS_VIEW_2D\n\n vec3 eastWard = southEastCorner - southWestCorner;\n float eastExtent = length(eastWard);\n eastWard /= eastExtent;\n\n vec3 northWard = northWestCorner - southWestCorner;\n float northExtent = length(northWard);\n northWard /= northExtent;\n\n v_westPlane = vec4(eastWard, -dot(eastWard, southWestCorner));\n v_southPlane = vec4(northWard, -dot(northWard, southWestCorner));\n v_inversePlaneExtents = vec2(1.0 / eastExtent, 1.0 / northExtent);\n#endif // SPHERICAL\n vec4 uvMinAndExtents = czm_batchTable_uvMinAndExtents(batchId);\n vec4 uMaxVmax = czm_batchTable_uMaxVmax(batchId);\n\n v_uMaxAndInverseDistance = vec3(uMaxVmax.xy, uvMinAndExtents.z);\n v_vMaxAndInverseDistance = vec3(uMaxVmax.zw, uvMinAndExtents.w);\n v_uvMinAndSphericalLongitudeRotation.xy = uvMinAndExtents.xy;\n#endif // TEXTURE_COORDINATES\n\n#ifdef PER_INSTANCE_COLOR\n v_color = czm_batchTable_color(batchId);\n#endif\n\n gl_Position = czm_depthClamp(czm_modelViewProjectionRelativeToEye * position);\n}\n';
// packages/engine/Source/Shaders/ShadowVolumeFS.js
var ShadowVolumeFS_default = "#ifdef VECTOR_TILE\nuniform vec4 u_highlightColor;\n#endif\n\nvoid main(void)\n{\n#ifdef VECTOR_TILE\n out_FragColor = czm_gammaCorrect(u_highlightColor);\n#else\n out_FragColor = vec4(1.0);\n#endif\n czm_writeDepthClamp();\n}\n";
// packages/engine/Source/Scene/ClassificationType.js
var ClassificationType = {
/**
* Only terrain will be classified.
*
* @type {number}
* @constant
*/
TERRAIN: 0,
/**
* Only 3D Tiles will be classified.
*
* @type {number}
* @constant
*/
CESIUM_3D_TILE: 1,
/**
* Both terrain and 3D Tiles will be classified.
*
* @type {number}
* @constant
*/
BOTH: 2
};
ClassificationType.NUMBER_OF_CLASSIFICATION_TYPES = 3;
var ClassificationType_default = Object.freeze(ClassificationType);
// packages/engine/Source/Scene/DepthFunction.js
var DepthFunction = {
/**
* The depth test never passes.
*
* @type {number}
* @constant
*/
NEVER: WebGLConstants_default.NEVER,
/**
* The depth test passes if the incoming depth is less than the stored depth.
*
* @type {number}
* @constant
*/
LESS: WebGLConstants_default.LESS,
/**
* The depth test passes if the incoming depth is equal to the stored depth.
*
* @type {number}
* @constant
*/
EQUAL: WebGLConstants_default.EQUAL,
/**
* The depth test passes if the incoming depth is less than or equal to the stored depth.
*
* @type {number}
* @constant
*/
LESS_OR_EQUAL: WebGLConstants_default.LEQUAL,
/**
* The depth test passes if the incoming depth is greater than the stored depth.
*
* @type {number}
* @constant
*/
GREATER: WebGLConstants_default.GREATER,
/**
* The depth test passes if the incoming depth is not equal to the stored depth.
*
* @type {number}
* @constant
*/
NOT_EQUAL: WebGLConstants_default.NOTEQUAL,
/**
* The depth test passes if the incoming depth is greater than or equal to the stored depth.
*
* @type {number}
* @constant
*/
GREATER_OR_EQUAL: WebGLConstants_default.GEQUAL,
/**
* The depth test always passes.
*
* @type {number}
* @constant
*/
ALWAYS: WebGLConstants_default.ALWAYS
};
var DepthFunction_default = Object.freeze(DepthFunction);
// packages/engine/Source/Core/subdivideArray.js
function subdivideArray(array, numberOfArrays) {
if (!defined_default(array)) {
throw new DeveloperError_default("array is required.");
}
if (!defined_default(numberOfArrays) || numberOfArrays < 1) {
throw new DeveloperError_default("numberOfArrays must be greater than 0.");
}
const result = [];
const len = array.length;
let i = 0;
while (i < len) {
const size = Math.ceil((len - i) / numberOfArrays--);
result.push(array.slice(i, i + size));
i += size;
}
return result;
}
var subdivideArray_default = subdivideArray;
// packages/engine/Source/Scene/BatchTable.js
function BatchTable(context, attributes, numberOfInstances) {
if (!defined_default(context)) {
throw new DeveloperError_default("context is required");
}
if (!defined_default(attributes)) {
throw new DeveloperError_default("attributes is required");
}
if (!defined_default(numberOfInstances)) {
throw new DeveloperError_default("numberOfInstances is required");
}
this._attributes = attributes;
this._numberOfInstances = numberOfInstances;
if (attributes.length === 0) {
return;
}
const pixelDatatype = getDatatype(attributes);
const textureFloatSupported = context.floatingPointTexture;
const packFloats = pixelDatatype === PixelDatatype_default.FLOAT && !textureFloatSupported;
const offsets = createOffsets(attributes, packFloats);
const stride = getStride(offsets, attributes, packFloats);
const maxNumberOfInstancesPerRow = Math.floor(
ContextLimits_default.maximumTextureSize / stride
);
const instancesPerWidth = Math.min(
numberOfInstances,
maxNumberOfInstancesPerRow
);
const width = stride * instancesPerWidth;
const height = Math.ceil(numberOfInstances / instancesPerWidth);
const stepX = 1 / width;
const centerX = stepX * 0.5;
const stepY = 1 / height;
const centerY = stepY * 0.5;
this._textureDimensions = new Cartesian2_default(width, height);
this._textureStep = new Cartesian4_default(stepX, centerX, stepY, centerY);
this._pixelDatatype = !packFloats ? pixelDatatype : PixelDatatype_default.UNSIGNED_BYTE;
this._packFloats = packFloats;
this._offsets = offsets;
this._stride = stride;
this._texture = void 0;
const batchLength = 4 * width * height;
this._batchValues = pixelDatatype === PixelDatatype_default.FLOAT && !packFloats ? new Float32Array(batchLength) : new Uint8Array(batchLength);
this._batchValuesDirty = false;
}
Object.defineProperties(BatchTable.prototype, {
/**
* The attribute descriptions.
* @memberOf BatchTable.prototype
* @type {Object[]}
* @readonly
*/
attributes: {
get: function() {
return this._attributes;
}
},
/**
* The number of instances.
* @memberOf BatchTable.prototype
* @type {number}
* @readonly
*/
numberOfInstances: {
get: function() {
return this._numberOfInstances;
}
}
});
function getDatatype(attributes) {
let foundFloatDatatype = false;
const length3 = attributes.length;
for (let i = 0; i < length3; ++i) {
if (attributes[i].componentDatatype !== ComponentDatatype_default.UNSIGNED_BYTE) {
foundFloatDatatype = true;
break;
}
}
return foundFloatDatatype ? PixelDatatype_default.FLOAT : PixelDatatype_default.UNSIGNED_BYTE;
}
function getAttributeType(attributes, attributeIndex) {
const componentsPerAttribute = attributes[attributeIndex].componentsPerAttribute;
if (componentsPerAttribute === 2) {
return Cartesian2_default;
} else if (componentsPerAttribute === 3) {
return Cartesian3_default;
} else if (componentsPerAttribute === 4) {
return Cartesian4_default;
}
return Number;
}
function createOffsets(attributes, packFloats) {
const offsets = new Array(attributes.length);
let currentOffset = 0;
const attributesLength = attributes.length;
for (let i = 0; i < attributesLength; ++i) {
const attribute = attributes[i];
const componentDatatype = attribute.componentDatatype;
offsets[i] = currentOffset;
if (componentDatatype !== ComponentDatatype_default.UNSIGNED_BYTE && packFloats) {
currentOffset += 4;
} else {
++currentOffset;
}
}
return offsets;
}
function getStride(offsets, attributes, packFloats) {
const length3 = offsets.length;
const lastOffset = offsets[length3 - 1];
const lastAttribute = attributes[length3 - 1];
const componentDatatype = lastAttribute.componentDatatype;
if (componentDatatype !== ComponentDatatype_default.UNSIGNED_BYTE && packFloats) {
return lastOffset + 4;
}
return lastOffset + 1;
}
var scratchPackedFloatCartesian4 = new Cartesian4_default();
function getPackedFloat(array, index, result) {
let packed = Cartesian4_default.unpack(array, index, scratchPackedFloatCartesian4);
const x = Cartesian4_default.unpackFloat(packed);
packed = Cartesian4_default.unpack(array, index + 4, scratchPackedFloatCartesian4);
const y = Cartesian4_default.unpackFloat(packed);
packed = Cartesian4_default.unpack(array, index + 8, scratchPackedFloatCartesian4);
const z = Cartesian4_default.unpackFloat(packed);
packed = Cartesian4_default.unpack(array, index + 12, scratchPackedFloatCartesian4);
const w = Cartesian4_default.unpackFloat(packed);
return Cartesian4_default.fromElements(x, y, z, w, result);
}
function setPackedAttribute(value, array, index) {
let packed = Cartesian4_default.packFloat(value.x, scratchPackedFloatCartesian4);
Cartesian4_default.pack(packed, array, index);
packed = Cartesian4_default.packFloat(value.y, packed);
Cartesian4_default.pack(packed, array, index + 4);
packed = Cartesian4_default.packFloat(value.z, packed);
Cartesian4_default.pack(packed, array, index + 8);
packed = Cartesian4_default.packFloat(value.w, packed);
Cartesian4_default.pack(packed, array, index + 12);
}
var scratchGetAttributeCartesian4 = new Cartesian4_default();
BatchTable.prototype.getBatchedAttribute = function(instanceIndex, attributeIndex, result) {
if (instanceIndex < 0 || instanceIndex >= this._numberOfInstances) {
throw new DeveloperError_default("instanceIndex is out of range.");
}
if (attributeIndex < 0 || attributeIndex >= this._attributes.length) {
throw new DeveloperError_default("attributeIndex is out of range");
}
const attributes = this._attributes;
const offset2 = this._offsets[attributeIndex];
const stride = this._stride;
const index = 4 * stride * instanceIndex + 4 * offset2;
let value;
if (this._packFloats && attributes[attributeIndex].componentDatatype !== PixelDatatype_default.UNSIGNED_BYTE) {
value = getPackedFloat(
this._batchValues,
index,
scratchGetAttributeCartesian4
);
} else {
value = Cartesian4_default.unpack(
this._batchValues,
index,
scratchGetAttributeCartesian4
);
}
const attributeType = getAttributeType(attributes, attributeIndex);
if (defined_default(attributeType.fromCartesian4)) {
return attributeType.fromCartesian4(value, result);
} else if (defined_default(attributeType.clone)) {
return attributeType.clone(value, result);
}
return value.x;
};
var setAttributeScratchValues = [
void 0,
void 0,
new Cartesian2_default(),
new Cartesian3_default(),
new Cartesian4_default()
];
var setAttributeScratchCartesian4 = new Cartesian4_default();
BatchTable.prototype.setBatchedAttribute = function(instanceIndex, attributeIndex, value) {
if (instanceIndex < 0 || instanceIndex >= this._numberOfInstances) {
throw new DeveloperError_default("instanceIndex is out of range.");
}
if (attributeIndex < 0 || attributeIndex >= this._attributes.length) {
throw new DeveloperError_default("attributeIndex is out of range");
}
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
const attributes = this._attributes;
const result = setAttributeScratchValues[attributes[attributeIndex].componentsPerAttribute];
const currentAttribute = this.getBatchedAttribute(
instanceIndex,
attributeIndex,
result
);
const attributeType = getAttributeType(this._attributes, attributeIndex);
const entriesEqual = defined_default(attributeType.equals) ? attributeType.equals(currentAttribute, value) : currentAttribute === value;
if (entriesEqual) {
return;
}
const attributeValue = setAttributeScratchCartesian4;
attributeValue.x = defined_default(value.x) ? value.x : value;
attributeValue.y = defined_default(value.y) ? value.y : 0;
attributeValue.z = defined_default(value.z) ? value.z : 0;
attributeValue.w = defined_default(value.w) ? value.w : 0;
const offset2 = this._offsets[attributeIndex];
const stride = this._stride;
const index = 4 * stride * instanceIndex + 4 * offset2;
if (this._packFloats && attributes[attributeIndex].componentDatatype !== PixelDatatype_default.UNSIGNED_BYTE) {
setPackedAttribute(attributeValue, this._batchValues, index);
} else {
Cartesian4_default.pack(attributeValue, this._batchValues, index);
}
this._batchValuesDirty = true;
};
function createTexture(batchTable, context) {
const dimensions = batchTable._textureDimensions;
batchTable._texture = new Texture_default({
context,
pixelFormat: PixelFormat_default.RGBA,
pixelDatatype: batchTable._pixelDatatype,
width: dimensions.x,
height: dimensions.y,
sampler: Sampler_default.NEAREST,
flipY: false
});
}
function updateTexture(batchTable) {
const dimensions = batchTable._textureDimensions;
batchTable._texture.copyFrom({
source: {
width: dimensions.x,
height: dimensions.y,
arrayBufferView: batchTable._batchValues
}
});
}
BatchTable.prototype.update = function(frameState) {
if (defined_default(this._texture) && !this._batchValuesDirty || this._attributes.length === 0) {
return;
}
this._batchValuesDirty = false;
if (!defined_default(this._texture)) {
createTexture(this, frameState.context);
}
updateTexture(this);
};
BatchTable.prototype.getUniformMapCallback = function() {
const that = this;
return function(uniformMap2) {
if (that._attributes.length === 0) {
return uniformMap2;
}
const batchUniformMap = {
batchTexture: function() {
return that._texture;
},
batchTextureDimensions: function() {
return that._textureDimensions;
},
batchTextureStep: function() {
return that._textureStep;
}
};
return combine_default(uniformMap2, batchUniformMap);
};
};
function getGlslComputeSt(batchTable) {
const stride = batchTable._stride;
if (batchTable._textureDimensions.y === 1) {
return `${"uniform vec4 batchTextureStep; \nvec2 computeSt(float batchId) \n{ \n float stepX = batchTextureStep.x; \n float centerX = batchTextureStep.y; \n float numberOfAttributes = float("}${stride});
return vec2(centerX + (batchId * numberOfAttributes * stepX), 0.5);
}
`;
}
return `${"uniform vec4 batchTextureStep; \nuniform vec2 batchTextureDimensions; \nvec2 computeSt(float batchId) \n{ \n float stepX = batchTextureStep.x; \n float centerX = batchTextureStep.y; \n float stepY = batchTextureStep.z; \n float centerY = batchTextureStep.w; \n float numberOfAttributes = float("}${stride});
float xId = mod(batchId * numberOfAttributes, batchTextureDimensions.x);
float yId = floor(batchId * numberOfAttributes / batchTextureDimensions.x);
return vec2(centerX + (xId * stepX), centerY + (yId * stepY));
}
`;
}
function getComponentType(componentsPerAttribute) {
if (componentsPerAttribute === 1) {
return "float";
}
return `vec${componentsPerAttribute}`;
}
function getComponentSwizzle(componentsPerAttribute) {
if (componentsPerAttribute === 1) {
return ".x";
} else if (componentsPerAttribute === 2) {
return ".xy";
} else if (componentsPerAttribute === 3) {
return ".xyz";
}
return "";
}
function getGlslAttributeFunction(batchTable, attributeIndex) {
const attributes = batchTable._attributes;
const attribute = attributes[attributeIndex];
const componentsPerAttribute = attribute.componentsPerAttribute;
const functionName = attribute.functionName;
const functionReturnType = getComponentType(componentsPerAttribute);
const functionReturnValue = getComponentSwizzle(componentsPerAttribute);
const offset2 = batchTable._offsets[attributeIndex];
let glslFunction = `${functionReturnType} ${functionName}(float batchId)
{
vec2 st = computeSt(batchId);
st.x += batchTextureStep.x * float(${offset2});
`;
if (batchTable._packFloats && attribute.componentDatatype !== PixelDatatype_default.UNSIGNED_BYTE) {
glslFunction += "vec4 textureValue; \ntextureValue.x = czm_unpackFloat(texture(batchTexture, st)); \ntextureValue.y = czm_unpackFloat(texture(batchTexture, st + vec2(batchTextureStep.x, 0.0))); \ntextureValue.z = czm_unpackFloat(texture(batchTexture, st + vec2(batchTextureStep.x * 2.0, 0.0))); \ntextureValue.w = czm_unpackFloat(texture(batchTexture, st + vec2(batchTextureStep.x * 3.0, 0.0))); \n";
} else {
glslFunction += " vec4 textureValue = texture(batchTexture, st); \n";
}
glslFunction += ` ${functionReturnType} value = textureValue${functionReturnValue};
`;
if (batchTable._pixelDatatype === PixelDatatype_default.UNSIGNED_BYTE && attribute.componentDatatype === ComponentDatatype_default.UNSIGNED_BYTE && !attribute.normalize) {
glslFunction += "value *= 255.0; \n";
} else if (batchTable._pixelDatatype === PixelDatatype_default.FLOAT && attribute.componentDatatype === ComponentDatatype_default.UNSIGNED_BYTE && attribute.normalize) {
glslFunction += "value /= 255.0; \n";
}
glslFunction += " return value; \n} \n";
return glslFunction;
}
BatchTable.prototype.getVertexShaderCallback = function() {
const attributes = this._attributes;
if (attributes.length === 0) {
return function(source) {
return source;
};
}
let batchTableShader = "uniform highp sampler2D batchTexture; \n";
batchTableShader += `${getGlslComputeSt(this)}
`;
const length3 = attributes.length;
for (let i = 0; i < length3; ++i) {
batchTableShader += getGlslAttributeFunction(this, i);
}
return function(source) {
const mainIndex = source.indexOf("void main");
const beforeMain = source.substring(0, mainIndex);
const afterMain = source.substring(mainIndex);
return `${beforeMain}
${batchTableShader}
${afterMain}`;
};
};
BatchTable.prototype.isDestroyed = function() {
return false;
};
BatchTable.prototype.destroy = function() {
this._texture = this._texture && this._texture.destroy();
return destroyObject_default(this);
};
var BatchTable_default = BatchTable;
// packages/engine/Source/Scene/AttributeType.js
var AttributeType = {
/**
* The attribute is a single component.
*
* @type {string}
* @constant
*/
SCALAR: "SCALAR",
/**
* The attribute is a two-component vector.
*
* @type {string}
* @constant
*/
VEC2: "VEC2",
/**
* The attribute is a three-component vector.
*
* @type {string}
* @constant
*/
VEC3: "VEC3",
/**
* The attribute is a four-component vector.
*
* @type {string}
* @constant
*/
VEC4: "VEC4",
/**
* The attribute is a 2x2 matrix.
*
* @type {string}
* @constant
*/
MAT2: "MAT2",
/**
* The attribute is a 3x3 matrix.
*
* @type {string}
* @constant
*/
MAT3: "MAT3",
/**
* The attribute is a 4x4 matrix.
*
* @type {string}
* @constant
*/
MAT4: "MAT4"
};
AttributeType.getMathType = function(attributeType) {
switch (attributeType) {
case AttributeType.SCALAR:
return Number;
case AttributeType.VEC2:
return Cartesian2_default;
case AttributeType.VEC3:
return Cartesian3_default;
case AttributeType.VEC4:
return Cartesian4_default;
case AttributeType.MAT2:
return Matrix2_default;
case AttributeType.MAT3:
return Matrix3_default;
case AttributeType.MAT4:
return Matrix4_default;
default:
throw new DeveloperError_default("attributeType is not a valid value.");
}
};
AttributeType.getNumberOfComponents = function(attributeType) {
switch (attributeType) {
case AttributeType.SCALAR:
return 1;
case AttributeType.VEC2:
return 2;
case AttributeType.VEC3:
return 3;
case AttributeType.VEC4:
case AttributeType.MAT2:
return 4;
case AttributeType.MAT3:
return 9;
case AttributeType.MAT4:
return 16;
default:
throw new DeveloperError_default("attributeType is not a valid value.");
}
};
AttributeType.getAttributeLocationCount = function(attributeType) {
switch (attributeType) {
case AttributeType.SCALAR:
case AttributeType.VEC2:
case AttributeType.VEC3:
case AttributeType.VEC4:
return 1;
case AttributeType.MAT2:
return 2;
case AttributeType.MAT3:
return 3;
case AttributeType.MAT4:
return 4;
default:
throw new DeveloperError_default("attributeType is not a valid value.");
}
};
AttributeType.getGlslType = function(attributeType) {
Check_default.typeOf.string("attributeType", attributeType);
switch (attributeType) {
case AttributeType.SCALAR:
return "float";
case AttributeType.VEC2:
return "vec2";
case AttributeType.VEC3:
return "vec3";
case AttributeType.VEC4:
return "vec4";
case AttributeType.MAT2:
return "mat2";
case AttributeType.MAT3:
return "mat3";
case AttributeType.MAT4:
return "mat4";
default:
throw new DeveloperError_default("attributeType is not a valid value.");
}
};
var AttributeType_default = Object.freeze(AttributeType);
// packages/engine/Source/Core/AttributeCompression.js
var RIGHT_SHIFT = 1 / 256;
var LEFT_SHIFT = 256;
var AttributeCompression = {};
AttributeCompression.octEncodeInRange = function(vector, rangeMax, result) {
Check_default.defined("vector", vector);
Check_default.defined("result", result);
const magSquared = Cartesian3_default.magnitudeSquared(vector);
if (Math.abs(magSquared - 1) > Math_default.EPSILON6) {
throw new DeveloperError_default("vector must be normalized.");
}
result.x = vector.x / (Math.abs(vector.x) + Math.abs(vector.y) + Math.abs(vector.z));
result.y = vector.y / (Math.abs(vector.x) + Math.abs(vector.y) + Math.abs(vector.z));
if (vector.z < 0) {
const x = result.x;
const y = result.y;
result.x = (1 - Math.abs(y)) * Math_default.signNotZero(x);
result.y = (1 - Math.abs(x)) * Math_default.signNotZero(y);
}
result.x = Math_default.toSNorm(result.x, rangeMax);
result.y = Math_default.toSNorm(result.y, rangeMax);
return result;
};
AttributeCompression.octEncode = function(vector, result) {
return AttributeCompression.octEncodeInRange(vector, 255, result);
};
var octEncodeScratch = new Cartesian2_default();
var uint8ForceArray = new Uint8Array(1);
function forceUint8(value) {
uint8ForceArray[0] = value;
return uint8ForceArray[0];
}
AttributeCompression.octEncodeToCartesian4 = function(vector, result) {
AttributeCompression.octEncodeInRange(vector, 65535, octEncodeScratch);
result.x = forceUint8(octEncodeScratch.x * RIGHT_SHIFT);
result.y = forceUint8(octEncodeScratch.x);
result.z = forceUint8(octEncodeScratch.y * RIGHT_SHIFT);
result.w = forceUint8(octEncodeScratch.y);
return result;
};
AttributeCompression.octDecodeInRange = function(x, y, rangeMax, result) {
Check_default.defined("result", result);
if (x < 0 || x > rangeMax || y < 0 || y > rangeMax) {
throw new DeveloperError_default(
`x and y must be unsigned normalized integers between 0 and ${rangeMax}`
);
}
result.x = Math_default.fromSNorm(x, rangeMax);
result.y = Math_default.fromSNorm(y, rangeMax);
result.z = 1 - (Math.abs(result.x) + Math.abs(result.y));
if (result.z < 0) {
const oldVX = result.x;
result.x = (1 - Math.abs(result.y)) * Math_default.signNotZero(oldVX);
result.y = (1 - Math.abs(oldVX)) * Math_default.signNotZero(result.y);
}
return Cartesian3_default.normalize(result, result);
};
AttributeCompression.octDecode = function(x, y, result) {
return AttributeCompression.octDecodeInRange(x, y, 255, result);
};
AttributeCompression.octDecodeFromCartesian4 = function(encoded, result) {
Check_default.typeOf.object("encoded", encoded);
Check_default.typeOf.object("result", result);
const x = encoded.x;
const y = encoded.y;
const z = encoded.z;
const w = encoded.w;
if (x < 0 || x > 255 || y < 0 || y > 255 || z < 0 || z > 255 || w < 0 || w > 255) {
throw new DeveloperError_default(
"x, y, z, and w must be unsigned normalized integers between 0 and 255"
);
}
const xOct16 = x * LEFT_SHIFT + y;
const yOct16 = z * LEFT_SHIFT + w;
return AttributeCompression.octDecodeInRange(xOct16, yOct16, 65535, result);
};
AttributeCompression.octPackFloat = function(encoded) {
Check_default.defined("encoded", encoded);
return 256 * encoded.x + encoded.y;
};
var scratchEncodeCart2 = new Cartesian2_default();
AttributeCompression.octEncodeFloat = function(vector) {
AttributeCompression.octEncode(vector, scratchEncodeCart2);
return AttributeCompression.octPackFloat(scratchEncodeCart2);
};
AttributeCompression.octDecodeFloat = function(value, result) {
Check_default.defined("value", value);
const temp = value / 256;
const x = Math.floor(temp);
const y = (temp - x) * 256;
return AttributeCompression.octDecode(x, y, result);
};
AttributeCompression.octPack = function(v13, v23, v32, result) {
Check_default.defined("v1", v13);
Check_default.defined("v2", v23);
Check_default.defined("v3", v32);
Check_default.defined("result", result);
const encoded1 = AttributeCompression.octEncodeFloat(v13);
const encoded2 = AttributeCompression.octEncodeFloat(v23);
const encoded3 = AttributeCompression.octEncode(v32, scratchEncodeCart2);
result.x = 65536 * encoded3.x + encoded1;
result.y = 65536 * encoded3.y + encoded2;
return result;
};
AttributeCompression.octUnpack = function(packed, v13, v23, v32) {
Check_default.defined("packed", packed);
Check_default.defined("v1", v13);
Check_default.defined("v2", v23);
Check_default.defined("v3", v32);
let temp = packed.x / 65536;
const x = Math.floor(temp);
const encodedFloat1 = (temp - x) * 65536;
temp = packed.y / 65536;
const y = Math.floor(temp);
const encodedFloat2 = (temp - y) * 65536;
AttributeCompression.octDecodeFloat(encodedFloat1, v13);
AttributeCompression.octDecodeFloat(encodedFloat2, v23);
AttributeCompression.octDecode(x, y, v32);
};
AttributeCompression.compressTextureCoordinates = function(textureCoordinates) {
Check_default.defined("textureCoordinates", textureCoordinates);
const x = textureCoordinates.x * 4095 | 0;
const y = textureCoordinates.y * 4095 | 0;
return 4096 * x + y;
};
AttributeCompression.decompressTextureCoordinates = function(compressed, result) {
Check_default.defined("compressed", compressed);
Check_default.defined("result", result);
const temp = compressed / 4096;
const xZeroTo4095 = Math.floor(temp);
result.x = xZeroTo4095 / 4095;
result.y = (compressed - xZeroTo4095 * 4096) / 4095;
return result;
};
function zigZagDecode(value) {
return value >> 1 ^ -(value & 1);
}
AttributeCompression.zigZagDeltaDecode = function(uBuffer, vBuffer, heightBuffer) {
Check_default.defined("uBuffer", uBuffer);
Check_default.defined("vBuffer", vBuffer);
Check_default.typeOf.number.equals(
"uBuffer.length",
"vBuffer.length",
uBuffer.length,
vBuffer.length
);
if (defined_default(heightBuffer)) {
Check_default.typeOf.number.equals(
"uBuffer.length",
"heightBuffer.length",
uBuffer.length,
heightBuffer.length
);
}
const count = uBuffer.length;
let u3 = 0;
let v7 = 0;
let height = 0;
for (let i = 0; i < count; ++i) {
u3 += zigZagDecode(uBuffer[i]);
v7 += zigZagDecode(vBuffer[i]);
uBuffer[i] = u3;
vBuffer[i] = v7;
if (defined_default(heightBuffer)) {
height += zigZagDecode(heightBuffer[i]);
heightBuffer[i] = height;
}
}
};
AttributeCompression.dequantize = function(typedArray, componentDatatype, type, count) {
Check_default.defined("typedArray", typedArray);
Check_default.defined("componentDatatype", componentDatatype);
Check_default.defined("type", type);
Check_default.defined("count", count);
const componentsPerAttribute = AttributeType_default.getNumberOfComponents(type);
let divisor;
switch (componentDatatype) {
case ComponentDatatype_default.BYTE:
divisor = 127;
break;
case ComponentDatatype_default.UNSIGNED_BYTE:
divisor = 255;
break;
case ComponentDatatype_default.SHORT:
divisor = 32767;
break;
case ComponentDatatype_default.UNSIGNED_SHORT:
divisor = 65535;
break;
case ComponentDatatype_default.INT:
divisor = 2147483647;
break;
case ComponentDatatype_default.UNSIGNED_INT:
divisor = 4294967295;
break;
default:
throw new DeveloperError_default(
`Cannot dequantize component datatype: ${componentDatatype}`
);
}
const dequantizedTypedArray = new Float32Array(
count * componentsPerAttribute
);
for (let i = 0; i < count; i++) {
for (let j = 0; j < componentsPerAttribute; j++) {
const index = i * componentsPerAttribute + j;
dequantizedTypedArray[index] = Math.max(
typedArray[index] / divisor,
-1
);
}
}
return dequantizedTypedArray;
};
AttributeCompression.decodeRGB565 = function(typedArray, result) {
Check_default.defined("typedArray", typedArray);
const expectedLength = typedArray.length * 3;
if (defined_default(result)) {
Check_default.typeOf.number.equals(
"result.length",
"typedArray.length * 3",
result.length,
expectedLength
);
}
const count = typedArray.length;
if (!defined_default(result)) {
result = new Float32Array(count * 3);
}
const mask5 = (1 << 5) - 1;
const mask6 = (1 << 6) - 1;
const normalize5 = 1 / 31;
const normalize6 = 1 / 63;
for (let i = 0; i < count; i++) {
const value = typedArray[i];
const red = value >> 11;
const green = value >> 5 & mask6;
const blue = value & mask5;
const offset2 = 3 * i;
result[offset2] = red * normalize5;
result[offset2 + 1] = green * normalize6;
result[offset2 + 2] = blue * normalize5;
}
return result;
};
var AttributeCompression_default = AttributeCompression;
// packages/engine/Source/Core/barycentricCoordinates.js
var scratchCartesian12 = new Cartesian3_default();
var scratchCartesian22 = new Cartesian3_default();
var scratchCartesian33 = new Cartesian3_default();
function barycentricCoordinates(point, p0, p1, p2, result) {
Check_default.defined("point", point);
Check_default.defined("p0", p0);
Check_default.defined("p1", p1);
Check_default.defined("p2", p2);
if (!defined_default(result)) {
result = new Cartesian3_default();
}
let v02;
let v13;
let v23;
let dot00;
let dot01;
let dot02;
let dot11;
let dot12;
if (!defined_default(p0.z)) {
if (Cartesian2_default.equalsEpsilon(point, p0, Math_default.EPSILON14)) {
return Cartesian3_default.clone(Cartesian3_default.UNIT_X, result);
}
if (Cartesian2_default.equalsEpsilon(point, p1, Math_default.EPSILON14)) {
return Cartesian3_default.clone(Cartesian3_default.UNIT_Y, result);
}
if (Cartesian2_default.equalsEpsilon(point, p2, Math_default.EPSILON14)) {
return Cartesian3_default.clone(Cartesian3_default.UNIT_Z, result);
}
v02 = Cartesian2_default.subtract(p1, p0, scratchCartesian12);
v13 = Cartesian2_default.subtract(p2, p0, scratchCartesian22);
v23 = Cartesian2_default.subtract(point, p0, scratchCartesian33);
dot00 = Cartesian2_default.dot(v02, v02);
dot01 = Cartesian2_default.dot(v02, v13);
dot02 = Cartesian2_default.dot(v02, v23);
dot11 = Cartesian2_default.dot(v13, v13);
dot12 = Cartesian2_default.dot(v13, v23);
} else {
if (Cartesian3_default.equalsEpsilon(point, p0, Math_default.EPSILON14)) {
return Cartesian3_default.clone(Cartesian3_default.UNIT_X, result);
}
if (Cartesian3_default.equalsEpsilon(point, p1, Math_default.EPSILON14)) {
return Cartesian3_default.clone(Cartesian3_default.UNIT_Y, result);
}
if (Cartesian3_default.equalsEpsilon(point, p2, Math_default.EPSILON14)) {
return Cartesian3_default.clone(Cartesian3_default.UNIT_Z, result);
}
v02 = Cartesian3_default.subtract(p1, p0, scratchCartesian12);
v13 = Cartesian3_default.subtract(p2, p0, scratchCartesian22);
v23 = Cartesian3_default.subtract(point, p0, scratchCartesian33);
dot00 = Cartesian3_default.dot(v02, v02);
dot01 = Cartesian3_default.dot(v02, v13);
dot02 = Cartesian3_default.dot(v02, v23);
dot11 = Cartesian3_default.dot(v13, v13);
dot12 = Cartesian3_default.dot(v13, v23);
}
result.y = dot11 * dot02 - dot01 * dot12;
result.z = dot00 * dot12 - dot01 * dot02;
const q = dot00 * dot11 - dot01 * dot01;
if (q === 0) {
return void 0;
}
result.y /= q;
result.z /= q;
result.x = 1 - result.y - result.z;
return result;
}
var barycentricCoordinates_default = barycentricCoordinates;
// packages/engine/Source/Core/Tipsify.js
var Tipsify = {};
Tipsify.calculateACMR = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const indices2 = options.indices;
let maximumIndex = options.maximumIndex;
const cacheSize = defaultValue_default(options.cacheSize, 24);
if (!defined_default(indices2)) {
throw new DeveloperError_default("indices is required.");
}
const numIndices = indices2.length;
if (numIndices < 3 || numIndices % 3 !== 0) {
throw new DeveloperError_default("indices length must be a multiple of three.");
}
if (maximumIndex <= 0) {
throw new DeveloperError_default("maximumIndex must be greater than zero.");
}
if (cacheSize < 3) {
throw new DeveloperError_default("cacheSize must be greater than two.");
}
if (!defined_default(maximumIndex)) {
maximumIndex = 0;
let currentIndex = 0;
let intoIndices = indices2[currentIndex];
while (currentIndex < numIndices) {
if (intoIndices > maximumIndex) {
maximumIndex = intoIndices;
}
++currentIndex;
intoIndices = indices2[currentIndex];
}
}
const vertexTimeStamps = [];
for (let i = 0; i < maximumIndex + 1; i++) {
vertexTimeStamps[i] = 0;
}
let s = cacheSize + 1;
for (let j = 0; j < numIndices; ++j) {
if (s - vertexTimeStamps[indices2[j]] > cacheSize) {
vertexTimeStamps[indices2[j]] = s;
++s;
}
}
return (s - cacheSize + 1) / (numIndices / 3);
};
Tipsify.tipsify = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const indices2 = options.indices;
const maximumIndex = options.maximumIndex;
const cacheSize = defaultValue_default(options.cacheSize, 24);
let cursor;
function skipDeadEnd(vertices2, deadEnd2, indices3, maximumIndexPlusOne2) {
while (deadEnd2.length >= 1) {
const d = deadEnd2[deadEnd2.length - 1];
deadEnd2.splice(deadEnd2.length - 1, 1);
if (vertices2[d].numLiveTriangles > 0) {
return d;
}
}
while (cursor < maximumIndexPlusOne2) {
if (vertices2[cursor].numLiveTriangles > 0) {
++cursor;
return cursor - 1;
}
++cursor;
}
return -1;
}
function getNextVertex(indices3, cacheSize2, oneRing2, vertices2, s2, deadEnd2, maximumIndexPlusOne2) {
let n = -1;
let p;
let m = -1;
let itOneRing = 0;
while (itOneRing < oneRing2.length) {
const index2 = oneRing2[itOneRing];
if (vertices2[index2].numLiveTriangles) {
p = 0;
if (s2 - vertices2[index2].timeStamp + 2 * vertices2[index2].numLiveTriangles <= cacheSize2) {
p = s2 - vertices2[index2].timeStamp;
}
if (p > m || m === -1) {
m = p;
n = index2;
}
}
++itOneRing;
}
if (n === -1) {
return skipDeadEnd(vertices2, deadEnd2, indices3, maximumIndexPlusOne2);
}
return n;
}
if (!defined_default(indices2)) {
throw new DeveloperError_default("indices is required.");
}
const numIndices = indices2.length;
if (numIndices < 3 || numIndices % 3 !== 0) {
throw new DeveloperError_default("indices length must be a multiple of three.");
}
if (maximumIndex <= 0) {
throw new DeveloperError_default("maximumIndex must be greater than zero.");
}
if (cacheSize < 3) {
throw new DeveloperError_default("cacheSize must be greater than two.");
}
let maximumIndexPlusOne = 0;
let currentIndex = 0;
let intoIndices = indices2[currentIndex];
const endIndex = numIndices;
if (defined_default(maximumIndex)) {
maximumIndexPlusOne = maximumIndex + 1;
} else {
while (currentIndex < endIndex) {
if (intoIndices > maximumIndexPlusOne) {
maximumIndexPlusOne = intoIndices;
}
++currentIndex;
intoIndices = indices2[currentIndex];
}
if (maximumIndexPlusOne === -1) {
return 0;
}
++maximumIndexPlusOne;
}
const vertices = [];
let i;
for (i = 0; i < maximumIndexPlusOne; i++) {
vertices[i] = {
numLiveTriangles: 0,
timeStamp: 0,
vertexTriangles: []
};
}
currentIndex = 0;
let triangle = 0;
while (currentIndex < endIndex) {
vertices[indices2[currentIndex]].vertexTriangles.push(triangle);
++vertices[indices2[currentIndex]].numLiveTriangles;
vertices[indices2[currentIndex + 1]].vertexTriangles.push(triangle);
++vertices[indices2[currentIndex + 1]].numLiveTriangles;
vertices[indices2[currentIndex + 2]].vertexTriangles.push(triangle);
++vertices[indices2[currentIndex + 2]].numLiveTriangles;
++triangle;
currentIndex += 3;
}
let f = 0;
let s = cacheSize + 1;
cursor = 1;
let oneRing = [];
const deadEnd = [];
let vertex;
let intoVertices;
let currentOutputIndex = 0;
const outputIndices = [];
const numTriangles = numIndices / 3;
const triangleEmitted = [];
for (i = 0; i < numTriangles; i++) {
triangleEmitted[i] = false;
}
let index;
let limit;
while (f !== -1) {
oneRing = [];
intoVertices = vertices[f];
limit = intoVertices.vertexTriangles.length;
for (let k = 0; k < limit; ++k) {
triangle = intoVertices.vertexTriangles[k];
if (!triangleEmitted[triangle]) {
triangleEmitted[triangle] = true;
currentIndex = triangle + triangle + triangle;
for (let j = 0; j < 3; ++j) {
index = indices2[currentIndex];
oneRing.push(index);
deadEnd.push(index);
outputIndices[currentOutputIndex] = index;
++currentOutputIndex;
vertex = vertices[index];
--vertex.numLiveTriangles;
if (s - vertex.timeStamp > cacheSize) {
vertex.timeStamp = s;
++s;
}
++currentIndex;
}
}
}
f = getNextVertex(
indices2,
cacheSize,
oneRing,
vertices,
s,
deadEnd,
maximumIndexPlusOne
);
}
return outputIndices;
};
var Tipsify_default = Tipsify;
// packages/engine/Source/Core/GeometryPipeline.js
var GeometryPipeline = {};
function addTriangle(lines, index, i0, i1, i2) {
lines[index++] = i0;
lines[index++] = i1;
lines[index++] = i1;
lines[index++] = i2;
lines[index++] = i2;
lines[index] = i0;
}
function trianglesToLines(triangles) {
const count = triangles.length;
const size = count / 3 * 6;
const lines = IndexDatatype_default.createTypedArray(count, size);
let index = 0;
for (let i = 0; i < count; i += 3, index += 6) {
addTriangle(lines, index, triangles[i], triangles[i + 1], triangles[i + 2]);
}
return lines;
}
function triangleStripToLines(triangles) {
const count = triangles.length;
if (count >= 3) {
const size = (count - 2) * 6;
const lines = IndexDatatype_default.createTypedArray(count, size);
addTriangle(lines, 0, triangles[0], triangles[1], triangles[2]);
let index = 6;
for (let i = 3; i < count; ++i, index += 6) {
addTriangle(
lines,
index,
triangles[i - 1],
triangles[i],
triangles[i - 2]
);
}
return lines;
}
return new Uint16Array();
}
function triangleFanToLines(triangles) {
if (triangles.length > 0) {
const count = triangles.length - 1;
const size = (count - 1) * 6;
const lines = IndexDatatype_default.createTypedArray(count, size);
const base = triangles[0];
let index = 0;
for (let i = 1; i < count; ++i, index += 6) {
addTriangle(lines, index, base, triangles[i], triangles[i + 1]);
}
return lines;
}
return new Uint16Array();
}
GeometryPipeline.toWireframe = function(geometry) {
if (!defined_default(geometry)) {
throw new DeveloperError_default("geometry is required.");
}
const indices2 = geometry.indices;
if (defined_default(indices2)) {
switch (geometry.primitiveType) {
case PrimitiveType_default.TRIANGLES:
geometry.indices = trianglesToLines(indices2);
break;
case PrimitiveType_default.TRIANGLE_STRIP:
geometry.indices = triangleStripToLines(indices2);
break;
case PrimitiveType_default.TRIANGLE_FAN:
geometry.indices = triangleFanToLines(indices2);
break;
default:
throw new DeveloperError_default(
"geometry.primitiveType must be TRIANGLES, TRIANGLE_STRIP, or TRIANGLE_FAN."
);
}
geometry.primitiveType = PrimitiveType_default.LINES;
}
return geometry;
};
GeometryPipeline.createLineSegmentsForVectors = function(geometry, attributeName, length3) {
attributeName = defaultValue_default(attributeName, "normal");
if (!defined_default(geometry)) {
throw new DeveloperError_default("geometry is required.");
}
if (!defined_default(geometry.attributes.position)) {
throw new DeveloperError_default("geometry.attributes.position is required.");
}
if (!defined_default(geometry.attributes[attributeName])) {
throw new DeveloperError_default(
`geometry.attributes must have an attribute with the same name as the attributeName parameter, ${attributeName}.`
);
}
length3 = defaultValue_default(length3, 1e4);
const positions = geometry.attributes.position.values;
const vectors = geometry.attributes[attributeName].values;
const positionsLength = positions.length;
const newPositions = new Float64Array(2 * positionsLength);
let j = 0;
for (let i = 0; i < positionsLength; i += 3) {
newPositions[j++] = positions[i];
newPositions[j++] = positions[i + 1];
newPositions[j++] = positions[i + 2];
newPositions[j++] = positions[i] + vectors[i] * length3;
newPositions[j++] = positions[i + 1] + vectors[i + 1] * length3;
newPositions[j++] = positions[i + 2] + vectors[i + 2] * length3;
}
let newBoundingSphere;
const bs = geometry.boundingSphere;
if (defined_default(bs)) {
newBoundingSphere = new BoundingSphere_default(bs.center, bs.radius + length3);
}
return new Geometry_default({
attributes: {
position: new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: newPositions
})
},
primitiveType: PrimitiveType_default.LINES,
boundingSphere: newBoundingSphere
});
};
GeometryPipeline.createAttributeLocations = function(geometry) {
if (!defined_default(geometry)) {
throw new DeveloperError_default("geometry is required.");
}
const semantics = [
"position",
"positionHigh",
"positionLow",
// From VertexFormat.position - after 2D projection and high-precision encoding
"position3DHigh",
"position3DLow",
"position2DHigh",
"position2DLow",
// From Primitive
"pickColor",
// From VertexFormat
"normal",
"st",
"tangent",
"bitangent",
// For shadow volumes
"extrudeDirection",
// From compressing texture coordinates and normals
"compressedAttributes"
];
const attributes = geometry.attributes;
const indices2 = {};
let j = 0;
let i;
const len = semantics.length;
for (i = 0; i < len; ++i) {
const semantic = semantics[i];
if (defined_default(attributes[semantic])) {
indices2[semantic] = j++;
}
}
for (const name in attributes) {
if (attributes.hasOwnProperty(name) && !defined_default(indices2[name])) {
indices2[name] = j++;
}
}
return indices2;
};
GeometryPipeline.reorderForPreVertexCache = function(geometry) {
if (!defined_default(geometry)) {
throw new DeveloperError_default("geometry is required.");
}
const numVertices = Geometry_default.computeNumberOfVertices(geometry);
const indices2 = geometry.indices;
if (defined_default(indices2)) {
const indexCrossReferenceOldToNew = new Int32Array(numVertices);
for (let i = 0; i < numVertices; i++) {
indexCrossReferenceOldToNew[i] = -1;
}
const indicesIn = indices2;
const numIndices = indicesIn.length;
const indicesOut = IndexDatatype_default.createTypedArray(numVertices, numIndices);
let intoIndicesIn = 0;
let intoIndicesOut = 0;
let nextIndex = 0;
let tempIndex;
while (intoIndicesIn < numIndices) {
tempIndex = indexCrossReferenceOldToNew[indicesIn[intoIndicesIn]];
if (tempIndex !== -1) {
indicesOut[intoIndicesOut] = tempIndex;
} else {
tempIndex = indicesIn[intoIndicesIn];
indexCrossReferenceOldToNew[tempIndex] = nextIndex;
indicesOut[intoIndicesOut] = nextIndex;
++nextIndex;
}
++intoIndicesIn;
++intoIndicesOut;
}
geometry.indices = indicesOut;
const attributes = geometry.attributes;
for (const property in attributes) {
if (attributes.hasOwnProperty(property) && defined_default(attributes[property]) && defined_default(attributes[property].values)) {
const attribute = attributes[property];
const elementsIn = attribute.values;
let intoElementsIn = 0;
const numComponents = attribute.componentsPerAttribute;
const elementsOut = ComponentDatatype_default.createTypedArray(
attribute.componentDatatype,
nextIndex * numComponents
);
while (intoElementsIn < numVertices) {
const temp = indexCrossReferenceOldToNew[intoElementsIn];
if (temp !== -1) {
for (let j = 0; j < numComponents; j++) {
elementsOut[numComponents * temp + j] = elementsIn[numComponents * intoElementsIn + j];
}
}
++intoElementsIn;
}
attribute.values = elementsOut;
}
}
}
return geometry;
};
GeometryPipeline.reorderForPostVertexCache = function(geometry, cacheCapacity) {
if (!defined_default(geometry)) {
throw new DeveloperError_default("geometry is required.");
}
const indices2 = geometry.indices;
if (geometry.primitiveType === PrimitiveType_default.TRIANGLES && defined_default(indices2)) {
const numIndices = indices2.length;
let maximumIndex = 0;
for (let j = 0; j < numIndices; j++) {
if (indices2[j] > maximumIndex) {
maximumIndex = indices2[j];
}
}
geometry.indices = Tipsify_default.tipsify({
indices: indices2,
maximumIndex,
cacheSize: cacheCapacity
});
}
return geometry;
};
function copyAttributesDescriptions(attributes) {
const newAttributes = {};
for (const attribute in attributes) {
if (attributes.hasOwnProperty(attribute) && defined_default(attributes[attribute]) && defined_default(attributes[attribute].values)) {
const attr = attributes[attribute];
newAttributes[attribute] = new GeometryAttribute_default({
componentDatatype: attr.componentDatatype,
componentsPerAttribute: attr.componentsPerAttribute,
normalize: attr.normalize,
values: []
});
}
}
return newAttributes;
}
function copyVertex(destinationAttributes, sourceAttributes, index) {
for (const attribute in sourceAttributes) {
if (sourceAttributes.hasOwnProperty(attribute) && defined_default(sourceAttributes[attribute]) && defined_default(sourceAttributes[attribute].values)) {
const attr = sourceAttributes[attribute];
for (let k = 0; k < attr.componentsPerAttribute; ++k) {
destinationAttributes[attribute].values.push(
attr.values[index * attr.componentsPerAttribute + k]
);
}
}
}
}
GeometryPipeline.fitToUnsignedShortIndices = function(geometry) {
if (!defined_default(geometry)) {
throw new DeveloperError_default("geometry is required.");
}
if (defined_default(geometry.indices) && geometry.primitiveType !== PrimitiveType_default.TRIANGLES && geometry.primitiveType !== PrimitiveType_default.LINES && geometry.primitiveType !== PrimitiveType_default.POINTS) {
throw new DeveloperError_default(
"geometry.primitiveType must equal to PrimitiveType.TRIANGLES, PrimitiveType.LINES, or PrimitiveType.POINTS."
);
}
const geometries = [];
const numberOfVertices = Geometry_default.computeNumberOfVertices(geometry);
if (defined_default(geometry.indices) && numberOfVertices >= Math_default.SIXTY_FOUR_KILOBYTES) {
let oldToNewIndex = [];
let newIndices = [];
let currentIndex = 0;
let newAttributes = copyAttributesDescriptions(geometry.attributes);
const originalIndices = geometry.indices;
const numberOfIndices = originalIndices.length;
let indicesPerPrimitive;
if (geometry.primitiveType === PrimitiveType_default.TRIANGLES) {
indicesPerPrimitive = 3;
} else if (geometry.primitiveType === PrimitiveType_default.LINES) {
indicesPerPrimitive = 2;
} else if (geometry.primitiveType === PrimitiveType_default.POINTS) {
indicesPerPrimitive = 1;
}
for (let j = 0; j < numberOfIndices; j += indicesPerPrimitive) {
for (let k = 0; k < indicesPerPrimitive; ++k) {
const x = originalIndices[j + k];
let i = oldToNewIndex[x];
if (!defined_default(i)) {
i = currentIndex++;
oldToNewIndex[x] = i;
copyVertex(newAttributes, geometry.attributes, x);
}
newIndices.push(i);
}
if (currentIndex + indicesPerPrimitive >= Math_default.SIXTY_FOUR_KILOBYTES) {
geometries.push(
new Geometry_default({
attributes: newAttributes,
indices: newIndices,
primitiveType: geometry.primitiveType,
boundingSphere: geometry.boundingSphere,
boundingSphereCV: geometry.boundingSphereCV
})
);
oldToNewIndex = [];
newIndices = [];
currentIndex = 0;
newAttributes = copyAttributesDescriptions(geometry.attributes);
}
}
if (newIndices.length !== 0) {
geometries.push(
new Geometry_default({
attributes: newAttributes,
indices: newIndices,
primitiveType: geometry.primitiveType,
boundingSphere: geometry.boundingSphere,
boundingSphereCV: geometry.boundingSphereCV
})
);
}
} else {
geometries.push(geometry);
}
return geometries;
};
var scratchProjectTo2DCartesian3 = new Cartesian3_default();
var scratchProjectTo2DCartographic = new Cartographic_default();
GeometryPipeline.projectTo2D = function(geometry, attributeName, attributeName3D, attributeName2D, projection) {
if (!defined_default(geometry)) {
throw new DeveloperError_default("geometry is required.");
}
if (!defined_default(attributeName)) {
throw new DeveloperError_default("attributeName is required.");
}
if (!defined_default(attributeName3D)) {
throw new DeveloperError_default("attributeName3D is required.");
}
if (!defined_default(attributeName2D)) {
throw new DeveloperError_default("attributeName2D is required.");
}
if (!defined_default(geometry.attributes[attributeName])) {
throw new DeveloperError_default(
`geometry must have attribute matching the attributeName argument: ${attributeName}.`
);
}
if (geometry.attributes[attributeName].componentDatatype !== ComponentDatatype_default.DOUBLE) {
throw new DeveloperError_default(
"The attribute componentDatatype must be ComponentDatatype.DOUBLE."
);
}
const attribute = geometry.attributes[attributeName];
projection = defined_default(projection) ? projection : new GeographicProjection_default();
const ellipsoid = projection.ellipsoid;
const values3D = attribute.values;
const projectedValues = new Float64Array(values3D.length);
let index = 0;
for (let i = 0; i < values3D.length; i += 3) {
const value = Cartesian3_default.fromArray(
values3D,
i,
scratchProjectTo2DCartesian3
);
const lonLat = ellipsoid.cartesianToCartographic(
value,
scratchProjectTo2DCartographic
);
if (!defined_default(lonLat)) {
throw new DeveloperError_default(
`Could not project point (${value.x}, ${value.y}, ${value.z}) to 2D.`
);
}
const projectedLonLat = projection.project(
lonLat,
scratchProjectTo2DCartesian3
);
projectedValues[index++] = projectedLonLat.x;
projectedValues[index++] = projectedLonLat.y;
projectedValues[index++] = projectedLonLat.z;
}
geometry.attributes[attributeName3D] = attribute;
geometry.attributes[attributeName2D] = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: projectedValues
});
delete geometry.attributes[attributeName];
return geometry;
};
var encodedResult = {
high: 0,
low: 0
};
GeometryPipeline.encodeAttribute = function(geometry, attributeName, attributeHighName, attributeLowName) {
if (!defined_default(geometry)) {
throw new DeveloperError_default("geometry is required.");
}
if (!defined_default(attributeName)) {
throw new DeveloperError_default("attributeName is required.");
}
if (!defined_default(attributeHighName)) {
throw new DeveloperError_default("attributeHighName is required.");
}
if (!defined_default(attributeLowName)) {
throw new DeveloperError_default("attributeLowName is required.");
}
if (!defined_default(geometry.attributes[attributeName])) {
throw new DeveloperError_default(
`geometry must have attribute matching the attributeName argument: ${attributeName}.`
);
}
if (geometry.attributes[attributeName].componentDatatype !== ComponentDatatype_default.DOUBLE) {
throw new DeveloperError_default(
"The attribute componentDatatype must be ComponentDatatype.DOUBLE."
);
}
const attribute = geometry.attributes[attributeName];
const values = attribute.values;
const length3 = values.length;
const highValues = new Float32Array(length3);
const lowValues = new Float32Array(length3);
for (let i = 0; i < length3; ++i) {
EncodedCartesian3_default.encode(values[i], encodedResult);
highValues[i] = encodedResult.high;
lowValues[i] = encodedResult.low;
}
const componentsPerAttribute = attribute.componentsPerAttribute;
geometry.attributes[attributeHighName] = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute,
values: highValues
});
geometry.attributes[attributeLowName] = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute,
values: lowValues
});
delete geometry.attributes[attributeName];
return geometry;
};
var scratchCartesian34 = new Cartesian3_default();
function transformPoint(matrix, attribute) {
if (defined_default(attribute)) {
const values = attribute.values;
const length3 = values.length;
for (let i = 0; i < length3; i += 3) {
Cartesian3_default.unpack(values, i, scratchCartesian34);
Matrix4_default.multiplyByPoint(matrix, scratchCartesian34, scratchCartesian34);
Cartesian3_default.pack(scratchCartesian34, values, i);
}
}
}
function transformVector(matrix, attribute) {
if (defined_default(attribute)) {
const values = attribute.values;
const length3 = values.length;
for (let i = 0; i < length3; i += 3) {
Cartesian3_default.unpack(values, i, scratchCartesian34);
Matrix3_default.multiplyByVector(matrix, scratchCartesian34, scratchCartesian34);
scratchCartesian34 = Cartesian3_default.normalize(
scratchCartesian34,
scratchCartesian34
);
Cartesian3_default.pack(scratchCartesian34, values, i);
}
}
}
var inverseTranspose = new Matrix4_default();
var normalMatrix = new Matrix3_default();
GeometryPipeline.transformToWorldCoordinates = function(instance) {
if (!defined_default(instance)) {
throw new DeveloperError_default("instance is required.");
}
const modelMatrix = instance.modelMatrix;
if (Matrix4_default.equals(modelMatrix, Matrix4_default.IDENTITY)) {
return instance;
}
const attributes = instance.geometry.attributes;
transformPoint(modelMatrix, attributes.position);
transformPoint(modelMatrix, attributes.prevPosition);
transformPoint(modelMatrix, attributes.nextPosition);
if (defined_default(attributes.normal) || defined_default(attributes.tangent) || defined_default(attributes.bitangent)) {
Matrix4_default.inverse(modelMatrix, inverseTranspose);
Matrix4_default.transpose(inverseTranspose, inverseTranspose);
Matrix4_default.getMatrix3(inverseTranspose, normalMatrix);
transformVector(normalMatrix, attributes.normal);
transformVector(normalMatrix, attributes.tangent);
transformVector(normalMatrix, attributes.bitangent);
}
const boundingSphere = instance.geometry.boundingSphere;
if (defined_default(boundingSphere)) {
instance.geometry.boundingSphere = BoundingSphere_default.transform(
boundingSphere,
modelMatrix,
boundingSphere
);
}
instance.modelMatrix = Matrix4_default.clone(Matrix4_default.IDENTITY);
return instance;
};
function findAttributesInAllGeometries(instances, propertyName) {
const length3 = instances.length;
const attributesInAllGeometries = {};
const attributes0 = instances[0][propertyName].attributes;
let name;
for (name in attributes0) {
if (attributes0.hasOwnProperty(name) && defined_default(attributes0[name]) && defined_default(attributes0[name].values)) {
const attribute = attributes0[name];
let numberOfComponents = attribute.values.length;
let inAllGeometries = true;
for (let i = 1; i < length3; ++i) {
const otherAttribute = instances[i][propertyName].attributes[name];
if (!defined_default(otherAttribute) || attribute.componentDatatype !== otherAttribute.componentDatatype || attribute.componentsPerAttribute !== otherAttribute.componentsPerAttribute || attribute.normalize !== otherAttribute.normalize) {
inAllGeometries = false;
break;
}
numberOfComponents += otherAttribute.values.length;
}
if (inAllGeometries) {
attributesInAllGeometries[name] = new GeometryAttribute_default({
componentDatatype: attribute.componentDatatype,
componentsPerAttribute: attribute.componentsPerAttribute,
normalize: attribute.normalize,
values: ComponentDatatype_default.createTypedArray(
attribute.componentDatatype,
numberOfComponents
)
});
}
}
}
return attributesInAllGeometries;
}
var tempScratch = new Cartesian3_default();
function combineGeometries(instances, propertyName) {
const length3 = instances.length;
let name;
let i;
let j;
let k;
const m = instances[0].modelMatrix;
const haveIndices = defined_default(instances[0][propertyName].indices);
const primitiveType = instances[0][propertyName].primitiveType;
for (i = 1; i < length3; ++i) {
if (!Matrix4_default.equals(instances[i].modelMatrix, m)) {
throw new DeveloperError_default("All instances must have the same modelMatrix.");
}
if (defined_default(instances[i][propertyName].indices) !== haveIndices) {
throw new DeveloperError_default(
"All instance geometries must have an indices or not have one."
);
}
if (instances[i][propertyName].primitiveType !== primitiveType) {
throw new DeveloperError_default(
"All instance geometries must have the same primitiveType."
);
}
}
const attributes = findAttributesInAllGeometries(instances, propertyName);
let values;
let sourceValues;
let sourceValuesLength;
for (name in attributes) {
if (attributes.hasOwnProperty(name)) {
values = attributes[name].values;
k = 0;
for (i = 0; i < length3; ++i) {
sourceValues = instances[i][propertyName].attributes[name].values;
sourceValuesLength = sourceValues.length;
for (j = 0; j < sourceValuesLength; ++j) {
values[k++] = sourceValues[j];
}
}
}
}
let indices2;
if (haveIndices) {
let numberOfIndices = 0;
for (i = 0; i < length3; ++i) {
numberOfIndices += instances[i][propertyName].indices.length;
}
const numberOfVertices = Geometry_default.computeNumberOfVertices(
new Geometry_default({
attributes,
primitiveType: PrimitiveType_default.POINTS
})
);
const destIndices = IndexDatatype_default.createTypedArray(
numberOfVertices,
numberOfIndices
);
let destOffset = 0;
let offset2 = 0;
for (i = 0; i < length3; ++i) {
const sourceIndices = instances[i][propertyName].indices;
const sourceIndicesLen = sourceIndices.length;
for (k = 0; k < sourceIndicesLen; ++k) {
destIndices[destOffset++] = offset2 + sourceIndices[k];
}
offset2 += Geometry_default.computeNumberOfVertices(instances[i][propertyName]);
}
indices2 = destIndices;
}
let center = new Cartesian3_default();
let radius = 0;
let bs;
for (i = 0; i < length3; ++i) {
bs = instances[i][propertyName].boundingSphere;
if (!defined_default(bs)) {
center = void 0;
break;
}
Cartesian3_default.add(bs.center, center, center);
}
if (defined_default(center)) {
Cartesian3_default.divideByScalar(center, length3, center);
for (i = 0; i < length3; ++i) {
bs = instances[i][propertyName].boundingSphere;
const tempRadius = Cartesian3_default.magnitude(
Cartesian3_default.subtract(bs.center, center, tempScratch)
) + bs.radius;
if (tempRadius > radius) {
radius = tempRadius;
}
}
}
return new Geometry_default({
attributes,
indices: indices2,
primitiveType,
boundingSphere: defined_default(center) ? new BoundingSphere_default(center, radius) : void 0
});
}
GeometryPipeline.combineInstances = function(instances) {
if (!defined_default(instances) || instances.length < 1) {
throw new DeveloperError_default(
"instances is required and must have length greater than zero."
);
}
const instanceGeometry = [];
const instanceSplitGeometry = [];
const length3 = instances.length;
for (let i = 0; i < length3; ++i) {
const instance = instances[i];
if (defined_default(instance.geometry)) {
instanceGeometry.push(instance);
} else if (defined_default(instance.westHemisphereGeometry) && defined_default(instance.eastHemisphereGeometry)) {
instanceSplitGeometry.push(instance);
}
}
const geometries = [];
if (instanceGeometry.length > 0) {
geometries.push(combineGeometries(instanceGeometry, "geometry"));
}
if (instanceSplitGeometry.length > 0) {
geometries.push(
combineGeometries(instanceSplitGeometry, "westHemisphereGeometry")
);
geometries.push(
combineGeometries(instanceSplitGeometry, "eastHemisphereGeometry")
);
}
return geometries;
};
var normal = new Cartesian3_default();
var v0 = new Cartesian3_default();
var v1 = new Cartesian3_default();
var v2 = new Cartesian3_default();
GeometryPipeline.computeNormal = function(geometry) {
if (!defined_default(geometry)) {
throw new DeveloperError_default("geometry is required.");
}
if (!defined_default(geometry.attributes.position) || !defined_default(geometry.attributes.position.values)) {
throw new DeveloperError_default(
"geometry.attributes.position.values is required."
);
}
if (!defined_default(geometry.indices)) {
throw new DeveloperError_default("geometry.indices is required.");
}
if (geometry.indices.length < 2 || geometry.indices.length % 3 !== 0) {
throw new DeveloperError_default(
"geometry.indices length must be greater than 0 and be a multiple of 3."
);
}
if (geometry.primitiveType !== PrimitiveType_default.TRIANGLES) {
throw new DeveloperError_default(
"geometry.primitiveType must be PrimitiveType.TRIANGLES."
);
}
const indices2 = geometry.indices;
const attributes = geometry.attributes;
const vertices = attributes.position.values;
const numVertices = attributes.position.values.length / 3;
const numIndices = indices2.length;
const normalsPerVertex = new Array(numVertices);
const normalsPerTriangle = new Array(numIndices / 3);
const normalIndices = new Array(numIndices);
let i;
for (i = 0; i < numVertices; i++) {
normalsPerVertex[i] = {
indexOffset: 0,
count: 0,
currentCount: 0
};
}
let j = 0;
for (i = 0; i < numIndices; i += 3) {
const i0 = indices2[i];
const i1 = indices2[i + 1];
const i2 = indices2[i + 2];
const i03 = i0 * 3;
const i13 = i1 * 3;
const i23 = i2 * 3;
v0.x = vertices[i03];
v0.y = vertices[i03 + 1];
v0.z = vertices[i03 + 2];
v1.x = vertices[i13];
v1.y = vertices[i13 + 1];
v1.z = vertices[i13 + 2];
v2.x = vertices[i23];
v2.y = vertices[i23 + 1];
v2.z = vertices[i23 + 2];
normalsPerVertex[i0].count++;
normalsPerVertex[i1].count++;
normalsPerVertex[i2].count++;
Cartesian3_default.subtract(v1, v0, v1);
Cartesian3_default.subtract(v2, v0, v2);
normalsPerTriangle[j] = Cartesian3_default.cross(v1, v2, new Cartesian3_default());
j++;
}
let indexOffset = 0;
for (i = 0; i < numVertices; i++) {
normalsPerVertex[i].indexOffset += indexOffset;
indexOffset += normalsPerVertex[i].count;
}
j = 0;
let vertexNormalData;
for (i = 0; i < numIndices; i += 3) {
vertexNormalData = normalsPerVertex[indices2[i]];
let index = vertexNormalData.indexOffset + vertexNormalData.currentCount;
normalIndices[index] = j;
vertexNormalData.currentCount++;
vertexNormalData = normalsPerVertex[indices2[i + 1]];
index = vertexNormalData.indexOffset + vertexNormalData.currentCount;
normalIndices[index] = j;
vertexNormalData.currentCount++;
vertexNormalData = normalsPerVertex[indices2[i + 2]];
index = vertexNormalData.indexOffset + vertexNormalData.currentCount;
normalIndices[index] = j;
vertexNormalData.currentCount++;
j++;
}
const normalValues = new Float32Array(numVertices * 3);
for (i = 0; i < numVertices; i++) {
const i3 = i * 3;
vertexNormalData = normalsPerVertex[i];
Cartesian3_default.clone(Cartesian3_default.ZERO, normal);
if (vertexNormalData.count > 0) {
for (j = 0; j < vertexNormalData.count; j++) {
Cartesian3_default.add(
normal,
normalsPerTriangle[normalIndices[vertexNormalData.indexOffset + j]],
normal
);
}
if (Cartesian3_default.equalsEpsilon(Cartesian3_default.ZERO, normal, Math_default.EPSILON10)) {
Cartesian3_default.clone(
normalsPerTriangle[normalIndices[vertexNormalData.indexOffset]],
normal
);
}
}
if (Cartesian3_default.equalsEpsilon(Cartesian3_default.ZERO, normal, Math_default.EPSILON10)) {
normal.z = 1;
}
Cartesian3_default.normalize(normal, normal);
normalValues[i3] = normal.x;
normalValues[i3 + 1] = normal.y;
normalValues[i3 + 2] = normal.z;
}
geometry.attributes.normal = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: normalValues
});
return geometry;
};
var normalScratch2 = new Cartesian3_default();
var normalScale = new Cartesian3_default();
var tScratch = new Cartesian3_default();
GeometryPipeline.computeTangentAndBitangent = function(geometry) {
if (!defined_default(geometry)) {
throw new DeveloperError_default("geometry is required.");
}
const attributes = geometry.attributes;
const indices2 = geometry.indices;
if (!defined_default(attributes.position) || !defined_default(attributes.position.values)) {
throw new DeveloperError_default(
"geometry.attributes.position.values is required."
);
}
if (!defined_default(attributes.normal) || !defined_default(attributes.normal.values)) {
throw new DeveloperError_default("geometry.attributes.normal.values is required.");
}
if (!defined_default(attributes.st) || !defined_default(attributes.st.values)) {
throw new DeveloperError_default("geometry.attributes.st.values is required.");
}
if (!defined_default(indices2)) {
throw new DeveloperError_default("geometry.indices is required.");
}
if (indices2.length < 2 || indices2.length % 3 !== 0) {
throw new DeveloperError_default(
"geometry.indices length must be greater than 0 and be a multiple of 3."
);
}
if (geometry.primitiveType !== PrimitiveType_default.TRIANGLES) {
throw new DeveloperError_default(
"geometry.primitiveType must be PrimitiveType.TRIANGLES."
);
}
const vertices = geometry.attributes.position.values;
const normals = geometry.attributes.normal.values;
const st = geometry.attributes.st.values;
const numVertices = geometry.attributes.position.values.length / 3;
const numIndices = indices2.length;
const tan1 = new Array(numVertices * 3);
let i;
for (i = 0; i < tan1.length; i++) {
tan1[i] = 0;
}
let i03;
let i13;
let i23;
for (i = 0; i < numIndices; i += 3) {
const i0 = indices2[i];
const i1 = indices2[i + 1];
const i2 = indices2[i + 2];
i03 = i0 * 3;
i13 = i1 * 3;
i23 = i2 * 3;
const i02 = i0 * 2;
const i12 = i1 * 2;
const i22 = i2 * 2;
const ux = vertices[i03];
const uy = vertices[i03 + 1];
const uz = vertices[i03 + 2];
const wx = st[i02];
const wy = st[i02 + 1];
const t1 = st[i12 + 1] - wy;
const t2 = st[i22 + 1] - wy;
const r = 1 / ((st[i12] - wx) * t2 - (st[i22] - wx) * t1);
const sdirx = (t2 * (vertices[i13] - ux) - t1 * (vertices[i23] - ux)) * r;
const sdiry = (t2 * (vertices[i13 + 1] - uy) - t1 * (vertices[i23 + 1] - uy)) * r;
const sdirz = (t2 * (vertices[i13 + 2] - uz) - t1 * (vertices[i23 + 2] - uz)) * r;
tan1[i03] += sdirx;
tan1[i03 + 1] += sdiry;
tan1[i03 + 2] += sdirz;
tan1[i13] += sdirx;
tan1[i13 + 1] += sdiry;
tan1[i13 + 2] += sdirz;
tan1[i23] += sdirx;
tan1[i23 + 1] += sdiry;
tan1[i23 + 2] += sdirz;
}
const tangentValues = new Float32Array(numVertices * 3);
const bitangentValues = new Float32Array(numVertices * 3);
for (i = 0; i < numVertices; i++) {
i03 = i * 3;
i13 = i03 + 1;
i23 = i03 + 2;
const n = Cartesian3_default.fromArray(normals, i03, normalScratch2);
const t = Cartesian3_default.fromArray(tan1, i03, tScratch);
const scalar = Cartesian3_default.dot(n, t);
Cartesian3_default.multiplyByScalar(n, scalar, normalScale);
Cartesian3_default.normalize(Cartesian3_default.subtract(t, normalScale, t), t);
tangentValues[i03] = t.x;
tangentValues[i13] = t.y;
tangentValues[i23] = t.z;
Cartesian3_default.normalize(Cartesian3_default.cross(n, t, t), t);
bitangentValues[i03] = t.x;
bitangentValues[i13] = t.y;
bitangentValues[i23] = t.z;
}
geometry.attributes.tangent = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: tangentValues
});
geometry.attributes.bitangent = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: bitangentValues
});
return geometry;
};
var scratchCartesian23 = new Cartesian2_default();
var toEncode1 = new Cartesian3_default();
var toEncode2 = new Cartesian3_default();
var toEncode3 = new Cartesian3_default();
var encodeResult2 = new Cartesian2_default();
GeometryPipeline.compressVertices = function(geometry) {
if (!defined_default(geometry)) {
throw new DeveloperError_default("geometry is required.");
}
const extrudeAttribute = geometry.attributes.extrudeDirection;
let i;
let numVertices;
if (defined_default(extrudeAttribute)) {
const extrudeDirections = extrudeAttribute.values;
numVertices = extrudeDirections.length / 3;
const compressedDirections = new Float32Array(numVertices * 2);
let i2 = 0;
for (i = 0; i < numVertices; ++i) {
Cartesian3_default.fromArray(extrudeDirections, i * 3, toEncode1);
if (Cartesian3_default.equals(toEncode1, Cartesian3_default.ZERO)) {
i2 += 2;
continue;
}
encodeResult2 = AttributeCompression_default.octEncodeInRange(
toEncode1,
65535,
encodeResult2
);
compressedDirections[i2++] = encodeResult2.x;
compressedDirections[i2++] = encodeResult2.y;
}
geometry.attributes.compressedAttributes = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 2,
values: compressedDirections
});
delete geometry.attributes.extrudeDirection;
return geometry;
}
const normalAttribute = geometry.attributes.normal;
const stAttribute = geometry.attributes.st;
const hasNormal = defined_default(normalAttribute);
const hasSt = defined_default(stAttribute);
if (!hasNormal && !hasSt) {
return geometry;
}
const tangentAttribute = geometry.attributes.tangent;
const bitangentAttribute = geometry.attributes.bitangent;
const hasTangent = defined_default(tangentAttribute);
const hasBitangent = defined_default(bitangentAttribute);
let normals;
let st;
let tangents;
let bitangents;
if (hasNormal) {
normals = normalAttribute.values;
}
if (hasSt) {
st = stAttribute.values;
}
if (hasTangent) {
tangents = tangentAttribute.values;
}
if (hasBitangent) {
bitangents = bitangentAttribute.values;
}
const length3 = hasNormal ? normals.length : st.length;
const numComponents = hasNormal ? 3 : 2;
numVertices = length3 / numComponents;
let compressedLength = numVertices;
let numCompressedComponents = hasSt && hasNormal ? 2 : 1;
numCompressedComponents += hasTangent || hasBitangent ? 1 : 0;
compressedLength *= numCompressedComponents;
const compressedAttributes = new Float32Array(compressedLength);
let normalIndex = 0;
for (i = 0; i < numVertices; ++i) {
if (hasSt) {
Cartesian2_default.fromArray(st, i * 2, scratchCartesian23);
compressedAttributes[normalIndex++] = AttributeCompression_default.compressTextureCoordinates(scratchCartesian23);
}
const index = i * 3;
if (hasNormal && defined_default(tangents) && defined_default(bitangents)) {
Cartesian3_default.fromArray(normals, index, toEncode1);
Cartesian3_default.fromArray(tangents, index, toEncode2);
Cartesian3_default.fromArray(bitangents, index, toEncode3);
AttributeCompression_default.octPack(
toEncode1,
toEncode2,
toEncode3,
scratchCartesian23
);
compressedAttributes[normalIndex++] = scratchCartesian23.x;
compressedAttributes[normalIndex++] = scratchCartesian23.y;
} else {
if (hasNormal) {
Cartesian3_default.fromArray(normals, index, toEncode1);
compressedAttributes[normalIndex++] = AttributeCompression_default.octEncodeFloat(toEncode1);
}
if (hasTangent) {
Cartesian3_default.fromArray(tangents, index, toEncode1);
compressedAttributes[normalIndex++] = AttributeCompression_default.octEncodeFloat(toEncode1);
}
if (hasBitangent) {
Cartesian3_default.fromArray(bitangents, index, toEncode1);
compressedAttributes[normalIndex++] = AttributeCompression_default.octEncodeFloat(toEncode1);
}
}
}
geometry.attributes.compressedAttributes = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: numCompressedComponents,
values: compressedAttributes
});
if (hasNormal) {
delete geometry.attributes.normal;
}
if (hasSt) {
delete geometry.attributes.st;
}
if (hasBitangent) {
delete geometry.attributes.bitangent;
}
if (hasTangent) {
delete geometry.attributes.tangent;
}
return geometry;
};
function indexTriangles(geometry) {
if (defined_default(geometry.indices)) {
return geometry;
}
const numberOfVertices = Geometry_default.computeNumberOfVertices(geometry);
if (numberOfVertices < 3) {
throw new DeveloperError_default("The number of vertices must be at least three.");
}
if (numberOfVertices % 3 !== 0) {
throw new DeveloperError_default(
"The number of vertices must be a multiple of three."
);
}
const indices2 = IndexDatatype_default.createTypedArray(
numberOfVertices,
numberOfVertices
);
for (let i = 0; i < numberOfVertices; ++i) {
indices2[i] = i;
}
geometry.indices = indices2;
return geometry;
}
function indexTriangleFan(geometry) {
const numberOfVertices = Geometry_default.computeNumberOfVertices(geometry);
if (numberOfVertices < 3) {
throw new DeveloperError_default("The number of vertices must be at least three.");
}
const indices2 = IndexDatatype_default.createTypedArray(
numberOfVertices,
(numberOfVertices - 2) * 3
);
indices2[0] = 1;
indices2[1] = 0;
indices2[2] = 2;
let indicesIndex = 3;
for (let i = 3; i < numberOfVertices; ++i) {
indices2[indicesIndex++] = i - 1;
indices2[indicesIndex++] = 0;
indices2[indicesIndex++] = i;
}
geometry.indices = indices2;
geometry.primitiveType = PrimitiveType_default.TRIANGLES;
return geometry;
}
function indexTriangleStrip(geometry) {
const numberOfVertices = Geometry_default.computeNumberOfVertices(geometry);
if (numberOfVertices < 3) {
throw new DeveloperError_default("The number of vertices must be at least 3.");
}
const indices2 = IndexDatatype_default.createTypedArray(
numberOfVertices,
(numberOfVertices - 2) * 3
);
indices2[0] = 0;
indices2[1] = 1;
indices2[2] = 2;
if (numberOfVertices > 3) {
indices2[3] = 0;
indices2[4] = 2;
indices2[5] = 3;
}
let indicesIndex = 6;
for (let i = 3; i < numberOfVertices - 1; i += 2) {
indices2[indicesIndex++] = i;
indices2[indicesIndex++] = i - 1;
indices2[indicesIndex++] = i + 1;
if (i + 2 < numberOfVertices) {
indices2[indicesIndex++] = i;
indices2[indicesIndex++] = i + 1;
indices2[indicesIndex++] = i + 2;
}
}
geometry.indices = indices2;
geometry.primitiveType = PrimitiveType_default.TRIANGLES;
return geometry;
}
function indexLines(geometry) {
if (defined_default(geometry.indices)) {
return geometry;
}
const numberOfVertices = Geometry_default.computeNumberOfVertices(geometry);
if (numberOfVertices < 2) {
throw new DeveloperError_default("The number of vertices must be at least two.");
}
if (numberOfVertices % 2 !== 0) {
throw new DeveloperError_default("The number of vertices must be a multiple of 2.");
}
const indices2 = IndexDatatype_default.createTypedArray(
numberOfVertices,
numberOfVertices
);
for (let i = 0; i < numberOfVertices; ++i) {
indices2[i] = i;
}
geometry.indices = indices2;
return geometry;
}
function indexLineStrip(geometry) {
const numberOfVertices = Geometry_default.computeNumberOfVertices(geometry);
if (numberOfVertices < 2) {
throw new DeveloperError_default("The number of vertices must be at least two.");
}
const indices2 = IndexDatatype_default.createTypedArray(
numberOfVertices,
(numberOfVertices - 1) * 2
);
indices2[0] = 0;
indices2[1] = 1;
let indicesIndex = 2;
for (let i = 2; i < numberOfVertices; ++i) {
indices2[indicesIndex++] = i - 1;
indices2[indicesIndex++] = i;
}
geometry.indices = indices2;
geometry.primitiveType = PrimitiveType_default.LINES;
return geometry;
}
function indexLineLoop(geometry) {
const numberOfVertices = Geometry_default.computeNumberOfVertices(geometry);
if (numberOfVertices < 2) {
throw new DeveloperError_default("The number of vertices must be at least two.");
}
const indices2 = IndexDatatype_default.createTypedArray(
numberOfVertices,
numberOfVertices * 2
);
indices2[0] = 0;
indices2[1] = 1;
let indicesIndex = 2;
for (let i = 2; i < numberOfVertices; ++i) {
indices2[indicesIndex++] = i - 1;
indices2[indicesIndex++] = i;
}
indices2[indicesIndex++] = numberOfVertices - 1;
indices2[indicesIndex] = 0;
geometry.indices = indices2;
geometry.primitiveType = PrimitiveType_default.LINES;
return geometry;
}
function indexPrimitive(geometry) {
switch (geometry.primitiveType) {
case PrimitiveType_default.TRIANGLE_FAN:
return indexTriangleFan(geometry);
case PrimitiveType_default.TRIANGLE_STRIP:
return indexTriangleStrip(geometry);
case PrimitiveType_default.TRIANGLES:
return indexTriangles(geometry);
case PrimitiveType_default.LINE_STRIP:
return indexLineStrip(geometry);
case PrimitiveType_default.LINE_LOOP:
return indexLineLoop(geometry);
case PrimitiveType_default.LINES:
return indexLines(geometry);
}
return geometry;
}
function offsetPointFromXZPlane(p, isBehind) {
if (Math.abs(p.y) < Math_default.EPSILON6) {
if (isBehind) {
p.y = -Math_default.EPSILON6;
} else {
p.y = Math_default.EPSILON6;
}
}
}
function offsetTriangleFromXZPlane(p0, p1, p2) {
if (p0.y !== 0 && p1.y !== 0 && p2.y !== 0) {
offsetPointFromXZPlane(p0, p0.y < 0);
offsetPointFromXZPlane(p1, p1.y < 0);
offsetPointFromXZPlane(p2, p2.y < 0);
return;
}
const p0y = Math.abs(p0.y);
const p1y = Math.abs(p1.y);
const p2y = Math.abs(p2.y);
let sign2;
if (p0y > p1y) {
if (p0y > p2y) {
sign2 = Math_default.sign(p0.y);
} else {
sign2 = Math_default.sign(p2.y);
}
} else if (p1y > p2y) {
sign2 = Math_default.sign(p1.y);
} else {
sign2 = Math_default.sign(p2.y);
}
const isBehind = sign2 < 0;
offsetPointFromXZPlane(p0, isBehind);
offsetPointFromXZPlane(p1, isBehind);
offsetPointFromXZPlane(p2, isBehind);
}
var c3 = new Cartesian3_default();
function getXZIntersectionOffsetPoints(p, p1, u12, v13) {
Cartesian3_default.add(
p,
Cartesian3_default.multiplyByScalar(
Cartesian3_default.subtract(p1, p, c3),
p.y / (p.y - p1.y),
c3
),
u12
);
Cartesian3_default.clone(u12, v13);
offsetPointFromXZPlane(u12, true);
offsetPointFromXZPlane(v13, false);
}
var u1 = new Cartesian3_default();
var u2 = new Cartesian3_default();
var q1 = new Cartesian3_default();
var q2 = new Cartesian3_default();
var splitTriangleResult = {
positions: new Array(7),
indices: new Array(3 * 3)
};
function splitTriangle(p0, p1, p2) {
if (p0.x >= 0 || p1.x >= 0 || p2.x >= 0) {
return void 0;
}
offsetTriangleFromXZPlane(p0, p1, p2);
const p0Behind = p0.y < 0;
const p1Behind = p1.y < 0;
const p2Behind = p2.y < 0;
let numBehind = 0;
numBehind += p0Behind ? 1 : 0;
numBehind += p1Behind ? 1 : 0;
numBehind += p2Behind ? 1 : 0;
const indices2 = splitTriangleResult.indices;
if (numBehind === 1) {
indices2[1] = 3;
indices2[2] = 4;
indices2[5] = 6;
indices2[7] = 6;
indices2[8] = 5;
if (p0Behind) {
getXZIntersectionOffsetPoints(p0, p1, u1, q1);
getXZIntersectionOffsetPoints(p0, p2, u2, q2);
indices2[0] = 0;
indices2[3] = 1;
indices2[4] = 2;
indices2[6] = 1;
} else if (p1Behind) {
getXZIntersectionOffsetPoints(p1, p2, u1, q1);
getXZIntersectionOffsetPoints(p1, p0, u2, q2);
indices2[0] = 1;
indices2[3] = 2;
indices2[4] = 0;
indices2[6] = 2;
} else if (p2Behind) {
getXZIntersectionOffsetPoints(p2, p0, u1, q1);
getXZIntersectionOffsetPoints(p2, p1, u2, q2);
indices2[0] = 2;
indices2[3] = 0;
indices2[4] = 1;
indices2[6] = 0;
}
} else if (numBehind === 2) {
indices2[2] = 4;
indices2[4] = 4;
indices2[5] = 3;
indices2[7] = 5;
indices2[8] = 6;
if (!p0Behind) {
getXZIntersectionOffsetPoints(p0, p1, u1, q1);
getXZIntersectionOffsetPoints(p0, p2, u2, q2);
indices2[0] = 1;
indices2[1] = 2;
indices2[3] = 1;
indices2[6] = 0;
} else if (!p1Behind) {
getXZIntersectionOffsetPoints(p1, p2, u1, q1);
getXZIntersectionOffsetPoints(p1, p0, u2, q2);
indices2[0] = 2;
indices2[1] = 0;
indices2[3] = 2;
indices2[6] = 1;
} else if (!p2Behind) {
getXZIntersectionOffsetPoints(p2, p0, u1, q1);
getXZIntersectionOffsetPoints(p2, p1, u2, q2);
indices2[0] = 0;
indices2[1] = 1;
indices2[3] = 0;
indices2[6] = 2;
}
}
const positions = splitTriangleResult.positions;
positions[0] = p0;
positions[1] = p1;
positions[2] = p2;
positions.length = 3;
if (numBehind === 1 || numBehind === 2) {
positions[3] = u1;
positions[4] = u2;
positions[5] = q1;
positions[6] = q2;
positions.length = 7;
}
return splitTriangleResult;
}
function updateGeometryAfterSplit(geometry, computeBoundingSphere) {
const attributes = geometry.attributes;
if (attributes.position.values.length === 0) {
return void 0;
}
for (const property in attributes) {
if (attributes.hasOwnProperty(property) && defined_default(attributes[property]) && defined_default(attributes[property].values)) {
const attribute = attributes[property];
attribute.values = ComponentDatatype_default.createTypedArray(
attribute.componentDatatype,
attribute.values
);
}
}
const numberOfVertices = Geometry_default.computeNumberOfVertices(geometry);
geometry.indices = IndexDatatype_default.createTypedArray(
numberOfVertices,
geometry.indices
);
if (computeBoundingSphere) {
geometry.boundingSphere = BoundingSphere_default.fromVertices(
attributes.position.values
);
}
return geometry;
}
function copyGeometryForSplit(geometry) {
const attributes = geometry.attributes;
const copiedAttributes = {};
for (const property in attributes) {
if (attributes.hasOwnProperty(property) && defined_default(attributes[property]) && defined_default(attributes[property].values)) {
const attribute = attributes[property];
copiedAttributes[property] = new GeometryAttribute_default({
componentDatatype: attribute.componentDatatype,
componentsPerAttribute: attribute.componentsPerAttribute,
normalize: attribute.normalize,
values: []
});
}
}
return new Geometry_default({
attributes: copiedAttributes,
indices: [],
primitiveType: geometry.primitiveType
});
}
function updateInstanceAfterSplit(instance, westGeometry, eastGeometry) {
const computeBoundingSphere = defined_default(instance.geometry.boundingSphere);
westGeometry = updateGeometryAfterSplit(westGeometry, computeBoundingSphere);
eastGeometry = updateGeometryAfterSplit(eastGeometry, computeBoundingSphere);
if (defined_default(eastGeometry) && !defined_default(westGeometry)) {
instance.geometry = eastGeometry;
} else if (!defined_default(eastGeometry) && defined_default(westGeometry)) {
instance.geometry = westGeometry;
} else {
instance.westHemisphereGeometry = westGeometry;
instance.eastHemisphereGeometry = eastGeometry;
instance.geometry = void 0;
}
}
function generateBarycentricInterpolateFunction(CartesianType, numberOfComponents) {
const v0Scratch = new CartesianType();
const v1Scratch2 = new CartesianType();
const v2Scratch2 = new CartesianType();
return function(i0, i1, i2, coords, sourceValues, currentValues, insertedIndex, normalize2) {
const v02 = CartesianType.fromArray(
sourceValues,
i0 * numberOfComponents,
v0Scratch
);
const v13 = CartesianType.fromArray(
sourceValues,
i1 * numberOfComponents,
v1Scratch2
);
const v23 = CartesianType.fromArray(
sourceValues,
i2 * numberOfComponents,
v2Scratch2
);
CartesianType.multiplyByScalar(v02, coords.x, v02);
CartesianType.multiplyByScalar(v13, coords.y, v13);
CartesianType.multiplyByScalar(v23, coords.z, v23);
const value = CartesianType.add(v02, v13, v02);
CartesianType.add(value, v23, value);
if (normalize2) {
CartesianType.normalize(value, value);
}
CartesianType.pack(
value,
currentValues,
insertedIndex * numberOfComponents
);
};
}
var interpolateAndPackCartesian4 = generateBarycentricInterpolateFunction(
Cartesian4_default,
4
);
var interpolateAndPackCartesian3 = generateBarycentricInterpolateFunction(
Cartesian3_default,
3
);
var interpolateAndPackCartesian2 = generateBarycentricInterpolateFunction(
Cartesian2_default,
2
);
var interpolateAndPackBoolean = function(i0, i1, i2, coords, sourceValues, currentValues, insertedIndex) {
const v13 = sourceValues[i0] * coords.x;
const v23 = sourceValues[i1] * coords.y;
const v32 = sourceValues[i2] * coords.z;
currentValues[insertedIndex] = v13 + v23 + v32 > Math_default.EPSILON6 ? 1 : 0;
};
var p0Scratch = new Cartesian3_default();
var p1Scratch = new Cartesian3_default();
var p2Scratch = new Cartesian3_default();
var barycentricScratch = new Cartesian3_default();
function computeTriangleAttributes(i0, i1, i2, point, positions, normals, tangents, bitangents, texCoords, extrudeDirections, applyOffset, currentAttributes, customAttributeNames, customAttributesLength, allAttributes, insertedIndex) {
if (!defined_default(normals) && !defined_default(tangents) && !defined_default(bitangents) && !defined_default(texCoords) && !defined_default(extrudeDirections) && customAttributesLength === 0) {
return;
}
const p0 = Cartesian3_default.fromArray(positions, i0 * 3, p0Scratch);
const p1 = Cartesian3_default.fromArray(positions, i1 * 3, p1Scratch);
const p2 = Cartesian3_default.fromArray(positions, i2 * 3, p2Scratch);
const coords = barycentricCoordinates_default(point, p0, p1, p2, barycentricScratch);
if (!defined_default(coords)) {
return;
}
if (defined_default(normals)) {
interpolateAndPackCartesian3(
i0,
i1,
i2,
coords,
normals,
currentAttributes.normal.values,
insertedIndex,
true
);
}
if (defined_default(extrudeDirections)) {
const d0 = Cartesian3_default.fromArray(extrudeDirections, i0 * 3, p0Scratch);
const d1 = Cartesian3_default.fromArray(extrudeDirections, i1 * 3, p1Scratch);
const d2 = Cartesian3_default.fromArray(extrudeDirections, i2 * 3, p2Scratch);
Cartesian3_default.multiplyByScalar(d0, coords.x, d0);
Cartesian3_default.multiplyByScalar(d1, coords.y, d1);
Cartesian3_default.multiplyByScalar(d2, coords.z, d2);
let direction2;
if (!Cartesian3_default.equals(d0, Cartesian3_default.ZERO) || !Cartesian3_default.equals(d1, Cartesian3_default.ZERO) || !Cartesian3_default.equals(d2, Cartesian3_default.ZERO)) {
direction2 = Cartesian3_default.add(d0, d1, d0);
Cartesian3_default.add(direction2, d2, direction2);
Cartesian3_default.normalize(direction2, direction2);
} else {
direction2 = p0Scratch;
direction2.x = 0;
direction2.y = 0;
direction2.z = 0;
}
Cartesian3_default.pack(
direction2,
currentAttributes.extrudeDirection.values,
insertedIndex * 3
);
}
if (defined_default(applyOffset)) {
interpolateAndPackBoolean(
i0,
i1,
i2,
coords,
applyOffset,
currentAttributes.applyOffset.values,
insertedIndex
);
}
if (defined_default(tangents)) {
interpolateAndPackCartesian3(
i0,
i1,
i2,
coords,
tangents,
currentAttributes.tangent.values,
insertedIndex,
true
);
}
if (defined_default(bitangents)) {
interpolateAndPackCartesian3(
i0,
i1,
i2,
coords,
bitangents,
currentAttributes.bitangent.values,
insertedIndex,
true
);
}
if (defined_default(texCoords)) {
interpolateAndPackCartesian2(
i0,
i1,
i2,
coords,
texCoords,
currentAttributes.st.values,
insertedIndex
);
}
if (customAttributesLength > 0) {
for (let i = 0; i < customAttributesLength; i++) {
const attributeName = customAttributeNames[i];
genericInterpolate(
i0,
i1,
i2,
coords,
insertedIndex,
allAttributes[attributeName],
currentAttributes[attributeName]
);
}
}
}
function genericInterpolate(i0, i1, i2, coords, insertedIndex, sourceAttribute, currentAttribute) {
const componentsPerAttribute = sourceAttribute.componentsPerAttribute;
const sourceValues = sourceAttribute.values;
const currentValues = currentAttribute.values;
switch (componentsPerAttribute) {
case 4:
interpolateAndPackCartesian4(
i0,
i1,
i2,
coords,
sourceValues,
currentValues,
insertedIndex,
false
);
break;
case 3:
interpolateAndPackCartesian3(
i0,
i1,
i2,
coords,
sourceValues,
currentValues,
insertedIndex,
false
);
break;
case 2:
interpolateAndPackCartesian2(
i0,
i1,
i2,
coords,
sourceValues,
currentValues,
insertedIndex,
false
);
break;
default:
currentValues[insertedIndex] = sourceValues[i0] * coords.x + sourceValues[i1] * coords.y + sourceValues[i2] * coords.z;
}
}
function insertSplitPoint(currentAttributes, currentIndices, currentIndexMap, indices2, currentIndex, point) {
const insertIndex = currentAttributes.position.values.length / 3;
if (currentIndex !== -1) {
const prevIndex = indices2[currentIndex];
const newIndex = currentIndexMap[prevIndex];
if (newIndex === -1) {
currentIndexMap[prevIndex] = insertIndex;
currentAttributes.position.values.push(point.x, point.y, point.z);
currentIndices.push(insertIndex);
return insertIndex;
}
currentIndices.push(newIndex);
return newIndex;
}
currentAttributes.position.values.push(point.x, point.y, point.z);
currentIndices.push(insertIndex);
return insertIndex;
}
var NAMED_ATTRIBUTES = {
position: true,
normal: true,
bitangent: true,
tangent: true,
st: true,
extrudeDirection: true,
applyOffset: true
};
function splitLongitudeTriangles(instance) {
const geometry = instance.geometry;
const attributes = geometry.attributes;
const positions = attributes.position.values;
const normals = defined_default(attributes.normal) ? attributes.normal.values : void 0;
const bitangents = defined_default(attributes.bitangent) ? attributes.bitangent.values : void 0;
const tangents = defined_default(attributes.tangent) ? attributes.tangent.values : void 0;
const texCoords = defined_default(attributes.st) ? attributes.st.values : void 0;
const extrudeDirections = defined_default(attributes.extrudeDirection) ? attributes.extrudeDirection.values : void 0;
const applyOffset = defined_default(attributes.applyOffset) ? attributes.applyOffset.values : void 0;
const indices2 = geometry.indices;
const customAttributeNames = [];
for (const attributeName in attributes) {
if (attributes.hasOwnProperty(attributeName) && !NAMED_ATTRIBUTES[attributeName] && defined_default(attributes[attributeName])) {
customAttributeNames.push(attributeName);
}
}
const customAttributesLength = customAttributeNames.length;
const eastGeometry = copyGeometryForSplit(geometry);
const westGeometry = copyGeometryForSplit(geometry);
let currentAttributes;
let currentIndices;
let currentIndexMap;
let insertedIndex;
let i;
const westGeometryIndexMap = [];
westGeometryIndexMap.length = positions.length / 3;
const eastGeometryIndexMap = [];
eastGeometryIndexMap.length = positions.length / 3;
for (i = 0; i < westGeometryIndexMap.length; ++i) {
westGeometryIndexMap[i] = -1;
eastGeometryIndexMap[i] = -1;
}
const len = indices2.length;
for (i = 0; i < len; i += 3) {
const i0 = indices2[i];
const i1 = indices2[i + 1];
const i2 = indices2[i + 2];
let p0 = Cartesian3_default.fromArray(positions, i0 * 3);
let p1 = Cartesian3_default.fromArray(positions, i1 * 3);
let p2 = Cartesian3_default.fromArray(positions, i2 * 3);
const result = splitTriangle(p0, p1, p2);
if (defined_default(result) && result.positions.length > 3) {
const resultPositions = result.positions;
const resultIndices = result.indices;
const resultLength = resultIndices.length;
for (let j = 0; j < resultLength; ++j) {
const resultIndex = resultIndices[j];
const point = resultPositions[resultIndex];
if (point.y < 0) {
currentAttributes = westGeometry.attributes;
currentIndices = westGeometry.indices;
currentIndexMap = westGeometryIndexMap;
} else {
currentAttributes = eastGeometry.attributes;
currentIndices = eastGeometry.indices;
currentIndexMap = eastGeometryIndexMap;
}
insertedIndex = insertSplitPoint(
currentAttributes,
currentIndices,
currentIndexMap,
indices2,
resultIndex < 3 ? i + resultIndex : -1,
point
);
computeTriangleAttributes(
i0,
i1,
i2,
point,
positions,
normals,
tangents,
bitangents,
texCoords,
extrudeDirections,
applyOffset,
currentAttributes,
customAttributeNames,
customAttributesLength,
attributes,
insertedIndex
);
}
} else {
if (defined_default(result)) {
p0 = result.positions[0];
p1 = result.positions[1];
p2 = result.positions[2];
}
if (p0.y < 0) {
currentAttributes = westGeometry.attributes;
currentIndices = westGeometry.indices;
currentIndexMap = westGeometryIndexMap;
} else {
currentAttributes = eastGeometry.attributes;
currentIndices = eastGeometry.indices;
currentIndexMap = eastGeometryIndexMap;
}
insertedIndex = insertSplitPoint(
currentAttributes,
currentIndices,
currentIndexMap,
indices2,
i,
p0
);
computeTriangleAttributes(
i0,
i1,
i2,
p0,
positions,
normals,
tangents,
bitangents,
texCoords,
extrudeDirections,
applyOffset,
currentAttributes,
customAttributeNames,
customAttributesLength,
attributes,
insertedIndex
);
insertedIndex = insertSplitPoint(
currentAttributes,
currentIndices,
currentIndexMap,
indices2,
i + 1,
p1
);
computeTriangleAttributes(
i0,
i1,
i2,
p1,
positions,
normals,
tangents,
bitangents,
texCoords,
extrudeDirections,
applyOffset,
currentAttributes,
customAttributeNames,
customAttributesLength,
attributes,
insertedIndex
);
insertedIndex = insertSplitPoint(
currentAttributes,
currentIndices,
currentIndexMap,
indices2,
i + 2,
p2
);
computeTriangleAttributes(
i0,
i1,
i2,
p2,
positions,
normals,
tangents,
bitangents,
texCoords,
extrudeDirections,
applyOffset,
currentAttributes,
customAttributeNames,
customAttributesLength,
attributes,
insertedIndex
);
}
}
updateInstanceAfterSplit(instance, westGeometry, eastGeometry);
}
var xzPlane = Plane_default.fromPointNormal(Cartesian3_default.ZERO, Cartesian3_default.UNIT_Y);
var offsetScratch = new Cartesian3_default();
var offsetPointScratch = new Cartesian3_default();
function computeLineAttributes(i0, i1, point, positions, insertIndex, currentAttributes, applyOffset) {
if (!defined_default(applyOffset)) {
return;
}
const p0 = Cartesian3_default.fromArray(positions, i0 * 3, p0Scratch);
if (Cartesian3_default.equalsEpsilon(p0, point, Math_default.EPSILON10)) {
currentAttributes.applyOffset.values[insertIndex] = applyOffset[i0];
} else {
currentAttributes.applyOffset.values[insertIndex] = applyOffset[i1];
}
}
function splitLongitudeLines(instance) {
const geometry = instance.geometry;
const attributes = geometry.attributes;
const positions = attributes.position.values;
const applyOffset = defined_default(attributes.applyOffset) ? attributes.applyOffset.values : void 0;
const indices2 = geometry.indices;
const eastGeometry = copyGeometryForSplit(geometry);
const westGeometry = copyGeometryForSplit(geometry);
let i;
const length3 = indices2.length;
const westGeometryIndexMap = [];
westGeometryIndexMap.length = positions.length / 3;
const eastGeometryIndexMap = [];
eastGeometryIndexMap.length = positions.length / 3;
for (i = 0; i < westGeometryIndexMap.length; ++i) {
westGeometryIndexMap[i] = -1;
eastGeometryIndexMap[i] = -1;
}
for (i = 0; i < length3; i += 2) {
const i0 = indices2[i];
const i1 = indices2[i + 1];
const p0 = Cartesian3_default.fromArray(positions, i0 * 3, p0Scratch);
const p1 = Cartesian3_default.fromArray(positions, i1 * 3, p1Scratch);
let insertIndex;
if (Math.abs(p0.y) < Math_default.EPSILON6) {
if (p0.y < 0) {
p0.y = -Math_default.EPSILON6;
} else {
p0.y = Math_default.EPSILON6;
}
}
if (Math.abs(p1.y) < Math_default.EPSILON6) {
if (p1.y < 0) {
p1.y = -Math_default.EPSILON6;
} else {
p1.y = Math_default.EPSILON6;
}
}
let p0Attributes = eastGeometry.attributes;
let p0Indices = eastGeometry.indices;
let p0IndexMap = eastGeometryIndexMap;
let p1Attributes = westGeometry.attributes;
let p1Indices = westGeometry.indices;
let p1IndexMap = westGeometryIndexMap;
const intersection = IntersectionTests_default.lineSegmentPlane(
p0,
p1,
xzPlane,
p2Scratch
);
if (defined_default(intersection)) {
const offset2 = Cartesian3_default.multiplyByScalar(
Cartesian3_default.UNIT_Y,
5 * Math_default.EPSILON9,
offsetScratch
);
if (p0.y < 0) {
Cartesian3_default.negate(offset2, offset2);
p0Attributes = westGeometry.attributes;
p0Indices = westGeometry.indices;
p0IndexMap = westGeometryIndexMap;
p1Attributes = eastGeometry.attributes;
p1Indices = eastGeometry.indices;
p1IndexMap = eastGeometryIndexMap;
}
const offsetPoint = Cartesian3_default.add(
intersection,
offset2,
offsetPointScratch
);
insertIndex = insertSplitPoint(
p0Attributes,
p0Indices,
p0IndexMap,
indices2,
i,
p0
);
computeLineAttributes(
i0,
i1,
p0,
positions,
insertIndex,
p0Attributes,
applyOffset
);
insertIndex = insertSplitPoint(
p0Attributes,
p0Indices,
p0IndexMap,
indices2,
-1,
offsetPoint
);
computeLineAttributes(
i0,
i1,
offsetPoint,
positions,
insertIndex,
p0Attributes,
applyOffset
);
Cartesian3_default.negate(offset2, offset2);
Cartesian3_default.add(intersection, offset2, offsetPoint);
insertIndex = insertSplitPoint(
p1Attributes,
p1Indices,
p1IndexMap,
indices2,
-1,
offsetPoint
);
computeLineAttributes(
i0,
i1,
offsetPoint,
positions,
insertIndex,
p1Attributes,
applyOffset
);
insertIndex = insertSplitPoint(
p1Attributes,
p1Indices,
p1IndexMap,
indices2,
i + 1,
p1
);
computeLineAttributes(
i0,
i1,
p1,
positions,
insertIndex,
p1Attributes,
applyOffset
);
} else {
let currentAttributes;
let currentIndices;
let currentIndexMap;
if (p0.y < 0) {
currentAttributes = westGeometry.attributes;
currentIndices = westGeometry.indices;
currentIndexMap = westGeometryIndexMap;
} else {
currentAttributes = eastGeometry.attributes;
currentIndices = eastGeometry.indices;
currentIndexMap = eastGeometryIndexMap;
}
insertIndex = insertSplitPoint(
currentAttributes,
currentIndices,
currentIndexMap,
indices2,
i,
p0
);
computeLineAttributes(
i0,
i1,
p0,
positions,
insertIndex,
currentAttributes,
applyOffset
);
insertIndex = insertSplitPoint(
currentAttributes,
currentIndices,
currentIndexMap,
indices2,
i + 1,
p1
);
computeLineAttributes(
i0,
i1,
p1,
positions,
insertIndex,
currentAttributes,
applyOffset
);
}
}
updateInstanceAfterSplit(instance, westGeometry, eastGeometry);
}
var cartesian2Scratch0 = new Cartesian2_default();
var cartesian2Scratch1 = new Cartesian2_default();
var cartesian3Scratch0 = new Cartesian3_default();
var cartesian3Scratch2 = new Cartesian3_default();
var cartesian3Scratch3 = new Cartesian3_default();
var cartesian3Scratch4 = new Cartesian3_default();
var cartesian3Scratch5 = new Cartesian3_default();
var cartesian3Scratch6 = new Cartesian3_default();
var cartesian4Scratch0 = new Cartesian4_default();
function updateAdjacencyAfterSplit(geometry) {
const attributes = geometry.attributes;
const positions = attributes.position.values;
const prevPositions = attributes.prevPosition.values;
const nextPositions = attributes.nextPosition.values;
const length3 = positions.length;
for (let j = 0; j < length3; j += 3) {
const position = Cartesian3_default.unpack(positions, j, cartesian3Scratch0);
if (position.x > 0) {
continue;
}
const prevPosition = Cartesian3_default.unpack(
prevPositions,
j,
cartesian3Scratch2
);
if (position.y < 0 && prevPosition.y > 0 || position.y > 0 && prevPosition.y < 0) {
if (j - 3 > 0) {
prevPositions[j] = positions[j - 3];
prevPositions[j + 1] = positions[j - 2];
prevPositions[j + 2] = positions[j - 1];
} else {
Cartesian3_default.pack(position, prevPositions, j);
}
}
const nextPosition = Cartesian3_default.unpack(
nextPositions,
j,
cartesian3Scratch3
);
if (position.y < 0 && nextPosition.y > 0 || position.y > 0 && nextPosition.y < 0) {
if (j + 3 < length3) {
nextPositions[j] = positions[j + 3];
nextPositions[j + 1] = positions[j + 4];
nextPositions[j + 2] = positions[j + 5];
} else {
Cartesian3_default.pack(position, nextPositions, j);
}
}
}
}
var offsetScalar = 5 * Math_default.EPSILON9;
var coplanarOffset = Math_default.EPSILON6;
function splitLongitudePolyline(instance) {
const geometry = instance.geometry;
const attributes = geometry.attributes;
const positions = attributes.position.values;
const prevPositions = attributes.prevPosition.values;
const nextPositions = attributes.nextPosition.values;
const expandAndWidths = attributes.expandAndWidth.values;
const texCoords = defined_default(attributes.st) ? attributes.st.values : void 0;
const colors = defined_default(attributes.color) ? attributes.color.values : void 0;
const eastGeometry = copyGeometryForSplit(geometry);
const westGeometry = copyGeometryForSplit(geometry);
let i;
let j;
let index;
let intersectionFound = false;
const length3 = positions.length / 3;
for (i = 0; i < length3; i += 4) {
const i0 = i;
const i2 = i + 2;
const p0 = Cartesian3_default.fromArray(positions, i0 * 3, cartesian3Scratch0);
const p2 = Cartesian3_default.fromArray(positions, i2 * 3, cartesian3Scratch2);
if (Math.abs(p0.y) < coplanarOffset) {
p0.y = coplanarOffset * (p2.y < 0 ? -1 : 1);
positions[i * 3 + 1] = p0.y;
positions[(i + 1) * 3 + 1] = p0.y;
for (j = i0 * 3; j < i0 * 3 + 4 * 3; j += 3) {
prevPositions[j] = positions[i * 3];
prevPositions[j + 1] = positions[i * 3 + 1];
prevPositions[j + 2] = positions[i * 3 + 2];
}
}
if (Math.abs(p2.y) < coplanarOffset) {
p2.y = coplanarOffset * (p0.y < 0 ? -1 : 1);
positions[(i + 2) * 3 + 1] = p2.y;
positions[(i + 3) * 3 + 1] = p2.y;
for (j = i0 * 3; j < i0 * 3 + 4 * 3; j += 3) {
nextPositions[j] = positions[(i + 2) * 3];
nextPositions[j + 1] = positions[(i + 2) * 3 + 1];
nextPositions[j + 2] = positions[(i + 2) * 3 + 2];
}
}
let p0Attributes = eastGeometry.attributes;
let p0Indices = eastGeometry.indices;
let p2Attributes = westGeometry.attributes;
let p2Indices = westGeometry.indices;
const intersection = IntersectionTests_default.lineSegmentPlane(
p0,
p2,
xzPlane,
cartesian3Scratch4
);
if (defined_default(intersection)) {
intersectionFound = true;
const offset2 = Cartesian3_default.multiplyByScalar(
Cartesian3_default.UNIT_Y,
offsetScalar,
cartesian3Scratch5
);
if (p0.y < 0) {
Cartesian3_default.negate(offset2, offset2);
p0Attributes = westGeometry.attributes;
p0Indices = westGeometry.indices;
p2Attributes = eastGeometry.attributes;
p2Indices = eastGeometry.indices;
}
const offsetPoint = Cartesian3_default.add(
intersection,
offset2,
cartesian3Scratch6
);
p0Attributes.position.values.push(p0.x, p0.y, p0.z, p0.x, p0.y, p0.z);
p0Attributes.position.values.push(
offsetPoint.x,
offsetPoint.y,
offsetPoint.z
);
p0Attributes.position.values.push(
offsetPoint.x,
offsetPoint.y,
offsetPoint.z
);
p0Attributes.prevPosition.values.push(
prevPositions[i0 * 3],
prevPositions[i0 * 3 + 1],
prevPositions[i0 * 3 + 2]
);
p0Attributes.prevPosition.values.push(
prevPositions[i0 * 3 + 3],
prevPositions[i0 * 3 + 4],
prevPositions[i0 * 3 + 5]
);
p0Attributes.prevPosition.values.push(p0.x, p0.y, p0.z, p0.x, p0.y, p0.z);
p0Attributes.nextPosition.values.push(
offsetPoint.x,
offsetPoint.y,
offsetPoint.z
);
p0Attributes.nextPosition.values.push(
offsetPoint.x,
offsetPoint.y,
offsetPoint.z
);
p0Attributes.nextPosition.values.push(
offsetPoint.x,
offsetPoint.y,
offsetPoint.z
);
p0Attributes.nextPosition.values.push(
offsetPoint.x,
offsetPoint.y,
offsetPoint.z
);
Cartesian3_default.negate(offset2, offset2);
Cartesian3_default.add(intersection, offset2, offsetPoint);
p2Attributes.position.values.push(
offsetPoint.x,
offsetPoint.y,
offsetPoint.z
);
p2Attributes.position.values.push(
offsetPoint.x,
offsetPoint.y,
offsetPoint.z
);
p2Attributes.position.values.push(p2.x, p2.y, p2.z, p2.x, p2.y, p2.z);
p2Attributes.prevPosition.values.push(
offsetPoint.x,
offsetPoint.y,
offsetPoint.z
);
p2Attributes.prevPosition.values.push(
offsetPoint.x,
offsetPoint.y,
offsetPoint.z
);
p2Attributes.prevPosition.values.push(
offsetPoint.x,
offsetPoint.y,
offsetPoint.z
);
p2Attributes.prevPosition.values.push(
offsetPoint.x,
offsetPoint.y,
offsetPoint.z
);
p2Attributes.nextPosition.values.push(p2.x, p2.y, p2.z, p2.x, p2.y, p2.z);
p2Attributes.nextPosition.values.push(
nextPositions[i2 * 3],
nextPositions[i2 * 3 + 1],
nextPositions[i2 * 3 + 2]
);
p2Attributes.nextPosition.values.push(
nextPositions[i2 * 3 + 3],
nextPositions[i2 * 3 + 4],
nextPositions[i2 * 3 + 5]
);
const ew0 = Cartesian2_default.fromArray(
expandAndWidths,
i0 * 2,
cartesian2Scratch0
);
const width = Math.abs(ew0.y);
p0Attributes.expandAndWidth.values.push(-1, width, 1, width);
p0Attributes.expandAndWidth.values.push(-1, -width, 1, -width);
p2Attributes.expandAndWidth.values.push(-1, width, 1, width);
p2Attributes.expandAndWidth.values.push(-1, -width, 1, -width);
let t = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(intersection, p0, cartesian3Scratch3)
);
t /= Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(p2, p0, cartesian3Scratch3)
);
if (defined_default(colors)) {
const c0 = Cartesian4_default.fromArray(colors, i0 * 4, cartesian4Scratch0);
const c22 = Cartesian4_default.fromArray(colors, i2 * 4, cartesian4Scratch0);
const r = Math_default.lerp(c0.x, c22.x, t);
const g = Math_default.lerp(c0.y, c22.y, t);
const b = Math_default.lerp(c0.z, c22.z, t);
const a3 = Math_default.lerp(c0.w, c22.w, t);
for (j = i0 * 4; j < i0 * 4 + 2 * 4; ++j) {
p0Attributes.color.values.push(colors[j]);
}
p0Attributes.color.values.push(r, g, b, a3);
p0Attributes.color.values.push(r, g, b, a3);
p2Attributes.color.values.push(r, g, b, a3);
p2Attributes.color.values.push(r, g, b, a3);
for (j = i2 * 4; j < i2 * 4 + 2 * 4; ++j) {
p2Attributes.color.values.push(colors[j]);
}
}
if (defined_default(texCoords)) {
const s0 = Cartesian2_default.fromArray(texCoords, i0 * 2, cartesian2Scratch0);
const s3 = Cartesian2_default.fromArray(
texCoords,
(i + 3) * 2,
cartesian2Scratch1
);
const sx = Math_default.lerp(s0.x, s3.x, t);
for (j = i0 * 2; j < i0 * 2 + 2 * 2; ++j) {
p0Attributes.st.values.push(texCoords[j]);
}
p0Attributes.st.values.push(sx, s0.y);
p0Attributes.st.values.push(sx, s3.y);
p2Attributes.st.values.push(sx, s0.y);
p2Attributes.st.values.push(sx, s3.y);
for (j = i2 * 2; j < i2 * 2 + 2 * 2; ++j) {
p2Attributes.st.values.push(texCoords[j]);
}
}
index = p0Attributes.position.values.length / 3 - 4;
p0Indices.push(index, index + 2, index + 1);
p0Indices.push(index + 1, index + 2, index + 3);
index = p2Attributes.position.values.length / 3 - 4;
p2Indices.push(index, index + 2, index + 1);
p2Indices.push(index + 1, index + 2, index + 3);
} else {
let currentAttributes;
let currentIndices;
if (p0.y < 0) {
currentAttributes = westGeometry.attributes;
currentIndices = westGeometry.indices;
} else {
currentAttributes = eastGeometry.attributes;
currentIndices = eastGeometry.indices;
}
currentAttributes.position.values.push(p0.x, p0.y, p0.z);
currentAttributes.position.values.push(p0.x, p0.y, p0.z);
currentAttributes.position.values.push(p2.x, p2.y, p2.z);
currentAttributes.position.values.push(p2.x, p2.y, p2.z);
for (j = i * 3; j < i * 3 + 4 * 3; ++j) {
currentAttributes.prevPosition.values.push(prevPositions[j]);
currentAttributes.nextPosition.values.push(nextPositions[j]);
}
for (j = i * 2; j < i * 2 + 4 * 2; ++j) {
currentAttributes.expandAndWidth.values.push(expandAndWidths[j]);
if (defined_default(texCoords)) {
currentAttributes.st.values.push(texCoords[j]);
}
}
if (defined_default(colors)) {
for (j = i * 4; j < i * 4 + 4 * 4; ++j) {
currentAttributes.color.values.push(colors[j]);
}
}
index = currentAttributes.position.values.length / 3 - 4;
currentIndices.push(index, index + 2, index + 1);
currentIndices.push(index + 1, index + 2, index + 3);
}
}
if (intersectionFound) {
updateAdjacencyAfterSplit(westGeometry);
updateAdjacencyAfterSplit(eastGeometry);
}
updateInstanceAfterSplit(instance, westGeometry, eastGeometry);
}
GeometryPipeline.splitLongitude = function(instance) {
if (!defined_default(instance)) {
throw new DeveloperError_default("instance is required.");
}
const geometry = instance.geometry;
const boundingSphere = geometry.boundingSphere;
if (defined_default(boundingSphere)) {
const minX = boundingSphere.center.x - boundingSphere.radius;
if (minX > 0 || BoundingSphere_default.intersectPlane(boundingSphere, Plane_default.ORIGIN_ZX_PLANE) !== Intersect_default.INTERSECTING) {
return instance;
}
}
if (geometry.geometryType !== GeometryType_default.NONE) {
switch (geometry.geometryType) {
case GeometryType_default.POLYLINES:
splitLongitudePolyline(instance);
break;
case GeometryType_default.TRIANGLES:
splitLongitudeTriangles(instance);
break;
case GeometryType_default.LINES:
splitLongitudeLines(instance);
break;
}
} else {
indexPrimitive(geometry);
if (geometry.primitiveType === PrimitiveType_default.TRIANGLES) {
splitLongitudeTriangles(instance);
} else if (geometry.primitiveType === PrimitiveType_default.LINES) {
splitLongitudeLines(instance);
}
}
return instance;
};
var GeometryPipeline_default = GeometryPipeline;
// packages/engine/Source/Core/WebMercatorProjection.js
function WebMercatorProjection(ellipsoid) {
this._ellipsoid = defaultValue_default(ellipsoid, Ellipsoid_default.WGS84);
this._semimajorAxis = this._ellipsoid.maximumRadius;
this._oneOverSemimajorAxis = 1 / this._semimajorAxis;
}
Object.defineProperties(WebMercatorProjection.prototype, {
/**
* Gets the {@link Ellipsoid}.
*
* @memberof WebMercatorProjection.prototype
*
* @type {Ellipsoid}
* @readonly
*/
ellipsoid: {
get: function() {
return this._ellipsoid;
}
}
});
WebMercatorProjection.mercatorAngleToGeodeticLatitude = function(mercatorAngle) {
return Math_default.PI_OVER_TWO - 2 * Math.atan(Math.exp(-mercatorAngle));
};
WebMercatorProjection.geodeticLatitudeToMercatorAngle = function(latitude) {
if (latitude > WebMercatorProjection.MaximumLatitude) {
latitude = WebMercatorProjection.MaximumLatitude;
} else if (latitude < -WebMercatorProjection.MaximumLatitude) {
latitude = -WebMercatorProjection.MaximumLatitude;
}
const sinLatitude = Math.sin(latitude);
return 0.5 * Math.log((1 + sinLatitude) / (1 - sinLatitude));
};
WebMercatorProjection.MaximumLatitude = WebMercatorProjection.mercatorAngleToGeodeticLatitude(
Math.PI
);
WebMercatorProjection.prototype.project = function(cartographic2, result) {
const semimajorAxis = this._semimajorAxis;
const x = cartographic2.longitude * semimajorAxis;
const y = WebMercatorProjection.geodeticLatitudeToMercatorAngle(
cartographic2.latitude
) * semimajorAxis;
const z = cartographic2.height;
if (!defined_default(result)) {
return new Cartesian3_default(x, y, z);
}
result.x = x;
result.y = y;
result.z = z;
return result;
};
WebMercatorProjection.prototype.unproject = function(cartesian11, result) {
if (!defined_default(cartesian11)) {
throw new DeveloperError_default("cartesian is required");
}
const oneOverEarthSemimajorAxis = this._oneOverSemimajorAxis;
const longitude = cartesian11.x * oneOverEarthSemimajorAxis;
const latitude = WebMercatorProjection.mercatorAngleToGeodeticLatitude(
cartesian11.y * oneOverEarthSemimajorAxis
);
const height = cartesian11.z;
if (!defined_default(result)) {
return new Cartographic_default(longitude, latitude, height);
}
result.longitude = longitude;
result.latitude = latitude;
result.height = height;
return result;
};
var WebMercatorProjection_default = WebMercatorProjection;
// packages/engine/Source/Scene/PrimitivePipeline.js
function transformToWorldCoordinates(instances, primitiveModelMatrix, scene3DOnly) {
let toWorld = !scene3DOnly;
const length3 = instances.length;
let i;
if (!toWorld && length3 > 1) {
const modelMatrix = instances[0].modelMatrix;
for (i = 1; i < length3; ++i) {
if (!Matrix4_default.equals(modelMatrix, instances[i].modelMatrix)) {
toWorld = true;
break;
}
}
}
if (toWorld) {
for (i = 0; i < length3; ++i) {
if (defined_default(instances[i].geometry)) {
GeometryPipeline_default.transformToWorldCoordinates(instances[i]);
}
}
} else {
Matrix4_default.multiplyTransformation(
primitiveModelMatrix,
instances[0].modelMatrix,
primitiveModelMatrix
);
}
}
function addGeometryBatchId(geometry, batchId) {
const attributes = geometry.attributes;
const positionAttr = attributes.position;
const numberOfComponents = positionAttr.values.length / positionAttr.componentsPerAttribute;
attributes.batchId = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 1,
values: new Float32Array(numberOfComponents)
});
const values = attributes.batchId.values;
for (let j = 0; j < numberOfComponents; ++j) {
values[j] = batchId;
}
}
function addBatchIds(instances) {
const length3 = instances.length;
for (let i = 0; i < length3; ++i) {
const instance = instances[i];
if (defined_default(instance.geometry)) {
addGeometryBatchId(instance.geometry, i);
} else if (defined_default(instance.westHemisphereGeometry) && defined_default(instance.eastHemisphereGeometry)) {
addGeometryBatchId(instance.westHemisphereGeometry, i);
addGeometryBatchId(instance.eastHemisphereGeometry, i);
}
}
}
function geometryPipeline(parameters) {
const instances = parameters.instances;
const projection = parameters.projection;
const uintIndexSupport = parameters.elementIndexUintSupported;
const scene3DOnly = parameters.scene3DOnly;
const vertexCacheOptimize = parameters.vertexCacheOptimize;
const compressVertices = parameters.compressVertices;
const modelMatrix = parameters.modelMatrix;
let i;
let geometry;
let primitiveType;
let length3 = instances.length;
for (i = 0; i < length3; ++i) {
if (defined_default(instances[i].geometry)) {
primitiveType = instances[i].geometry.primitiveType;
break;
}
}
for (i = 1; i < length3; ++i) {
if (defined_default(instances[i].geometry) && instances[i].geometry.primitiveType !== primitiveType) {
throw new DeveloperError_default(
"All instance geometries must have the same primitiveType."
);
}
}
transformToWorldCoordinates(instances, modelMatrix, scene3DOnly);
if (!scene3DOnly) {
for (i = 0; i < length3; ++i) {
if (defined_default(instances[i].geometry)) {
GeometryPipeline_default.splitLongitude(instances[i]);
}
}
}
addBatchIds(instances);
if (vertexCacheOptimize) {
for (i = 0; i < length3; ++i) {
const instance = instances[i];
if (defined_default(instance.geometry)) {
GeometryPipeline_default.reorderForPostVertexCache(instance.geometry);
GeometryPipeline_default.reorderForPreVertexCache(instance.geometry);
} else if (defined_default(instance.westHemisphereGeometry) && defined_default(instance.eastHemisphereGeometry)) {
GeometryPipeline_default.reorderForPostVertexCache(
instance.westHemisphereGeometry
);
GeometryPipeline_default.reorderForPreVertexCache(
instance.westHemisphereGeometry
);
GeometryPipeline_default.reorderForPostVertexCache(
instance.eastHemisphereGeometry
);
GeometryPipeline_default.reorderForPreVertexCache(
instance.eastHemisphereGeometry
);
}
}
}
let geometries = GeometryPipeline_default.combineInstances(instances);
length3 = geometries.length;
for (i = 0; i < length3; ++i) {
geometry = geometries[i];
const attributes = geometry.attributes;
if (!scene3DOnly) {
for (const name in attributes) {
if (attributes.hasOwnProperty(name) && attributes[name].componentDatatype === ComponentDatatype_default.DOUBLE) {
const name3D = `${name}3D`;
const name2D = `${name}2D`;
GeometryPipeline_default.projectTo2D(
geometry,
name,
name3D,
name2D,
projection
);
if (defined_default(geometry.boundingSphere) && name === "position") {
geometry.boundingSphereCV = BoundingSphere_default.fromVertices(
geometry.attributes.position2D.values
);
}
GeometryPipeline_default.encodeAttribute(
geometry,
name3D,
`${name3D}High`,
`${name3D}Low`
);
GeometryPipeline_default.encodeAttribute(
geometry,
name2D,
`${name2D}High`,
`${name2D}Low`
);
}
}
} else {
for (const name in attributes) {
if (attributes.hasOwnProperty(name) && attributes[name].componentDatatype === ComponentDatatype_default.DOUBLE) {
GeometryPipeline_default.encodeAttribute(
geometry,
name,
`${name}3DHigh`,
`${name}3DLow`
);
}
}
}
if (compressVertices) {
GeometryPipeline_default.compressVertices(geometry);
}
}
if (!uintIndexSupport) {
let splitGeometries = [];
length3 = geometries.length;
for (i = 0; i < length3; ++i) {
geometry = geometries[i];
splitGeometries = splitGeometries.concat(
GeometryPipeline_default.fitToUnsignedShortIndices(geometry)
);
}
geometries = splitGeometries;
}
return geometries;
}
function createPickOffsets(instances, geometryName, geometries, pickOffsets) {
let offset2;
let indexCount;
let geometryIndex;
const offsetIndex = pickOffsets.length - 1;
if (offsetIndex >= 0) {
const pickOffset = pickOffsets[offsetIndex];
offset2 = pickOffset.offset + pickOffset.count;
geometryIndex = pickOffset.index;
indexCount = geometries[geometryIndex].indices.length;
} else {
offset2 = 0;
geometryIndex = 0;
indexCount = geometries[geometryIndex].indices.length;
}
const length3 = instances.length;
for (let i = 0; i < length3; ++i) {
const instance = instances[i];
const geometry = instance[geometryName];
if (!defined_default(geometry)) {
continue;
}
const count = geometry.indices.length;
if (offset2 + count > indexCount) {
offset2 = 0;
indexCount = geometries[++geometryIndex].indices.length;
}
pickOffsets.push({
index: geometryIndex,
offset: offset2,
count
});
offset2 += count;
}
}
function createInstancePickOffsets(instances, geometries) {
const pickOffsets = [];
createPickOffsets(instances, "geometry", geometries, pickOffsets);
createPickOffsets(
instances,
"westHemisphereGeometry",
geometries,
pickOffsets
);
createPickOffsets(
instances,
"eastHemisphereGeometry",
geometries,
pickOffsets
);
return pickOffsets;
}
var PrimitivePipeline = {};
PrimitivePipeline.combineGeometry = function(parameters) {
let geometries;
let attributeLocations8;
const instances = parameters.instances;
const length3 = instances.length;
let pickOffsets;
let offsetInstanceExtend;
let hasOffset = false;
if (length3 > 0) {
geometries = geometryPipeline(parameters);
if (geometries.length > 0) {
attributeLocations8 = GeometryPipeline_default.createAttributeLocations(
geometries[0]
);
if (parameters.createPickOffsets) {
pickOffsets = createInstancePickOffsets(instances, geometries);
}
}
if (defined_default(instances[0].attributes) && defined_default(instances[0].attributes.offset)) {
offsetInstanceExtend = new Array(length3);
hasOffset = true;
}
}
const boundingSpheres = new Array(length3);
const boundingSpheresCV = new Array(length3);
for (let i = 0; i < length3; ++i) {
const instance = instances[i];
const geometry = instance.geometry;
if (defined_default(geometry)) {
boundingSpheres[i] = geometry.boundingSphere;
boundingSpheresCV[i] = geometry.boundingSphereCV;
if (hasOffset) {
offsetInstanceExtend[i] = instance.geometry.offsetAttribute;
}
}
const eastHemisphereGeometry = instance.eastHemisphereGeometry;
const westHemisphereGeometry = instance.westHemisphereGeometry;
if (defined_default(eastHemisphereGeometry) && defined_default(westHemisphereGeometry)) {
if (defined_default(eastHemisphereGeometry.boundingSphere) && defined_default(westHemisphereGeometry.boundingSphere)) {
boundingSpheres[i] = BoundingSphere_default.union(
eastHemisphereGeometry.boundingSphere,
westHemisphereGeometry.boundingSphere
);
}
if (defined_default(eastHemisphereGeometry.boundingSphereCV) && defined_default(westHemisphereGeometry.boundingSphereCV)) {
boundingSpheresCV[i] = BoundingSphere_default.union(
eastHemisphereGeometry.boundingSphereCV,
westHemisphereGeometry.boundingSphereCV
);
}
}
}
return {
geometries,
modelMatrix: parameters.modelMatrix,
attributeLocations: attributeLocations8,
pickOffsets,
offsetInstanceExtend,
boundingSpheres,
boundingSpheresCV
};
};
function transferGeometry(geometry, transferableObjects) {
const attributes = geometry.attributes;
for (const name in attributes) {
if (attributes.hasOwnProperty(name)) {
const attribute = attributes[name];
if (defined_default(attribute) && defined_default(attribute.values)) {
transferableObjects.push(attribute.values.buffer);
}
}
}
if (defined_default(geometry.indices)) {
transferableObjects.push(geometry.indices.buffer);
}
}
function transferGeometries(geometries, transferableObjects) {
const length3 = geometries.length;
for (let i = 0; i < length3; ++i) {
transferGeometry(geometries[i], transferableObjects);
}
}
function countCreateGeometryResults(items) {
let count = 1;
const length3 = items.length;
for (let i = 0; i < length3; i++) {
const geometry = items[i];
++count;
if (!defined_default(geometry)) {
continue;
}
const attributes = geometry.attributes;
count += 7 + 2 * BoundingSphere_default.packedLength + (defined_default(geometry.indices) ? geometry.indices.length : 0);
for (const property in attributes) {
if (attributes.hasOwnProperty(property) && defined_default(attributes[property])) {
const attribute = attributes[property];
count += 5 + attribute.values.length;
}
}
}
return count;
}
PrimitivePipeline.packCreateGeometryResults = function(items, transferableObjects) {
const packedData = new Float64Array(countCreateGeometryResults(items));
const stringTable = [];
const stringHash = {};
const length3 = items.length;
let count = 0;
packedData[count++] = length3;
for (let i = 0; i < length3; i++) {
const geometry = items[i];
const validGeometry = defined_default(geometry);
packedData[count++] = validGeometry ? 1 : 0;
if (!validGeometry) {
continue;
}
packedData[count++] = geometry.primitiveType;
packedData[count++] = geometry.geometryType;
packedData[count++] = defaultValue_default(geometry.offsetAttribute, -1);
const validBoundingSphere = defined_default(geometry.boundingSphere) ? 1 : 0;
packedData[count++] = validBoundingSphere;
if (validBoundingSphere) {
BoundingSphere_default.pack(geometry.boundingSphere, packedData, count);
}
count += BoundingSphere_default.packedLength;
const validBoundingSphereCV = defined_default(geometry.boundingSphereCV) ? 1 : 0;
packedData[count++] = validBoundingSphereCV;
if (validBoundingSphereCV) {
BoundingSphere_default.pack(geometry.boundingSphereCV, packedData, count);
}
count += BoundingSphere_default.packedLength;
const attributes = geometry.attributes;
const attributesToWrite = [];
for (const property in attributes) {
if (attributes.hasOwnProperty(property) && defined_default(attributes[property])) {
attributesToWrite.push(property);
if (!defined_default(stringHash[property])) {
stringHash[property] = stringTable.length;
stringTable.push(property);
}
}
}
packedData[count++] = attributesToWrite.length;
for (let q = 0; q < attributesToWrite.length; q++) {
const name = attributesToWrite[q];
const attribute = attributes[name];
packedData[count++] = stringHash[name];
packedData[count++] = attribute.componentDatatype;
packedData[count++] = attribute.componentsPerAttribute;
packedData[count++] = attribute.normalize ? 1 : 0;
packedData[count++] = attribute.values.length;
packedData.set(attribute.values, count);
count += attribute.values.length;
}
const indicesLength = defined_default(geometry.indices) ? geometry.indices.length : 0;
packedData[count++] = indicesLength;
if (indicesLength > 0) {
packedData.set(geometry.indices, count);
count += indicesLength;
}
}
transferableObjects.push(packedData.buffer);
return {
stringTable,
packedData
};
};
PrimitivePipeline.unpackCreateGeometryResults = function(createGeometryResult) {
const stringTable = createGeometryResult.stringTable;
const packedGeometry = createGeometryResult.packedData;
let i;
const result = new Array(packedGeometry[0]);
let resultIndex = 0;
let packedGeometryIndex = 1;
while (packedGeometryIndex < packedGeometry.length) {
const valid = packedGeometry[packedGeometryIndex++] === 1;
if (!valid) {
result[resultIndex++] = void 0;
continue;
}
const primitiveType = packedGeometry[packedGeometryIndex++];
const geometryType = packedGeometry[packedGeometryIndex++];
let offsetAttribute = packedGeometry[packedGeometryIndex++];
if (offsetAttribute === -1) {
offsetAttribute = void 0;
}
let boundingSphere;
let boundingSphereCV;
const validBoundingSphere = packedGeometry[packedGeometryIndex++] === 1;
if (validBoundingSphere) {
boundingSphere = BoundingSphere_default.unpack(
packedGeometry,
packedGeometryIndex
);
}
packedGeometryIndex += BoundingSphere_default.packedLength;
const validBoundingSphereCV = packedGeometry[packedGeometryIndex++] === 1;
if (validBoundingSphereCV) {
boundingSphereCV = BoundingSphere_default.unpack(
packedGeometry,
packedGeometryIndex
);
}
packedGeometryIndex += BoundingSphere_default.packedLength;
let length3;
let values;
let componentsPerAttribute;
const attributes = new GeometryAttributes_default();
const numAttributes = packedGeometry[packedGeometryIndex++];
for (i = 0; i < numAttributes; i++) {
const name = stringTable[packedGeometry[packedGeometryIndex++]];
const componentDatatype = packedGeometry[packedGeometryIndex++];
componentsPerAttribute = packedGeometry[packedGeometryIndex++];
const normalize2 = packedGeometry[packedGeometryIndex++] !== 0;
length3 = packedGeometry[packedGeometryIndex++];
values = ComponentDatatype_default.createTypedArray(componentDatatype, length3);
for (let valuesIndex = 0; valuesIndex < length3; valuesIndex++) {
values[valuesIndex] = packedGeometry[packedGeometryIndex++];
}
attributes[name] = new GeometryAttribute_default({
componentDatatype,
componentsPerAttribute,
normalize: normalize2,
values
});
}
let indices2;
length3 = packedGeometry[packedGeometryIndex++];
if (length3 > 0) {
const numberOfVertices = values.length / componentsPerAttribute;
indices2 = IndexDatatype_default.createTypedArray(numberOfVertices, length3);
for (i = 0; i < length3; i++) {
indices2[i] = packedGeometry[packedGeometryIndex++];
}
}
result[resultIndex++] = new Geometry_default({
primitiveType,
geometryType,
boundingSphere,
boundingSphereCV,
indices: indices2,
attributes,
offsetAttribute
});
}
return result;
};
function packInstancesForCombine(instances, transferableObjects) {
const length3 = instances.length;
const packedData = new Float64Array(1 + length3 * 19);
let count = 0;
packedData[count++] = length3;
for (let i = 0; i < length3; i++) {
const instance = instances[i];
Matrix4_default.pack(instance.modelMatrix, packedData, count);
count += Matrix4_default.packedLength;
if (defined_default(instance.attributes) && defined_default(instance.attributes.offset)) {
const values = instance.attributes.offset.value;
packedData[count] = values[0];
packedData[count + 1] = values[1];
packedData[count + 2] = values[2];
}
count += 3;
}
transferableObjects.push(packedData.buffer);
return packedData;
}
function unpackInstancesForCombine(data) {
const packedInstances = data;
const result = new Array(packedInstances[0]);
let count = 0;
let i = 1;
while (i < packedInstances.length) {
const modelMatrix = Matrix4_default.unpack(packedInstances, i);
let attributes;
i += Matrix4_default.packedLength;
if (defined_default(packedInstances[i])) {
attributes = {
offset: new OffsetGeometryInstanceAttribute_default(
packedInstances[i],
packedInstances[i + 1],
packedInstances[i + 2]
)
};
}
i += 3;
result[count++] = {
modelMatrix,
attributes
};
}
return result;
}
PrimitivePipeline.packCombineGeometryParameters = function(parameters, transferableObjects) {
const createGeometryResults = parameters.createGeometryResults;
const length3 = createGeometryResults.length;
for (let i = 0; i < length3; i++) {
transferableObjects.push(createGeometryResults[i].packedData.buffer);
}
return {
createGeometryResults: parameters.createGeometryResults,
packedInstances: packInstancesForCombine(
parameters.instances,
transferableObjects
),
ellipsoid: parameters.ellipsoid,
isGeographic: parameters.projection instanceof GeographicProjection_default,
elementIndexUintSupported: parameters.elementIndexUintSupported,
scene3DOnly: parameters.scene3DOnly,
vertexCacheOptimize: parameters.vertexCacheOptimize,
compressVertices: parameters.compressVertices,
modelMatrix: parameters.modelMatrix,
createPickOffsets: parameters.createPickOffsets
};
};
PrimitivePipeline.unpackCombineGeometryParameters = function(packedParameters) {
const instances = unpackInstancesForCombine(packedParameters.packedInstances);
const createGeometryResults = packedParameters.createGeometryResults;
const length3 = createGeometryResults.length;
let instanceIndex = 0;
for (let resultIndex = 0; resultIndex < length3; resultIndex++) {
const geometries = PrimitivePipeline.unpackCreateGeometryResults(
createGeometryResults[resultIndex]
);
const geometriesLength = geometries.length;
for (let geometryIndex = 0; geometryIndex < geometriesLength; geometryIndex++) {
const geometry = geometries[geometryIndex];
const instance = instances[instanceIndex];
instance.geometry = geometry;
++instanceIndex;
}
}
const ellipsoid = Ellipsoid_default.clone(packedParameters.ellipsoid);
const projection = packedParameters.isGeographic ? new GeographicProjection_default(ellipsoid) : new WebMercatorProjection_default(ellipsoid);
return {
instances,
ellipsoid,
projection,
elementIndexUintSupported: packedParameters.elementIndexUintSupported,
scene3DOnly: packedParameters.scene3DOnly,
vertexCacheOptimize: packedParameters.vertexCacheOptimize,
compressVertices: packedParameters.compressVertices,
modelMatrix: Matrix4_default.clone(packedParameters.modelMatrix),
createPickOffsets: packedParameters.createPickOffsets
};
};
function packBoundingSpheres(boundingSpheres) {
const length3 = boundingSpheres.length;
const bufferLength = 1 + (BoundingSphere_default.packedLength + 1) * length3;
const buffer = new Float32Array(bufferLength);
let bufferIndex = 0;
buffer[bufferIndex++] = length3;
for (let i = 0; i < length3; ++i) {
const bs = boundingSpheres[i];
if (!defined_default(bs)) {
buffer[bufferIndex++] = 0;
} else {
buffer[bufferIndex++] = 1;
BoundingSphere_default.pack(boundingSpheres[i], buffer, bufferIndex);
}
bufferIndex += BoundingSphere_default.packedLength;
}
return buffer;
}
function unpackBoundingSpheres(buffer) {
const result = new Array(buffer[0]);
let count = 0;
let i = 1;
while (i < buffer.length) {
if (buffer[i++] === 1) {
result[count] = BoundingSphere_default.unpack(buffer, i);
}
++count;
i += BoundingSphere_default.packedLength;
}
return result;
}
PrimitivePipeline.packCombineGeometryResults = function(results, transferableObjects) {
if (defined_default(results.geometries)) {
transferGeometries(results.geometries, transferableObjects);
}
const packedBoundingSpheres = packBoundingSpheres(results.boundingSpheres);
const packedBoundingSpheresCV = packBoundingSpheres(
results.boundingSpheresCV
);
transferableObjects.push(
packedBoundingSpheres.buffer,
packedBoundingSpheresCV.buffer
);
return {
geometries: results.geometries,
attributeLocations: results.attributeLocations,
modelMatrix: results.modelMatrix,
pickOffsets: results.pickOffsets,
offsetInstanceExtend: results.offsetInstanceExtend,
boundingSpheres: packedBoundingSpheres,
boundingSpheresCV: packedBoundingSpheresCV
};
};
PrimitivePipeline.unpackCombineGeometryResults = function(packedResult) {
return {
geometries: packedResult.geometries,
attributeLocations: packedResult.attributeLocations,
modelMatrix: packedResult.modelMatrix,
pickOffsets: packedResult.pickOffsets,
offsetInstanceExtend: packedResult.offsetInstanceExtend,
boundingSpheres: unpackBoundingSpheres(packedResult.boundingSpheres),
boundingSpheresCV: unpackBoundingSpheres(packedResult.boundingSpheresCV)
};
};
var PrimitivePipeline_default = PrimitivePipeline;
// packages/engine/Source/Scene/PrimitiveState.js
var PrimitiveState = {
READY: 0,
CREATING: 1,
CREATED: 2,
COMBINING: 3,
COMBINED: 4,
COMPLETE: 5,
FAILED: 6
};
var PrimitiveState_default = Object.freeze(PrimitiveState);
// packages/engine/Source/Scene/ShadowMode.js
var ShadowMode = {
/**
* The object does not cast or receive shadows.
*
* @type {number}
* @constant
*/
DISABLED: 0,
/**
* The object casts and receives shadows.
*
* @type {number}
* @constant
*/
ENABLED: 1,
/**
* The object casts shadows only.
*
* @type {number}
* @constant
*/
CAST_ONLY: 2,
/**
* The object receives shadows only.
*
* @type {number}
* @constant
*/
RECEIVE_ONLY: 3
};
ShadowMode.NUMBER_OF_SHADOW_MODES = 4;
ShadowMode.castShadows = function(shadowMode) {
return shadowMode === ShadowMode.ENABLED || shadowMode === ShadowMode.CAST_ONLY;
};
ShadowMode.receiveShadows = function(shadowMode) {
return shadowMode === ShadowMode.ENABLED || shadowMode === ShadowMode.RECEIVE_ONLY;
};
ShadowMode.fromCastReceive = function(castShadows, receiveShadows) {
if (castShadows && receiveShadows) {
return ShadowMode.ENABLED;
} else if (castShadows) {
return ShadowMode.CAST_ONLY;
} else if (receiveShadows) {
return ShadowMode.RECEIVE_ONLY;
}
return ShadowMode.DISABLED;
};
var ShadowMode_default = Object.freeze(ShadowMode);
// packages/engine/Source/Scene/Primitive.js
function Primitive(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this.geometryInstances = options.geometryInstances;
this.appearance = options.appearance;
this._appearance = void 0;
this._material = void 0;
this.depthFailAppearance = options.depthFailAppearance;
this._depthFailAppearance = void 0;
this._depthFailMaterial = void 0;
this.modelMatrix = Matrix4_default.clone(
defaultValue_default(options.modelMatrix, Matrix4_default.IDENTITY)
);
this._modelMatrix = new Matrix4_default();
this.show = defaultValue_default(options.show, true);
this._vertexCacheOptimize = defaultValue_default(options.vertexCacheOptimize, false);
this._interleave = defaultValue_default(options.interleave, false);
this._releaseGeometryInstances = defaultValue_default(
options.releaseGeometryInstances,
true
);
this._allowPicking = defaultValue_default(options.allowPicking, true);
this._asynchronous = defaultValue_default(options.asynchronous, true);
this._compressVertices = defaultValue_default(options.compressVertices, true);
this.cull = defaultValue_default(options.cull, true);
this.debugShowBoundingVolume = defaultValue_default(
options.debugShowBoundingVolume,
false
);
this.rtcCenter = options.rtcCenter;
if (defined_default(this.rtcCenter) && (!defined_default(this.geometryInstances) || Array.isArray(this.geometryInstances) && this.geometryInstances.length !== 1)) {
throw new DeveloperError_default(
"Relative-to-center rendering only supports one geometry instance."
);
}
this.shadows = defaultValue_default(options.shadows, ShadowMode_default.DISABLED);
this._translucent = void 0;
this._state = PrimitiveState_default.READY;
this._geometries = [];
this._error = void 0;
this._numberOfInstances = 0;
this._boundingSpheres = [];
this._boundingSphereWC = [];
this._boundingSphereCV = [];
this._boundingSphere2D = [];
this._boundingSphereMorph = [];
this._perInstanceAttributeCache = /* @__PURE__ */ new Map();
this._instanceIds = [];
this._lastPerInstanceAttributeIndex = 0;
this._va = [];
this._attributeLocations = void 0;
this._primitiveType = void 0;
this._frontFaceRS = void 0;
this._backFaceRS = void 0;
this._sp = void 0;
this._depthFailAppearance = void 0;
this._spDepthFail = void 0;
this._frontFaceDepthFailRS = void 0;
this._backFaceDepthFailRS = void 0;
this._pickIds = [];
this._colorCommands = [];
this._pickCommands = [];
this._createBoundingVolumeFunction = options._createBoundingVolumeFunction;
this._createRenderStatesFunction = options._createRenderStatesFunction;
this._createShaderProgramFunction = options._createShaderProgramFunction;
this._createCommandsFunction = options._createCommandsFunction;
this._updateAndQueueCommandsFunction = options._updateAndQueueCommandsFunction;
this._createPickOffsets = options._createPickOffsets;
this._pickOffsets = void 0;
this._createGeometryResults = void 0;
this._ready = false;
const primitive = this;
this._readyPromise = new Promise((resolve2, reject) => {
primitive._completeLoad = (frameState, state, error) => {
this._error = error;
this._state = state;
frameState.afterRender.push(function() {
primitive._ready = primitive._state === PrimitiveState_default.COMPLETE || primitive._state === PrimitiveState_default.FAILED;
if (!defined_default(error)) {
resolve2(primitive);
return true;
}
reject(error);
});
};
});
this._batchTable = void 0;
this._batchTableAttributeIndices = void 0;
this._offsetInstanceExtend = void 0;
this._batchTableOffsetAttribute2DIndex = void 0;
this._batchTableOffsetsUpdated = false;
this._instanceBoundingSpheres = void 0;
this._instanceBoundingSpheresCV = void 0;
this._tempBoundingSpheres = void 0;
this._recomputeBoundingSpheres = false;
this._batchTableBoundingSpheresUpdated = false;
this._batchTableBoundingSphereAttributeIndices = void 0;
}
Object.defineProperties(Primitive.prototype, {
/**
* When true
, geometry vertices are optimized for the pre and post-vertex-shader caches.
*
* @memberof Primitive.prototype
*
* @type {boolean}
* @readonly
*
* @default true
*/
vertexCacheOptimize: {
get: function() {
return this._vertexCacheOptimize;
}
},
/**
* Determines if geometry vertex attributes are interleaved, which can slightly improve rendering performance.
*
* @memberof Primitive.prototype
*
* @type {boolean}
* @readonly
*
* @default false
*/
interleave: {
get: function() {
return this._interleave;
}
},
/**
* When true
, the primitive does not keep a reference to the input geometryInstances
to save memory.
*
* @memberof Primitive.prototype
*
* @type {boolean}
* @readonly
*
* @default true
*/
releaseGeometryInstances: {
get: function() {
return this._releaseGeometryInstances;
}
},
/**
* When true
, each geometry instance will only be pickable with {@link Scene#pick}. When false
, GPU memory is saved. *
*
* @memberof Primitive.prototype
*
* @type {boolean}
* @readonly
*
* @default true
*/
allowPicking: {
get: function() {
return this._allowPicking;
}
},
/**
* Determines if the geometry instances will be created and batched on a web worker.
*
* @memberof Primitive.prototype
*
* @type {boolean}
* @readonly
*
* @default true
*/
asynchronous: {
get: function() {
return this._asynchronous;
}
},
/**
* When true
, geometry vertices are compressed, which will save memory.
*
* @memberof Primitive.prototype
*
* @type {boolean}
* @readonly
*
* @default true
*/
compressVertices: {
get: function() {
return this._compressVertices;
}
},
/**
* Determines if the primitive is complete and ready to render. If this property is
* true, the primitive will be rendered the next time that {@link Primitive#update}
* is called.
*
* @memberof Primitive.prototype
*
* @type {boolean}
* @readonly
*
* @example
* // Wait for a primitive to become ready before accessing attributes
* const removeListener = scene.postRender.addEventListener(() => {
* if (!frustumPrimitive.ready) {
* return;
* }
*
* const attributes = primitive.getGeometryInstanceAttributes('an id');
* attributes.color = Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.AQUA);
*
* removeListener();
* });
*/
ready: {
get: function() {
return this._ready;
}
},
/**
* Gets a promise that resolves when the primitive is ready to render.
* @memberof Primitive.prototype
* @type {Promisetrue
, geometry vertices are optimized for the pre and post-vertex-shader caches.
*
* @memberof ClassificationPrimitive.prototype
*
* @type {boolean}
* @readonly
*
* @default true
*/
vertexCacheOptimize: {
get: function() {
return this._primitiveOptions.vertexCacheOptimize;
}
},
/**
* Determines if geometry vertex attributes are interleaved, which can slightly improve rendering performance.
*
* @memberof ClassificationPrimitive.prototype
*
* @type {boolean}
* @readonly
*
* @default false
*/
interleave: {
get: function() {
return this._primitiveOptions.interleave;
}
},
/**
* When true
, the primitive does not keep a reference to the input geometryInstances
to save memory.
*
* @memberof ClassificationPrimitive.prototype
*
* @type {boolean}
* @readonly
*
* @default true
*/
releaseGeometryInstances: {
get: function() {
return this._primitiveOptions.releaseGeometryInstances;
}
},
/**
* When true
, each geometry instance will only be pickable with {@link Scene#pick}. When false
, GPU memory is saved.
*
* @memberof ClassificationPrimitive.prototype
*
* @type {boolean}
* @readonly
*
* @default true
*/
allowPicking: {
get: function() {
return this._primitiveOptions.allowPicking;
}
},
/**
* Determines if the geometry instances will be created and batched on a web worker.
*
* @memberof ClassificationPrimitive.prototype
*
* @type {boolean}
* @readonly
*
* @default true
*/
asynchronous: {
get: function() {
return this._primitiveOptions.asynchronous;
}
},
/**
* When true
, geometry vertices are compressed, which will save memory.
*
* @memberof ClassificationPrimitive.prototype
*
* @type {boolean}
* @readonly
*
* @default true
*/
compressVertices: {
get: function() {
return this._primitiveOptions.compressVertices;
}
},
/**
* Determines if the primitive is complete and ready to render. If this property is
* true, the primitive will be rendered the next time that {@link ClassificationPrimitive#update}
* is called.
*
* @memberof ClassificationPrimitive.prototype
*
* @type {boolean}
* @readonly
*/
ready: {
get: function() {
return this._ready;
}
},
/**
* Gets a promise that resolves when the primitive is ready to render.
* @memberof ClassificationPrimitive.prototype
* @type {Promisetrue
, geometry vertices are optimized for the pre and post-vertex-shader caches.
*
* @memberof GroundPrimitive.prototype
*
* @type {boolean}
* @readonly
*
* @default true
*/
vertexCacheOptimize: {
get: function() {
return this._classificationPrimitiveOptions.vertexCacheOptimize;
}
},
/**
* Determines if geometry vertex attributes are interleaved, which can slightly improve rendering performance.
*
* @memberof GroundPrimitive.prototype
*
* @type {boolean}
* @readonly
*
* @default false
*/
interleave: {
get: function() {
return this._classificationPrimitiveOptions.interleave;
}
},
/**
* When true
, the primitive does not keep a reference to the input geometryInstances
to save memory.
*
* @memberof GroundPrimitive.prototype
*
* @type {boolean}
* @readonly
*
* @default true
*/
releaseGeometryInstances: {
get: function() {
return this._classificationPrimitiveOptions.releaseGeometryInstances;
}
},
/**
* When true
, each geometry instance will only be pickable with {@link Scene#pick}. When false
, GPU memory is saved.
*
* @memberof GroundPrimitive.prototype
*
* @type {boolean}
* @readonly
*
* @default true
*/
allowPicking: {
get: function() {
return this._classificationPrimitiveOptions.allowPicking;
}
},
/**
* Determines if the geometry instances will be created and batched on a web worker.
*
* @memberof GroundPrimitive.prototype
*
* @type {boolean}
* @readonly
*
* @default true
*/
asynchronous: {
get: function() {
return this._classificationPrimitiveOptions.asynchronous;
}
},
/**
* When true
, geometry vertices are compressed, which will save memory.
*
* @memberof GroundPrimitive.prototype
*
* @type {boolean}
* @readonly
*
* @default true
*/
compressVertices: {
get: function() {
return this._classificationPrimitiveOptions.compressVertices;
}
},
/**
* Determines if the primitive is complete and ready to render. If this property is
* true, the primitive will be rendered the next time that {@link GroundPrimitive#update}
* is called.
*
* @memberof GroundPrimitive.prototype
*
* @type {boolean}
* @readonly
*/
ready: {
get: function() {
return this._ready;
}
},
/**
* Gets a promise that resolves when the primitive is ready to render.
* @memberof GroundPrimitive.prototype
* @type {Promise* The render state can be explicitly defined when constructing a {@link PolylineColorAppearance} * instance, or it is set implicitly via {@link PolylineColorAppearance#translucent}. *
* * @memberof PolylineColorAppearance.prototype * * @type {object} * @readonly */ renderState: { get: function() { return this._renderState; } }, /** * Whentrue
, the geometry is expected to be closed so
* {@link PolylineColorAppearance#renderState} has backface culling enabled.
* This is always false
for PolylineColorAppearance
.
*
* @memberof PolylineColorAppearance.prototype
*
* @type {boolean}
* @readonly
*
* @default false
*/
closed: {
get: function() {
return this._closed;
}
},
/**
* The {@link VertexFormat} that this appearance instance is compatible with.
* A geometry can have more vertex attributes and still be compatible - at a
* potential performance cost - but it can't have less.
*
* @memberof PolylineColorAppearance.prototype
*
* @type VertexFormat
* @readonly
*
* @default {@link PolylineColorAppearance.VERTEX_FORMAT}
*/
vertexFormat: {
get: function() {
return this._vertexFormat;
}
}
});
PolylineColorAppearance.VERTEX_FORMAT = VertexFormat_default.POSITION_ONLY;
PolylineColorAppearance.prototype.getFragmentShaderSource = Appearance_default.prototype.getFragmentShaderSource;
PolylineColorAppearance.prototype.isTranslucent = Appearance_default.prototype.isTranslucent;
PolylineColorAppearance.prototype.getRenderState = Appearance_default.prototype.getRenderState;
var PolylineColorAppearance_default = PolylineColorAppearance;
// packages/engine/Source/Shaders/Appearances/PolylineMaterialAppearanceVS.js
var PolylineMaterialAppearanceVS_default = "in vec3 position3DHigh;\nin vec3 position3DLow;\nin vec3 prevPosition3DHigh;\nin vec3 prevPosition3DLow;\nin vec3 nextPosition3DHigh;\nin vec3 nextPosition3DLow;\nin vec2 expandAndWidth;\nin vec2 st;\nin float batchId;\n\nout float v_width;\nout vec2 v_st;\nout float v_polylineAngle;\n\nvoid main()\n{\n float expandDir = expandAndWidth.x;\n float width = abs(expandAndWidth.y) + 0.5;\n bool usePrev = expandAndWidth.y < 0.0;\n\n vec4 p = czm_computePosition();\n vec4 prev = czm_computePrevPosition();\n vec4 next = czm_computeNextPosition();\n\n float angle;\n vec4 positionWC = getPolylineWindowCoordinates(p, prev, next, expandDir, width, usePrev, angle);\n gl_Position = czm_viewportOrthographic * positionWC;\n\n v_width = width;\n v_st.s = st.s;\n v_st.t = czm_writeNonPerspective(st.t, gl_Position.w);\n v_polylineAngle = angle;\n}\n";
// packages/engine/Source/Shaders/PolylineFS.js
var PolylineFS_default = "#ifdef VECTOR_TILE\nuniform vec4 u_highlightColor;\n#endif\n\nin vec2 v_st;\n\nvoid main()\n{\n czm_materialInput materialInput;\n\n vec2 st = v_st;\n st.t = czm_readNonPerspective(st.t, gl_FragCoord.w);\n\n materialInput.s = st.s;\n materialInput.st = st;\n materialInput.str = vec3(st, 0.0);\n\n czm_material material = czm_getMaterial(materialInput);\n out_FragColor = vec4(material.diffuse + material.emission, material.alpha);\n#ifdef VECTOR_TILE\n out_FragColor *= u_highlightColor;\n#endif\n\n czm_writeLogDepth();\n}\n";
// packages/engine/Source/Scene/PolylineMaterialAppearance.js
var defaultVertexShaderSource2 = `${PolylineCommon_default}
${PolylineMaterialAppearanceVS_default}`;
var defaultFragmentShaderSource2 = PolylineFS_default;
if (!FeatureDetection_default.isInternetExplorer()) {
defaultVertexShaderSource2 = `#define CLIP_POLYLINE
${defaultVertexShaderSource2}`;
}
function PolylineMaterialAppearance(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const translucent = defaultValue_default(options.translucent, true);
const closed = false;
const vertexFormat = PolylineMaterialAppearance.VERTEX_FORMAT;
this.material = defined_default(options.material) ? options.material : Material_default.fromType(Material_default.ColorType);
this.translucent = translucent;
this._vertexShaderSource = defaultValue_default(
options.vertexShaderSource,
defaultVertexShaderSource2
);
this._fragmentShaderSource = defaultValue_default(
options.fragmentShaderSource,
defaultFragmentShaderSource2
);
this._renderState = Appearance_default.getDefaultRenderState(
translucent,
closed,
options.renderState
);
this._closed = closed;
this._vertexFormat = vertexFormat;
}
Object.defineProperties(PolylineMaterialAppearance.prototype, {
/**
* The GLSL source code for the vertex shader.
*
* @memberof PolylineMaterialAppearance.prototype
*
* @type {string}
* @readonly
*/
vertexShaderSource: {
get: function() {
let vs = this._vertexShaderSource;
if (this.material.shaderSource.search(/in\s+float\s+v_polylineAngle;/g) !== -1) {
vs = `#define POLYLINE_DASH
${vs}`;
}
return vs;
}
},
/**
* The GLSL source code for the fragment shader.
*
* @memberof PolylineMaterialAppearance.prototype
*
* @type {string}
* @readonly
*/
fragmentShaderSource: {
get: function() {
return this._fragmentShaderSource;
}
},
/**
* The WebGL fixed-function state to use when rendering the geometry.
* * The render state can be explicitly defined when constructing a {@link PolylineMaterialAppearance} * instance, or it is set implicitly via {@link PolylineMaterialAppearance#translucent} * and {@link PolylineMaterialAppearance#closed}. *
* * @memberof PolylineMaterialAppearance.prototype * * @type {object} * @readonly */ renderState: { get: function() { return this._renderState; } }, /** * Whentrue
, the geometry is expected to be closed so
* {@link PolylineMaterialAppearance#renderState} has backface culling enabled.
* This is always false
for PolylineMaterialAppearance
.
*
* @memberof PolylineMaterialAppearance.prototype
*
* @type {boolean}
* @readonly
*
* @default false
*/
closed: {
get: function() {
return this._closed;
}
},
/**
* The {@link VertexFormat} that this appearance instance is compatible with.
* A geometry can have more vertex attributes and still be compatible - at a
* potential performance cost - but it can't have less.
*
* @memberof PolylineMaterialAppearance.prototype
*
* @type VertexFormat
* @readonly
*
* @default {@link PolylineMaterialAppearance.VERTEX_FORMAT}
*/
vertexFormat: {
get: function() {
return this._vertexFormat;
}
}
});
PolylineMaterialAppearance.VERTEX_FORMAT = VertexFormat_default.POSITION_AND_ST;
PolylineMaterialAppearance.prototype.getFragmentShaderSource = Appearance_default.prototype.getFragmentShaderSource;
PolylineMaterialAppearance.prototype.isTranslucent = Appearance_default.prototype.isTranslucent;
PolylineMaterialAppearance.prototype.getRenderState = Appearance_default.prototype.getRenderState;
var PolylineMaterialAppearance_default = PolylineMaterialAppearance;
// packages/engine/Source/Scene/GroundPolylinePrimitive.js
function GroundPolylinePrimitive(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this.geometryInstances = options.geometryInstances;
this._hasPerInstanceColors = true;
let appearance = options.appearance;
if (!defined_default(appearance)) {
appearance = new PolylineMaterialAppearance_default();
}
this.appearance = appearance;
this.show = defaultValue_default(options.show, true);
this.classificationType = defaultValue_default(
options.classificationType,
ClassificationType_default.BOTH
);
this.debugShowBoundingVolume = defaultValue_default(
options.debugShowBoundingVolume,
false
);
this._debugShowShadowVolume = defaultValue_default(
options.debugShowShadowVolume,
false
);
this._primitiveOptions = {
geometryInstances: void 0,
appearance: void 0,
vertexCacheOptimize: false,
interleave: defaultValue_default(options.interleave, false),
releaseGeometryInstances: defaultValue_default(
options.releaseGeometryInstances,
true
),
allowPicking: defaultValue_default(options.allowPicking, true),
asynchronous: defaultValue_default(options.asynchronous, true),
compressVertices: false,
_createShaderProgramFunction: void 0,
_createCommandsFunction: void 0,
_updateAndQueueCommandsFunction: void 0
};
this._zIndex = void 0;
this._ready = false;
const groundPolylinePrimitive = this;
this._readyPromise = new Promise((resolve2, reject) => {
groundPolylinePrimitive._completeLoad = () => {
this._ready = true;
if (this.releaseGeometryInstances) {
this.geometryInstances = void 0;
}
const error = this._error;
if (!defined_default(error)) {
resolve2(this);
} else {
reject(error);
}
};
});
this._primitive = void 0;
this._sp = void 0;
this._sp2D = void 0;
this._spMorph = void 0;
this._renderState = getRenderState(false);
this._renderState3DTiles = getRenderState(true);
this._renderStateMorph = RenderState_default.fromCache({
cull: {
enabled: true,
face: CullFace_default.FRONT
// Geometry is "inverted," so cull front when materials on volume instead of on terrain (morph)
},
depthTest: {
enabled: true
},
blending: BlendingState_default.PRE_MULTIPLIED_ALPHA_BLEND,
depthMask: false
});
}
Object.defineProperties(GroundPolylinePrimitive.prototype, {
/**
* Determines if geometry vertex attributes are interleaved, which can slightly improve rendering performance.
*
* @memberof GroundPolylinePrimitive.prototype
*
* @type {boolean}
* @readonly
*
* @default false
*/
interleave: {
get: function() {
return this._primitiveOptions.interleave;
}
},
/**
* When true
, the primitive does not keep a reference to the input geometryInstances
to save memory.
*
* @memberof GroundPolylinePrimitive.prototype
*
* @type {boolean}
* @readonly
*
* @default true
*/
releaseGeometryInstances: {
get: function() {
return this._primitiveOptions.releaseGeometryInstances;
}
},
/**
* When true
, each geometry instance will only be pickable with {@link Scene#pick}. When false
, GPU memory is saved.
*
* @memberof GroundPolylinePrimitive.prototype
*
* @type {boolean}
* @readonly
*
* @default true
*/
allowPicking: {
get: function() {
return this._primitiveOptions.allowPicking;
}
},
/**
* Determines if the geometry instances will be created and batched on a web worker.
*
* @memberof GroundPolylinePrimitive.prototype
*
* @type {boolean}
* @readonly
*
* @default true
*/
asynchronous: {
get: function() {
return this._primitiveOptions.asynchronous;
}
},
/**
* Determines if the primitive is complete and ready to render. If this property is
* true, the primitive will be rendered the next time that {@link GroundPolylinePrimitive#update}
* is called.
*
* @memberof GroundPolylinePrimitive.prototype
*
* @type {boolean}
* @readonly
*/
ready: {
get: function() {
return this._ready;
}
},
/**
* Gets a promise that resolves when the primitive is ready to render.
* @memberof GroundPolylinePrimitive.prototype
* @type {Promise* If true, draws the shadow volume for each geometry in the primitive. *
* * @memberof GroundPolylinePrimitive.prototype * * @type {boolean} * @readonly * * @default false */ debugShowShadowVolume: { get: function() { return this._debugShowShadowVolume; } } }); GroundPolylinePrimitive.initializeTerrainHeights = function() { return ApproximateTerrainHeights_default.initialize(); }; function createShaderProgram3(groundPolylinePrimitive, frameState, appearance) { const context = frameState.context; const primitive = groundPolylinePrimitive._primitive; const attributeLocations8 = primitive._attributeLocations; let vs = primitive._batchTable.getVertexShaderCallback()( PolylineShadowVolumeVS_default ); vs = Primitive_default._appendShowToShader(primitive, vs); vs = Primitive_default._appendDistanceDisplayConditionToShader(primitive, vs); vs = Primitive_default._modifyShaderPosition( groundPolylinePrimitive, vs, frameState.scene3DOnly ); let vsMorph = primitive._batchTable.getVertexShaderCallback()( PolylineShadowVolumeMorphVS_default ); vsMorph = Primitive_default._appendShowToShader(primitive, vsMorph); vsMorph = Primitive_default._appendDistanceDisplayConditionToShader( primitive, vsMorph ); vsMorph = Primitive_default._modifyShaderPosition( groundPolylinePrimitive, vsMorph, frameState.scene3DOnly ); let fs = primitive._batchTable.getVertexShaderCallback()( PolylineShadowVolumeFS_default ); const vsDefines = [ `GLOBE_MINIMUM_ALTITUDE ${frameState.mapProjection.ellipsoid.minimumRadius.toFixed( 1 )}` ]; let colorDefine = ""; let materialShaderSource = ""; if (defined_default(appearance.material)) { materialShaderSource = defined_default(appearance.material) ? appearance.material.shaderSource : ""; if (materialShaderSource.search(/in\s+float\s+v_polylineAngle;/g) !== -1) { vsDefines.push("ANGLE_VARYING"); } if (materialShaderSource.search(/in\s+float\s+v_width;/g) !== -1) { vsDefines.push("WIDTH_VARYING"); } } else { colorDefine = "PER_INSTANCE_COLOR"; } vsDefines.push(colorDefine); const fsDefines = groundPolylinePrimitive.debugShowShadowVolume ? ["DEBUG_SHOW_VOLUME", colorDefine] : [colorDefine]; const vsColor3D = new ShaderSource_default({ defines: vsDefines, sources: [vs] }); const fsColor3D = new ShaderSource_default({ defines: fsDefines, sources: [materialShaderSource, fs] }); groundPolylinePrimitive._sp = ShaderProgram_default.replaceCache({ context, shaderProgram: primitive._sp, vertexShaderSource: vsColor3D, fragmentShaderSource: fsColor3D, attributeLocations: attributeLocations8 }); let colorProgram2D = context.shaderCache.getDerivedShaderProgram( groundPolylinePrimitive._sp, "2dColor" ); if (!defined_default(colorProgram2D)) { const vsColor2D = new ShaderSource_default({ defines: vsDefines.concat(["COLUMBUS_VIEW_2D"]), sources: [vs] }); colorProgram2D = context.shaderCache.createDerivedShaderProgram( groundPolylinePrimitive._sp, "2dColor", { context, shaderProgram: groundPolylinePrimitive._sp2D, vertexShaderSource: vsColor2D, fragmentShaderSource: fsColor3D, attributeLocations: attributeLocations8 } ); } groundPolylinePrimitive._sp2D = colorProgram2D; let colorProgramMorph = context.shaderCache.getDerivedShaderProgram( groundPolylinePrimitive._sp, "MorphColor" ); if (!defined_default(colorProgramMorph)) { const vsColorMorph = new ShaderSource_default({ defines: vsDefines.concat([ `MAX_TERRAIN_HEIGHT ${ApproximateTerrainHeights_default._defaultMaxTerrainHeight.toFixed( 1 )}` ]), sources: [vsMorph] }); fs = primitive._batchTable.getVertexShaderCallback()( PolylineShadowVolumeMorphFS_default ); const fsColorMorph = new ShaderSource_default({ defines: fsDefines, sources: [materialShaderSource, fs] }); colorProgramMorph = context.shaderCache.createDerivedShaderProgram( groundPolylinePrimitive._sp, "MorphColor", { context, shaderProgram: groundPolylinePrimitive._spMorph, vertexShaderSource: vsColorMorph, fragmentShaderSource: fsColorMorph, attributeLocations: attributeLocations8 } ); } groundPolylinePrimitive._spMorph = colorProgramMorph; } function getRenderState(mask3DTiles) { return RenderState_default.fromCache({ cull: { enabled: true // prevent double-draw. Geometry is "inverted" (reversed winding order) so we're drawing backfaces. }, blending: BlendingState_default.PRE_MULTIPLIED_ALPHA_BLEND, depthMask: false, stencilTest: { enabled: mask3DTiles, frontFunction: StencilFunction_default.EQUAL, frontOperation: { fail: StencilOperation_default.KEEP, zFail: StencilOperation_default.KEEP, zPass: StencilOperation_default.KEEP }, backFunction: StencilFunction_default.EQUAL, backOperation: { fail: StencilOperation_default.KEEP, zFail: StencilOperation_default.KEEP, zPass: StencilOperation_default.KEEP }, reference: StencilConstants_default.CESIUM_3D_TILE_MASK, mask: StencilConstants_default.CESIUM_3D_TILE_MASK } }); } function createCommands3(groundPolylinePrimitive, appearance, material, translucent, colorCommands, pickCommands) { const primitive = groundPolylinePrimitive._primitive; const length3 = primitive._va.length; colorCommands.length = length3; pickCommands.length = length3; const isPolylineColorAppearance = appearance instanceof PolylineColorAppearance_default; const materialUniforms = isPolylineColorAppearance ? {} : material._uniforms; const uniformMap2 = primitive._batchTable.getUniformMapCallback()( materialUniforms ); for (let i = 0; i < length3; i++) { const vertexArray = primitive._va[i]; let command = colorCommands[i]; if (!defined_default(command)) { command = colorCommands[i] = new DrawCommand_default({ owner: groundPolylinePrimitive, primitiveType: primitive._primitiveType }); } command.vertexArray = vertexArray; command.renderState = groundPolylinePrimitive._renderState; command.shaderProgram = groundPolylinePrimitive._sp; command.uniformMap = uniformMap2; command.pass = Pass_default.TERRAIN_CLASSIFICATION; command.pickId = "czm_batchTable_pickColor(v_endPlaneNormalEcAndBatchId.w)"; const derivedTilesetCommand = DrawCommand_default.shallowClone( command, command.derivedCommands.tileset ); derivedTilesetCommand.renderState = groundPolylinePrimitive._renderState3DTiles; derivedTilesetCommand.pass = Pass_default.CESIUM_3D_TILE_CLASSIFICATION; command.derivedCommands.tileset = derivedTilesetCommand; const derived2DCommand = DrawCommand_default.shallowClone( command, command.derivedCommands.color2D ); derived2DCommand.shaderProgram = groundPolylinePrimitive._sp2D; command.derivedCommands.color2D = derived2DCommand; const derived2DTilesetCommand = DrawCommand_default.shallowClone( derivedTilesetCommand, derivedTilesetCommand.derivedCommands.color2D ); derived2DTilesetCommand.shaderProgram = groundPolylinePrimitive._sp2D; derivedTilesetCommand.derivedCommands.color2D = derived2DTilesetCommand; const derivedMorphCommand = DrawCommand_default.shallowClone( command, command.derivedCommands.colorMorph ); derivedMorphCommand.renderState = groundPolylinePrimitive._renderStateMorph; derivedMorphCommand.shaderProgram = groundPolylinePrimitive._spMorph; derivedMorphCommand.pickId = "czm_batchTable_pickColor(v_batchId)"; command.derivedCommands.colorMorph = derivedMorphCommand; } } function updateAndQueueCommand(groundPolylinePrimitive, command, frameState, modelMatrix, cull, boundingVolume, debugShowBoundingVolume2) { if (frameState.mode === SceneMode_default.MORPHING) { command = command.derivedCommands.colorMorph; } else if (frameState.mode !== SceneMode_default.SCENE3D) { command = command.derivedCommands.color2D; } command.modelMatrix = modelMatrix; command.boundingVolume = boundingVolume; command.cull = cull; command.debugShowBoundingVolume = debugShowBoundingVolume2; frameState.commandList.push(command); } function updateAndQueueCommands4(groundPolylinePrimitive, frameState, colorCommands, pickCommands, modelMatrix, cull, debugShowBoundingVolume2) { const primitive = groundPolylinePrimitive._primitive; Primitive_default._updateBoundingVolumes(primitive, frameState, modelMatrix); let boundingSpheres; if (frameState.mode === SceneMode_default.SCENE3D) { boundingSpheres = primitive._boundingSphereWC; } else if (frameState.mode === SceneMode_default.COLUMBUS_VIEW) { boundingSpheres = primitive._boundingSphereCV; } else if (frameState.mode === SceneMode_default.SCENE2D && defined_default(primitive._boundingSphere2D)) { boundingSpheres = primitive._boundingSphere2D; } else if (defined_default(primitive._boundingSphereMorph)) { boundingSpheres = primitive._boundingSphereMorph; } const morphing = frameState.mode === SceneMode_default.MORPHING; const classificationType = groundPolylinePrimitive.classificationType; const queueTerrainCommands = classificationType !== ClassificationType_default.CESIUM_3D_TILE; const queue3DTilesCommands = classificationType !== ClassificationType_default.TERRAIN && !morphing; let command; const passes = frameState.passes; if (passes.render || passes.pick && primitive.allowPicking) { const colorLength = colorCommands.length; for (let j = 0; j < colorLength; ++j) { const boundingVolume = boundingSpheres[j]; if (queueTerrainCommands) { command = colorCommands[j]; updateAndQueueCommand( groundPolylinePrimitive, command, frameState, modelMatrix, cull, boundingVolume, debugShowBoundingVolume2 ); } if (queue3DTilesCommands) { command = colorCommands[j].derivedCommands.tileset; updateAndQueueCommand( groundPolylinePrimitive, command, frameState, modelMatrix, cull, boundingVolume, debugShowBoundingVolume2 ); } } } } GroundPolylinePrimitive.prototype.update = function(frameState) { if (!defined_default(this._primitive) && !defined_default(this.geometryInstances)) { return; } if (!ApproximateTerrainHeights_default.initialized) { if (!this.asynchronous) { throw new DeveloperError_default( "For synchronous GroundPolylinePrimitives, you must call GroundPolylinePrimitives.initializeTerrainHeights() and wait for the returned promise to resolve." ); } GroundPolylinePrimitive.initializeTerrainHeights(); return; } let i; const that = this; const primitiveOptions = this._primitiveOptions; if (!defined_default(this._primitive)) { const geometryInstances = Array.isArray(this.geometryInstances) ? this.geometryInstances : [this.geometryInstances]; const geometryInstancesLength = geometryInstances.length; const groundInstances = new Array(geometryInstancesLength); let attributes; for (i = 0; i < geometryInstancesLength; ++i) { attributes = geometryInstances[i].attributes; if (!defined_default(attributes) || !defined_default(attributes.color)) { this._hasPerInstanceColors = false; break; } } for (i = 0; i < geometryInstancesLength; ++i) { const geometryInstance = geometryInstances[i]; attributes = {}; const instanceAttributes = geometryInstance.attributes; for (const attributeKey in instanceAttributes) { if (instanceAttributes.hasOwnProperty(attributeKey)) { attributes[attributeKey] = instanceAttributes[attributeKey]; } } if (!defined_default(attributes.width)) { attributes.width = new GeometryInstanceAttribute_default({ componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE, componentsPerAttribute: 1, value: [geometryInstance.geometry.width] }); } geometryInstance.geometry._scene3DOnly = frameState.scene3DOnly; GroundPolylineGeometry_default.setProjectionAndEllipsoid( geometryInstance.geometry, frameState.mapProjection ); groundInstances[i] = new GeometryInstance_default({ geometry: geometryInstance.geometry, attributes, id: geometryInstance.id, pickPrimitive: that }); } primitiveOptions.geometryInstances = groundInstances; primitiveOptions.appearance = this.appearance; primitiveOptions._createShaderProgramFunction = function(primitive, frameState2, appearance) { createShaderProgram3(that, frameState2, appearance); }; primitiveOptions._createCommandsFunction = function(primitive, appearance, material, translucent, twoPasses, colorCommands, pickCommands) { createCommands3( that, appearance, material, translucent, colorCommands, pickCommands ); }; primitiveOptions._updateAndQueueCommandsFunction = function(primitive, frameState2, colorCommands, pickCommands, modelMatrix, cull, debugShowBoundingVolume2, twoPasses) { updateAndQueueCommands4( that, frameState2, colorCommands, pickCommands, modelMatrix, cull, debugShowBoundingVolume2 ); }; this._primitive = new Primitive_default(primitiveOptions); } if (this.appearance instanceof PolylineColorAppearance_default && !this._hasPerInstanceColors) { throw new DeveloperError_default( "All GeometryInstances must have color attributes to use PolylineColorAppearance with GroundPolylinePrimitive." ); } this._primitive.appearance = this.appearance; this._primitive.show = this.show; this._primitive.debugShowBoundingVolume = this.debugShowBoundingVolume; this._primitive.update(frameState); frameState.afterRender.push(() => { if (!this._ready && defined_default(this._primitive) && this._primitive.ready) { this._completeLoad(); } }); }; GroundPolylinePrimitive.prototype.getGeometryInstanceAttributes = function(id) { if (!defined_default(this._primitive)) { throw new DeveloperError_default( "must call update before calling getGeometryInstanceAttributes" ); } return this._primitive.getGeometryInstanceAttributes(id); }; GroundPolylinePrimitive.isSupported = function(scene) { return scene.frameState.context.depthTexture; }; GroundPolylinePrimitive.prototype.isDestroyed = function() { return false; }; GroundPolylinePrimitive.prototype.destroy = function() { this._primitive = this._primitive && this._primitive.destroy(); this._sp = this._sp && this._sp.destroy(); this._sp2D = void 0; this._spMorph = void 0; return destroyObject_default(this); }; var GroundPolylinePrimitive_default = GroundPolylinePrimitive; // packages/engine/Source/DataSources/ImageMaterialProperty.js var defaultRepeat = new Cartesian2_default(1, 1); var defaultTransparent = false; var defaultColor2 = Color_default.WHITE; function ImageMaterialProperty(options) { options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT); this._definitionChanged = new Event_default(); this._image = void 0; this._imageSubscription = void 0; this._repeat = void 0; this._repeatSubscription = void 0; this._color = void 0; this._colorSubscription = void 0; this._transparent = void 0; this._transparentSubscription = void 0; this.image = options.image; this.repeat = options.repeat; this.color = options.color; this.transparent = options.transparent; } Object.defineProperties(ImageMaterialProperty.prototype, { /** * Gets a value indicating if this property is constant. A property is considered * constant if getValue always returns the same result for the current definition. * @memberof ImageMaterialProperty.prototype * * @type {boolean} * @readonly */ isConstant: { get: function() { return Property_default.isConstant(this._image) && Property_default.isConstant(this._repeat); } }, /** * Gets the event that is raised whenever the definition of this property changes. * The definition is considered to have changed if a call to getValue would return * a different result for the same time. * @memberof ImageMaterialProperty.prototype * * @type {Event} * @readonly */ definitionChanged: { get: function() { return this._definitionChanged; } }, /** * Gets or sets the Property specifying Image, URL, Canvas, or Video to use. * @memberof ImageMaterialProperty.prototype * @type {Property|undefined} */ image: createPropertyDescriptor_default("image"), /** * Gets or sets the {@link Cartesian2} Property specifying the number of times the image repeats in each direction. * @memberof ImageMaterialProperty.prototype * @type {Property|undefined} * @default new Cartesian2(1, 1) */ repeat: createPropertyDescriptor_default("repeat"), /** * Gets or sets the Color Property specifying the desired color applied to the image. * @memberof ImageMaterialProperty.prototype * @type {Property|undefined} * @default 1.0 */ color: createPropertyDescriptor_default("color"), /** * Gets or sets the Boolean Property specifying whether the image has transparency * @memberof ImageMaterialProperty.prototype * @type {Property|undefined} * @default 1.0 */ transparent: createPropertyDescriptor_default("transparent") }); ImageMaterialProperty.prototype.getType = function(time) { return "Image"; }; ImageMaterialProperty.prototype.getValue = function(time, result) { if (!defined_default(result)) { result = {}; } result.image = Property_default.getValueOrUndefined(this._image, time); result.repeat = Property_default.getValueOrClonedDefault( this._repeat, time, defaultRepeat, result.repeat ); result.color = Property_default.getValueOrClonedDefault( this._color, time, defaultColor2, result.color ); if (Property_default.getValueOrDefault(this._transparent, time, defaultTransparent)) { result.color.alpha = Math.min(0.99, result.color.alpha); } return result; }; ImageMaterialProperty.prototype.equals = function(other) { return this === other || other instanceof ImageMaterialProperty && Property_default.equals(this._image, other._image) && Property_default.equals(this._repeat, other._repeat) && Property_default.equals(this._color, other._color) && Property_default.equals(this._transparent, other._transparent); }; var ImageMaterialProperty_default = ImageMaterialProperty; // packages/engine/Source/DataSources/createMaterialPropertyDescriptor.js function createMaterialProperty(value) { if (value instanceof Color_default) { return new ColorMaterialProperty_default(value); } if (typeof value === "string" || value instanceof Resource_default || value instanceof HTMLCanvasElement || value instanceof HTMLVideoElement) { const result = new ImageMaterialProperty_default(); result.image = value; return result; } throw new DeveloperError_default(`Unable to infer material type: ${value}`); } function createMaterialPropertyDescriptor(name, configurable) { return createPropertyDescriptor_default(name, configurable, createMaterialProperty); } var createMaterialPropertyDescriptor_default = createMaterialPropertyDescriptor; // packages/engine/Source/DataSources/BoxGraphics.js function BoxGraphics(options) { this._definitionChanged = new Event_default(); this._show = void 0; this._showSubscription = void 0; this._dimensions = void 0; this._dimensionsSubscription = void 0; this._heightReference = void 0; this._heightReferenceSubscription = void 0; this._fill = void 0; this._fillSubscription = void 0; this._material = void 0; this._materialSubscription = void 0; this._outline = void 0; this._outlineSubscription = void 0; this._outlineColor = void 0; this._outlineColorSubscription = void 0; this._outlineWidth = void 0; this._outlineWidthSubscription = void 0; this._shadows = void 0; this._shadowsSubscription = void 0; this._distanceDisplayCondition = void 0; this._distanceDisplayConditionSubscription = void 0; this.merge(defaultValue_default(options, defaultValue_default.EMPTY_OBJECT)); } Object.defineProperties(BoxGraphics.prototype, { /** * Gets the event that is raised whenever a property or sub-property is changed or modified. * @memberof BoxGraphics.prototype * @type {Event} * @readonly */ definitionChanged: { get: function() { return this._definitionChanged; } }, /** * Gets or sets the boolean Property specifying the visibility of the box. * @memberof BoxGraphics.prototype * @type {Property|undefined} * @default true */ show: createPropertyDescriptor_default("show"), /** * Gets or sets {@link Cartesian3} Property property specifying the length, width, and height of the box. * @memberof BoxGraphics.prototype * @type {Property|undefined} */ dimensions: createPropertyDescriptor_default("dimensions"), /** * Gets or sets the Property specifying the {@link HeightReference}. * @memberof BoxGraphics.prototype * @type {Property|undefined} * @default HeightReference.NONE */ heightReference: createPropertyDescriptor_default("heightReference"), /** * Gets or sets the boolean Property specifying whether the box is filled with the provided material. * @memberof BoxGraphics.prototype * @type {Property|undefined} * @default true */ fill: createPropertyDescriptor_default("fill"), /** * Gets or sets the material used to fill the box. * @memberof BoxGraphics.prototype * @type {MaterialProperty|undefined} * @default Color.WHITE */ material: createMaterialPropertyDescriptor_default("material"), /** * Gets or sets the Property specifying whether the box is outlined. * @memberof BoxGraphics.prototype * @type {Property|undefined} * @default false */ outline: createPropertyDescriptor_default("outline"), /** * Gets or sets the Property specifying the {@link Color} of the outline. * @memberof BoxGraphics.prototype * @type {Property|undefined} * @default Color.BLACK */ outlineColor: createPropertyDescriptor_default("outlineColor"), /** * Gets or sets the numeric Property specifying the width of the outline. ** Note: This property will be ignored on all major browsers on Windows platforms. For details, see (@link https://github.com/CesiumGS/cesium/issues/40}. *
* @memberof BoxGraphics.prototype * @type {Property|undefined} * @default 1.0 */ outlineWidth: createPropertyDescriptor_default("outlineWidth"), /** * Get or sets the enum Property specifying whether the box * casts or receives shadows from light sources. * @memberof BoxGraphics.prototype * @type {Property|undefined} * @default ShadowMode.DISABLED */ shadows: createPropertyDescriptor_default("shadows"), /** * Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this box will be displayed. * @memberof BoxGraphics.prototype * @type {Property|undefined} */ distanceDisplayCondition: createPropertyDescriptor_default( "distanceDisplayCondition" ) }); BoxGraphics.prototype.clone = function(result) { if (!defined_default(result)) { return new BoxGraphics(this); } result.show = this.show; result.dimensions = this.dimensions; result.heightReference = this.heightReference; result.fill = this.fill; result.material = this.material; result.outline = this.outline; result.outlineColor = this.outlineColor; result.outlineWidth = this.outlineWidth; result.shadows = this.shadows; result.distanceDisplayCondition = this.distanceDisplayCondition; return result; }; BoxGraphics.prototype.merge = function(source) { if (!defined_default(source)) { throw new DeveloperError_default("source is required."); } this.show = defaultValue_default(this.show, source.show); this.dimensions = defaultValue_default(this.dimensions, source.dimensions); this.heightReference = defaultValue_default( this.heightReference, source.heightReference ); this.fill = defaultValue_default(this.fill, source.fill); this.material = defaultValue_default(this.material, source.material); this.outline = defaultValue_default(this.outline, source.outline); this.outlineColor = defaultValue_default(this.outlineColor, source.outlineColor); this.outlineWidth = defaultValue_default(this.outlineWidth, source.outlineWidth); this.shadows = defaultValue_default(this.shadows, source.shadows); this.distanceDisplayCondition = defaultValue_default( this.distanceDisplayCondition, source.distanceDisplayCondition ); }; var BoxGraphics_default = BoxGraphics; // packages/engine/Source/Core/ReferenceFrame.js var ReferenceFrame = { /** * The fixed frame. * * @type {number} * @constant */ FIXED: 0, /** * The inertial frame. * * @type {number} * @constant */ INERTIAL: 1 }; var ReferenceFrame_default = Object.freeze(ReferenceFrame); // packages/engine/Source/DataSources/PositionProperty.js function PositionProperty() { DeveloperError_default.throwInstantiationError(); } Object.defineProperties(PositionProperty.prototype, { /** * Gets a value indicating if this property is constant. A property is considered * constant if getValue always returns the same result for the current definition. * @memberof PositionProperty.prototype * * @type {boolean} * @readonly */ isConstant: { get: DeveloperError_default.throwInstantiationError }, /** * Gets the event that is raised whenever the definition of this property changes. * The definition is considered to have changed if a call to getValue would return * a different result for the same time. * @memberof PositionProperty.prototype * * @type {Event} * @readonly */ definitionChanged: { get: DeveloperError_default.throwInstantiationError }, /** * Gets the reference frame that the position is defined in. * @memberof PositionProperty.prototype * @type {ReferenceFrame} */ referenceFrame: { get: DeveloperError_default.throwInstantiationError } }); PositionProperty.prototype.getValue = DeveloperError_default.throwInstantiationError; PositionProperty.prototype.getValueInReferenceFrame = DeveloperError_default.throwInstantiationError; PositionProperty.prototype.equals = DeveloperError_default.throwInstantiationError; var scratchMatrix3 = new Matrix3_default(); PositionProperty.convertToReferenceFrame = function(time, value, inputFrame, outputFrame, result) { if (!defined_default(value)) { return value; } if (!defined_default(result)) { result = new Cartesian3_default(); } if (inputFrame === outputFrame) { return Cartesian3_default.clone(value, result); } let icrfToFixed2 = Transforms_default.computeIcrfToFixedMatrix(time, scratchMatrix3); if (!defined_default(icrfToFixed2)) { icrfToFixed2 = Transforms_default.computeTemeToPseudoFixedMatrix( time, scratchMatrix3 ); } if (inputFrame === ReferenceFrame_default.INERTIAL) { return Matrix3_default.multiplyByVector(icrfToFixed2, value, result); } if (inputFrame === ReferenceFrame_default.FIXED) { return Matrix3_default.multiplyByVector( Matrix3_default.transpose(icrfToFixed2, scratchMatrix3), value, result ); } }; var PositionProperty_default = PositionProperty; // packages/engine/Source/DataSources/ConstantPositionProperty.js function ConstantPositionProperty(value, referenceFrame) { this._definitionChanged = new Event_default(); this._value = Cartesian3_default.clone(value); this._referenceFrame = defaultValue_default(referenceFrame, ReferenceFrame_default.FIXED); } Object.defineProperties(ConstantPositionProperty.prototype, { /** * Gets a value indicating if this property is constant. A property is considered * constant if getValue always returns the same result for the current definition. * @memberof ConstantPositionProperty.prototype * * @type {boolean} * @readonly */ isConstant: { get: function() { return !defined_default(this._value) || this._referenceFrame === ReferenceFrame_default.FIXED; } }, /** * Gets the event that is raised whenever the definition of this property changes. * The definition is considered to have changed if a call to getValue would return * a different result for the same time. * @memberof ConstantPositionProperty.prototype * * @type {Event} * @readonly */ definitionChanged: { get: function() { return this._definitionChanged; } }, /** * Gets the reference frame in which the position is defined. * @memberof ConstantPositionProperty.prototype * @type {ReferenceFrame} * @default ReferenceFrame.FIXED; */ referenceFrame: { get: function() { return this._referenceFrame; } } }); ConstantPositionProperty.prototype.getValue = function(time, result) { return this.getValueInReferenceFrame(time, ReferenceFrame_default.FIXED, result); }; ConstantPositionProperty.prototype.setValue = function(value, referenceFrame) { let definitionChanged = false; if (!Cartesian3_default.equals(this._value, value)) { definitionChanged = true; this._value = Cartesian3_default.clone(value); } if (defined_default(referenceFrame) && this._referenceFrame !== referenceFrame) { definitionChanged = true; this._referenceFrame = referenceFrame; } if (definitionChanged) { this._definitionChanged.raiseEvent(this); } }; ConstantPositionProperty.prototype.getValueInReferenceFrame = function(time, referenceFrame, result) { if (!defined_default(time)) { throw new DeveloperError_default("time is required."); } if (!defined_default(referenceFrame)) { throw new DeveloperError_default("referenceFrame is required."); } return PositionProperty_default.convertToReferenceFrame( time, this._value, this._referenceFrame, referenceFrame, result ); }; ConstantPositionProperty.prototype.equals = function(other) { return this === other || other instanceof ConstantPositionProperty && Cartesian3_default.equals(this._value, other._value) && this._referenceFrame === other._referenceFrame; }; var ConstantPositionProperty_default = ConstantPositionProperty; // packages/engine/Source/DataSources/CorridorGraphics.js function CorridorGraphics(options) { this._definitionChanged = new Event_default(); this._show = void 0; this._showSubscription = void 0; this._positions = void 0; this._positionsSubscription = void 0; this._width = void 0; this._widthSubscription = void 0; this._height = void 0; this._heightSubscription = void 0; this._heightReference = void 0; this._heightReferenceSubscription = void 0; this._extrudedHeight = void 0; this._extrudedHeightSubscription = void 0; this._extrudedHeightReference = void 0; this._extrudedHeightReferenceSubscription = void 0; this._cornerType = void 0; this._cornerTypeSubscription = void 0; this._granularity = void 0; this._granularitySubscription = void 0; this._fill = void 0; this._fillSubscription = void 0; this._material = void 0; this._materialSubscription = void 0; this._outline = void 0; this._outlineSubscription = void 0; this._outlineColor = void 0; this._outlineColorSubscription = void 0; this._outlineWidth = void 0; this._outlineWidthSubscription = void 0; this._shadows = void 0; this._shadowsSubscription = void 0; this._distanceDisplayCondition = void 0; this._distanceDisplayConditionSubscription = void 0; this._classificationType = void 0; this._classificationTypeSubscription = void 0; this._zIndex = void 0; this._zIndexSubscription = void 0; this.merge(defaultValue_default(options, defaultValue_default.EMPTY_OBJECT)); } Object.defineProperties(CorridorGraphics.prototype, { /** * Gets the event that is raised whenever a property or sub-property is changed or modified. * @memberof CorridorGraphics.prototype * @type {Event} * @readonly */ definitionChanged: { get: function() { return this._definitionChanged; } }, /** * Gets or sets the boolean Property specifying the visibility of the corridor. * @memberof CorridorGraphics.prototype * @type {Property|undefined} * @default true */ show: createPropertyDescriptor_default("show"), /** * Gets or sets a Property specifying the array of {@link Cartesian3} positions that define the centerline of the corridor. * @memberof CorridorGraphics.prototype * @type {Property|undefined} */ positions: createPropertyDescriptor_default("positions"), /** * Gets or sets the numeric Property specifying the width of the outline. * @memberof CorridorGraphics.prototype * @type {Property|undefined} */ width: createPropertyDescriptor_default("width"), /** * Gets or sets the numeric Property specifying the altitude of the corridor. * @memberof CorridorGraphics.prototype * @type {Property|undefined} * @default 0.0 */ height: createPropertyDescriptor_default("height"), /** * Gets or sets the Property specifying the {@link HeightReference}. * @memberof CorridorGraphics.prototype * @type {Property|undefined} * @default HeightReference.NONE */ heightReference: createPropertyDescriptor_default("heightReference"), /** * Gets or sets the numeric Property specifying the altitude of the corridor extrusion. * Setting this property creates a corridor shaped volume starting at height and ending * at this altitude. * @memberof CorridorGraphics.prototype * @type {Property|undefined} */ extrudedHeight: createPropertyDescriptor_default("extrudedHeight"), /** * Gets or sets the Property specifying the extruded {@link HeightReference}. * @memberof CorridorGraphics.prototype * @type {Property|undefined} * @default HeightReference.NONE */ extrudedHeightReference: createPropertyDescriptor_default("extrudedHeightReference"), /** * Gets or sets the {@link CornerType} Property specifying how corners are styled. * @memberof CorridorGraphics.prototype * @type {Property|undefined} * @default CornerType.ROUNDED */ cornerType: createPropertyDescriptor_default("cornerType"), /** * Gets or sets the numeric Property specifying the sampling distance between each latitude and longitude point. * @memberof CorridorGraphics.prototype * @type {Property|undefined} * @default {CesiumMath.RADIANS_PER_DEGREE} */ granularity: createPropertyDescriptor_default("granularity"), /** * Gets or sets the boolean Property specifying whether the corridor is filled with the provided material. * @memberof CorridorGraphics.prototype * @type {Property|undefined} * @default true */ fill: createPropertyDescriptor_default("fill"), /** * Gets or sets the Property specifying the material used to fill the corridor. * @memberof CorridorGraphics.prototype * @type {MaterialProperty|undefined} * @default Color.WHITE */ material: createMaterialPropertyDescriptor_default("material"), /** * Gets or sets the Property specifying whether the corridor is outlined. * @memberof CorridorGraphics.prototype * @type {Property|undefined} * @default false */ outline: createPropertyDescriptor_default("outline"), /** * Gets or sets the Property specifying the {@link Color} of the outline. * @memberof CorridorGraphics.prototype * @type {Property|undefined} * @default Color.BLACK */ outlineColor: createPropertyDescriptor_default("outlineColor"), /** * Gets or sets the numeric Property specifying the width of the outline. ** Note: This property will be ignored on all major browsers on Windows platforms. For details, see (@link https://github.com/CesiumGS/cesium/issues/40}. *
* @memberof CorridorGraphics.prototype * @type {Property|undefined} * @default 1.0 */ outlineWidth: createPropertyDescriptor_default("outlineWidth"), /** * Get or sets the enum Property specifying whether the corridor * casts or receives shadows from light sources. * @memberof CorridorGraphics.prototype * @type {Property|undefined} * @default ShadowMode.DISABLED */ shadows: createPropertyDescriptor_default("shadows"), /** * Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this corridor will be displayed. * @memberof CorridorGraphics.prototype * @type {Property|undefined} */ distanceDisplayCondition: createPropertyDescriptor_default( "distanceDisplayCondition" ), /** * Gets or sets the {@link ClassificationType} Property specifying whether this corridor will classify terrain, 3D Tiles, or both when on the ground. * @memberof CorridorGraphics.prototype * @type {Property|undefined} * @default ClassificationType.BOTH */ classificationType: createPropertyDescriptor_default("classificationType"), /** * Gets or sets the zIndex Property specifying the ordering of the corridor. Only has an effect if the coridor is static and neither height or exturdedHeight are specified. * @memberof CorridorGraphics.prototype * @type {ConstantProperty|undefined} * @default 0 */ zIndex: createPropertyDescriptor_default("zIndex") }); CorridorGraphics.prototype.clone = function(result) { if (!defined_default(result)) { return new CorridorGraphics(this); } result.show = this.show; result.positions = this.positions; result.width = this.width; result.height = this.height; result.heightReference = this.heightReference; result.extrudedHeight = this.extrudedHeight; result.extrudedHeightReference = this.extrudedHeightReference; result.cornerType = this.cornerType; result.granularity = this.granularity; result.fill = this.fill; result.material = this.material; result.outline = this.outline; result.outlineColor = this.outlineColor; result.outlineWidth = this.outlineWidth; result.shadows = this.shadows; result.distanceDisplayCondition = this.distanceDisplayCondition; result.classificationType = this.classificationType; result.zIndex = this.zIndex; return result; }; CorridorGraphics.prototype.merge = function(source) { if (!defined_default(source)) { throw new DeveloperError_default("source is required."); } this.show = defaultValue_default(this.show, source.show); this.positions = defaultValue_default(this.positions, source.positions); this.width = defaultValue_default(this.width, source.width); this.height = defaultValue_default(this.height, source.height); this.heightReference = defaultValue_default( this.heightReference, source.heightReference ); this.extrudedHeight = defaultValue_default( this.extrudedHeight, source.extrudedHeight ); this.extrudedHeightReference = defaultValue_default( this.extrudedHeightReference, source.extrudedHeightReference ); this.cornerType = defaultValue_default(this.cornerType, source.cornerType); this.granularity = defaultValue_default(this.granularity, source.granularity); this.fill = defaultValue_default(this.fill, source.fill); this.material = defaultValue_default(this.material, source.material); this.outline = defaultValue_default(this.outline, source.outline); this.outlineColor = defaultValue_default(this.outlineColor, source.outlineColor); this.outlineWidth = defaultValue_default(this.outlineWidth, source.outlineWidth); this.shadows = defaultValue_default(this.shadows, source.shadows); this.distanceDisplayCondition = defaultValue_default( this.distanceDisplayCondition, source.distanceDisplayCondition ); this.classificationType = defaultValue_default( this.classificationType, source.classificationType ); this.zIndex = defaultValue_default(this.zIndex, source.zIndex); }; var CorridorGraphics_default = CorridorGraphics; // packages/engine/Source/DataSources/createRawPropertyDescriptor.js function createRawProperty(value) { return value; } function createRawPropertyDescriptor(name, configurable) { return createPropertyDescriptor_default(name, configurable, createRawProperty); } var createRawPropertyDescriptor_default = createRawPropertyDescriptor; // packages/engine/Source/DataSources/CylinderGraphics.js function CylinderGraphics(options) { this._definitionChanged = new Event_default(); this._show = void 0; this._showSubscription = void 0; this._length = void 0; this._lengthSubscription = void 0; this._topRadius = void 0; this._topRadiusSubscription = void 0; this._bottomRadius = void 0; this._bottomRadiusSubscription = void 0; this._heightReference = void 0; this._heightReferenceSubscription = void 0; this._fill = void 0; this._fillSubscription = void 0; this._material = void 0; this._materialSubscription = void 0; this._outline = void 0; this._outlineSubscription = void 0; this._outlineColor = void 0; this._outlineColorSubscription = void 0; this._outlineWidth = void 0; this._outlineWidthSubscription = void 0; this._numberOfVerticalLines = void 0; this._numberOfVerticalLinesSubscription = void 0; this._slices = void 0; this._slicesSubscription = void 0; this._shadows = void 0; this._shadowsSubscription = void 0; this._distanceDisplayCondition = void 0; this._distanceDisplayConditionSubscription = void 0; this.merge(defaultValue_default(options, defaultValue_default.EMPTY_OBJECT)); } Object.defineProperties(CylinderGraphics.prototype, { /** * Gets the event that is raised whenever a property or sub-property is changed or modified. * @memberof CylinderGraphics.prototype * * @type {Event} * @readonly */ definitionChanged: { get: function() { return this._definitionChanged; } }, /** * Gets or sets the boolean Property specifying the visibility of the cylinder. * @memberof CylinderGraphics.prototype * @type {Property|undefined} * @default true */ show: createPropertyDescriptor_default("show"), /** * Gets or sets the numeric Property specifying the length of the cylinder. * @memberof CylinderGraphics.prototype * @type {Property|undefined} */ length: createPropertyDescriptor_default("length"), /** * Gets or sets the numeric Property specifying the radius of the top of the cylinder. * @memberof CylinderGraphics.prototype * @type {Property|undefined} */ topRadius: createPropertyDescriptor_default("topRadius"), /** * Gets or sets the numeric Property specifying the radius of the bottom of the cylinder. * @memberof CylinderGraphics.prototype * @type {Property|undefined} */ bottomRadius: createPropertyDescriptor_default("bottomRadius"), /** * Gets or sets the Property specifying the {@link HeightReference}. * @memberof CylinderGraphics.prototype * @type {Property|undefined} * @default HeightReference.NONE */ heightReference: createPropertyDescriptor_default("heightReference"), /** * Gets or sets the boolean Property specifying whether the cylinder is filled with the provided material. * @memberof CylinderGraphics.prototype * @type {Property|undefined} * @default true */ fill: createPropertyDescriptor_default("fill"), /** * Gets or sets the Property specifying the material used to fill the cylinder. * @memberof CylinderGraphics.prototype * @type {MaterialProperty|undefined} * @default Color.WHITE */ material: createMaterialPropertyDescriptor_default("material"), /** * Gets or sets the boolean Property specifying whether the cylinder is outlined. * @memberof CylinderGraphics.prototype * @type {Property|undefined} * @default false */ outline: createPropertyDescriptor_default("outline"), /** * Gets or sets the Property specifying the {@link Color} of the outline. * @memberof CylinderGraphics.prototype * @type {Property|undefined} * @default Color.BLACK */ outlineColor: createPropertyDescriptor_default("outlineColor"), /** * Gets or sets the numeric Property specifying the width of the outline. ** Note: This property will be ignored on all major browsers on Windows platforms. For details, see (@link https://github.com/CesiumGS/cesium/issues/40}. *
* @memberof CylinderGraphics.prototype * @type {Property|undefined} * @default 1.0 */ outlineWidth: createPropertyDescriptor_default("outlineWidth"), /** * Gets or sets the Property specifying the number of vertical lines to draw along the perimeter for the outline. * @memberof CylinderGraphics.prototype * @type {Property|undefined} * @default 16 */ numberOfVerticalLines: createPropertyDescriptor_default("numberOfVerticalLines"), /** * Gets or sets the Property specifying the number of edges around the perimeter of the cylinder. * @memberof CylinderGraphics.prototype * @type {Property|undefined} * @default 128 */ slices: createPropertyDescriptor_default("slices"), /** * Get or sets the enum Property specifying whether the cylinder * casts or receives shadows from light sources. * @memberof CylinderGraphics.prototype * @type {Property|undefined} * @default ShadowMode.DISABLED */ shadows: createPropertyDescriptor_default("shadows"), /** * Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this cylinder will be displayed. * @memberof CylinderGraphics.prototype * @type {Property|undefined} */ distanceDisplayCondition: createPropertyDescriptor_default( "distanceDisplayCondition" ) }); CylinderGraphics.prototype.clone = function(result) { if (!defined_default(result)) { return new CylinderGraphics(this); } result.show = this.show; result.length = this.length; result.topRadius = this.topRadius; result.bottomRadius = this.bottomRadius; result.heightReference = this.heightReference; result.fill = this.fill; result.material = this.material; result.outline = this.outline; result.outlineColor = this.outlineColor; result.outlineWidth = this.outlineWidth; result.numberOfVerticalLines = this.numberOfVerticalLines; result.slices = this.slices; result.shadows = this.shadows; result.distanceDisplayCondition = this.distanceDisplayCondition; return result; }; CylinderGraphics.prototype.merge = function(source) { if (!defined_default(source)) { throw new DeveloperError_default("source is required."); } this.show = defaultValue_default(this.show, source.show); this.length = defaultValue_default(this.length, source.length); this.topRadius = defaultValue_default(this.topRadius, source.topRadius); this.bottomRadius = defaultValue_default(this.bottomRadius, source.bottomRadius); this.heightReference = defaultValue_default( this.heightReference, source.heightReference ); this.fill = defaultValue_default(this.fill, source.fill); this.material = defaultValue_default(this.material, source.material); this.outline = defaultValue_default(this.outline, source.outline); this.outlineColor = defaultValue_default(this.outlineColor, source.outlineColor); this.outlineWidth = defaultValue_default(this.outlineWidth, source.outlineWidth); this.numberOfVerticalLines = defaultValue_default( this.numberOfVerticalLines, source.numberOfVerticalLines ); this.slices = defaultValue_default(this.slices, source.slices); this.shadows = defaultValue_default(this.shadows, source.shadows); this.distanceDisplayCondition = defaultValue_default( this.distanceDisplayCondition, source.distanceDisplayCondition ); }; var CylinderGraphics_default = CylinderGraphics; // packages/engine/Source/DataSources/EllipseGraphics.js function EllipseGraphics(options) { this._definitionChanged = new Event_default(); this._show = void 0; this._showSubscription = void 0; this._semiMajorAxis = void 0; this._semiMajorAxisSubscription = void 0; this._semiMinorAxis = void 0; this._semiMinorAxisSubscription = void 0; this._height = void 0; this._heightSubscription = void 0; this._heightReference = void 0; this._heightReferenceSubscription = void 0; this._extrudedHeight = void 0; this._extrudedHeightSubscription = void 0; this._extrudedHeightReference = void 0; this._extrudedHeightReferenceSubscription = void 0; this._rotation = void 0; this._rotationSubscription = void 0; this._stRotation = void 0; this._stRotationSubscription = void 0; this._granularity = void 0; this._granularitySubscription = void 0; this._fill = void 0; this._fillSubscription = void 0; this._material = void 0; this._materialSubscription = void 0; this._outline = void 0; this._outlineSubscription = void 0; this._outlineColor = void 0; this._outlineColorSubscription = void 0; this._outlineWidth = void 0; this._outlineWidthSubscription = void 0; this._numberOfVerticalLines = void 0; this._numberOfVerticalLinesSubscription = void 0; this._shadows = void 0; this._shadowsSubscription = void 0; this._distanceDisplayCondition = void 0; this._distanceDisplayConditionSubscription = void 0; this._classificationType = void 0; this._classificationTypeSubscription = void 0; this._zIndex = void 0; this._zIndexSubscription = void 0; this.merge(defaultValue_default(options, defaultValue_default.EMPTY_OBJECT)); } Object.defineProperties(EllipseGraphics.prototype, { /** * Gets the event that is raised whenever a property or sub-property is changed or modified. * @memberof EllipseGraphics.prototype * * @type {Event} * @readonly */ definitionChanged: { get: function() { return this._definitionChanged; } }, /** * Gets or sets the boolean Property specifying the visibility of the ellipse. * @memberof EllipseGraphics.prototype * @type {Property|undefined} * @default true */ show: createPropertyDescriptor_default("show"), /** * Gets or sets the numeric Property specifying the semi-major axis. * @memberof EllipseGraphics.prototype * @type {Property|undefined} */ semiMajorAxis: createPropertyDescriptor_default("semiMajorAxis"), /** * Gets or sets the numeric Property specifying the semi-minor axis. * @memberof EllipseGraphics.prototype * @type {Property|undefined} */ semiMinorAxis: createPropertyDescriptor_default("semiMinorAxis"), /** * Gets or sets the numeric Property specifying the altitude of the ellipse. * @memberof EllipseGraphics.prototype * @type {Property|undefined} * @default 0.0 */ height: createPropertyDescriptor_default("height"), /** * Gets or sets the Property specifying the {@link HeightReference}. * @memberof EllipseGraphics.prototype * @type {Property|undefined} * @default HeightReference.NONE */ heightReference: createPropertyDescriptor_default("heightReference"), /** * Gets or sets the numeric Property specifying the altitude of the ellipse extrusion. * Setting this property creates volume starting at height and ending at this altitude. * @memberof EllipseGraphics.prototype * @type {Property|undefined} */ extrudedHeight: createPropertyDescriptor_default("extrudedHeight"), /** * Gets or sets the Property specifying the extruded {@link HeightReference}. * @memberof EllipseGraphics.prototype * @type {Property|undefined} * @default HeightReference.NONE */ extrudedHeightReference: createPropertyDescriptor_default("extrudedHeightReference"), /** * Gets or sets the numeric property specifying the rotation of the ellipse counter-clockwise from north. * @memberof EllipseGraphics.prototype * @type {Property|undefined} * @default 0 */ rotation: createPropertyDescriptor_default("rotation"), /** * Gets or sets the numeric property specifying the rotation of the ellipse texture counter-clockwise from north. * @memberof EllipseGraphics.prototype * @type {Property|undefined} * @default 0 */ stRotation: createPropertyDescriptor_default("stRotation"), /** * Gets or sets the numeric Property specifying the angular distance between points on the ellipse. * @memberof EllipseGraphics.prototype * @type {Property|undefined} * @default {CesiumMath.RADIANS_PER_DEGREE} */ granularity: createPropertyDescriptor_default("granularity"), /** * Gets or sets the boolean Property specifying whether the ellipse is filled with the provided material. * @memberof EllipseGraphics.prototype * @type {Property|undefined} * @default true */ fill: createPropertyDescriptor_default("fill"), /** * Gets or sets the Property specifying the material used to fill the ellipse. * @memberof EllipseGraphics.prototype * @type {MaterialProperty|undefined} * @default Color.WHITE */ material: createMaterialPropertyDescriptor_default("material"), /** * Gets or sets the Property specifying whether the ellipse is outlined. * @memberof EllipseGraphics.prototype * @type {Property|undefined} * @default false */ outline: createPropertyDescriptor_default("outline"), /** * Gets or sets the Property specifying the {@link Color} of the outline. * @memberof EllipseGraphics.prototype * @type {Property|undefined} * @default Color.BLACK */ outlineColor: createPropertyDescriptor_default("outlineColor"), /** * Gets or sets the numeric Property specifying the width of the outline. ** Note: This property will be ignored on all major browsers on Windows platforms. For details, see (@link https://github.com/CesiumGS/cesium/issues/40}. *
* @memberof EllipseGraphics.prototype * @type {Property|undefined} * @default 1.0 */ outlineWidth: createPropertyDescriptor_default("outlineWidth"), /** * Gets or sets the numeric Property specifying the number of vertical lines to draw along the perimeter for the outline. * @memberof EllipseGraphics.prototype * @type {Property|undefined} * @default 16 */ numberOfVerticalLines: createPropertyDescriptor_default("numberOfVerticalLines"), /** * Get or sets the enum Property specifying whether the ellipse * casts or receives shadows from light sources. * @memberof EllipseGraphics.prototype * @type {Property|undefined} * @default ShadowMode.DISABLED */ shadows: createPropertyDescriptor_default("shadows"), /** * Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this ellipse will be displayed. * @memberof EllipseGraphics.prototype * @type {Property|undefined} */ distanceDisplayCondition: createPropertyDescriptor_default( "distanceDisplayCondition" ), /** * Gets or sets the {@link ClassificationType} Property specifying whether this ellipse will classify terrain, 3D Tiles, or both when on the ground. * @memberof EllipseGraphics.prototype * @type {Property|undefined} * @default ClassificationType.BOTH */ classificationType: createPropertyDescriptor_default("classificationType"), /** * Gets or sets the zIndex Property specifying the ellipse ordering. Only has an effect if the ellipse is constant and neither height or extrudedHeight are specified * @memberof EllipseGraphics.prototype * @type {ConstantProperty|undefined} * @default 0 */ zIndex: createPropertyDescriptor_default("zIndex") }); EllipseGraphics.prototype.clone = function(result) { if (!defined_default(result)) { return new EllipseGraphics(this); } result.show = this.show; result.semiMajorAxis = this.semiMajorAxis; result.semiMinorAxis = this.semiMinorAxis; result.height = this.height; result.heightReference = this.heightReference; result.extrudedHeight = this.extrudedHeight; result.extrudedHeightReference = this.extrudedHeightReference; result.rotation = this.rotation; result.stRotation = this.stRotation; result.granularity = this.granularity; result.fill = this.fill; result.material = this.material; result.outline = this.outline; result.outlineColor = this.outlineColor; result.outlineWidth = this.outlineWidth; result.numberOfVerticalLines = this.numberOfVerticalLines; result.shadows = this.shadows; result.distanceDisplayCondition = this.distanceDisplayCondition; result.classificationType = this.classificationType; result.zIndex = this.zIndex; return result; }; EllipseGraphics.prototype.merge = function(source) { if (!defined_default(source)) { throw new DeveloperError_default("source is required."); } this.show = defaultValue_default(this.show, source.show); this.semiMajorAxis = defaultValue_default(this.semiMajorAxis, source.semiMajorAxis); this.semiMinorAxis = defaultValue_default(this.semiMinorAxis, source.semiMinorAxis); this.height = defaultValue_default(this.height, source.height); this.heightReference = defaultValue_default( this.heightReference, source.heightReference ); this.extrudedHeight = defaultValue_default( this.extrudedHeight, source.extrudedHeight ); this.extrudedHeightReference = defaultValue_default( this.extrudedHeightReference, source.extrudedHeightReference ); this.rotation = defaultValue_default(this.rotation, source.rotation); this.stRotation = defaultValue_default(this.stRotation, source.stRotation); this.granularity = defaultValue_default(this.granularity, source.granularity); this.fill = defaultValue_default(this.fill, source.fill); this.material = defaultValue_default(this.material, source.material); this.outline = defaultValue_default(this.outline, source.outline); this.outlineColor = defaultValue_default(this.outlineColor, source.outlineColor); this.outlineWidth = defaultValue_default(this.outlineWidth, source.outlineWidth); this.numberOfVerticalLines = defaultValue_default( this.numberOfVerticalLines, source.numberOfVerticalLines ); this.shadows = defaultValue_default(this.shadows, source.shadows); this.distanceDisplayCondition = defaultValue_default( this.distanceDisplayCondition, source.distanceDisplayCondition ); this.classificationType = defaultValue_default( this.classificationType, source.classificationType ); this.zIndex = defaultValue_default(this.zIndex, source.zIndex); }; var EllipseGraphics_default = EllipseGraphics; // packages/engine/Source/DataSources/EllipsoidGraphics.js function EllipsoidGraphics(options) { this._definitionChanged = new Event_default(); this._show = void 0; this._showSubscription = void 0; this._radii = void 0; this._radiiSubscription = void 0; this._innerRadii = void 0; this._innerRadiiSubscription = void 0; this._minimumClock = void 0; this._minimumClockSubscription = void 0; this._maximumClock = void 0; this._maximumClockSubscription = void 0; this._minimumCone = void 0; this._minimumConeSubscription = void 0; this._maximumCone = void 0; this._maximumConeSubscription = void 0; this._heightReference = void 0; this._heightReferenceSubscription = void 0; this._fill = void 0; this._fillSubscription = void 0; this._material = void 0; this._materialSubscription = void 0; this._outline = void 0; this._outlineSubscription = void 0; this._outlineColor = void 0; this._outlineColorSubscription = void 0; this._outlineWidth = void 0; this._outlineWidthSubscription = void 0; this._stackPartitions = void 0; this._stackPartitionsSubscription = void 0; this._slicePartitions = void 0; this._slicePartitionsSubscription = void 0; this._subdivisions = void 0; this._subdivisionsSubscription = void 0; this._shadows = void 0; this._shadowsSubscription = void 0; this._distanceDisplayCondition = void 0; this._distanceDisplayConditionSubscription = void 0; this.merge(defaultValue_default(options, defaultValue_default.EMPTY_OBJECT)); } Object.defineProperties(EllipsoidGraphics.prototype, { /** * Gets the event that is raised whenever a property or sub-property is changed or modified. * @memberof EllipsoidGraphics.prototype * * @type {Event} * @readonly */ definitionChanged: { get: function() { return this._definitionChanged; } }, /** * Gets or sets the boolean Property specifying the visibility of the ellipsoid. * @memberof EllipsoidGraphics.prototype * @type {Property|undefined} * @default true */ show: createPropertyDescriptor_default("show"), /** * Gets or sets the {@link Cartesian3} {@link Property} specifying the radii of the ellipsoid. * @memberof EllipsoidGraphics.prototype * @type {Property|undefined} */ radii: createPropertyDescriptor_default("radii"), /** * Gets or sets the {@link Cartesian3} {@link Property} specifying the inner radii of the ellipsoid. * @memberof EllipsoidGraphics.prototype * @type {Property|undefined} * @default radii */ innerRadii: createPropertyDescriptor_default("innerRadii"), /** * Gets or sets the Property specifying the minimum clock angle of the ellipsoid. * @memberof EllipsoidGraphics.prototype * @type {Property|undefined} * @default 0.0 */ minimumClock: createPropertyDescriptor_default("minimumClock"), /** * Gets or sets the Property specifying the maximum clock angle of the ellipsoid. * @memberof EllipsoidGraphics.prototype * @type {Property|undefined} * @default 2*PI */ maximumClock: createPropertyDescriptor_default("maximumClock"), /** * Gets or sets the Property specifying the minimum cone angle of the ellipsoid. * @memberof EllipsoidGraphics.prototype * @type {Property|undefined} * @default 0.0 */ minimumCone: createPropertyDescriptor_default("minimumCone"), /** * Gets or sets the Property specifying the maximum cone angle of the ellipsoid. * @memberof EllipsoidGraphics.prototype * @type {Property|undefined} * @default PI */ maximumCone: createPropertyDescriptor_default("maximumCone"), /** * Gets or sets the Property specifying the {@link HeightReference}. * @memberof EllipsoidGraphics.prototype * @type {Property|undefined} * @default HeightReference.NONE */ heightReference: createPropertyDescriptor_default("heightReference"), /** * Gets or sets the boolean Property specifying whether the ellipsoid is filled with the provided material. * @memberof EllipsoidGraphics.prototype * @type {Property|undefined} * @default true */ fill: createPropertyDescriptor_default("fill"), /** * Gets or sets the Property specifying the material used to fill the ellipsoid. * @memberof EllipsoidGraphics.prototype * @type {MaterialProperty} * @default Color.WHITE */ material: createMaterialPropertyDescriptor_default("material"), /** * Gets or sets the Property specifying whether the ellipsoid is outlined. * @memberof EllipsoidGraphics.prototype * @type {Property|undefined} * @default false */ outline: createPropertyDescriptor_default("outline"), /** * Gets or sets the Property specifying the {@link Color} of the outline. * @memberof EllipsoidGraphics.prototype * @type {Property|undefined} * @default Color.BLACK */ outlineColor: createPropertyDescriptor_default("outlineColor"), /** * Gets or sets the numeric Property specifying the width of the outline. ** Note: This property will be ignored on all major browsers on Windows platforms. For details, see (@link https://github.com/CesiumGS/cesium/issues/40}. *
* @memberof EllipsoidGraphics.prototype * @type {Property|undefined} * @default 1.0 */ outlineWidth: createPropertyDescriptor_default("outlineWidth"), /** * Gets or sets the Property specifying the number of stacks. * @memberof EllipsoidGraphics.prototype * @type {Property|undefined} * @default 64 */ stackPartitions: createPropertyDescriptor_default("stackPartitions"), /** * Gets or sets the Property specifying the number of radial slices per 360 degrees. * @memberof EllipsoidGraphics.prototype * @type {Property|undefined} * @default 64 */ slicePartitions: createPropertyDescriptor_default("slicePartitions"), /** * Gets or sets the Property specifying the number of samples per outline ring, determining the granularity of the curvature. * @memberof EllipsoidGraphics.prototype * @type {Property|undefined} * @default 128 */ subdivisions: createPropertyDescriptor_default("subdivisions"), /** * Get or sets the enum Property specifying whether the ellipsoid * casts or receives shadows from light sources. * @memberof EllipsoidGraphics.prototype * @type {Property|undefined} * @default ShadowMode.DISABLED */ shadows: createPropertyDescriptor_default("shadows"), /** * Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this ellipsoid will be displayed. * @memberof EllipsoidGraphics.prototype * @type {Property|undefined} */ distanceDisplayCondition: createPropertyDescriptor_default( "distanceDisplayCondition" ) }); EllipsoidGraphics.prototype.clone = function(result) { if (!defined_default(result)) { return new EllipsoidGraphics(this); } result.show = this.show; result.radii = this.radii; result.innerRadii = this.innerRadii; result.minimumClock = this.minimumClock; result.maximumClock = this.maximumClock; result.minimumCone = this.minimumCone; result.maximumCone = this.maximumCone; result.heightReference = this.heightReference; result.fill = this.fill; result.material = this.material; result.outline = this.outline; result.outlineColor = this.outlineColor; result.outlineWidth = this.outlineWidth; result.stackPartitions = this.stackPartitions; result.slicePartitions = this.slicePartitions; result.subdivisions = this.subdivisions; result.shadows = this.shadows; result.distanceDisplayCondition = this.distanceDisplayCondition; return result; }; EllipsoidGraphics.prototype.merge = function(source) { if (!defined_default(source)) { throw new DeveloperError_default("source is required."); } this.show = defaultValue_default(this.show, source.show); this.radii = defaultValue_default(this.radii, source.radii); this.innerRadii = defaultValue_default(this.innerRadii, source.innerRadii); this.minimumClock = defaultValue_default(this.minimumClock, source.minimumClock); this.maximumClock = defaultValue_default(this.maximumClock, source.maximumClock); this.minimumCone = defaultValue_default(this.minimumCone, source.minimumCone); this.maximumCone = defaultValue_default(this.maximumCone, source.maximumCone); this.heightReference = defaultValue_default( this.heightReference, source.heightReference ); this.fill = defaultValue_default(this.fill, source.fill); this.material = defaultValue_default(this.material, source.material); this.outline = defaultValue_default(this.outline, source.outline); this.outlineColor = defaultValue_default(this.outlineColor, source.outlineColor); this.outlineWidth = defaultValue_default(this.outlineWidth, source.outlineWidth); this.stackPartitions = defaultValue_default( this.stackPartitions, source.stackPartitions ); this.slicePartitions = defaultValue_default( this.slicePartitions, source.slicePartitions ); this.subdivisions = defaultValue_default(this.subdivisions, source.subdivisions); this.shadows = defaultValue_default(this.shadows, source.shadows); this.distanceDisplayCondition = defaultValue_default( this.distanceDisplayCondition, source.distanceDisplayCondition ); }; var EllipsoidGraphics_default = EllipsoidGraphics; // packages/engine/Source/DataSources/LabelGraphics.js function LabelGraphics(options) { this._definitionChanged = new Event_default(); this._show = void 0; this._showSubscription = void 0; this._text = void 0; this._textSubscription = void 0; this._font = void 0; this._fontSubscription = void 0; this._style = void 0; this._styleSubscription = void 0; this._scale = void 0; this._scaleSubscription = void 0; this._showBackground = void 0; this._showBackgroundSubscription = void 0; this._backgroundColor = void 0; this._backgroundColorSubscription = void 0; this._backgroundPadding = void 0; this._backgroundPaddingSubscription = void 0; this._pixelOffset = void 0; this._pixelOffsetSubscription = void 0; this._eyeOffset = void 0; this._eyeOffsetSubscription = void 0; this._horizontalOrigin = void 0; this._horizontalOriginSubscription = void 0; this._verticalOrigin = void 0; this._verticalOriginSubscription = void 0; this._heightReference = void 0; this._heightReferenceSubscription = void 0; this._fillColor = void 0; this._fillColorSubscription = void 0; this._outlineColor = void 0; this._outlineColorSubscription = void 0; this._outlineWidth = void 0; this._outlineWidthSubscription = void 0; this._translucencyByDistance = void 0; this._translucencyByDistanceSubscription = void 0; this._pixelOffsetScaleByDistance = void 0; this._pixelOffsetScaleByDistanceSubscription = void 0; this._scaleByDistance = void 0; this._scaleByDistanceSubscription = void 0; this._distanceDisplayCondition = void 0; this._distanceDisplayConditionSubscription = void 0; this._disableDepthTestDistance = void 0; this._disableDepthTestDistanceSubscription = void 0; this.merge(defaultValue_default(options, defaultValue_default.EMPTY_OBJECT)); } Object.defineProperties(LabelGraphics.prototype, { /** * Gets the event that is raised whenever a property or sub-property is changed or modified. * @memberof LabelGraphics.prototype * * @type {Event} * @readonly */ definitionChanged: { get: function() { return this._definitionChanged; } }, /** * Gets or sets the boolean Property specifying the visibility of the label. * @memberof LabelGraphics.prototype * @type {Property|undefined} */ show: createPropertyDescriptor_default("show"), /** * Gets or sets the string Property specifying the text of the label. * Explicit newlines '\n' are supported. * @memberof LabelGraphics.prototype * @type {Property|undefined} */ text: createPropertyDescriptor_default("text"), /** * Gets or sets the string Property specifying the font in CSS syntax. * @memberof LabelGraphics.prototype * @type {Property|undefined} * @see {@link https://developer.mozilla.org/en-US/docs/Web/CSS/font|CSS font on MDN} */ font: createPropertyDescriptor_default("font"), /** * Gets or sets the Property specifying the {@link LabelStyle}. * @memberof LabelGraphics.prototype * @type {Property|undefined} */ style: createPropertyDescriptor_default("style"), /** * Gets or sets the numeric Property specifying the uniform scale to apply to the image. * A scale greater than1.0
enlarges the label while a scale less than 1.0
shrinks it.
* *
0.5
, 1.0
,
* and 2.0
.
* x
increases from left to right, and y
increases from top to bottom.
* *
default ![]() |
* l.pixeloffset = new Cartesian2(25, 75); ![]() |
*
x
points towards the viewer's
* right, y
points up, and z
points into the screen.
* * An eye offset is commonly used to arrange multiple labels or objects at the same position, e.g., to * arrange a label above its corresponding 3D model. *
* Below, the label is positioned at the center of the Earth but an eye offset makes it always * appear on top of the Earth regardless of the viewer's or Earth's orientation. **
![]() |
* ![]() |
*
l.eyeOffset = new Cartesian3(0.0, 8000000.0, 0.0);
0.0
,
* no minimum size is enforced.
* @memberof ModelGraphics.prototype
* @type {Property|undefined}
* @default 0.0
*/
minimumPixelSize: createPropertyDescriptor_default("minimumPixelSize"),
/**
* Gets or sets the numeric Property specifying the maximum scale
* size of a model. This property is used as an upper limit for
* {@link ModelGraphics#minimumPixelSize}.
* @memberof ModelGraphics.prototype
* @type {Property|undefined}
*/
maximumScale: createPropertyDescriptor_default("maximumScale"),
/**
* Get or sets the boolean Property specifying whether textures
* may continue to stream in after the model is loaded.
* @memberof ModelGraphics.prototype
* @type {Property|undefined}
*/
incrementallyLoadTextures: createPropertyDescriptor_default(
"incrementallyLoadTextures"
),
/**
* Gets or sets the boolean Property specifying if glTF animations should be run.
* @memberof ModelGraphics.prototype
* @type {Property|undefined}
* @default true
*/
runAnimations: createPropertyDescriptor_default("runAnimations"),
/**
* Gets or sets the boolean Property specifying if glTF animations should hold the last pose for time durations with no keyframes.
* @memberof ModelGraphics.prototype
* @type {Property|undefined}
* @default true
*/
clampAnimations: createPropertyDescriptor_default("clampAnimations"),
/**
* Get or sets the enum Property specifying whether the model
* casts or receives shadows from light sources.
* @memberof ModelGraphics.prototype
* @type {Property|undefined}
* @default ShadowMode.ENABLED
*/
shadows: createPropertyDescriptor_default("shadows"),
/**
* Gets or sets the Property specifying the {@link HeightReference}.
* @memberof ModelGraphics.prototype
* @type {Property|undefined}
* @default HeightReference.NONE
*/
heightReference: createPropertyDescriptor_default("heightReference"),
/**
* Gets or sets the Property specifying the {@link Color} of the silhouette.
* @memberof ModelGraphics.prototype
* @type {Property|undefined}
* @default Color.RED
*/
silhouetteColor: createPropertyDescriptor_default("silhouetteColor"),
/**
* Gets or sets the numeric Property specifying the size of the silhouette in pixels.
* @memberof ModelGraphics.prototype
* @type {Property|undefined}
* @default 0.0
*/
silhouetteSize: createPropertyDescriptor_default("silhouetteSize"),
/**
* Gets or sets the Property specifying the {@link Color} that blends with the model's rendered color.
* @memberof ModelGraphics.prototype
* @type {Property|undefined}
* @default Color.WHITE
*/
color: createPropertyDescriptor_default("color"),
/**
* Gets or sets the enum Property specifying how the color blends with the model.
* @memberof ModelGraphics.prototype
* @type {Property|undefined}
* @default ColorBlendMode.HIGHLIGHT
*/
colorBlendMode: createPropertyDescriptor_default("colorBlendMode"),
/**
* A numeric Property specifying the color strength when the colorBlendMode
is MIX.
* A value of 0.0 results in the model's rendered color while a value of 1.0 results in a solid color, with
* any value in-between resulting in a mix of the two.
* @memberof ModelGraphics.prototype
* @type {Property|undefined}
* @default 0.5
*/
colorBlendAmount: createPropertyDescriptor_default("colorBlendAmount"),
/**
* A property specifying the {@link Cartesian2} used to scale the diffuse and specular image-based lighting contribution to the final color.
* @memberof ModelGraphics.prototype
* @type {Property|undefined}
*/
imageBasedLightingFactor: createPropertyDescriptor_default(
"imageBasedLightingFactor"
),
/**
* A property specifying the {@link Cartesian3} light color when shading the model. When undefined
the scene's light color is used instead.
* @memberOf ModelGraphics.prototype
* @type {Property|undefined}
*/
lightColor: createPropertyDescriptor_default("lightColor"),
/**
* Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this model will be displayed.
* @memberof ModelGraphics.prototype
* @type {Property|undefined}
*/
distanceDisplayCondition: createPropertyDescriptor_default(
"distanceDisplayCondition"
),
/**
* Gets or sets the set of node transformations to apply to this model. This is represented as an {@link PropertyBag}, where keys are
* names of nodes, and values are {@link TranslationRotationScale} Properties describing the transformation to apply to that node.
* The transformation is applied after the node's existing transformation as specified in the glTF, and does not replace the node's existing transformation.
* @memberof ModelGraphics.prototype
* @type {PropertyBag}
*/
nodeTransformations: createPropertyDescriptor_default(
"nodeTransformations",
void 0,
createNodeTransformationPropertyBag
),
/**
* Gets or sets the set of articulation values to apply to this model. This is represented as an {@link PropertyBag}, where keys are
* composed as the name of the articulation, a single space, and the name of the stage.
* @memberof ModelGraphics.prototype
* @type {PropertyBag}
*/
articulations: createPropertyDescriptor_default(
"articulations",
void 0,
createArticulationStagePropertyBag
),
/**
* A property specifying the {@link ClippingPlaneCollection} used to selectively disable rendering the model.
* @memberof ModelGraphics.prototype
* @type {Property|undefined}
*/
clippingPlanes: createPropertyDescriptor_default("clippingPlanes"),
/**
* Gets or sets the {@link CustomShader} to apply to this model. When undefined
, no custom shader code is used.
* @memberof ModelGraphics.prototype
* @type {Property|undefined}
*/
customShader: createPropertyDescriptor_default("customShader")
});
ModelGraphics.prototype.clone = function(result) {
if (!defined_default(result)) {
return new ModelGraphics(this);
}
result.show = this.show;
result.uri = this.uri;
result.scale = this.scale;
result.minimumPixelSize = this.minimumPixelSize;
result.maximumScale = this.maximumScale;
result.incrementallyLoadTextures = this.incrementallyLoadTextures;
result.runAnimations = this.runAnimations;
result.clampAnimations = this.clampAnimations;
result.heightReference = this._heightReference;
result.silhouetteColor = this.silhouetteColor;
result.silhouetteSize = this.silhouetteSize;
result.color = this.color;
result.colorBlendMode = this.colorBlendMode;
result.colorBlendAmount = this.colorBlendAmount;
result.imageBasedLightingFactor = this.imageBasedLightingFactor;
result.lightColor = this.lightColor;
result.distanceDisplayCondition = this.distanceDisplayCondition;
result.nodeTransformations = this.nodeTransformations;
result.articulations = this.articulations;
result.clippingPlanes = this.clippingPlanes;
result.customShader = this.customShader;
return result;
};
ModelGraphics.prototype.merge = function(source) {
if (!defined_default(source)) {
throw new DeveloperError_default("source is required.");
}
this.show = defaultValue_default(this.show, source.show);
this.uri = defaultValue_default(this.uri, source.uri);
this.scale = defaultValue_default(this.scale, source.scale);
this.minimumPixelSize = defaultValue_default(
this.minimumPixelSize,
source.minimumPixelSize
);
this.maximumScale = defaultValue_default(this.maximumScale, source.maximumScale);
this.incrementallyLoadTextures = defaultValue_default(
this.incrementallyLoadTextures,
source.incrementallyLoadTextures
);
this.runAnimations = defaultValue_default(this.runAnimations, source.runAnimations);
this.clampAnimations = defaultValue_default(
this.clampAnimations,
source.clampAnimations
);
this.shadows = defaultValue_default(this.shadows, source.shadows);
this.heightReference = defaultValue_default(
this.heightReference,
source.heightReference
);
this.silhouetteColor = defaultValue_default(
this.silhouetteColor,
source.silhouetteColor
);
this.silhouetteSize = defaultValue_default(
this.silhouetteSize,
source.silhouetteSize
);
this.color = defaultValue_default(this.color, source.color);
this.colorBlendMode = defaultValue_default(
this.colorBlendMode,
source.colorBlendMode
);
this.colorBlendAmount = defaultValue_default(
this.colorBlendAmount,
source.colorBlendAmount
);
this.imageBasedLightingFactor = defaultValue_default(
this.imageBasedLightingFactor,
source.imageBasedLightingFactor
);
this.lightColor = defaultValue_default(this.lightColor, source.lightColor);
this.distanceDisplayCondition = defaultValue_default(
this.distanceDisplayCondition,
source.distanceDisplayCondition
);
this.clippingPlanes = defaultValue_default(
this.clippingPlanes,
source.clippingPlanes
);
this.customShader = defaultValue_default(this.customShader, source.customShader);
const sourceNodeTransformations = source.nodeTransformations;
if (defined_default(sourceNodeTransformations)) {
const targetNodeTransformations = this.nodeTransformations;
if (defined_default(targetNodeTransformations)) {
targetNodeTransformations.merge(sourceNodeTransformations);
} else {
this.nodeTransformations = new PropertyBag_default(
sourceNodeTransformations,
createNodeTransformationProperty
);
}
}
const sourceArticulations = source.articulations;
if (defined_default(sourceArticulations)) {
const targetArticulations = this.articulations;
if (defined_default(targetArticulations)) {
targetArticulations.merge(sourceArticulations);
} else {
this.articulations = new PropertyBag_default(sourceArticulations);
}
}
};
var ModelGraphics_default = ModelGraphics;
// packages/engine/Source/DataSources/Cesium3DTilesetGraphics.js
function Cesium3DTilesetGraphics(options) {
this._definitionChanged = new Event_default();
this._show = void 0;
this._showSubscription = void 0;
this._uri = void 0;
this._uriSubscription = void 0;
this._maximumScreenSpaceError = void 0;
this._maximumScreenSpaceErrorSubscription = void 0;
this.merge(defaultValue_default(options, defaultValue_default.EMPTY_OBJECT));
}
Object.defineProperties(Cesium3DTilesetGraphics.prototype, {
/**
* Gets the event that is raised whenever a property or sub-property is changed or modified.
* @memberof Cesium3DTilesetGraphics.prototype
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
/**
* Gets or sets the boolean Property specifying the visibility of the model.
* @memberof Cesium3DTilesetGraphics.prototype
* @type {Property|undefined}
* @default true
*/
show: createPropertyDescriptor_default("show"),
/**
* Gets or sets the string Property specifying the URI of the glTF asset.
* @memberof Cesium3DTilesetGraphics.prototype
* @type {Property|undefined}
*/
uri: createPropertyDescriptor_default("uri"),
/**
* Gets or sets the maximum screen space error used to drive level of detail refinement.
* @memberof Cesium3DTilesetGraphics.prototype
* @type {Property|undefined}
*/
maximumScreenSpaceError: createPropertyDescriptor_default("maximumScreenSpaceError")
});
Cesium3DTilesetGraphics.prototype.clone = function(result) {
if (!defined_default(result)) {
return new Cesium3DTilesetGraphics(this);
}
result.show = this.show;
result.uri = this.uri;
result.maximumScreenSpaceError = this.maximumScreenSpaceError;
return result;
};
Cesium3DTilesetGraphics.prototype.merge = function(source) {
if (!defined_default(source)) {
throw new DeveloperError_default("source is required.");
}
this.show = defaultValue_default(this.show, source.show);
this.uri = defaultValue_default(this.uri, source.uri);
this.maximumScreenSpaceError = defaultValue_default(
this.maximumScreenSpaceError,
source.maximumScreenSpaceError
);
};
var Cesium3DTilesetGraphics_default = Cesium3DTilesetGraphics;
// packages/engine/Source/DataSources/PathGraphics.js
function PathGraphics(options) {
this._definitionChanged = new Event_default();
this._show = void 0;
this._showSubscription = void 0;
this._leadTime = void 0;
this._leadTimeSubscription = void 0;
this._trailTime = void 0;
this._trailTimeSubscription = void 0;
this._width = void 0;
this._widthSubscription = void 0;
this._resolution = void 0;
this._resolutionSubscription = void 0;
this._material = void 0;
this._materialSubscription = void 0;
this._distanceDisplayCondition = void 0;
this._distanceDisplayConditionSubscription = void 0;
this.merge(defaultValue_default(options, defaultValue_default.EMPTY_OBJECT));
}
Object.defineProperties(PathGraphics.prototype, {
/**
* Gets the event that is raised whenever a property or sub-property is changed or modified.
* @memberof PathGraphics.prototype
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
/**
* Gets or sets the boolean Property specifying the visibility of the path.
* @memberof PathGraphics.prototype
* @type {Property|undefined}
* @default true
*/
show: createPropertyDescriptor_default("show"),
/**
* Gets or sets the Property specifying the number of seconds in front of the object to show.
* @memberof PathGraphics.prototype
* @type {Property|undefined}
*/
leadTime: createPropertyDescriptor_default("leadTime"),
/**
* Gets or sets the Property specifying the number of seconds behind the object to show.
* @memberof PathGraphics.prototype
* @type {Property|undefined}
*/
trailTime: createPropertyDescriptor_default("trailTime"),
/**
* Gets or sets the numeric Property specifying the width in pixels.
* @memberof PathGraphics.prototype
* @type {Property|undefined}
* @default 1.0
*/
width: createPropertyDescriptor_default("width"),
/**
* Gets or sets the Property specifying the maximum number of seconds to step when sampling the position.
* @memberof PathGraphics.prototype
* @type {Property|undefined}
* @default 60
*/
resolution: createPropertyDescriptor_default("resolution"),
/**
* Gets or sets the Property specifying the material used to draw the path.
* @memberof PathGraphics.prototype
* @type {MaterialProperty}
* @default Color.WHITE
*/
material: createMaterialPropertyDescriptor_default("material"),
/**
* Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this path will be displayed.
* @memberof PathGraphics.prototype
* @type {Property|undefined}
*/
distanceDisplayCondition: createPropertyDescriptor_default(
"distanceDisplayCondition"
)
});
PathGraphics.prototype.clone = function(result) {
if (!defined_default(result)) {
return new PathGraphics(this);
}
result.show = this.show;
result.leadTime = this.leadTime;
result.trailTime = this.trailTime;
result.width = this.width;
result.resolution = this.resolution;
result.material = this.material;
result.distanceDisplayCondition = this.distanceDisplayCondition;
return result;
};
PathGraphics.prototype.merge = function(source) {
if (!defined_default(source)) {
throw new DeveloperError_default("source is required.");
}
this.show = defaultValue_default(this.show, source.show);
this.leadTime = defaultValue_default(this.leadTime, source.leadTime);
this.trailTime = defaultValue_default(this.trailTime, source.trailTime);
this.width = defaultValue_default(this.width, source.width);
this.resolution = defaultValue_default(this.resolution, source.resolution);
this.material = defaultValue_default(this.material, source.material);
this.distanceDisplayCondition = defaultValue_default(
this.distanceDisplayCondition,
source.distanceDisplayCondition
);
};
var PathGraphics_default = PathGraphics;
// packages/engine/Source/DataSources/PlaneGraphics.js
function PlaneGraphics(options) {
this._definitionChanged = new Event_default();
this._show = void 0;
this._showSubscription = void 0;
this._plane = void 0;
this._planeSubscription = void 0;
this._dimensions = void 0;
this._dimensionsSubscription = void 0;
this._fill = void 0;
this._fillSubscription = void 0;
this._material = void 0;
this._materialSubscription = void 0;
this._outline = void 0;
this._outlineSubscription = void 0;
this._outlineColor = void 0;
this._outlineColorSubscription = void 0;
this._outlineWidth = void 0;
this._outlineWidthSubscription = void 0;
this._shadows = void 0;
this._shadowsSubscription = void 0;
this._distanceDisplayCondition = void 0;
this._distanceDisplayConditionSubscription = void 0;
this.merge(defaultValue_default(options, defaultValue_default.EMPTY_OBJECT));
}
Object.defineProperties(PlaneGraphics.prototype, {
/**
* Gets the event that is raised whenever a property or sub-property is changed or modified.
* @memberof PlaneGraphics.prototype
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
/**
* Gets or sets the boolean Property specifying the visibility of the plane.
* @memberof PlaneGraphics.prototype
* @type {Property|undefined}
* @default true
*/
show: createPropertyDescriptor_default("show"),
/**
* Gets or sets the {@link Plane} Property specifying the normal and distance of the plane.
*
* @memberof PlaneGraphics.prototype
* @type {Property|undefined}
*/
plane: createPropertyDescriptor_default("plane"),
/**
* Gets or sets the {@link Cartesian2} Property specifying the width and height of the plane.
*
* @memberof PlaneGraphics.prototype
* @type {Property|undefined}
*/
dimensions: createPropertyDescriptor_default("dimensions"),
/**
* Gets or sets the boolean Property specifying whether the plane is filled with the provided material.
* @memberof PlaneGraphics.prototype
* @type {Property|undefined}
* @default true
*/
fill: createPropertyDescriptor_default("fill"),
/**
* Gets or sets the material used to fill the plane.
* @memberof PlaneGraphics.prototype
* @type {MaterialProperty}
* @default Color.WHITE
*/
material: createMaterialPropertyDescriptor_default("material"),
/**
* Gets or sets the Property specifying whether the plane is outlined.
* @memberof PlaneGraphics.prototype
* @type {Property|undefined}
* @default false
*/
outline: createPropertyDescriptor_default("outline"),
/**
* Gets or sets the Property specifying the {@link Color} of the outline.
* @memberof PlaneGraphics.prototype
* @type {Property|undefined}
* @default Color.BLACK
*/
outlineColor: createPropertyDescriptor_default("outlineColor"),
/**
* Gets or sets the numeric Property specifying the width of the outline.
* * Note: This property will be ignored on all major browsers on Windows platforms. For details, see (@link https://github.com/CesiumGS/cesium/issues/40}. *
* @memberof PlaneGraphics.prototype * @type {Property|undefined} * @default 1.0 */ outlineWidth: createPropertyDescriptor_default("outlineWidth"), /** * Get or sets the enum Property specifying whether the plane * casts or receives shadows from light sources. * @memberof PlaneGraphics.prototype * @type {Property|undefined} * @default ShadowMode.DISABLED */ shadows: createPropertyDescriptor_default("shadows"), /** * Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this plane will be displayed. * @memberof PlaneGraphics.prototype * @type {Property|undefined} */ distanceDisplayCondition: createPropertyDescriptor_default( "distanceDisplayCondition" ) }); PlaneGraphics.prototype.clone = function(result) { if (!defined_default(result)) { return new PlaneGraphics(this); } result.show = this.show; result.plane = this.plane; result.dimensions = this.dimensions; result.fill = this.fill; result.material = this.material; result.outline = this.outline; result.outlineColor = this.outlineColor; result.outlineWidth = this.outlineWidth; result.shadows = this.shadows; result.distanceDisplayCondition = this.distanceDisplayCondition; return result; }; PlaneGraphics.prototype.merge = function(source) { if (!defined_default(source)) { throw new DeveloperError_default("source is required."); } this.show = defaultValue_default(this.show, source.show); this.plane = defaultValue_default(this.plane, source.plane); this.dimensions = defaultValue_default(this.dimensions, source.dimensions); this.fill = defaultValue_default(this.fill, source.fill); this.material = defaultValue_default(this.material, source.material); this.outline = defaultValue_default(this.outline, source.outline); this.outlineColor = defaultValue_default(this.outlineColor, source.outlineColor); this.outlineWidth = defaultValue_default(this.outlineWidth, source.outlineWidth); this.shadows = defaultValue_default(this.shadows, source.shadows); this.distanceDisplayCondition = defaultValue_default( this.distanceDisplayCondition, source.distanceDisplayCondition ); }; var PlaneGraphics_default = PlaneGraphics; // packages/engine/Source/DataSources/PointGraphics.js function PointGraphics(options) { this._definitionChanged = new Event_default(); this._show = void 0; this._showSubscription = void 0; this._pixelSize = void 0; this._pixelSizeSubscription = void 0; this._heightReference = void 0; this._heightReferenceSubscription = void 0; this._color = void 0; this._colorSubscription = void 0; this._outlineColor = void 0; this._outlineColorSubscription = void 0; this._outlineWidth = void 0; this._outlineWidthSubscription = void 0; this._scaleByDistance = void 0; this._scaleByDistanceSubscription = void 0; this._translucencyByDistance = void 0; this._translucencyByDistanceSubscription = void 0; this._distanceDisplayCondition = void 0; this._distanceDisplayConditionSubscription = void 0; this._disableDepthTestDistance = void 0; this._disableDepthTestDistanceSubscription = void 0; this.merge(defaultValue_default(options, defaultValue_default.EMPTY_OBJECT)); } Object.defineProperties(PointGraphics.prototype, { /** * Gets the event that is raised whenever a property or sub-property is changed or modified. * @memberof PointGraphics.prototype * * @type {Event} * @readonly */ definitionChanged: { get: function() { return this._definitionChanged; } }, /** * Gets or sets the boolean Property specifying the visibility of the point. * @memberof PointGraphics.prototype * @type {Property|undefined} * @default true */ show: createPropertyDescriptor_default("show"), /** * Gets or sets the numeric Property specifying the size in pixels. * @memberof PointGraphics.prototype * @type {Property|undefined} * @default 1 */ pixelSize: createPropertyDescriptor_default("pixelSize"), /** * Gets or sets the Property specifying the {@link HeightReference}. * @memberof PointGraphics.prototype * @type {Property|undefined} * @default HeightReference.NONE */ heightReference: createPropertyDescriptor_default("heightReference"), /** * Gets or sets the Property specifying the {@link Color} of the point. * @memberof PointGraphics.prototype * @type {Property|undefined} * @default Color.WHITE */ color: createPropertyDescriptor_default("color"), /** * Gets or sets the Property specifying the {@link Color} of the outline. * @memberof PointGraphics.prototype * @type {Property|undefined} * @default Color.BLACK */ outlineColor: createPropertyDescriptor_default("outlineColor"), /** * Gets or sets the numeric Property specifying the the outline width in pixels. * @memberof PointGraphics.prototype * @type {Property|undefined} * @default 0 */ outlineWidth: createPropertyDescriptor_default("outlineWidth"), /** * Gets or sets the {@link NearFarScalar} Property used to scale the point based on distance. * If undefined, a constant size is used. * @memberof PointGraphics.prototype * @type {Property|undefined} */ scaleByDistance: createPropertyDescriptor_default("scaleByDistance"), /** * Gets or sets {@link NearFarScalar} Property specifying the translucency of the point based on the distance from the camera. * A point's translucency will interpolate between the {@link NearFarScalar#nearValue} and * {@link NearFarScalar#farValue} while the camera distance falls within the lower and upper bounds * of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}. * Outside of these ranges the points's translucency remains clamped to the nearest bound. * @memberof PointGraphics.prototype * @type {Property|undefined} */ translucencyByDistance: createPropertyDescriptor_default("translucencyByDistance"), /** * Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this point will be displayed. * @memberof PointGraphics.prototype * @type {Property|undefined} */ distanceDisplayCondition: createPropertyDescriptor_default( "distanceDisplayCondition" ), /** * Gets or sets the distance from the camera at which to disable the depth test to, for example, prevent clipping against terrain. * When set to zero, the depth test is always applied. When set to Number.POSITIVE_INFINITY, the depth test is never applied. * @memberof PointGraphics.prototype * @type {Property|undefined} */ disableDepthTestDistance: createPropertyDescriptor_default( "disableDepthTestDistance" ) }); PointGraphics.prototype.clone = function(result) { if (!defined_default(result)) { return new PointGraphics(this); } result.show = this.show; result.pixelSize = this.pixelSize; result.heightReference = this.heightReference; result.color = this.color; result.outlineColor = this.outlineColor; result.outlineWidth = this.outlineWidth; result.scaleByDistance = this.scaleByDistance; result.translucencyByDistance = this._translucencyByDistance; result.distanceDisplayCondition = this.distanceDisplayCondition; result.disableDepthTestDistance = this.disableDepthTestDistance; return result; }; PointGraphics.prototype.merge = function(source) { if (!defined_default(source)) { throw new DeveloperError_default("source is required."); } this.show = defaultValue_default(this.show, source.show); this.pixelSize = defaultValue_default(this.pixelSize, source.pixelSize); this.heightReference = defaultValue_default( this.heightReference, source.heightReference ); this.color = defaultValue_default(this.color, source.color); this.outlineColor = defaultValue_default(this.outlineColor, source.outlineColor); this.outlineWidth = defaultValue_default(this.outlineWidth, source.outlineWidth); this.scaleByDistance = defaultValue_default( this.scaleByDistance, source.scaleByDistance ); this.translucencyByDistance = defaultValue_default( this._translucencyByDistance, source.translucencyByDistance ); this.distanceDisplayCondition = defaultValue_default( this.distanceDisplayCondition, source.distanceDisplayCondition ); this.disableDepthTestDistance = defaultValue_default( this.disableDepthTestDistance, source.disableDepthTestDistance ); }; var PointGraphics_default = PointGraphics; // packages/engine/Source/Core/PolygonHierarchy.js function PolygonHierarchy(positions, holes) { this.positions = defined_default(positions) ? positions : []; this.holes = defined_default(holes) ? holes : []; } var PolygonHierarchy_default = PolygonHierarchy; // packages/engine/Source/DataSources/PolygonGraphics.js function createPolygonHierarchyProperty(value) { if (Array.isArray(value)) { value = new PolygonHierarchy_default(value); } return new ConstantProperty_default(value); } function PolygonGraphics(options) { this._definitionChanged = new Event_default(); this._show = void 0; this._showSubscription = void 0; this._hierarchy = void 0; this._hierarchySubscription = void 0; this._height = void 0; this._heightSubscription = void 0; this._heightReference = void 0; this._heightReferenceSubscription = void 0; this._extrudedHeight = void 0; this._extrudedHeightSubscription = void 0; this._extrudedHeightReference = void 0; this._extrudedHeightReferenceSubscription = void 0; this._stRotation = void 0; this._stRotationSubscription = void 0; this._granularity = void 0; this._granularitySubscription = void 0; this._fill = void 0; this._fillSubscription = void 0; this._material = void 0; this._materialSubscription = void 0; this._outline = void 0; this._outlineSubscription = void 0; this._outlineColor = void 0; this._outlineColorSubscription = void 0; this._outlineWidth = void 0; this._outlineWidthSubscription = void 0; this._perPositionHeight = void 0; this._perPositionHeightSubscription = void 0; this._closeTop = void 0; this._closeTopSubscription = void 0; this._closeBottom = void 0; this._closeBottomSubscription = void 0; this._arcType = void 0; this._arcTypeSubscription = void 0; this._shadows = void 0; this._shadowsSubscription = void 0; this._distanceDisplayCondition = void 0; this._distanceDisplayConditionSubscription = void 0; this._classificationType = void 0; this._classificationTypeSubscription = void 0; this._zIndex = void 0; this._zIndexSubscription = void 0; this._textureCoordinates = void 0; this._textureCoordinatesSubscription = void 0; this.merge(defaultValue_default(options, defaultValue_default.EMPTY_OBJECT)); } Object.defineProperties(PolygonGraphics.prototype, { /** * Gets the event that is raised whenever a property or sub-property is changed or modified. * @memberof PolygonGraphics.prototype * * @type {Event} * @readonly */ definitionChanged: { get: function() { return this._definitionChanged; } }, /** * Gets or sets the boolean Property specifying the visibility of the polygon. * @memberof PolygonGraphics.prototype * @type {Property|undefined} * @default true */ show: createPropertyDescriptor_default("show"), /** * Gets or sets the Property specifying the {@link PolygonHierarchy}. * @memberof PolygonGraphics.prototype * @type {Property|undefined} */ hierarchy: createPropertyDescriptor_default( "hierarchy", void 0, createPolygonHierarchyProperty ), /** * Gets or sets the numeric Property specifying the constant altitude of the polygon. * @memberof PolygonGraphics.prototype * @type {Property|undefined} * @default 0.0 */ height: createPropertyDescriptor_default("height"), /** * Gets or sets the Property specifying the {@link HeightReference}. * @memberof PolygonGraphics.prototype * @type {Property|undefined} * @default HeightReference.NONE */ heightReference: createPropertyDescriptor_default("heightReference"), /** * Gets or sets the numeric Property specifying the altitude of the polygon extrusion. * If {@link PolygonGraphics#perPositionHeight} is false, the volume starts at {@link PolygonGraphics#height} and ends at this altitude. * If {@link PolygonGraphics#perPositionHeight} is true, the volume starts at the height of each {@link PolygonGraphics#hierarchy} position and ends at this altitude. * @memberof PolygonGraphics.prototype * @type {Property|undefined} */ extrudedHeight: createPropertyDescriptor_default("extrudedHeight"), /** * Gets or sets the Property specifying the extruded {@link HeightReference}. * @memberof PolygonGraphics.prototype * @type {Property|undefined} * @default HeightReference.NONE */ extrudedHeightReference: createPropertyDescriptor_default("extrudedHeightReference"), /** * Gets or sets the numeric property specifying the rotation of the polygon texture counter-clockwise from north. Only has an effect if textureCoordinates is not defined. * @memberof PolygonGraphics.prototype * @type {Property|undefined} * @default 0 */ stRotation: createPropertyDescriptor_default("stRotation"), /** * Gets or sets the numeric Property specifying the angular distance between points on the polygon. * @memberof PolygonGraphics.prototype * @type {Property|undefined} * @default {CesiumMath.RADIANS_PER_DEGREE} */ granularity: createPropertyDescriptor_default("granularity"), /** * Gets or sets the boolean Property specifying whether the polygon is filled with the provided material. * @memberof PolygonGraphics.prototype * @type {Property|undefined} * @default true */ fill: createPropertyDescriptor_default("fill"), /** * Gets or sets the Property specifying the material used to fill the polygon. * @memberof PolygonGraphics.prototype * @type {MaterialProperty} * @default Color.WHITE */ material: createMaterialPropertyDescriptor_default("material"), /** * Gets or sets the Property specifying whether the polygon is outlined. * @memberof PolygonGraphics.prototype * @type {Property|undefined} * @default false */ outline: createPropertyDescriptor_default("outline"), /** * Gets or sets the Property specifying the {@link Color} of the outline. * @memberof PolygonGraphics.prototype * @type {Property|undefined} * @default Color.BLACK */ outlineColor: createPropertyDescriptor_default("outlineColor"), /** * Gets or sets the numeric Property specifying the width of the outline. ** Note: This property will be ignored on all major browsers on Windows platforms. For details, see (@link https://github.com/CesiumGS/cesium/issues/40}. *
* @memberof PolygonGraphics.prototype * @type {Property|undefined} * @default 1.0 */ outlineWidth: createPropertyDescriptor_default("outlineWidth"), /** * Gets or sets the boolean specifying whether or not the the height of each position is used. * If true, the shape will have non-uniform altitude defined by the height of each {@link PolygonGraphics#hierarchy} position. * If false, the shape will have a constant altitude as specified by {@link PolygonGraphics#height}. * @memberof PolygonGraphics.prototype * @type {Property|undefined} */ perPositionHeight: createPropertyDescriptor_default("perPositionHeight"), /** * Gets or sets a boolean specifying whether or not the top of an extruded polygon is included. * @memberof PolygonGraphics.prototype * @type {Property|undefined} */ closeTop: createPropertyDescriptor_default("closeTop"), /** * Gets or sets a boolean specifying whether or not the bottom of an extruded polygon is included. * @memberof PolygonGraphics.prototype * @type {Property|undefined} */ closeBottom: createPropertyDescriptor_default("closeBottom"), /** * Gets or sets the {@link ArcType} Property specifying the type of lines the polygon edges use. * @memberof PolygonGraphics.prototype * @type {Property|undefined} * @default ArcType.GEODESIC */ arcType: createPropertyDescriptor_default("arcType"), /** * Get or sets the enum Property specifying whether the polygon * casts or receives shadows from light sources. * @memberof PolygonGraphics.prototype * @type {Property|undefined} * @default ShadowMode.DISABLED */ shadows: createPropertyDescriptor_default("shadows"), /** * Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this polygon will be displayed. * @memberof PolygonGraphics.prototype * @type {Property|undefined} */ distanceDisplayCondition: createPropertyDescriptor_default( "distanceDisplayCondition" ), /** * Gets or sets the {@link ClassificationType} Property specifying whether this polygon will classify terrain, 3D Tiles, or both when on the ground. * @memberof PolygonGraphics.prototype * @type {Property|undefined} * @default ClassificationType.BOTH */ classificationType: createPropertyDescriptor_default("classificationType"), /** * Gets or sets the zIndex Prperty specifying the ordering of ground geometry. Only has an effect if the polygon is constant and neither height or extrudedHeight are specified. * @memberof PolygonGraphics.prototype * @type {ConstantProperty|undefined} * @default 0 */ zIndex: createPropertyDescriptor_default("zIndex"), /** * A Property specifying texture coordinates as a {@link PolygonHierarchy} of {@link Cartesian2} points. Has no effect for ground primitives. * @memberof PolygonGraphics.prototype * @type {Property|undefined} */ textureCoordinates: createPropertyDescriptor_default("textureCoordinates") }); PolygonGraphics.prototype.clone = function(result) { if (!defined_default(result)) { return new PolygonGraphics(this); } result.show = this.show; result.hierarchy = this.hierarchy; result.height = this.height; result.heightReference = this.heightReference; result.extrudedHeight = this.extrudedHeight; result.extrudedHeightReference = this.extrudedHeightReference; result.stRotation = this.stRotation; result.granularity = this.granularity; result.fill = this.fill; result.material = this.material; result.outline = this.outline; result.outlineColor = this.outlineColor; result.outlineWidth = this.outlineWidth; result.perPositionHeight = this.perPositionHeight; result.closeTop = this.closeTop; result.closeBottom = this.closeBottom; result.arcType = this.arcType; result.shadows = this.shadows; result.distanceDisplayCondition = this.distanceDisplayCondition; result.classificationType = this.classificationType; result.zIndex = this.zIndex; result.textureCoordinates = this.textureCoordinates; return result; }; PolygonGraphics.prototype.merge = function(source) { if (!defined_default(source)) { throw new DeveloperError_default("source is required."); } this.show = defaultValue_default(this.show, source.show); this.hierarchy = defaultValue_default(this.hierarchy, source.hierarchy); this.height = defaultValue_default(this.height, source.height); this.heightReference = defaultValue_default( this.heightReference, source.heightReference ); this.extrudedHeight = defaultValue_default( this.extrudedHeight, source.extrudedHeight ); this.extrudedHeightReference = defaultValue_default( this.extrudedHeightReference, source.extrudedHeightReference ); this.stRotation = defaultValue_default(this.stRotation, source.stRotation); this.granularity = defaultValue_default(this.granularity, source.granularity); this.fill = defaultValue_default(this.fill, source.fill); this.material = defaultValue_default(this.material, source.material); this.outline = defaultValue_default(this.outline, source.outline); this.outlineColor = defaultValue_default(this.outlineColor, source.outlineColor); this.outlineWidth = defaultValue_default(this.outlineWidth, source.outlineWidth); this.perPositionHeight = defaultValue_default( this.perPositionHeight, source.perPositionHeight ); this.closeTop = defaultValue_default(this.closeTop, source.closeTop); this.closeBottom = defaultValue_default(this.closeBottom, source.closeBottom); this.arcType = defaultValue_default(this.arcType, source.arcType); this.shadows = defaultValue_default(this.shadows, source.shadows); this.distanceDisplayCondition = defaultValue_default( this.distanceDisplayCondition, source.distanceDisplayCondition ); this.classificationType = defaultValue_default( this.classificationType, source.classificationType ); this.zIndex = defaultValue_default(this.zIndex, source.zIndex); this.textureCoordinates = defaultValue_default( this.textureCoordinates, source.textureCoordinates ); }; var PolygonGraphics_default = PolygonGraphics; // packages/engine/Source/DataSources/PolylineGraphics.js function PolylineGraphics(options) { this._definitionChanged = new Event_default(); this._show = void 0; this._showSubscription = void 0; this._positions = void 0; this._positionsSubscription = void 0; this._width = void 0; this._widthSubscription = void 0; this._granularity = void 0; this._granularitySubscription = void 0; this._material = void 0; this._materialSubscription = void 0; this._depthFailMaterial = void 0; this._depthFailMaterialSubscription = void 0; this._arcType = void 0; this._arcTypeSubscription = void 0; this._clampToGround = void 0; this._clampToGroundSubscription = void 0; this._shadows = void 0; this._shadowsSubscription = void 0; this._distanceDisplayCondition = void 0; this._distanceDisplayConditionSubscription = void 0; this._classificationType = void 0; this._classificationTypeSubscription = void 0; this._zIndex = void 0; this._zIndexSubscription = void 0; this.merge(defaultValue_default(options, defaultValue_default.EMPTY_OBJECT)); } Object.defineProperties(PolylineGraphics.prototype, { /** * Gets the event that is raised whenever a property or sub-property is changed or modified. * @memberof PolylineGraphics.prototype * * @type {Event} * @readonly */ definitionChanged: { get: function() { return this._definitionChanged; } }, /** * Gets or sets the boolean Property specifying the visibility of the polyline. * @memberof PolylineGraphics.prototype * @type {Property|undefined} * @default true */ show: createPropertyDescriptor_default("show"), /** * Gets or sets the Property specifying the array of {@link Cartesian3} * positions that define the line strip. * @memberof PolylineGraphics.prototype * @type {Property|undefined} */ positions: createPropertyDescriptor_default("positions"), /** * Gets or sets the numeric Property specifying the width in pixels. * @memberof PolylineGraphics.prototype * @type {Property|undefined} * @default 1.0 */ width: createPropertyDescriptor_default("width"), /** * Gets or sets the numeric Property specifying the angular distance between each latitude and longitude if arcType is not ArcType.NONE and clampToGround is false. * @memberof PolylineGraphics.prototype * @type {Property|undefined} * @default Cesium.Math.RADIANS_PER_DEGREE */ granularity: createPropertyDescriptor_default("granularity"), /** * Gets or sets the Property specifying the material used to draw the polyline. * @memberof PolylineGraphics.prototype * @type {MaterialProperty} * @default Color.WHITE */ material: createMaterialPropertyDescriptor_default("material"), /** * Gets or sets the Property specifying the material used to draw the polyline when it fails the depth test. ** Requires the EXT_frag_depth WebGL extension to render properly. If the extension is not supported, * there may be artifacts. *
* @memberof PolylineGraphics.prototype * @type {MaterialProperty} * @default undefined */ depthFailMaterial: createMaterialPropertyDescriptor_default("depthFailMaterial"), /** * Gets or sets the {@link ArcType} Property specifying whether the line segments should be great arcs, rhumb lines or linearly connected. * @memberof PolylineGraphics.prototype * @type {Property|undefined} * @default ArcType.GEODESIC */ arcType: createPropertyDescriptor_default("arcType"), /** * Gets or sets the boolean Property specifying whether the polyline * should be clamped to the ground. * @memberof PolylineGraphics.prototype * @type {Property|undefined} * @default false */ clampToGround: createPropertyDescriptor_default("clampToGround"), /** * Get or sets the enum Property specifying whether the polyline * casts or receives shadows from light sources. * @memberof PolylineGraphics.prototype * @type {Property|undefined} * @default ShadowMode.DISABLED */ shadows: createPropertyDescriptor_default("shadows"), /** * Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this polyline will be displayed. * @memberof PolylineGraphics.prototype * @type {Property|undefined} */ distanceDisplayCondition: createPropertyDescriptor_default( "distanceDisplayCondition" ), /** * Gets or sets the {@link ClassificationType} Property specifying whether this polyline will classify terrain, 3D Tiles, or both when on the ground. * @memberof PolylineGraphics.prototype * @type {Property|undefined} * @default ClassificationType.BOTH */ classificationType: createPropertyDescriptor_default("classificationType"), /** * Gets or sets the zIndex Property specifying the ordering of the polyline. Only has an effect if `clampToGround` is true and polylines on terrain is supported. * @memberof PolylineGraphics.prototype * @type {ConstantProperty|undefined} * @default 0 */ zIndex: createPropertyDescriptor_default("zIndex") }); PolylineGraphics.prototype.clone = function(result) { if (!defined_default(result)) { return new PolylineGraphics(this); } result.show = this.show; result.positions = this.positions; result.width = this.width; result.granularity = this.granularity; result.material = this.material; result.depthFailMaterial = this.depthFailMaterial; result.arcType = this.arcType; result.clampToGround = this.clampToGround; result.shadows = this.shadows; result.distanceDisplayCondition = this.distanceDisplayCondition; result.classificationType = this.classificationType; result.zIndex = this.zIndex; return result; }; PolylineGraphics.prototype.merge = function(source) { if (!defined_default(source)) { throw new DeveloperError_default("source is required."); } this.show = defaultValue_default(this.show, source.show); this.positions = defaultValue_default(this.positions, source.positions); this.width = defaultValue_default(this.width, source.width); this.granularity = defaultValue_default(this.granularity, source.granularity); this.material = defaultValue_default(this.material, source.material); this.depthFailMaterial = defaultValue_default( this.depthFailMaterial, source.depthFailMaterial ); this.arcType = defaultValue_default(this.arcType, source.arcType); this.clampToGround = defaultValue_default(this.clampToGround, source.clampToGround); this.shadows = defaultValue_default(this.shadows, source.shadows); this.distanceDisplayCondition = defaultValue_default( this.distanceDisplayCondition, source.distanceDisplayCondition ); this.classificationType = defaultValue_default( this.classificationType, source.classificationType ); this.zIndex = defaultValue_default(this.zIndex, source.zIndex); }; var PolylineGraphics_default = PolylineGraphics; // packages/engine/Source/DataSources/PolylineVolumeGraphics.js function PolylineVolumeGraphics(options) { this._definitionChanged = new Event_default(); this._show = void 0; this._showSubscription = void 0; this._positions = void 0; this._positionsSubscription = void 0; this._shape = void 0; this._shapeSubscription = void 0; this._cornerType = void 0; this._cornerTypeSubscription = void 0; this._granularity = void 0; this._granularitySubscription = void 0; this._fill = void 0; this._fillSubscription = void 0; this._material = void 0; this._materialSubscription = void 0; this._outline = void 0; this._outlineSubscription = void 0; this._outlineColor = void 0; this._outlineColorSubscription = void 0; this._outlineWidth = void 0; this._outlineWidthSubscription = void 0; this._shadows = void 0; this._shadowsSubscription = void 0; this._distanceDisplayCondition = void 0; this._distanceDisplayConditionSubsription = void 0; this.merge(defaultValue_default(options, defaultValue_default.EMPTY_OBJECT)); } Object.defineProperties(PolylineVolumeGraphics.prototype, { /** * Gets the event that is raised whenever a property or sub-property is changed or modified. * @memberof PolylineVolumeGraphics.prototype * * @type {Event} * @readonly */ definitionChanged: { get: function() { return this._definitionChanged; } }, /** * Gets or sets the boolean Property specifying the visibility of the volume. * @memberof PolylineVolumeGraphics.prototype * @type {Property|undefined} * @default true */ show: createPropertyDescriptor_default("show"), /** * Gets or sets the Property specifying the array of {@link Cartesian3} positions which define the line strip. * @memberof PolylineVolumeGraphics.prototype * @type {Property|undefined} */ positions: createPropertyDescriptor_default("positions"), /** * Gets or sets the Property specifying the array of {@link Cartesian2} positions which define the shape to be extruded. * @memberof PolylineVolumeGraphics.prototype * @type {Property|undefined} */ shape: createPropertyDescriptor_default("shape"), /** * Gets or sets the {@link CornerType} Property specifying the style of the corners. * @memberof PolylineVolumeGraphics.prototype * @type {Property|undefined} * @default CornerType.ROUNDED */ cornerType: createPropertyDescriptor_default("cornerType"), /** * Gets or sets the numeric Property specifying the angular distance between points on the volume. * @memberof PolylineVolumeGraphics.prototype * @type {Property|undefined} * @default {CesiumMath.RADIANS_PER_DEGREE} */ granularity: createPropertyDescriptor_default("granularity"), /** * Gets or sets the boolean Property specifying whether the volume is filled with the provided material. * @memberof PolylineVolumeGraphics.prototype * @type {Property|undefined} * @default true */ fill: createPropertyDescriptor_default("fill"), /** * Gets or sets the Property specifying the material used to fill the volume. * @memberof PolylineVolumeGraphics.prototype * @type {MaterialProperty} * @default Color.WHITE */ material: createMaterialPropertyDescriptor_default("material"), /** * Gets or sets the Property specifying whether the volume is outlined. * @memberof PolylineVolumeGraphics.prototype * @type {Property|undefined} * @default false */ outline: createPropertyDescriptor_default("outline"), /** * Gets or sets the Property specifying the {@link Color} of the outline. * @memberof PolylineVolumeGraphics.prototype * @type {Property|undefined} * @default Color.BLACK */ outlineColor: createPropertyDescriptor_default("outlineColor"), /** * Gets or sets the numeric Property specifying the width of the outline. ** Note: This property will be ignored on all major browsers on Windows platforms. For details, see (@link https://github.com/CesiumGS/cesium/issues/40}. *
* @memberof PolylineVolumeGraphics.prototype * @type {Property|undefined} * @default 1.0 */ outlineWidth: createPropertyDescriptor_default("outlineWidth"), /** * Get or sets the enum Property specifying whether the volume * casts or receives shadows from light sources. * @memberof PolylineVolumeGraphics.prototype * @type {Property|undefined} * @default ShadowMode.DISABLED */ shadows: createPropertyDescriptor_default("shadows"), /** * Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this volume will be displayed. * @memberof PolylineVolumeGraphics.prototype * @type {Property|undefined} */ distanceDisplayCondition: createPropertyDescriptor_default( "distanceDisplayCondition" ) }); PolylineVolumeGraphics.prototype.clone = function(result) { if (!defined_default(result)) { return new PolylineVolumeGraphics(this); } result.show = this.show; result.positions = this.positions; result.shape = this.shape; result.cornerType = this.cornerType; result.granularity = this.granularity; result.fill = this.fill; result.material = this.material; result.outline = this.outline; result.outlineColor = this.outlineColor; result.outlineWidth = this.outlineWidth; result.shadows = this.shadows; result.distanceDisplayCondition = this.distanceDisplayCondition; return result; }; PolylineVolumeGraphics.prototype.merge = function(source) { if (!defined_default(source)) { throw new DeveloperError_default("source is required."); } this.show = defaultValue_default(this.show, source.show); this.positions = defaultValue_default(this.positions, source.positions); this.shape = defaultValue_default(this.shape, source.shape); this.cornerType = defaultValue_default(this.cornerType, source.cornerType); this.granularity = defaultValue_default(this.granularity, source.granularity); this.fill = defaultValue_default(this.fill, source.fill); this.material = defaultValue_default(this.material, source.material); this.outline = defaultValue_default(this.outline, source.outline); this.outlineColor = defaultValue_default(this.outlineColor, source.outlineColor); this.outlineWidth = defaultValue_default(this.outlineWidth, source.outlineWidth); this.shadows = defaultValue_default(this.shadows, source.shadows); this.distanceDisplayCondition = defaultValue_default( this.distanceDisplayCondition, source.distanceDisplayCondition ); }; var PolylineVolumeGraphics_default = PolylineVolumeGraphics; // packages/engine/Source/DataSources/RectangleGraphics.js function RectangleGraphics(options) { this._definitionChanged = new Event_default(); this._show = void 0; this._showSubscription = void 0; this._coordinates = void 0; this._coordinatesSubscription = void 0; this._height = void 0; this._heightSubscription = void 0; this._heightReference = void 0; this._heightReferenceSubscription = void 0; this._extrudedHeight = void 0; this._extrudedHeightSubscription = void 0; this._extrudedHeightReference = void 0; this._extrudedHeightReferenceSubscription = void 0; this._rotation = void 0; this._rotationSubscription = void 0; this._stRotation = void 0; this._stRotationSubscription = void 0; this._granularity = void 0; this._granularitySubscription = void 0; this._fill = void 0; this._fillSubscription = void 0; this._material = void 0; this._materialSubscription = void 0; this._outline = void 0; this._outlineSubscription = void 0; this._outlineColor = void 0; this._outlineColorSubscription = void 0; this._outlineWidth = void 0; this._outlineWidthSubscription = void 0; this._shadows = void 0; this._shadowsSubscription = void 0; this._distanceDisplayCondition = void 0; this._distancedisplayConditionSubscription = void 0; this._classificationType = void 0; this._classificationTypeSubscription = void 0; this._zIndex = void 0; this._zIndexSubscription = void 0; this.merge(defaultValue_default(options, defaultValue_default.EMPTY_OBJECT)); } Object.defineProperties(RectangleGraphics.prototype, { /** * Gets the event that is raised whenever a property or sub-property is changed or modified. * @memberof RectangleGraphics.prototype * * @type {Event} * @readonly */ definitionChanged: { get: function() { return this._definitionChanged; } }, /** * Gets or sets the boolean Property specifying the visibility of the rectangle. * @memberof RectangleGraphics.prototype * @type {Property|undefined} * @default true */ show: createPropertyDescriptor_default("show"), /** * Gets or sets the Property specifying the {@link Rectangle}. * @memberof RectangleGraphics.prototype * @type {Property|undefined} */ coordinates: createPropertyDescriptor_default("coordinates"), /** * Gets or sets the numeric Property specifying the altitude of the rectangle. * @memberof RectangleGraphics.prototype * @type {Property|undefined} * @default 0.0 */ height: createPropertyDescriptor_default("height"), /** * Gets or sets the Property specifying the {@link HeightReference}. * @memberof RectangleGraphics.prototype * @type {Property|undefined} * @default HeightReference.NONE */ heightReference: createPropertyDescriptor_default("heightReference"), /** * Gets or sets the numeric Property specifying the altitude of the rectangle extrusion. * Setting this property creates volume starting at height and ending at this altitude. * @memberof RectangleGraphics.prototype * @type {Property|undefined} */ extrudedHeight: createPropertyDescriptor_default("extrudedHeight"), /** * Gets or sets the Property specifying the extruded {@link HeightReference}. * @memberof RectangleGraphics.prototype * @type {Property|undefined} * @default HeightReference.NONE */ extrudedHeightReference: createPropertyDescriptor_default("extrudedHeightReference"), /** * Gets or sets the numeric property specifying the rotation of the rectangle clockwise from north. * @memberof RectangleGraphics.prototype * @type {Property|undefined} * @default 0 */ rotation: createPropertyDescriptor_default("rotation"), /** * Gets or sets the numeric property specifying the rotation of the rectangle texture counter-clockwise from north. * @memberof RectangleGraphics.prototype * @type {Property|undefined} * @default 0 */ stRotation: createPropertyDescriptor_default("stRotation"), /** * Gets or sets the numeric Property specifying the angular distance between points on the rectangle. * @memberof RectangleGraphics.prototype * @type {Property|undefined} * @default {CesiumMath.RADIANS_PER_DEGREE} */ granularity: createPropertyDescriptor_default("granularity"), /** * Gets or sets the boolean Property specifying whether the rectangle is filled with the provided material. * @memberof RectangleGraphics.prototype * @type {Property|undefined} * @default true */ fill: createPropertyDescriptor_default("fill"), /** * Gets or sets the Property specifying the material used to fill the rectangle. * @memberof RectangleGraphics.prototype * @type {MaterialProperty} * @default Color.WHITE */ material: createMaterialPropertyDescriptor_default("material"), /** * Gets or sets the Property specifying whether the rectangle is outlined. * @memberof RectangleGraphics.prototype * @type {Property|undefined} * @default false */ outline: createPropertyDescriptor_default("outline"), /** * Gets or sets the Property specifying the {@link Color} of the outline. * @memberof RectangleGraphics.prototype * @type {Property|undefined} * @default Color.BLACK */ outlineColor: createPropertyDescriptor_default("outlineColor"), /** * Gets or sets the numeric Property specifying the width of the outline. ** Note: This property will be ignored on all major browsers on Windows platforms. For details, see (@link https://github.com/CesiumGS/cesium/issues/40}. *
* @memberof RectangleGraphics.prototype * @type {Property|undefined} * @default 1.0 */ outlineWidth: createPropertyDescriptor_default("outlineWidth"), /** * Get or sets the enum Property specifying whether the rectangle * casts or receives shadows from light sources. * @memberof RectangleGraphics.prototype * @type {Property|undefined} * @default ShadowMode.DISABLED */ shadows: createPropertyDescriptor_default("shadows"), /** * Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this rectangle will be displayed. * @memberof RectangleGraphics.prototype * @type {Property|undefined} */ distanceDisplayCondition: createPropertyDescriptor_default( "distanceDisplayCondition" ), /** * Gets or sets the {@link ClassificationType} Property specifying whether this rectangle will classify terrain, 3D Tiles, or both when on the ground. * @memberof RectangleGraphics.prototype * @type {Property|undefined} * @default ClassificationType.BOTH */ classificationType: createPropertyDescriptor_default("classificationType"), /** * Gets or sets the zIndex Property specifying the ordering of the rectangle. Only has an effect if the rectangle is constant and neither height or extrudedHeight are specified. * @memberof RectangleGraphics.prototype * @type {ConstantProperty|undefined} * @default 0 */ zIndex: createPropertyDescriptor_default("zIndex") }); RectangleGraphics.prototype.clone = function(result) { if (!defined_default(result)) { return new RectangleGraphics(this); } result.show = this.show; result.coordinates = this.coordinates; result.height = this.height; result.heightReference = this.heightReference; result.extrudedHeight = this.extrudedHeight; result.extrudedHeightReference = this.extrudedHeightReference; result.rotation = this.rotation; result.stRotation = this.stRotation; result.granularity = this.granularity; result.fill = this.fill; result.material = this.material; result.outline = this.outline; result.outlineColor = this.outlineColor; result.outlineWidth = this.outlineWidth; result.shadows = this.shadows; result.distanceDisplayCondition = this.distanceDisplayCondition; result.classificationType = this.classificationType; result.zIndex = this.zIndex; return result; }; RectangleGraphics.prototype.merge = function(source) { if (!defined_default(source)) { throw new DeveloperError_default("source is required."); } this.show = defaultValue_default(this.show, source.show); this.coordinates = defaultValue_default(this.coordinates, source.coordinates); this.height = defaultValue_default(this.height, source.height); this.heightReference = defaultValue_default( this.heightReference, source.heightReference ); this.extrudedHeight = defaultValue_default( this.extrudedHeight, source.extrudedHeight ); this.extrudedHeightReference = defaultValue_default( this.extrudedHeightReference, source.extrudedHeightReference ); this.rotation = defaultValue_default(this.rotation, source.rotation); this.stRotation = defaultValue_default(this.stRotation, source.stRotation); this.granularity = defaultValue_default(this.granularity, source.granularity); this.fill = defaultValue_default(this.fill, source.fill); this.material = defaultValue_default(this.material, source.material); this.outline = defaultValue_default(this.outline, source.outline); this.outlineColor = defaultValue_default(this.outlineColor, source.outlineColor); this.outlineWidth = defaultValue_default(this.outlineWidth, source.outlineWidth); this.shadows = defaultValue_default(this.shadows, source.shadows); this.distanceDisplayCondition = defaultValue_default( this.distanceDisplayCondition, source.distanceDisplayCondition ); this.classificationType = defaultValue_default( this.classificationType, source.classificationType ); this.zIndex = defaultValue_default(this.zIndex, source.zIndex); }; var RectangleGraphics_default = RectangleGraphics; // packages/engine/Source/DataSources/WallGraphics.js function WallGraphics(options) { this._definitionChanged = new Event_default(); this._show = void 0; this._showSubscription = void 0; this._positions = void 0; this._positionsSubscription = void 0; this._minimumHeights = void 0; this._minimumHeightsSubscription = void 0; this._maximumHeights = void 0; this._maximumHeightsSubscription = void 0; this._granularity = void 0; this._granularitySubscription = void 0; this._fill = void 0; this._fillSubscription = void 0; this._material = void 0; this._materialSubscription = void 0; this._outline = void 0; this._outlineSubscription = void 0; this._outlineColor = void 0; this._outlineColorSubscription = void 0; this._outlineWidth = void 0; this._outlineWidthSubscription = void 0; this._shadows = void 0; this._shadowsSubscription = void 0; this._distanceDisplayCondition = void 0; this._distanceDisplayConditionSubscription = void 0; this.merge(defaultValue_default(options, defaultValue_default.EMPTY_OBJECT)); } Object.defineProperties(WallGraphics.prototype, { /** * Gets the event that is raised whenever a property or sub-property is changed or modified. * @memberof WallGraphics.prototype * * @type {Event} * @readonly */ definitionChanged: { get: function() { return this._definitionChanged; } }, /** * Gets or sets the boolean Property specifying the visibility of the wall. * @memberof WallGraphics.prototype * @type {Property|undefined} * @default true */ show: createPropertyDescriptor_default("show"), /** * Gets or sets the Property specifying the array of {@link Cartesian3} positions which define the top of the wall. * @memberof WallGraphics.prototype * @type {Property|undefined} */ positions: createPropertyDescriptor_default("positions"), /** * Gets or sets the Property specifying an array of heights to be used for the bottom of the wall instead of the surface of the globe. * If defined, the array must be the same length as {@link Wall#positions}. * @memberof WallGraphics.prototype * @type {Property|undefined} */ minimumHeights: createPropertyDescriptor_default("minimumHeights"), /** * Gets or sets the Property specifying an array of heights to be used for the top of the wall instead of the height of each position. * If defined, the array must be the same length as {@link Wall#positions}. * @memberof WallGraphics.prototype * @type {Property|undefined} */ maximumHeights: createPropertyDescriptor_default("maximumHeights"), /** * Gets or sets the numeric Property specifying the angular distance between points on the wall. * @memberof WallGraphics.prototype * @type {Property|undefined} * @default {CesiumMath.RADIANS_PER_DEGREE} */ granularity: createPropertyDescriptor_default("granularity"), /** * Gets or sets the boolean Property specifying whether the wall is filled with the provided material. * @memberof WallGraphics.prototype * @type {Property|undefined} * @default true */ fill: createPropertyDescriptor_default("fill"), /** * Gets or sets the Property specifying the material used to fill the wall. * @memberof WallGraphics.prototype * @type {MaterialProperty} * @default Color.WHITE */ material: createMaterialPropertyDescriptor_default("material"), /** * Gets or sets the Property specifying whether the wall is outlined. * @memberof WallGraphics.prototype * @type {Property|undefined} * @default false */ outline: createPropertyDescriptor_default("outline"), /** * Gets or sets the Property specifying the {@link Color} of the outline. * @memberof WallGraphics.prototype * @type {Property|undefined} * @default Color.BLACK */ outlineColor: createPropertyDescriptor_default("outlineColor"), /** * Gets or sets the numeric Property specifying the width of the outline. ** Note: This property will be ignored on all major browsers on Windows platforms. For details, see (@link https://github.com/CesiumGS/cesium/issues/40}. *
* @memberof WallGraphics.prototype * @type {Property|undefined} * @default 1.0 */ outlineWidth: createPropertyDescriptor_default("outlineWidth"), /** * Get or sets the enum Property specifying whether the wall * casts or receives shadows from light sources. * @memberof WallGraphics.prototype * @type {Property|undefined} * @default ShadowMode.DISABLED */ shadows: createPropertyDescriptor_default("shadows"), /** * Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this wall will be displayed. * @memberof WallGraphics.prototype * @type {Property|undefined} */ distanceDisplayCondition: createPropertyDescriptor_default( "distanceDisplayCondition" ) }); WallGraphics.prototype.clone = function(result) { if (!defined_default(result)) { return new WallGraphics(this); } result.show = this.show; result.positions = this.positions; result.minimumHeights = this.minimumHeights; result.maximumHeights = this.maximumHeights; result.granularity = this.granularity; result.fill = this.fill; result.material = this.material; result.outline = this.outline; result.outlineColor = this.outlineColor; result.outlineWidth = this.outlineWidth; result.shadows = this.shadows; result.distanceDisplayCondition = this.distanceDisplayCondition; return result; }; WallGraphics.prototype.merge = function(source) { if (!defined_default(source)) { throw new DeveloperError_default("source is required."); } this.show = defaultValue_default(this.show, source.show); this.positions = defaultValue_default(this.positions, source.positions); this.minimumHeights = defaultValue_default( this.minimumHeights, source.minimumHeights ); this.maximumHeights = defaultValue_default( this.maximumHeights, source.maximumHeights ); this.granularity = defaultValue_default(this.granularity, source.granularity); this.fill = defaultValue_default(this.fill, source.fill); this.material = defaultValue_default(this.material, source.material); this.outline = defaultValue_default(this.outline, source.outline); this.outlineColor = defaultValue_default(this.outlineColor, source.outlineColor); this.outlineWidth = defaultValue_default(this.outlineWidth, source.outlineWidth); this.shadows = defaultValue_default(this.shadows, source.shadows); this.distanceDisplayCondition = defaultValue_default( this.distanceDisplayCondition, source.distanceDisplayCondition ); }; var WallGraphics_default = WallGraphics; // packages/engine/Source/DataSources/Entity.js var cartoScratch = new Cartographic_default(); function createConstantPositionProperty(value) { return new ConstantPositionProperty_default(value); } function createPositionPropertyDescriptor(name) { return createPropertyDescriptor_default( name, void 0, createConstantPositionProperty ); } function createPropertyTypeDescriptor(name, Type) { return createPropertyDescriptor_default(name, void 0, function(value) { if (value instanceof Type) { return value; } return new Type(value); }); } function Entity(options) { options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT); let id = options.id; if (!defined_default(id)) { id = createGuid_default(); } this._availability = void 0; this._id = id; this._definitionChanged = new Event_default(); this._name = options.name; this._show = defaultValue_default(options.show, true); this._parent = void 0; this._propertyNames = [ "billboard", "box", "corridor", "cylinder", "description", "ellipse", // "ellipsoid", "label", "model", "tileset", "orientation", "path", "plane", "point", "polygon", // "polyline", "polylineVolume", "position", "properties", "rectangle", "viewFrom", "wall" ]; this._billboard = void 0; this._billboardSubscription = void 0; this._box = void 0; this._boxSubscription = void 0; this._corridor = void 0; this._corridorSubscription = void 0; this._cylinder = void 0; this._cylinderSubscription = void 0; this._description = void 0; this._descriptionSubscription = void 0; this._ellipse = void 0; this._ellipseSubscription = void 0; this._ellipsoid = void 0; this._ellipsoidSubscription = void 0; this._label = void 0; this._labelSubscription = void 0; this._model = void 0; this._modelSubscription = void 0; this._tileset = void 0; this._tilesetSubscription = void 0; this._orientation = void 0; this._orientationSubscription = void 0; this._path = void 0; this._pathSubscription = void 0; this._plane = void 0; this._planeSubscription = void 0; this._point = void 0; this._pointSubscription = void 0; this._polygon = void 0; this._polygonSubscription = void 0; this._polyline = void 0; this._polylineSubscription = void 0; this._polylineVolume = void 0; this._polylineVolumeSubscription = void 0; this._position = void 0; this._positionSubscription = void 0; this._properties = void 0; this._propertiesSubscription = void 0; this._rectangle = void 0; this._rectangleSubscription = void 0; this._viewFrom = void 0; this._viewFromSubscription = void 0; this._wall = void 0; this._wallSubscription = void 0; this._children = []; this.entityCollection = void 0; this.parent = options.parent; this.merge(options); } function updateShow(entity, children, isShowing) { const length3 = children.length; for (let i = 0; i < length3; i++) { const child = children[i]; const childShow = child._show; const oldValue2 = !isShowing && childShow; const newValue = isShowing && childShow; if (oldValue2 !== newValue) { updateShow(child, child._children, isShowing); } } entity._definitionChanged.raiseEvent( entity, "isShowing", isShowing, !isShowing ); } Object.defineProperties(Entity.prototype, { /** * The availability, if any, associated with this object. * If availability is undefined, it is assumed that this object's * other properties will return valid data for any provided time. * If availability exists, the objects other properties will only * provide valid data if queried within the given interval. * @memberof Entity.prototype * @type {TimeIntervalCollection|undefined} */ availability: createRawPropertyDescriptor_default("availability"), /** * Gets the unique ID associated with this object. * @memberof Entity.prototype * @type {string} */ id: { get: function() { return this._id; } }, /** * Gets the event that is raised whenever a property or sub-property is changed or modified. * @memberof Entity.prototype * * @type {Event} * @readonly */ definitionChanged: { get: function() { return this._definitionChanged; } }, /** * Gets or sets the name of the object. The name is intended for end-user * consumption and does not need to be unique. * @memberof Entity.prototype * @type {string|undefined} */ name: createRawPropertyDescriptor_default("name"), /** * Gets or sets whether this entity should be displayed. When set to true, * the entity is only displayed if the parent entity's show property is also true. * @memberof Entity.prototype * @type {boolean} */ show: { get: function() { return this._show; }, set: function(value) { if (!defined_default(value)) { throw new DeveloperError_default("value is required."); } if (value === this._show) { return; } const wasShowing = this.isShowing; this._show = value; const isShowing = this.isShowing; if (wasShowing !== isShowing) { updateShow(this, this._children, isShowing); } this._definitionChanged.raiseEvent(this, "show", value, !value); } }, /** * Gets whether this entity is being displayed, taking into account * the visibility of any ancestor entities. * @memberof Entity.prototype * @type {boolean} */ isShowing: { get: function() { return this._show && (!defined_default(this.entityCollection) || this.entityCollection.show) && (!defined_default(this._parent) || this._parent.isShowing); } }, /** * Gets or sets the parent object. * @memberof Entity.prototype * @type {Entity|undefined} */ parent: { get: function() { return this._parent; }, set: function(value) { const oldValue2 = this._parent; if (oldValue2 === value) { return; } const wasShowing = this.isShowing; if (defined_default(oldValue2)) { const index = oldValue2._children.indexOf(this); oldValue2._children.splice(index, 1); } this._parent = value; if (defined_default(value)) { value._children.push(this); } const isShowing = this.isShowing; if (wasShowing !== isShowing) { updateShow(this, this._children, isShowing); } this._definitionChanged.raiseEvent(this, "parent", value, oldValue2); } }, /** * Gets the names of all properties registered on this instance. * @memberof Entity.prototype * @type {string[]} */ propertyNames: { get: function() { return this._propertyNames; } }, /** * Gets or sets the billboard. * @memberof Entity.prototype * @type {BillboardGraphics|undefined} */ billboard: createPropertyTypeDescriptor("billboard", BillboardGraphics_default), /** * Gets or sets the box. * @memberof Entity.prototype * @type {BoxGraphics|undefined} */ box: createPropertyTypeDescriptor("box", BoxGraphics_default), /** * Gets or sets the corridor. * @memberof Entity.prototype * @type {CorridorGraphics|undefined} */ corridor: createPropertyTypeDescriptor("corridor", CorridorGraphics_default), /** * Gets or sets the cylinder. * @memberof Entity.prototype * @type {CylinderGraphics|undefined} */ cylinder: createPropertyTypeDescriptor("cylinder", CylinderGraphics_default), /** * Gets or sets the description. * @memberof Entity.prototype * @type {Property|undefined} */ description: createPropertyDescriptor_default("description"), /** * Gets or sets the ellipse. * @memberof Entity.prototype * @type {EllipseGraphics|undefined} */ ellipse: createPropertyTypeDescriptor("ellipse", EllipseGraphics_default), /** * Gets or sets the ellipsoid. * @memberof Entity.prototype * @type {EllipsoidGraphics|undefined} */ ellipsoid: createPropertyTypeDescriptor("ellipsoid", EllipsoidGraphics_default), /** * Gets or sets the label. * @memberof Entity.prototype * @type {LabelGraphics|undefined} */ label: createPropertyTypeDescriptor("label", LabelGraphics_default), /** * Gets or sets the model. * @memberof Entity.prototype * @type {ModelGraphics|undefined} */ model: createPropertyTypeDescriptor("model", ModelGraphics_default), /** * Gets or sets the tileset. * @memberof Entity.prototype * @type {Cesium3DTilesetGraphics|undefined} */ tileset: createPropertyTypeDescriptor("tileset", Cesium3DTilesetGraphics_default), /** * Gets or sets the orientation. * @memberof Entity.prototype * @type {Property|undefined} */ orientation: createPropertyDescriptor_default("orientation"), /** * Gets or sets the path. * @memberof Entity.prototype * @type {PathGraphics|undefined} */ path: createPropertyTypeDescriptor("path", PathGraphics_default), /** * Gets or sets the plane. * @memberof Entity.prototype * @type {PlaneGraphics|undefined} */ plane: createPropertyTypeDescriptor("plane", PlaneGraphics_default), /** * Gets or sets the point graphic. * @memberof Entity.prototype * @type {PointGraphics|undefined} */ point: createPropertyTypeDescriptor("point", PointGraphics_default), /** * Gets or sets the polygon. * @memberof Entity.prototype * @type {PolygonGraphics|undefined} */ polygon: createPropertyTypeDescriptor("polygon", PolygonGraphics_default), /** * Gets or sets the polyline. * @memberof Entity.prototype * @type {PolylineGraphics|undefined} */ polyline: createPropertyTypeDescriptor("polyline", PolylineGraphics_default), /** * Gets or sets the polyline volume. * @memberof Entity.prototype * @type {PolylineVolumeGraphics|undefined} */ polylineVolume: createPropertyTypeDescriptor( "polylineVolume", PolylineVolumeGraphics_default ), /** * Gets or sets the bag of arbitrary properties associated with this entity. * @memberof Entity.prototype * @type {PropertyBag|undefined} */ properties: createPropertyTypeDescriptor("properties", PropertyBag_default), /** * Gets or sets the position. * @memberof Entity.prototype * @type {PositionProperty|undefined} */ position: createPositionPropertyDescriptor("position"), /** * Gets or sets the rectangle. * @memberof Entity.prototype * @type {RectangleGraphics|undefined} */ rectangle: createPropertyTypeDescriptor("rectangle", RectangleGraphics_default), /** * Gets or sets the suggested initial offset when tracking this object. * The offset is typically defined in the east-north-up reference frame, * but may be another frame depending on the object's velocity. * @memberof Entity.prototype * @type {Property|undefined} */ viewFrom: createPropertyDescriptor_default("viewFrom"), /** * Gets or sets the wall. * @memberof Entity.prototype * @type {WallGraphics|undefined} */ wall: createPropertyTypeDescriptor("wall", WallGraphics_default) }); Entity.prototype.isAvailable = function(time) { if (!defined_default(time)) { throw new DeveloperError_default("time is required."); } const availability = this._availability; return !defined_default(availability) || availability.contains(time); }; Entity.prototype.addProperty = function(propertyName) { const propertyNames = this._propertyNames; if (!defined_default(propertyName)) { throw new DeveloperError_default("propertyName is required."); } if (propertyNames.indexOf(propertyName) !== -1) { throw new DeveloperError_default( `${propertyName} is already a registered property.` ); } if (propertyName in this) { throw new DeveloperError_default(`${propertyName} is a reserved property name.`); } propertyNames.push(propertyName); Object.defineProperty( this, propertyName, createRawPropertyDescriptor_default(propertyName, true) ); }; Entity.prototype.removeProperty = function(propertyName) { const propertyNames = this._propertyNames; const index = propertyNames.indexOf(propertyName); if (!defined_default(propertyName)) { throw new DeveloperError_default("propertyName is required."); } if (index === -1) { throw new DeveloperError_default(`${propertyName} is not a registered property.`); } this._propertyNames.splice(index, 1); delete this[propertyName]; }; Entity.prototype.merge = function(source) { if (!defined_default(source)) { throw new DeveloperError_default("source is required."); } this.name = defaultValue_default(this.name, source.name); this.availability = defaultValue_default(this.availability, source.availability); const propertyNames = this._propertyNames; const sourcePropertyNames = defined_default(source._propertyNames) ? source._propertyNames : Object.keys(source); const propertyNamesLength = sourcePropertyNames.length; for (let i = 0; i < propertyNamesLength; i++) { const name = sourcePropertyNames[i]; if (name === "parent" || name === "name" || name === "availability" || name === "children") { continue; } const targetProperty = this[name]; const sourceProperty = source[name]; if (!defined_default(targetProperty) && propertyNames.indexOf(name) === -1) { this.addProperty(name); } if (defined_default(sourceProperty)) { if (defined_default(targetProperty)) { if (defined_default(targetProperty.merge)) { targetProperty.merge(sourceProperty); } } else if (defined_default(sourceProperty.merge) && defined_default(sourceProperty.clone)) { this[name] = sourceProperty.clone(); } else { this[name] = sourceProperty; } } } }; var matrix3Scratch2 = new Matrix3_default(); var positionScratch2 = new Cartesian3_default(); var orientationScratch = new Quaternion_default(); Entity.prototype.computeModelMatrix = function(time, result) { Check_default.typeOf.object("time", time); const position = Property_default.getValueOrUndefined( this._position, time, positionScratch2 ); if (!defined_default(position)) { return void 0; } const orientation = Property_default.getValueOrUndefined( this._orientation, time, orientationScratch ); if (!defined_default(orientation)) { result = Transforms_default.eastNorthUpToFixedFrame(position, void 0, result); } else { result = Matrix4_default.fromRotationTranslation( Matrix3_default.fromQuaternion(orientation, matrix3Scratch2), position, result ); } return result; }; Entity.prototype.computeModelMatrixForHeightReference = function(time, heightReferenceProperty, heightOffset, ellipsoid, result) { Check_default.typeOf.object("time", time); const heightReference = Property_default.getValueOrDefault( heightReferenceProperty, time, HeightReference_default.NONE ); let position = Property_default.getValueOrUndefined( this._position, time, positionScratch2 ); if (heightReference === HeightReference_default.NONE || !defined_default(position) || Cartesian3_default.equalsEpsilon(position, Cartesian3_default.ZERO, Math_default.EPSILON8)) { return this.computeModelMatrix(time, result); } const carto = ellipsoid.cartesianToCartographic(position, cartoScratch); if (heightReference === HeightReference_default.CLAMP_TO_GROUND) { carto.height = heightOffset; } else { carto.height += heightOffset; } position = ellipsoid.cartographicToCartesian(carto, position); const orientation = Property_default.getValueOrUndefined( this._orientation, time, orientationScratch ); if (!defined_default(orientation)) { result = Transforms_default.eastNorthUpToFixedFrame(position, void 0, result); } else { result = Matrix4_default.fromRotationTranslation( Matrix3_default.fromQuaternion(orientation, matrix3Scratch2), position, result ); } return result; }; Entity.supportsMaterialsforEntitiesOnTerrain = function(scene) { return GroundPrimitive_default.supportsMaterials(scene); }; Entity.supportsPolylinesOnTerrain = function(scene) { return GroundPolylinePrimitive_default.isSupported(scene); }; var Entity_default = Entity; // packages/engine/Source/DataSources/GeometryUpdater.js var defaultMaterial = new ColorMaterialProperty_default(Color_default.WHITE); var defaultShow = new ConstantProperty_default(true); var defaultFill = new ConstantProperty_default(true); var defaultOutline = new ConstantProperty_default(false); var defaultOutlineColor = new ConstantProperty_default(Color_default.BLACK); var defaultShadows = new ConstantProperty_default(ShadowMode_default.DISABLED); var defaultDistanceDisplayCondition = new ConstantProperty_default( new DistanceDisplayCondition_default() ); var defaultClassificationType = new ConstantProperty_default(ClassificationType_default.BOTH); function GeometryUpdater(options) { Check_default.defined("options.entity", options.entity); Check_default.defined("options.scene", options.scene); Check_default.defined("options.geometryOptions", options.geometryOptions); Check_default.defined("options.geometryPropertyName", options.geometryPropertyName); Check_default.defined("options.observedPropertyNames", options.observedPropertyNames); const entity = options.entity; const geometryPropertyName = options.geometryPropertyName; this._entity = entity; this._scene = options.scene; this._fillEnabled = false; this._isClosed = false; this._onTerrain = false; this._dynamic = false; this._outlineEnabled = false; this._geometryChanged = new Event_default(); this._showProperty = void 0; this._materialProperty = void 0; this._showOutlineProperty = void 0; this._outlineColorProperty = void 0; this._outlineWidth = 1; this._shadowsProperty = void 0; this._distanceDisplayConditionProperty = void 0; this._classificationTypeProperty = void 0; this._options = options.geometryOptions; this._geometryPropertyName = geometryPropertyName; this._id = `${geometryPropertyName}-${entity.id}`; this._observedPropertyNames = options.observedPropertyNames; this._supportsMaterialsforEntitiesOnTerrain = Entity_default.supportsMaterialsforEntitiesOnTerrain( options.scene ); } Object.defineProperties(GeometryUpdater.prototype, { /** * Gets the unique ID associated with this updater * @memberof GeometryUpdater.prototype * @type {string} * @readonly */ id: { get: function() { return this._id; } }, /** * Gets the entity associated with this geometry. * @memberof GeometryUpdater.prototype * * @type {Entity} * @readonly */ entity: { get: function() { return this._entity; } }, /** * Gets a value indicating if the geometry has a fill component. * @memberof GeometryUpdater.prototype * * @type {boolean} * @readonly */ fillEnabled: { get: function() { return this._fillEnabled; } }, /** * Gets a value indicating if fill visibility varies with simulation time. * @memberof GeometryUpdater.prototype * * @type {boolean} * @readonly */ hasConstantFill: { get: function() { return !this._fillEnabled || !defined_default(this._entity.availability) && Property_default.isConstant(this._showProperty) && Property_default.isConstant(this._fillProperty); } }, /** * Gets the material property used to fill the geometry. * @memberof GeometryUpdater.prototype * * @type {MaterialProperty} * @readonly */ fillMaterialProperty: { get: function() { return this._materialProperty; } }, /** * Gets a value indicating if the geometry has an outline component. * @memberof GeometryUpdater.prototype * * @type {boolean} * @readonly */ outlineEnabled: { get: function() { return this._outlineEnabled; } }, /** * Gets a value indicating if the geometry has an outline component. * @memberof GeometryUpdater.prototype * * @type {boolean} * @readonly */ hasConstantOutline: { get: function() { return !this._outlineEnabled || !defined_default(this._entity.availability) && Property_default.isConstant(this._showProperty) && Property_default.isConstant(this._showOutlineProperty); } }, /** * Gets the {@link Color} property for the geometry outline. * @memberof GeometryUpdater.prototype * * @type {Property} * @readonly */ outlineColorProperty: { get: function() { return this._outlineColorProperty; } }, /** * Gets the constant with of the geometry outline, in pixels. * This value is only valid if isDynamic is false. * @memberof GeometryUpdater.prototype * * @type {number} * @readonly */ outlineWidth: { get: function() { return this._outlineWidth; } }, /** * Gets the property specifying whether the geometry * casts or receives shadows from light sources. * @memberof GeometryUpdater.prototype * * @type {Property} * @readonly */ shadowsProperty: { get: function() { return this._shadowsProperty; } }, /** * Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this geometry will be displayed. * @memberof GeometryUpdater.prototype * * @type {Property} * @readonly */ distanceDisplayConditionProperty: { get: function() { return this._distanceDisplayConditionProperty; } }, /** * Gets or sets the {@link ClassificationType} Property specifying if this geometry will classify terrain, 3D Tiles, or both when on the ground. * @memberof GeometryUpdater.prototype * * @type {Property} * @readonly */ classificationTypeProperty: { get: function() { return this._classificationTypeProperty; } }, /** * Gets a value indicating if the geometry is time-varying. * If true, all visualization is delegated to a DynamicGeometryUpdater * returned by GeometryUpdater#createDynamicUpdater. * @memberof GeometryUpdater.prototype * * @type {boolean} * @readonly */ isDynamic: { get: function() { return this._dynamic; } }, /** * Gets a value indicating if the geometry is closed. * This property is only valid for static geometry. * @memberof GeometryUpdater.prototype * * @type {boolean} * @readonly */ isClosed: { get: function() { return this._isClosed; } }, /** * Gets a value indicating if the geometry should be drawn on terrain. * @memberof EllipseGeometryUpdater.prototype * * @type {boolean} * @readonly */ onTerrain: { get: function() { return this._onTerrain; } }, /** * Gets an event that is raised whenever the public properties * of this updater change. * @memberof GeometryUpdater.prototype * * @type {boolean} * @readonly */ geometryChanged: { get: function() { return this._geometryChanged; } } }); GeometryUpdater.prototype.isOutlineVisible = function(time) { const entity = this._entity; const visible = this._outlineEnabled && entity.isAvailable(time) && this._showProperty.getValue(time) && this._showOutlineProperty.getValue(time); return defaultValue_default(visible, false); }; GeometryUpdater.prototype.isFilled = function(time) { const entity = this._entity; const visible = this._fillEnabled && entity.isAvailable(time) && this._showProperty.getValue(time) && this._fillProperty.getValue(time); return defaultValue_default(visible, false); }; GeometryUpdater.prototype.createFillGeometryInstance = DeveloperError_default.throwInstantiationError; GeometryUpdater.prototype.createOutlineGeometryInstance = DeveloperError_default.throwInstantiationError; GeometryUpdater.prototype.isDestroyed = function() { return false; }; GeometryUpdater.prototype.destroy = function() { destroyObject_default(this); }; GeometryUpdater.prototype._isHidden = function(entity, geometry) { const show = geometry.show; return defined_default(show) && show.isConstant && !show.getValue(Iso8601_default.MINIMUM_VALUE); }; GeometryUpdater.prototype._isOnTerrain = function(entity, geometry) { return false; }; GeometryUpdater.prototype._getIsClosed = function(options) { return true; }; GeometryUpdater.prototype._isDynamic = DeveloperError_default.throwInstantiationError; GeometryUpdater.prototype._setStaticOptions = DeveloperError_default.throwInstantiationError; GeometryUpdater.prototype._onEntityPropertyChanged = function(entity, propertyName, newValue, oldValue2) { if (this._observedPropertyNames.indexOf(propertyName) === -1) { return; } const geometry = this._entity[this._geometryPropertyName]; if (!defined_default(geometry)) { if (this._fillEnabled || this._outlineEnabled) { this._fillEnabled = false; this._outlineEnabled = false; this._geometryChanged.raiseEvent(this); } return; } const fillProperty = geometry.fill; const fillEnabled = defined_default(fillProperty) && fillProperty.isConstant ? fillProperty.getValue(Iso8601_default.MINIMUM_VALUE) : true; const outlineProperty = geometry.outline; let outlineEnabled = defined_default(outlineProperty); if (outlineEnabled && outlineProperty.isConstant) { outlineEnabled = outlineProperty.getValue(Iso8601_default.MINIMUM_VALUE); } if (!fillEnabled && !outlineEnabled) { if (this._fillEnabled || this._outlineEnabled) { this._fillEnabled = false; this._outlineEnabled = false; this._geometryChanged.raiseEvent(this); } return; } const show = geometry.show; if (this._isHidden(entity, geometry)) { if (this._fillEnabled || this._outlineEnabled) { this._fillEnabled = false; this._outlineEnabled = false; this._geometryChanged.raiseEvent(this); } return; } this._materialProperty = defaultValue_default(geometry.material, defaultMaterial); this._fillProperty = defaultValue_default(fillProperty, defaultFill); this._showProperty = defaultValue_default(show, defaultShow); this._showOutlineProperty = defaultValue_default(geometry.outline, defaultOutline); this._outlineColorProperty = outlineEnabled ? defaultValue_default(geometry.outlineColor, defaultOutlineColor) : void 0; this._shadowsProperty = defaultValue_default(geometry.shadows, defaultShadows); this._distanceDisplayConditionProperty = defaultValue_default( geometry.distanceDisplayCondition, defaultDistanceDisplayCondition ); this._classificationTypeProperty = defaultValue_default( geometry.classificationType, defaultClassificationType ); this._fillEnabled = fillEnabled; const onTerrain = this._isOnTerrain(entity, geometry) && (this._supportsMaterialsforEntitiesOnTerrain || this._materialProperty instanceof ColorMaterialProperty_default); if (outlineEnabled && onTerrain) { oneTimeWarning_default(oneTimeWarning_default.geometryOutlines); outlineEnabled = false; } this._onTerrain = onTerrain; this._outlineEnabled = outlineEnabled; if (this._isDynamic(entity, geometry)) { if (!this._dynamic) { this._dynamic = true; this._geometryChanged.raiseEvent(this); } } else { this._setStaticOptions(entity, geometry); this._isClosed = this._getIsClosed(this._options); const outlineWidth = geometry.outlineWidth; this._outlineWidth = defined_default(outlineWidth) ? outlineWidth.getValue(Iso8601_default.MINIMUM_VALUE) : 1; this._dynamic = false; this._geometryChanged.raiseEvent(this); } }; GeometryUpdater.prototype.createDynamicUpdater = function(primitives, groundPrimitives) { Check_default.defined("primitives", primitives); Check_default.defined("groundPrimitives", groundPrimitives); if (!this._dynamic) { throw new DeveloperError_default( "This instance does not represent dynamic geometry." ); } return new this.constructor.DynamicGeometryUpdater( this, primitives, groundPrimitives ); }; var GeometryUpdater_default = GeometryUpdater; // packages/engine/Source/DataSources/CallbackProperty.js function CallbackProperty(callback, isConstant) { this._callback = void 0; this._isConstant = void 0; this._definitionChanged = new Event_default(); this.setCallback(callback, isConstant); } Object.defineProperties(CallbackProperty.prototype, { /** * Gets a value indicating if this property is constant. * @memberof CallbackProperty.prototype * * @type {boolean} * @readonly */ isConstant: { get: function() { return this._isConstant; } }, /** * Gets the event that is raised whenever the definition of this property changes. * The definition is changed whenever setCallback is called. * @memberof CallbackProperty.prototype * * @type {Event} * @readonly */ definitionChanged: { get: function() { return this._definitionChanged; } } }); CallbackProperty.prototype.getValue = function(time, result) { return this._callback(time, result); }; CallbackProperty.prototype.setCallback = function(callback, isConstant) { if (!defined_default(callback)) { throw new DeveloperError_default("callback is required."); } if (!defined_default(isConstant)) { throw new DeveloperError_default("isConstant is required."); } const changed = this._callback !== callback || this._isConstant !== isConstant; this._callback = callback; this._isConstant = isConstant; if (changed) { this._definitionChanged.raiseEvent(this); } }; CallbackProperty.prototype.equals = function(other) { return this === other || other instanceof CallbackProperty && this._callback === other._callback && this._isConstant === other._isConstant; }; var CallbackProperty_default = CallbackProperty; // packages/engine/Source/DataSources/TerrainOffsetProperty.js var scratchPosition = new Cartesian3_default(); var scratchCarto = new Cartographic_default(); function TerrainOffsetProperty(scene, positionProperty, heightReferenceProperty, extrudedHeightReferenceProperty) { Check_default.defined("scene", scene); Check_default.defined("positionProperty", positionProperty); this._scene = scene; this._heightReference = heightReferenceProperty; this._extrudedHeightReference = extrudedHeightReferenceProperty; this._positionProperty = positionProperty; this._position = new Cartesian3_default(); this._cartographicPosition = new Cartographic_default(); this._normal = new Cartesian3_default(); this._definitionChanged = new Event_default(); this._terrainHeight = 0; this._removeCallbackFunc = void 0; this._removeEventListener = void 0; this._removeModeListener = void 0; const that = this; if (defined_default(scene.globe)) { this._removeEventListener = scene.terrainProviderChanged.addEventListener( function() { that._updateClamping(); } ); this._removeModeListener = scene.morphComplete.addEventListener( function() { that._updateClamping(); } ); } if (positionProperty.isConstant) { const position = positionProperty.getValue( Iso8601_default.MINIMUM_VALUE, scratchPosition ); if (!defined_default(position) || Cartesian3_default.equals(position, Cartesian3_default.ZERO) || !defined_default(scene.globe)) { return; } this._position = Cartesian3_default.clone(position, this._position); this._updateClamping(); this._normal = scene.globe.ellipsoid.geodeticSurfaceNormal( position, this._normal ); } } Object.defineProperties(TerrainOffsetProperty.prototype, { /** * Gets a value indicating if this property is constant. * @memberof TerrainOffsetProperty.prototype * * @type {boolean} * @readonly */ isConstant: { get: function() { return false; } }, /** * Gets the event that is raised whenever the definition of this property changes. * @memberof TerrainOffsetProperty.prototype * * @type {Event} * @readonly */ definitionChanged: { get: function() { return this._definitionChanged; } } }); TerrainOffsetProperty.prototype._updateClamping = function() { if (defined_default(this._removeCallbackFunc)) { this._removeCallbackFunc(); } const scene = this._scene; const globe = scene.globe; const position = this._position; if (!defined_default(globe) || Cartesian3_default.equals(position, Cartesian3_default.ZERO)) { this._terrainHeight = 0; return; } const ellipsoid = globe.ellipsoid; const surface = globe._surface; const that = this; const cartographicPosition = ellipsoid.cartesianToCartographic( position, this._cartographicPosition ); const height = globe.getHeight(cartographicPosition); if (defined_default(height)) { this._terrainHeight = height; } else { this._terrainHeight = 0; } function updateFunction(clampedPosition) { if (scene.mode === SceneMode_default.SCENE3D) { const carto = ellipsoid.cartesianToCartographic( clampedPosition, scratchCarto ); that._terrainHeight = carto.height; } else { that._terrainHeight = clampedPosition.x; } that.definitionChanged.raiseEvent(); } this._removeCallbackFunc = surface.updateHeight( cartographicPosition, updateFunction ); }; TerrainOffsetProperty.prototype.getValue = function(time, result) { const heightReference = Property_default.getValueOrDefault( this._heightReference, time, HeightReference_default.NONE ); const extrudedHeightReference = Property_default.getValueOrDefault( this._extrudedHeightReference, time, HeightReference_default.NONE ); if (heightReference === HeightReference_default.NONE && extrudedHeightReference !== HeightReference_default.RELATIVE_TO_GROUND) { this._position = Cartesian3_default.clone(Cartesian3_default.ZERO, this._position); return Cartesian3_default.clone(Cartesian3_default.ZERO, result); } if (this._positionProperty.isConstant) { return Cartesian3_default.multiplyByScalar( this._normal, this._terrainHeight, result ); } const scene = this._scene; const position = this._positionProperty.getValue(time, scratchPosition); if (!defined_default(position) || Cartesian3_default.equals(position, Cartesian3_default.ZERO) || !defined_default(scene.globe)) { return Cartesian3_default.clone(Cartesian3_default.ZERO, result); } if (Cartesian3_default.equalsEpsilon(this._position, position, Math_default.EPSILON10)) { return Cartesian3_default.multiplyByScalar( this._normal, this._terrainHeight, result ); } this._position = Cartesian3_default.clone(position, this._position); this._updateClamping(); const normal2 = scene.globe.ellipsoid.geodeticSurfaceNormal( position, this._normal ); return Cartesian3_default.multiplyByScalar(normal2, this._terrainHeight, result); }; TerrainOffsetProperty.prototype.isDestroyed = function() { return false; }; TerrainOffsetProperty.prototype.destroy = function() { if (defined_default(this._removeEventListener)) { this._removeEventListener(); } if (defined_default(this._removeModeListener)) { this._removeModeListener(); } if (defined_default(this._removeCallbackFunc)) { this._removeCallbackFunc(); } return destroyObject_default(this); }; var TerrainOffsetProperty_default = TerrainOffsetProperty; // packages/engine/Source/DataSources/heightReferenceOnEntityPropertyChanged.js function heightReferenceOnEntityPropertyChanged(entity, propertyName, newValue, oldValue2) { GeometryUpdater_default.prototype._onEntityPropertyChanged.call( this, entity, propertyName, newValue, oldValue2 ); if (this._observedPropertyNames.indexOf(propertyName) === -1) { return; } const geometry = this._entity[this._geometryPropertyName]; if (!defined_default(geometry)) { return; } if (defined_default(this._terrainOffsetProperty)) { this._terrainOffsetProperty.destroy(); this._terrainOffsetProperty = void 0; } const heightReferenceProperty = geometry.heightReference; if (defined_default(heightReferenceProperty)) { const centerPosition = new CallbackProperty_default( this._computeCenter.bind(this), !this._dynamic ); this._terrainOffsetProperty = new TerrainOffsetProperty_default( this._scene, centerPosition, heightReferenceProperty ); } } var heightReferenceOnEntityPropertyChanged_default = heightReferenceOnEntityPropertyChanged; // packages/engine/Source/DataSources/BoxGeometryUpdater.js var defaultOffset = Cartesian3_default.ZERO; var offsetScratch4 = new Cartesian3_default(); var positionScratch3 = new Cartesian3_default(); var scratchColor = new Color_default(); function BoxGeometryOptions(entity) { this.id = entity; this.vertexFormat = void 0; this.dimensions = void 0; this.offsetAttribute = void 0; } function BoxGeometryUpdater(entity, scene) { GeometryUpdater_default.call(this, { entity, scene, geometryOptions: new BoxGeometryOptions(entity), geometryPropertyName: "box", observedPropertyNames: ["availability", "position", "orientation", "box"] }); this._onEntityPropertyChanged(entity, "box", entity.box, void 0); } if (defined_default(Object.create)) { BoxGeometryUpdater.prototype = Object.create(GeometryUpdater_default.prototype); BoxGeometryUpdater.prototype.constructor = BoxGeometryUpdater; } Object.defineProperties(BoxGeometryUpdater.prototype, { /** * Gets the terrain offset property * @type {TerrainOffsetProperty} * @memberof BoxGeometryUpdater.prototype * @readonly * @private */ terrainOffsetProperty: { get: function() { return this._terrainOffsetProperty; } } }); BoxGeometryUpdater.prototype.createFillGeometryInstance = function(time) { Check_default.defined("time", time); if (!this._fillEnabled) { throw new DeveloperError_default( "This instance does not represent a filled geometry." ); } const entity = this._entity; const isAvailable = entity.isAvailable(time); const show = new ShowGeometryInstanceAttribute_default( isAvailable && entity.isShowing && this._showProperty.getValue(time) && this._fillProperty.getValue(time) ); const distanceDisplayCondition = this._distanceDisplayConditionProperty.getValue( time ); const distanceDisplayConditionAttribute = DistanceDisplayConditionGeometryInstanceAttribute_default.fromDistanceDisplayCondition( distanceDisplayCondition ); const attributes = { show, distanceDisplayCondition: distanceDisplayConditionAttribute, color: void 0, offset: void 0 }; if (this._materialProperty instanceof ColorMaterialProperty_default) { let currentColor; if (defined_default(this._materialProperty.color) && (this._materialProperty.color.isConstant || isAvailable)) { currentColor = this._materialProperty.color.getValue(time, scratchColor); } if (!defined_default(currentColor)) { currentColor = Color_default.WHITE; } attributes.color = ColorGeometryInstanceAttribute_default.fromColor(currentColor); } if (defined_default(this._options.offsetAttribute)) { attributes.offset = OffsetGeometryInstanceAttribute_default.fromCartesian3( Property_default.getValueOrDefault( this._terrainOffsetProperty, time, defaultOffset, offsetScratch4 ) ); } return new GeometryInstance_default({ id: entity, geometry: BoxGeometry_default.fromDimensions(this._options), modelMatrix: entity.computeModelMatrixForHeightReference( time, entity.box.heightReference, this._options.dimensions.z * 0.5, this._scene.mapProjection.ellipsoid ), attributes }); }; BoxGeometryUpdater.prototype.createOutlineGeometryInstance = function(time) { Check_default.defined("time", time); if (!this._outlineEnabled) { throw new DeveloperError_default( "This instance does not represent an outlined geometry." ); } const entity = this._entity; const isAvailable = entity.isAvailable(time); const outlineColor = Property_default.getValueOrDefault( this._outlineColorProperty, time, Color_default.BLACK, scratchColor ); const distanceDisplayCondition = this._distanceDisplayConditionProperty.getValue( time ); const attributes = { show: new ShowGeometryInstanceAttribute_default( isAvailable && entity.isShowing && this._showProperty.getValue(time) && this._showOutlineProperty.getValue(time) ), color: ColorGeometryInstanceAttribute_default.fromColor(outlineColor), distanceDisplayCondition: DistanceDisplayConditionGeometryInstanceAttribute_default.fromDistanceDisplayCondition( distanceDisplayCondition ), offset: void 0 }; if (defined_default(this._options.offsetAttribute)) { attributes.offset = OffsetGeometryInstanceAttribute_default.fromCartesian3( Property_default.getValueOrDefault( this._terrainOffsetProperty, time, defaultOffset, offsetScratch4 ) ); } return new GeometryInstance_default({ id: entity, geometry: BoxOutlineGeometry_default.fromDimensions(this._options), modelMatrix: entity.computeModelMatrixForHeightReference( time, entity.box.heightReference, this._options.dimensions.z * 0.5, this._scene.mapProjection.ellipsoid ), attributes }); }; BoxGeometryUpdater.prototype._computeCenter = function(time, result) { return Property_default.getValueOrUndefined(this._entity.position, time, result); }; BoxGeometryUpdater.prototype._isHidden = function(entity, box) { return !defined_default(box.dimensions) || !defined_default(entity.position) || GeometryUpdater_default.prototype._isHidden.call(this, entity, box); }; BoxGeometryUpdater.prototype._isDynamic = function(entity, box) { return !entity.position.isConstant || !Property_default.isConstant(entity.orientation) || !box.dimensions.isConstant || !Property_default.isConstant(box.outlineWidth); }; BoxGeometryUpdater.prototype._setStaticOptions = function(entity, box) { const heightReference = Property_default.getValueOrDefault( box.heightReference, Iso8601_default.MINIMUM_VALUE, HeightReference_default.NONE ); const options = this._options; options.vertexFormat = this._materialProperty instanceof ColorMaterialProperty_default ? PerInstanceColorAppearance_default.VERTEX_FORMAT : MaterialAppearance_default.MaterialSupport.TEXTURED.vertexFormat; options.dimensions = box.dimensions.getValue( Iso8601_default.MINIMUM_VALUE, options.dimensions ); options.offsetAttribute = heightReference !== HeightReference_default.NONE ? GeometryOffsetAttribute_default.ALL : void 0; }; BoxGeometryUpdater.prototype._onEntityPropertyChanged = heightReferenceOnEntityPropertyChanged_default; BoxGeometryUpdater.DynamicGeometryUpdater = DynamicBoxGeometryUpdater; function DynamicBoxGeometryUpdater(geometryUpdater, primitives, groundPrimitives) { DynamicGeometryUpdater_default.call( this, geometryUpdater, primitives, groundPrimitives ); } if (defined_default(Object.create)) { DynamicBoxGeometryUpdater.prototype = Object.create( DynamicGeometryUpdater_default.prototype ); DynamicBoxGeometryUpdater.prototype.constructor = DynamicBoxGeometryUpdater; } DynamicBoxGeometryUpdater.prototype._isHidden = function(entity, box, time) { const position = Property_default.getValueOrUndefined( entity.position, time, positionScratch3 ); const dimensions = this._options.dimensions; return !defined_default(position) || !defined_default(dimensions) || DynamicGeometryUpdater_default.prototype._isHidden.call(this, entity, box, time); }; DynamicBoxGeometryUpdater.prototype._setOptions = function(entity, box, time) { const heightReference = Property_default.getValueOrDefault( box.heightReference, time, HeightReference_default.NONE ); const options = this._options; options.dimensions = Property_default.getValueOrUndefined( box.dimensions, time, options.dimensions ); options.offsetAttribute = heightReference !== HeightReference_default.NONE ? GeometryOffsetAttribute_default.ALL : void 0; }; var BoxGeometryUpdater_default = BoxGeometryUpdater; // packages/engine/Source/Core/Credit.js var import_dompurify = __toESM(require_purify(), 1); var nextCreditId = 0; var creditToId = {}; function Credit(html, showOnScreen) { Check_default.typeOf.string("html", html); let id; const key = html; if (defined_default(creditToId[key])) { id = creditToId[key]; } else { id = nextCreditId++; creditToId[key] = id; } showOnScreen = defaultValue_default(showOnScreen, false); this._id = id; this._html = html; this._showOnScreen = showOnScreen; this._element = void 0; } Object.defineProperties(Credit.prototype, { /** * The credit content * @memberof Credit.prototype * @type {string} * @readonly */ html: { get: function() { return this._html; } }, /** * @memberof Credit.prototype * @type {number} * @readonly * * @private */ id: { get: function() { return this._id; } }, /** * Whether the credit should be displayed on screen or in a lightbox * @memberof Credit.prototype * @type {boolean} */ showOnScreen: { get: function() { return this._showOnScreen; }, set: function(value) { this._showOnScreen = value; } }, /** * Gets the credit element * @memberof Credit.prototype * @type {HTMLElement} * @readonly */ element: { get: function() { if (!defined_default(this._element)) { const html = import_dompurify.default.sanitize(this._html); const div = document.createElement("div"); div._creditId = this._id; div.style.display = "inline"; div.innerHTML = html; const links = div.querySelectorAll("a"); for (let i = 0; i < links.length; i++) { links[i].setAttribute("target", "_blank"); } this._element = div; } return this._element; } } }); Credit.equals = function(left, right) { return left === right || defined_default(left) && defined_default(right) && left._id === right._id && left._showOnScreen === right._showOnScreen; }; Credit.prototype.equals = function(credit) { return Credit.equals(this, credit); }; Credit.getIonCredit = function(attribution) { const showOnScreen = defined_default(attribution.collapsible) && !attribution.collapsible; const credit = new Credit(attribution.html, showOnScreen); credit._isIon = credit.html.indexOf("ion-credit.png") !== -1; return credit; }; Credit.clone = function(credit) { if (defined_default(credit)) { return new Credit(credit.html, credit.showOnScreen); } }; var Credit_default = Credit; // packages/engine/Source/Shaders/OctahedralProjectionAtlasFS.js var OctahedralProjectionAtlasFS_default = "in vec2 v_textureCoordinates;\n\nuniform float originalSize;\nuniform sampler2D texture0;\nuniform sampler2D texture1;\nuniform sampler2D texture2;\nuniform sampler2D texture3;\nuniform sampler2D texture4;\nuniform sampler2D texture5;\n\nconst float yMipLevel1 = 1.0 - (1.0 / pow(2.0, 1.0));\nconst float yMipLevel2 = 1.0 - (1.0 / pow(2.0, 2.0));\nconst float yMipLevel3 = 1.0 - (1.0 / pow(2.0, 3.0));\nconst float yMipLevel4 = 1.0 - (1.0 / pow(2.0, 4.0));\n\nvoid main()\n{\n vec2 uv = v_textureCoordinates;\n vec2 textureSize = vec2(originalSize * 1.5 + 2.0, originalSize);\n vec2 pixel = 1.0 / textureSize;\n\n float mipLevel = 0.0;\n\n if (uv.x - pixel.x > (textureSize.y / textureSize.x))\n {\n mipLevel = 1.0;\n if (uv.y - pixel.y > yMipLevel1)\n {\n mipLevel = 2.0;\n if (uv.y - pixel.y * 3.0 > yMipLevel2)\n {\n mipLevel = 3.0;\n if (uv.y - pixel.y * 5.0 > yMipLevel3)\n {\n mipLevel = 4.0;\n if (uv.y - pixel.y * 7.0 > yMipLevel4)\n {\n mipLevel = 5.0;\n }\n }\n }\n }\n }\n\n if (mipLevel > 0.0)\n {\n float scale = pow(2.0, mipLevel);\n\n uv.y -= (pixel.y * (mipLevel - 1.0) * 2.0);\n uv.x *= ((textureSize.x - 2.0) / textureSize.y);\n\n uv.x -= 1.0 + pixel.x;\n uv.y -= (1.0 - (1.0 / pow(2.0, mipLevel - 1.0)));\n uv *= scale;\n }\n else\n {\n uv.x *= (textureSize.x / textureSize.y);\n }\n\n if(mipLevel == 0.0)\n {\n out_FragColor = texture(texture0, uv);\n }\n else if(mipLevel == 1.0)\n {\n out_FragColor = texture(texture1, uv);\n }\n else if(mipLevel == 2.0)\n {\n out_FragColor = texture(texture2, uv);\n }\n else if(mipLevel == 3.0)\n {\n out_FragColor = texture(texture3, uv);\n }\n else if(mipLevel == 4.0)\n {\n out_FragColor = texture(texture4, uv);\n }\n else if(mipLevel == 5.0)\n {\n out_FragColor = texture(texture5, uv);\n }\n else\n {\n out_FragColor = vec4(0.0);\n }\n}\n"; // packages/engine/Source/Shaders/OctahedralProjectionFS.js var OctahedralProjectionFS_default = "in vec3 v_cubeMapCoordinates;\nuniform samplerCube cubeMap;\n\nvoid main()\n{\n vec4 rgba = czm_textureCube(cubeMap, v_cubeMapCoordinates);\n #ifdef RGBA_NORMALIZED\n out_FragColor = vec4(rgba.rgb, 1.0);\n #else\n float m = rgba.a * 16.0;\n vec3 r = rgba.rgb * m;\n out_FragColor = vec4(r * r, 1.0);\n #endif\n}\n"; // packages/engine/Source/Shaders/OctahedralProjectionVS.js var OctahedralProjectionVS_default = "in vec4 position;\nin vec3 cubeMapCoordinates;\n\nout vec3 v_cubeMapCoordinates;\n\nvoid main()\n{\n gl_Position = position;\n v_cubeMapCoordinates = cubeMapCoordinates;\n}\n"; // packages/engine/Source/Scene/OctahedralProjectedCubeMap.js function OctahedralProjectedCubeMap(url2) { this._url = url2; this._cubeMapBuffers = void 0; this._cubeMaps = void 0; this._texture = void 0; this._mipTextures = void 0; this._va = void 0; this._sp = void 0; this._maximumMipmapLevel = void 0; this._loading = false; this._ready = false; this._errorEvent = new Event_default(); } Object.defineProperties(OctahedralProjectedCubeMap.prototype, { /** * The url to the KTX2 file containing the specular environment map and convoluted mipmaps. * @memberof OctahedralProjectedCubeMap.prototype * @type {string} * @readonly */ url: { get: function() { return this._url; } }, /** * Gets an event that is raised when encountering an asynchronous error. By subscribing * to the event, you will be notified of the error and can potentially recover from it. * @memberof OctahedralProjectedCubeMap.prototype * @type {Event} * @readonly */ errorEvent: { get: function() { return this._errorEvent; } }, /** * A texture containing all the packed convolutions. * @memberof OctahedralProjectedCubeMap.prototype * @type {Texture} * @readonly */ texture: { get: function() { return this._texture; } }, /** * The maximum number of mip levels. * @memberOf OctahedralProjectedCubeMap.prototype * @type {number} * @readonly */ maximumMipmapLevel: { get: function() { return this._maximumMipmapLevel; } }, /** * Determines if the texture atlas is complete and ready to use. * @memberof OctahedralProjectedCubeMap.prototype * @type {boolean} * @readonly */ ready: { get: function() { return this._ready; } } }); OctahedralProjectedCubeMap.isSupported = function(context) { return context.colorBufferHalfFloat && context.halfFloatingPointTexture || context.floatingPointTexture && context.colorBufferFloat; }; var v12 = new Cartesian3_default(1, 0, 0); var v22 = new Cartesian3_default(0, 0, 1); var v3 = new Cartesian3_default(-1, 0, 0); var v4 = new Cartesian3_default(0, 0, -1); var v5 = new Cartesian3_default(0, 1, 0); var v6 = new Cartesian3_default(0, -1, 0); var cubeMapCoordinates = [v5, v3, v22, v6, v12, v5, v4, v5, v5]; var length = cubeMapCoordinates.length; var flatCubeMapCoordinates = new Float32Array(length * 3); var offset = 0; for (let i = 0; i < length; ++i, offset += 3) { Cartesian3_default.pack(cubeMapCoordinates[i], flatCubeMapCoordinates, offset); } var flatPositions = new Float32Array([ -1, 1, // top left -1, 0, // left 0, 1, // top 0, 0, // center 1, 0, // right 1, 1, // top right 0, -1, // bottom -1, -1, // bottom left 1, -1 // bottom right ]); var indices = new Uint16Array([ 0, 1, 2, // top left, left, top, 2, 3, 1, // top, center, left, 7, 6, 1, // bottom left, bottom, left, 3, 6, 1, // center, bottom, left, 2, 5, 4, // top, top right, right, 3, 4, 2, // center, right, top, 4, 8, 6, // right, bottom right, bottom, 3, 4, 6 //center, right, bottom ]); function createVertexArray2(context) { const positionBuffer = Buffer_default.createVertexBuffer({ context, typedArray: flatPositions, usage: BufferUsage_default.STATIC_DRAW }); const cubeMapCoordinatesBuffer = Buffer_default.createVertexBuffer({ context, typedArray: flatCubeMapCoordinates, usage: BufferUsage_default.STATIC_DRAW }); const indexBuffer = Buffer_default.createIndexBuffer({ context, typedArray: indices, usage: BufferUsage_default.STATIC_DRAW, indexDatatype: IndexDatatype_default.UNSIGNED_SHORT }); const attributes = [ { index: 0, vertexBuffer: positionBuffer, componentsPerAttribute: 2, componentDatatype: ComponentDatatype_default.FLOAT }, { index: 1, vertexBuffer: cubeMapCoordinatesBuffer, componentsPerAttribute: 3, componentDatatype: ComponentDatatype_default.FLOAT } ]; return new VertexArray_default({ context, attributes, indexBuffer }); } function createUniformTexture(texture) { return function() { return texture; }; } function cleanupResources(map) { map._va = map._va && map._va.destroy(); map._sp = map._sp && map._sp.destroy(); let i; let length3; const cubeMaps = map._cubeMaps; if (defined_default(cubeMaps)) { length3 = cubeMaps.length; for (i = 0; i < length3; ++i) { cubeMaps[i].destroy(); } } const mipTextures = map._mipTextures; if (defined_default(mipTextures)) { length3 = mipTextures.length; for (i = 0; i < length3; ++i) { mipTextures[i].destroy(); } } map._va = void 0; map._sp = void 0; map._cubeMaps = void 0; map._cubeMapBuffers = void 0; map._mipTextures = void 0; } OctahedralProjectedCubeMap.prototype.update = function(frameState) { const context = frameState.context; if (!OctahedralProjectedCubeMap.isSupported(context)) { return; } if (defined_default(this._texture) && defined_default(this._va)) { cleanupResources(this); } if (defined_default(this._texture)) { return; } if (!defined_default(this._texture) && !this._loading) { const cachedTexture = frameState.context.textureCache.getTexture(this._url); if (defined_default(cachedTexture)) { cleanupResources(this); this._texture = cachedTexture; this._maximumMipmapLevel = this._texture.maximumMipmapLevel; this._ready = true; } } const cubeMapBuffers = this._cubeMapBuffers; if (!defined_default(cubeMapBuffers) && !this._loading) { const that = this; loadKTX2_default(this._url).then(function(buffers) { that._cubeMapBuffers = buffers; that._loading = false; }).catch(function(error) { if (that.isDestroyed()) { return; } that._errorEvent.raiseEvent(error); }); this._loading = true; } if (!defined_default(this._cubeMapBuffers)) { return; } const defines = []; let pixelDatatype = cubeMapBuffers[0].positiveX.pixelDatatype; if (!defined_default(pixelDatatype)) { pixelDatatype = context.halfFloatingPointTexture ? PixelDatatype_default.HALF_FLOAT : PixelDatatype_default.FLOAT; } else { defines.push("RGBA_NORMALIZED"); } const pixelFormat = PixelFormat_default.RGBA; const fs = new ShaderSource_default({ defines, sources: [OctahedralProjectionFS_default] }); this._va = createVertexArray2(context); this._sp = ShaderProgram_default.fromCache({ context, vertexShaderSource: OctahedralProjectionVS_default, fragmentShaderSource: fs, attributeLocations: { position: 0, cubeMapCoordinates: 1 } }); const length3 = Math.min(cubeMapBuffers.length, 6); this._maximumMipmapLevel = length3 - 1; const cubeMaps = this._cubeMaps = new Array(length3); const mipTextures = this._mipTextures = new Array(length3); const originalSize = cubeMapBuffers[0].positiveX.width * 2; const uniformMap2 = { originalSize: function() { return originalSize; } }; for (let i = 0; i < length3; ++i) { const positiveY = cubeMapBuffers[i].positiveY; cubeMapBuffers[i].positiveY = cubeMapBuffers[i].negativeY; cubeMapBuffers[i].negativeY = positiveY; const cubeMap = cubeMaps[i] = new CubeMap_default({ context, source: cubeMapBuffers[i], pixelDatatype }); const size = cubeMaps[i].width * 2; const mipTexture = mipTextures[i] = new Texture_default({ context, width: size, height: size, pixelDatatype, pixelFormat }); const command = new ComputeCommand_default({ vertexArray: this._va, shaderProgram: this._sp, uniformMap: { cubeMap: createUniformTexture(cubeMap) }, outputTexture: mipTexture, persists: true, owner: this }); frameState.commandList.push(command); uniformMap2[`texture${i}`] = createUniformTexture(mipTexture); } this._texture = new Texture_default({ context, width: originalSize * 1.5 + 2, // We add a 1 pixel border to avoid linear sampling artifacts. height: originalSize, pixelDatatype, pixelFormat }); this._texture.maximumMipmapLevel = this._maximumMipmapLevel; context.textureCache.addTexture(this._url, this._texture); const atlasCommand = new ComputeCommand_default({ fragmentShaderSource: OctahedralProjectionAtlasFS_default, uniformMap: uniformMap2, outputTexture: this._texture, persists: false, owner: this }); frameState.commandList.push(atlasCommand); this._ready = true; }; OctahedralProjectedCubeMap.prototype.isDestroyed = function() { return false; }; OctahedralProjectedCubeMap.prototype.destroy = function() { cleanupResources(this); this._texture = this._texture && this._texture.destroy(); return destroyObject_default(this); }; var OctahedralProjectedCubeMap_default = OctahedralProjectedCubeMap; // packages/engine/Source/Scene/ImageBasedLighting.js function ImageBasedLighting(options) { options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT); const imageBasedLightingFactor = defined_default(options.imageBasedLightingFactor) ? Cartesian2_default.clone(options.imageBasedLightingFactor) : new Cartesian2_default(1, 1); Check_default.typeOf.object( "options.imageBasedLightingFactor", imageBasedLightingFactor ); Check_default.typeOf.number.greaterThanOrEquals( "options.imageBasedLightingFactor.x", imageBasedLightingFactor.x, 0 ); Check_default.typeOf.number.lessThanOrEquals( "options.imageBasedLightingFactor.x", imageBasedLightingFactor.x, 1 ); Check_default.typeOf.number.greaterThanOrEquals( "options.imageBasedLightingFactor.y", imageBasedLightingFactor.y, 0 ); Check_default.typeOf.number.lessThanOrEquals( "options.imageBasedLightingFactor.y", imageBasedLightingFactor.y, 1 ); this._imageBasedLightingFactor = imageBasedLightingFactor; const luminanceAtZenith = defaultValue_default(options.luminanceAtZenith, 0.2); Check_default.typeOf.number("options.luminanceAtZenith", luminanceAtZenith); this._luminanceAtZenith = luminanceAtZenith; const sphericalHarmonicCoefficients = options.sphericalHarmonicCoefficients; if (defined_default(sphericalHarmonicCoefficients) && (!Array.isArray(sphericalHarmonicCoefficients) || sphericalHarmonicCoefficients.length !== 9)) { throw new DeveloperError_default( "options.sphericalHarmonicCoefficients must be an array of 9 Cartesian3 values." ); } this._sphericalHarmonicCoefficients = sphericalHarmonicCoefficients; this._specularEnvironmentMaps = options.specularEnvironmentMaps; this._specularEnvironmentMapAtlas = void 0; this._specularEnvironmentMapAtlasDirty = true; this._specularEnvironmentMapLoaded = false; this._previousSpecularEnvironmentMapLoaded = false; this._useDefaultSpecularMaps = false; this._useDefaultSphericalHarmonics = false; this._shouldRegenerateShaders = false; this._previousFrameNumber = void 0; this._previousImageBasedLightingFactor = Cartesian2_default.clone( imageBasedLightingFactor ); this._previousLuminanceAtZenith = luminanceAtZenith; this._previousSphericalHarmonicCoefficients = sphericalHarmonicCoefficients; this._removeErrorListener = void 0; } Object.defineProperties(ImageBasedLighting.prototype, { /** * Cesium adds lighting from the earth, sky, atmosphere, and star skybox. * This cartesian is used to scale the final diffuse and specular lighting * contribution from those sources to the final color. A value of 0.0 will * disable those light sources. * * @memberof ImageBasedLighting.prototype * * @type {Cartesian2} * @default Cartesian2(1.0, 1.0) */ imageBasedLightingFactor: { get: function() { return this._imageBasedLightingFactor; }, set: function(value) { Check_default.typeOf.object("imageBasedLightingFactor", value); Check_default.typeOf.number.greaterThanOrEquals( "imageBasedLightingFactor.x", value.x, 0 ); Check_default.typeOf.number.lessThanOrEquals( "imageBasedLightingFactor.x", value.x, 1 ); Check_default.typeOf.number.greaterThanOrEquals( "imageBasedLightingFactor.y", value.y, 0 ); Check_default.typeOf.number.lessThanOrEquals( "imageBasedLightingFactor.y", value.y, 1 ); this._previousImageBasedLightingFactor = Cartesian2_default.clone( this._imageBasedLightingFactor, this._previousImageBasedLightingFactor ); this._imageBasedLightingFactor = Cartesian2_default.clone( value, this._imageBasedLightingFactor ); } }, /** * The sun's luminance at the zenith in kilo candela per meter squared * to use for this model's procedural environment map. This is used when * {@link ImageBasedLighting#specularEnvironmentMaps} and {@link ImageBasedLighting#sphericalHarmonicCoefficients} * are not defined. * * @memberof ImageBasedLighting.prototype * * @type {number} * @default 0.2 */ luminanceAtZenith: { get: function() { return this._luminanceAtZenith; }, set: function(value) { this._previousLuminanceAtZenith = this._luminanceAtZenith; this._luminanceAtZenith = value; } }, /** * The third order spherical harmonic coefficients used for the diffuse color of image-based lighting. Whenundefined
, a diffuse irradiance
* computed from the atmosphere color is used.
*
* There are nine Cartesian3
coefficients.
* The order of the coefficients is: L0,0, L1,-1, L1,0, L1,1, L2,-2, L2,-1, L2,0, L2,1, L2,2
*
cmgen
tool of
* {@link https://github.com/google/filament/releases|Google's Filament project}. This will also generate a KTX file that can be
* supplied to {@link Model#specularEnvironmentMaps}.
*
* @memberof ImageBasedLighting.prototype
*
* @type {Cartesian3[]}
* @demo {@link https://sandcastle.cesium.com/index.html?src=Image-Based Lighting.html|Sandcastle Image Based Lighting Demo}
* @see {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf|An Efficient Representation for Irradiance Environment Maps}
*/
sphericalHarmonicCoefficients: {
get: function() {
return this._sphericalHarmonicCoefficients;
},
set: function(value) {
if (defined_default(value) && (!Array.isArray(value) || value.length !== 9)) {
throw new DeveloperError_default(
"sphericalHarmonicCoefficients must be an array of 9 Cartesian3 values."
);
}
this._previousSphericalHarmonicCoefficients = this._sphericalHarmonicCoefficients;
this._sphericalHarmonicCoefficients = value;
}
},
/**
* A URL to a KTX2 file that contains a cube map of the specular lighting and the convoluted specular mipmaps.
*
* @memberof ImageBasedLighting.prototype
* @demo {@link https://sandcastle.cesium.com/index.html?src=Image-Based Lighting.html|Sandcastle Image Based Lighting Demo}
* @type {string}
* @see ImageBasedLighting#sphericalHarmonicCoefficients
*/
specularEnvironmentMaps: {
get: function() {
return this._specularEnvironmentMaps;
},
set: function(value) {
if (value !== this._specularEnvironmentMaps) {
this._specularEnvironmentMapAtlasDirty = this._specularEnvironmentMapAtlasDirty || value !== this._specularEnvironmentMaps;
this._specularEnvironmentMapLoaded = false;
}
this._specularEnvironmentMaps = value;
}
},
/**
* Whether or not image-based lighting is enabled.
*
* @memberof ImageBasedLighting.prototype
* @type {boolean}
*
* @private
*/
enabled: {
get: function() {
return this._imageBasedLightingFactor.x > 0 || this._imageBasedLightingFactor.y > 0;
}
},
/**
* Whether or not the models that use this lighting should regenerate their shaders,
* based on the properties and resources have changed.
*
* @memberof ImageBasedLighting.prototype
* @type {boolean}
*
* @private
*/
shouldRegenerateShaders: {
get: function() {
return this._shouldRegenerateShaders;
}
},
/**
* Whether or not to use the default spherical harmonic coefficients.
*
* @memberof ImageBasedLighting.prototype
* @type {boolean}
*
* @private
*/
useDefaultSphericalHarmonics: {
get: function() {
return this._useDefaultSphericalHarmonics;
}
},
/**
* Whether or not the image-based lighting settings use spherical harmonic coefficients.
*
* @memberof ImageBasedLighting.prototype
* @type {boolean}
*
* @private
*/
useSphericalHarmonicCoefficients: {
get: function() {
return defined_default(this._sphericalHarmonicCoefficients) || this._useDefaultSphericalHarmonics;
}
},
/**
* The texture atlas for the specular environment maps.
*
* @memberof ImageBasedLighting.prototype
* @type {OctahedralProjectedCubeMap}
*
* @private
*/
specularEnvironmentMapAtlas: {
get: function() {
return this._specularEnvironmentMapAtlas;
}
},
/**
* Whether or not to use the default specular environment maps.
*
* @memberof ImageBasedLighting.prototype
* @type {boolean}
*
* @private
*/
useDefaultSpecularMaps: {
get: function() {
return this._useDefaultSpecularMaps;
}
},
/**
* Whether or not the image-based lighting settings use specular environment maps.
*
* @memberof ImageBasedLighting.prototype
* @type {boolean}
*
* @private
*/
useSpecularEnvironmentMaps: {
get: function() {
return defined_default(this._specularEnvironmentMapAtlas) && this._specularEnvironmentMapAtlas.ready || this._useDefaultSpecularMaps;
}
}
});
function createSpecularEnvironmentMapAtlas(imageBasedLighting, context) {
if (!OctahedralProjectedCubeMap_default.isSupported(context)) {
return;
}
imageBasedLighting._specularEnvironmentMapAtlas = imageBasedLighting._specularEnvironmentMapAtlas && imageBasedLighting._specularEnvironmentMapAtlas.destroy();
if (defined_default(imageBasedLighting._specularEnvironmentMaps)) {
const atlas = new OctahedralProjectedCubeMap_default(
imageBasedLighting._specularEnvironmentMaps
);
imageBasedLighting._specularEnvironmentMapAtlas = atlas;
imageBasedLighting._removeErrorListener = atlas.errorEvent.addEventListener(
(error) => {
console.error(`Error loading specularEnvironmentMaps: ${error}`);
}
);
}
imageBasedLighting._shouldRegenerateShaders = true;
}
ImageBasedLighting.prototype.update = function(frameState) {
if (frameState.frameNumber === this._previousFrameNumber) {
return;
}
this._previousFrameNumber = frameState.frameNumber;
const context = frameState.context;
frameState.brdfLutGenerator.update(frameState);
this._shouldRegenerateShaders = false;
const iblFactor = this._imageBasedLightingFactor;
const previousIBLFactor = this._previousImageBasedLightingFactor;
if (!Cartesian2_default.equals(iblFactor, previousIBLFactor)) {
this._shouldRegenerateShaders = iblFactor.x > 0 && previousIBLFactor.x === 0 || iblFactor.x === 0 && previousIBLFactor.x > 0;
this._shouldRegenerateShaders = this._shouldRegenerateShaders || iblFactor.y > 0 && previousIBLFactor.y === 0 || iblFactor.y === 0 && previousIBLFactor.y > 0;
this._previousImageBasedLightingFactor = Cartesian2_default.clone(
this._imageBasedLightingFactor,
this._previousImageBasedLightingFactor
);
}
if (this._luminanceAtZenith !== this._previousLuminanceAtZenith) {
this._shouldRegenerateShaders = this._shouldRegenerateShaders || defined_default(this._luminanceAtZenith) !== defined_default(this._previousLuminanceAtZenith);
this._previousLuminanceAtZenith = this._luminanceAtZenith;
}
if (this._previousSphericalHarmonicCoefficients !== this._sphericalHarmonicCoefficients) {
this._shouldRegenerateShaders = this._shouldRegenerateShaders || defined_default(this._previousSphericalHarmonicCoefficients) !== defined_default(this._sphericalHarmonicCoefficients);
this._previousSphericalHarmonicCoefficients = this._sphericalHarmonicCoefficients;
}
this._shouldRegenerateShaders = this._shouldRegenerateShaders || this._previousSpecularEnvironmentMapLoaded !== this._specularEnvironmentMapLoaded;
this._previousSpecularEnvironmentMapLoaded = this._specularEnvironmentMapLoaded;
if (this._specularEnvironmentMapAtlasDirty) {
createSpecularEnvironmentMapAtlas(this, context);
this._specularEnvironmentMapAtlasDirty = false;
}
if (defined_default(this._specularEnvironmentMapAtlas)) {
this._specularEnvironmentMapAtlas.update(frameState);
if (this._specularEnvironmentMapAtlas.ready) {
this._specularEnvironmentMapLoaded = true;
}
}
const recompileWithDefaultAtlas = !defined_default(this._specularEnvironmentMapAtlas) && defined_default(frameState.specularEnvironmentMaps) && !this._useDefaultSpecularMaps;
const recompileWithoutDefaultAtlas = !defined_default(frameState.specularEnvironmentMaps) && this._useDefaultSpecularMaps;
const recompileWithDefaultSHCoeffs = !defined_default(this._sphericalHarmonicCoefficients) && defined_default(frameState.sphericalHarmonicCoefficients) && !this._useDefaultSphericalHarmonics;
const recompileWithoutDefaultSHCoeffs = !defined_default(frameState.sphericalHarmonicCoefficients) && this._useDefaultSphericalHarmonics;
this._shouldRegenerateShaders = this._shouldRegenerateShaders || recompileWithDefaultAtlas || recompileWithoutDefaultAtlas || recompileWithDefaultSHCoeffs || recompileWithoutDefaultSHCoeffs;
this._useDefaultSpecularMaps = !defined_default(this._specularEnvironmentMapAtlas) && defined_default(frameState.specularEnvironmentMaps);
this._useDefaultSphericalHarmonics = !defined_default(this._sphericalHarmonicCoefficients) && defined_default(frameState.sphericalHarmonicCoefficients);
};
ImageBasedLighting.prototype.isDestroyed = function() {
return false;
};
ImageBasedLighting.prototype.destroy = function() {
this._specularEnvironmentMapAtlas = this._specularEnvironmentMapAtlas && this._specularEnvironmentMapAtlas.destroy();
this._removeErrorListener = this._removeErrorListener && this._removeErrorListener();
return destroyObject_default(this);
};
var ImageBasedLighting_default = ImageBasedLighting;
// packages/engine/Source/Core/IonResource.js
var import_urijs8 = __toESM(require_URI(), 1);
// packages/engine/Source/Core/Ion.js
var defaultTokenCredit;
var defaultAccessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIwZWQ3OWFlZC1kOTg3LTRlZjctYTAyYy0xNjFmODE1MWE2NGUiLCJpZCI6MjU5LCJpYXQiOjE2ODI5NDYzODh9.DEH4GpqliH-xsDE7h-ZCICtHgnGu32wdSjt4hFqw7lU";
var Ion = {};
Ion.defaultAccessToken = defaultAccessToken;
Ion.defaultServer = new Resource_default({ url: "https://api.cesium.com/" });
Ion.getDefaultTokenCredit = function(providedKey) {
if (providedKey !== defaultAccessToken) {
return void 0;
}
if (!defined_default(defaultTokenCredit)) {
const defaultTokenMessage = ` This application is using Cesium's default ion access token. Please assign Cesium.Ion.defaultAccessToken with an access token from your ion account before making any Cesium API calls. You can sign up for a free ion account at https://cesium.com.`;
defaultTokenCredit = new Credit_default(defaultTokenMessage, true);
}
return defaultTokenCredit;
};
var Ion_default = Ion;
// packages/engine/Source/Core/IonResource.js
function IonResource(endpoint, endpointResource) {
Check_default.defined("endpoint", endpoint);
Check_default.defined("endpointResource", endpointResource);
let options;
const externalType = endpoint.externalType;
const isExternal = defined_default(externalType);
if (!isExternal) {
options = {
url: endpoint.url,
retryAttempts: 1,
retryCallback
};
} else if (externalType === "3DTILES" || externalType === "STK_TERRAIN_SERVER") {
options = { url: endpoint.options.url };
} else {
throw new RuntimeError_default(
"Ion.createResource does not support external imagery assets; use IonImageryProvider instead."
);
}
Resource_default.call(this, options);
this._ionEndpoint = endpoint;
this._ionEndpointDomain = isExternal ? void 0 : new import_urijs8.default(endpoint.url).authority();
this._ionEndpointResource = endpointResource;
this._ionRoot = void 0;
this._pendingPromise = void 0;
this._credits = void 0;
this._isExternal = isExternal;
}
if (defined_default(Object.create)) {
IonResource.prototype = Object.create(Resource_default.prototype);
IonResource.prototype.constructor = IonResource;
}
IonResource.fromAssetId = function(assetId, options) {
const endpointResource = IonResource._createEndpointResource(
assetId,
options
);
return endpointResource.fetchJson().then(function(endpoint) {
return new IonResource(endpoint, endpointResource);
});
};
Object.defineProperties(IonResource.prototype, {
/**
* Gets the credits required for attribution of the asset.
*
* @memberof IonResource.prototype
* @type {Credit[]}
* @readonly
*/
credits: {
get: function() {
if (defined_default(this._ionRoot)) {
return this._ionRoot.credits;
}
if (defined_default(this._credits)) {
return this._credits;
}
this._credits = IonResource.getCreditsFromEndpoint(
this._ionEndpoint,
this._ionEndpointResource
);
return this._credits;
}
}
});
IonResource.getCreditsFromEndpoint = function(endpoint, endpointResource) {
const credits = endpoint.attributions.map(Credit_default.getIonCredit);
const defaultTokenCredit3 = Ion_default.getDefaultTokenCredit(
endpointResource.queryParameters.access_token
);
if (defined_default(defaultTokenCredit3)) {
credits.push(Credit_default.clone(defaultTokenCredit3));
}
return credits;
};
IonResource.prototype.clone = function(result) {
const ionRoot = defaultValue_default(this._ionRoot, this);
if (!defined_default(result)) {
result = new IonResource(
ionRoot._ionEndpoint,
ionRoot._ionEndpointResource
);
}
result = Resource_default.prototype.clone.call(this, result);
result._ionRoot = ionRoot;
result._isExternal = this._isExternal;
return result;
};
IonResource.prototype.fetchImage = function(options) {
if (!this._isExternal) {
const userOptions = options;
options = {
preferBlob: true
};
if (defined_default(userOptions)) {
options.flipY = userOptions.flipY;
options.preferImageBitmap = userOptions.preferImageBitmap;
}
}
return Resource_default.prototype.fetchImage.call(this, options);
};
IonResource.prototype._makeRequest = function(options) {
if (this._isExternal || new import_urijs8.default(this.url).authority() !== this._ionEndpointDomain) {
return Resource_default.prototype._makeRequest.call(this, options);
}
if (!defined_default(options.headers)) {
options.headers = {};
}
options.headers.Authorization = `Bearer ${this._ionEndpoint.accessToken}`;
options.headers["X-Cesium-Client"] = "CesiumJS";
if (typeof CESIUM_VERSION !== "undefined") {
options.headers["X-Cesium-Client-Version"] = CESIUM_VERSION;
}
return Resource_default.prototype._makeRequest.call(this, options);
};
IonResource._createEndpointResource = function(assetId, options) {
Check_default.defined("assetId", assetId);
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
let server = defaultValue_default(options.server, Ion_default.defaultServer);
const accessToken = defaultValue_default(options.accessToken, Ion_default.defaultAccessToken);
server = Resource_default.createIfNeeded(server);
const resourceOptions = {
url: `v1/assets/${assetId}/endpoint`
};
if (defined_default(accessToken)) {
resourceOptions.queryParameters = { access_token: accessToken };
}
return server.getDerivedResource(resourceOptions);
};
function retryCallback(that, error) {
const ionRoot = defaultValue_default(that._ionRoot, that);
const endpointResource = ionRoot._ionEndpointResource;
const imageDefined = typeof Image !== "undefined";
if (!defined_default(error) || error.statusCode !== 401 && !(imageDefined && error.target instanceof Image)) {
return Promise.resolve(false);
}
if (!defined_default(ionRoot._pendingPromise)) {
ionRoot._pendingPromise = endpointResource.fetchJson().then(function(newEndpoint) {
ionRoot._ionEndpoint = newEndpoint;
return newEndpoint;
}).finally(function(newEndpoint) {
ionRoot._pendingPromise = void 0;
return newEndpoint;
});
}
return ionRoot._pendingPromise.then(function(newEndpoint) {
that._ionEndpoint = newEndpoint;
return true;
});
}
var IonResource_default = IonResource;
// packages/engine/Source/Core/ManagedArray.js
function ManagedArray(length3) {
length3 = defaultValue_default(length3, 0);
this._array = new Array(length3);
this._length = length3;
}
Object.defineProperties(ManagedArray.prototype, {
/**
* Gets or sets the length of the array.
* If the set length is greater than the length of the internal array, the internal array is resized.
*
* @memberof ManagedArray.prototype
* @type {number}
*/
length: {
get: function() {
return this._length;
},
set: function(length3) {
Check_default.typeOf.number.greaterThanOrEquals("length", length3, 0);
const array = this._array;
const originalLength = this._length;
if (length3 < originalLength) {
for (let i = length3; i < originalLength; ++i) {
array[i] = void 0;
}
} else if (length3 > array.length) {
array.length = length3;
}
this._length = length3;
}
},
/**
* Gets the internal array.
*
* @memberof ManagedArray.prototype
* @type {Array}
* @readonly
*/
values: {
get: function() {
return this._array;
}
}
});
ManagedArray.prototype.get = function(index) {
Check_default.typeOf.number.lessThan("index", index, this._array.length);
return this._array[index];
};
ManagedArray.prototype.set = function(index, element) {
Check_default.typeOf.number("index", index);
if (index >= this._length) {
this.length = index + 1;
}
this._array[index] = element;
};
ManagedArray.prototype.peek = function() {
return this._array[this._length - 1];
};
ManagedArray.prototype.push = function(element) {
const index = this.length++;
this._array[index] = element;
};
ManagedArray.prototype.pop = function() {
if (this._length === 0) {
return void 0;
}
const element = this._array[this._length - 1];
--this.length;
return element;
};
ManagedArray.prototype.reserve = function(length3) {
Check_default.typeOf.number.greaterThanOrEquals("length", length3, 0);
if (length3 > this._array.length) {
this._array.length = length3;
}
};
ManagedArray.prototype.resize = function(length3) {
Check_default.typeOf.number.greaterThanOrEquals("length", length3, 0);
this.length = length3;
};
ManagedArray.prototype.trim = function(length3) {
length3 = defaultValue_default(length3, this._length);
this._array.length = length3;
};
var ManagedArray_default = ManagedArray;
// packages/engine/Source/Scene/Axis.js
var Axis = {
/**
* Denotes the x-axis.
*
* @type {number}
* @constant
*/
X: 0,
/**
* Denotes the y-axis.
*
* @type {number}
* @constant
*/
Y: 1,
/**
* Denotes the z-axis.
*
* @type {number}
* @constant
*/
Z: 2
};
Axis.Y_UP_TO_Z_UP = Matrix4_default.fromRotationTranslation(
Matrix3_default.fromRotationX(Math_default.PI_OVER_TWO)
);
Axis.Z_UP_TO_Y_UP = Matrix4_default.fromRotationTranslation(
Matrix3_default.fromRotationX(-Math_default.PI_OVER_TWO)
);
Axis.X_UP_TO_Z_UP = Matrix4_default.fromRotationTranslation(
Matrix3_default.fromRotationY(-Math_default.PI_OVER_TWO)
);
Axis.Z_UP_TO_X_UP = Matrix4_default.fromRotationTranslation(
Matrix3_default.fromRotationY(Math_default.PI_OVER_TWO)
);
Axis.X_UP_TO_Y_UP = Matrix4_default.fromRotationTranslation(
Matrix3_default.fromRotationZ(Math_default.PI_OVER_TWO)
);
Axis.Y_UP_TO_X_UP = Matrix4_default.fromRotationTranslation(
Matrix3_default.fromRotationZ(-Math_default.PI_OVER_TWO)
);
Axis.fromName = function(name) {
Check_default.typeOf.string("name", name);
return Axis[name];
};
var Axis_default = Object.freeze(Axis);
// packages/engine/Source/Scene/Cesium3DContentGroup.js
function Cesium3DContentGroup(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
Check_default.typeOf.object("options.metadata", options.metadata);
this._metadata = options.metadata;
}
Object.defineProperties(Cesium3DContentGroup.prototype, {
/**
* Get the metadata for this group
*
* @memberof Cesium3DContentGroup.prototype
*
* @type {GroupMetadata}
*
* @readonly
*/
metadata: {
get: function() {
return this._metadata;
}
}
});
var Cesium3DContentGroup_default = Cesium3DContentGroup;
// packages/engine/Source/Core/getStringFromTypedArray.js
function getStringFromTypedArray(uint8Array, byteOffset, byteLength) {
if (!defined_default(uint8Array)) {
throw new DeveloperError_default("uint8Array is required.");
}
if (byteOffset < 0) {
throw new DeveloperError_default("byteOffset cannot be negative.");
}
if (byteLength < 0) {
throw new DeveloperError_default("byteLength cannot be negative.");
}
if (byteOffset + byteLength > uint8Array.byteLength) {
throw new DeveloperError_default("sub-region exceeds array bounds.");
}
byteOffset = defaultValue_default(byteOffset, 0);
byteLength = defaultValue_default(byteLength, uint8Array.byteLength - byteOffset);
uint8Array = uint8Array.subarray(byteOffset, byteOffset + byteLength);
return getStringFromTypedArray.decode(uint8Array);
}
getStringFromTypedArray.decodeWithTextDecoder = function(view) {
const decoder = new TextDecoder("utf-8");
return decoder.decode(view);
};
getStringFromTypedArray.decodeWithFromCharCode = function(view) {
let result = "";
const codePoints = utf8Handler(view);
const length3 = codePoints.length;
for (let i = 0; i < length3; ++i) {
let cp = codePoints[i];
if (cp <= 65535) {
result += String.fromCharCode(cp);
} else {
cp -= 65536;
result += String.fromCharCode((cp >> 10) + 55296, (cp & 1023) + 56320);
}
}
return result;
};
function inRange(a3, min3, max3) {
return min3 <= a3 && a3 <= max3;
}
function utf8Handler(utfBytes) {
let codePoint = 0;
let bytesSeen = 0;
let bytesNeeded = 0;
let lowerBoundary = 128;
let upperBoundary = 191;
const codePoints = [];
const length3 = utfBytes.length;
for (let i = 0; i < length3; ++i) {
const currentByte = utfBytes[i];
if (bytesNeeded === 0) {
if (inRange(currentByte, 0, 127)) {
codePoints.push(currentByte);
continue;
}
if (inRange(currentByte, 194, 223)) {
bytesNeeded = 1;
codePoint = currentByte & 31;
continue;
}
if (inRange(currentByte, 224, 239)) {
if (currentByte === 224) {
lowerBoundary = 160;
}
if (currentByte === 237) {
upperBoundary = 159;
}
bytesNeeded = 2;
codePoint = currentByte & 15;
continue;
}
if (inRange(currentByte, 240, 244)) {
if (currentByte === 240) {
lowerBoundary = 144;
}
if (currentByte === 244) {
upperBoundary = 143;
}
bytesNeeded = 3;
codePoint = currentByte & 7;
continue;
}
throw new RuntimeError_default("String decoding failed.");
}
if (!inRange(currentByte, lowerBoundary, upperBoundary)) {
codePoint = bytesNeeded = bytesSeen = 0;
lowerBoundary = 128;
upperBoundary = 191;
--i;
continue;
}
lowerBoundary = 128;
upperBoundary = 191;
codePoint = codePoint << 6 | currentByte & 63;
++bytesSeen;
if (bytesSeen === bytesNeeded) {
codePoints.push(codePoint);
codePoint = bytesNeeded = bytesSeen = 0;
}
}
return codePoints;
}
if (typeof TextDecoder !== "undefined") {
getStringFromTypedArray.decode = getStringFromTypedArray.decodeWithTextDecoder;
} else {
getStringFromTypedArray.decode = getStringFromTypedArray.decodeWithFromCharCode;
}
var getStringFromTypedArray_default = getStringFromTypedArray;
// packages/engine/Source/Core/getMagic.js
function getMagic(uint8Array, byteOffset) {
byteOffset = defaultValue_default(byteOffset, 0);
return getStringFromTypedArray_default(
uint8Array,
byteOffset,
Math.min(4, uint8Array.length)
);
}
var getMagic_default = getMagic;
// packages/engine/Source/Scene/Composite3DTileContent.js
function Composite3DTileContent(tileset, tile, resource, contents) {
this._tileset = tileset;
this._tile = tile;
this._resource = resource;
if (!defined_default(contents)) {
contents = [];
}
this._contents = contents;
this._metadata = void 0;
this._group = void 0;
this._ready = false;
this._resolveContent = void 0;
this._readyPromise = new Promise((resolve2) => {
this._resolveContent = resolve2;
});
}
Object.defineProperties(Composite3DTileContent.prototype, {
featurePropertiesDirty: {
get: function() {
const contents = this._contents;
const length3 = contents.length;
for (let i = 0; i < length3; ++i) {
if (contents[i].featurePropertiesDirty) {
return true;
}
}
return false;
},
set: function(value) {
const contents = this._contents;
const length3 = contents.length;
for (let i = 0; i < length3; ++i) {
contents[i].featurePropertiesDirty = value;
}
}
},
/**
* Part of the {@link Cesium3DTileContent} interface. Composite3DTileContent
* always returns 0
. Instead call featuresLength
for a tile in the composite.
* @memberof Composite3DTileContent.prototype
*/
featuresLength: {
get: function() {
return 0;
}
},
/**
* Part of the {@link Cesium3DTileContent} interface. Composite3DTileContent
* always returns 0
. Instead call pointsLength
for a tile in the composite.
* @memberof Composite3DTileContent.prototype
*/
pointsLength: {
get: function() {
return 0;
}
},
/**
* Part of the {@link Cesium3DTileContent} interface. Composite3DTileContent
* always returns 0
. Instead call trianglesLength
for a tile in the composite.
* @memberof Composite3DTileContent.prototype
*/
trianglesLength: {
get: function() {
return 0;
}
},
/**
* Part of the {@link Cesium3DTileContent} interface. Composite3DTileContent
* always returns 0
. Instead call geometryByteLength
for a tile in the composite.
* @memberof Composite3DTileContent.prototype
*/
geometryByteLength: {
get: function() {
return 0;
}
},
/**
* Part of the {@link Cesium3DTileContent} interface. Composite3DTileContent
* always returns 0
. Instead call texturesByteLength
for a tile in the composite.
* @memberof Composite3DTileContent.prototype
*/
texturesByteLength: {
get: function() {
return 0;
}
},
/**
* Part of the {@link Cesium3DTileContent} interface. Composite3DTileContent
* always returns 0
. Instead call batchTableByteLength
for a tile in the composite.
* @memberof Composite3DTileContent.prototype
*/
batchTableByteLength: {
get: function() {
return 0;
}
},
innerContents: {
get: function() {
return this._contents;
}
},
/**
* Returns true when the tile's content is ready to render; otherwise false
*
* @memberof Composite3DTileContent.prototype
*
* @type {boolean}
* @readonly
* @private
*/
ready: {
get: function() {
return this._ready;
}
},
/**
* Gets the promise that will be resolved when the tile's content is ready to render.
*
* @memberof Composite3DTileContent.prototype
*
* @type {PromiseComposite3DTileContent
* both stores the content metadata and propagates the content metadata to all of its children.
* @memberof Composite3DTileContent.prototype
* @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.
*/
metadata: {
get: function() {
return this._metadata;
},
set: function(value) {
this._metadata = value;
const contents = this._contents;
const length3 = contents.length;
for (let i = 0; i < length3; ++i) {
contents[i].metadata = value;
}
}
},
/**
* Part of the {@link Cesium3DTileContent} interface. Composite3DTileContent
* always returns undefined
. Instead call batchTable
for a tile in the composite.
* @memberof Composite3DTileContent.prototype
*/
batchTable: {
get: function() {
return void 0;
}
},
/**
* Part of the {@link Cesium3DTileContent} interface. Composite3DTileContent
* both stores the group metadata and propagates the group metadata to all of its children.
* @memberof Composite3DTileContent.prototype
* @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.
*/
group: {
get: function() {
return this._group;
},
set: function(value) {
this._group = value;
const contents = this._contents;
const length3 = contents.length;
for (let i = 0; i < length3; ++i) {
contents[i].group = value;
}
}
}
});
var sizeOfUint32 = Uint32Array.BYTES_PER_ELEMENT;
Composite3DTileContent.fromTileType = async function(tileset, tile, resource, arrayBuffer, byteOffset, factory) {
byteOffset = defaultValue_default(byteOffset, 0);
const uint8Array = new Uint8Array(arrayBuffer);
const view = new DataView(arrayBuffer);
byteOffset += sizeOfUint32;
const version2 = view.getUint32(byteOffset, true);
if (version2 !== 1) {
throw new RuntimeError_default(
`Only Composite Tile version 1 is supported. Version ${version2} is not.`
);
}
byteOffset += sizeOfUint32;
byteOffset += sizeOfUint32;
const tilesLength = view.getUint32(byteOffset, true);
byteOffset += sizeOfUint32;
let prefix = resource.queryParameters.compositeIndex;
if (defined_default(prefix)) {
prefix = `${prefix}_`;
} else {
prefix = "";
}
const promises = [];
promises.length = tilesLength;
for (let i = 0; i < tilesLength; ++i) {
const tileType = getMagic_default(uint8Array, byteOffset);
const tileByteLength = view.getUint32(byteOffset + sizeOfUint32 * 2, true);
const contentFactory = factory[tileType];
const compositeIndex = `${prefix}${i}`;
const childResource = resource.getDerivedResource({
queryParameters: {
compositeIndex
}
});
if (defined_default(contentFactory)) {
promises[i] = Promise.resolve(
contentFactory(tileset, tile, childResource, arrayBuffer, byteOffset)
);
} else {
throw new RuntimeError_default(
`Unknown tile content type, ${tileType}, inside Composite tile`
);
}
byteOffset += tileByteLength;
}
const innerContents = await Promise.all(promises);
const content = new Composite3DTileContent(
tileset,
tile,
resource,
innerContents
);
return content;
};
Composite3DTileContent.prototype.hasProperty = function(batchId, name) {
return false;
};
Composite3DTileContent.prototype.getFeature = function(batchId) {
return void 0;
};
Composite3DTileContent.prototype.applyDebugSettings = function(enabled, color) {
const contents = this._contents;
const length3 = contents.length;
for (let i = 0; i < length3; ++i) {
contents[i].applyDebugSettings(enabled, color);
}
};
Composite3DTileContent.prototype.applyStyle = function(style) {
const contents = this._contents;
const length3 = contents.length;
for (let i = 0; i < length3; ++i) {
contents[i].applyStyle(style);
}
};
Composite3DTileContent.prototype.update = function(tileset, frameState) {
const contents = this._contents;
const length3 = contents.length;
let ready = true;
for (let i = 0; i < length3; ++i) {
contents[i].update(tileset, frameState);
ready = ready && contents[i].ready;
}
if (!this._ready && ready) {
this._ready = true;
this._resolveContent(this);
}
};
Composite3DTileContent.prototype.isDestroyed = function() {
return false;
};
Composite3DTileContent.prototype.destroy = function() {
const contents = this._contents;
const length3 = contents.length;
for (let i = 0; i < length3; ++i) {
contents[i].destroy();
}
return destroyObject_default(this);
};
var Composite3DTileContent_default = Composite3DTileContent;
// packages/engine/Source/Core/getJsonFromTypedArray.js
function getJsonFromTypedArray(uint8Array, byteOffset, byteLength) {
return JSON.parse(
getStringFromTypedArray_default(uint8Array, byteOffset, byteLength)
);
}
var getJsonFromTypedArray_default = getJsonFromTypedArray;
// packages/engine/Source/Scene/BatchTexture.js
function BatchTexture(options) {
Check_default.typeOf.number("options.featuresLength", options.featuresLength);
Check_default.typeOf.object("options.owner", options.owner);
this._id = createGuid_default();
const featuresLength = options.featuresLength;
this._showAlphaProperties = void 0;
this._batchValues = void 0;
this._batchValuesDirty = false;
this._batchTexture = void 0;
this._defaultTexture = void 0;
this._pickTexture = void 0;
this._pickIds = [];
let textureDimensions;
let textureStep;
if (featuresLength > 0) {
const width = Math.min(featuresLength, ContextLimits_default.maximumTextureSize);
const height = Math.ceil(featuresLength / ContextLimits_default.maximumTextureSize);
const stepX = 1 / width;
const centerX = stepX * 0.5;
const stepY = 1 / height;
const centerY = stepY * 0.5;
textureDimensions = new Cartesian2_default(width, height);
textureStep = new Cartesian4_default(stepX, centerX, stepY, centerY);
}
this._translucentFeaturesLength = 0;
this._featuresLength = featuresLength;
this._textureDimensions = textureDimensions;
this._textureStep = textureStep;
this._owner = options.owner;
this._statistics = options.statistics;
this._colorChangedCallback = options.colorChangedCallback;
}
Object.defineProperties(BatchTexture.prototype, {
/**
* Number of features that are translucent
*
* @memberof BatchTexture.prototype
* @type {number}
* @readonly
* @private
*/
translucentFeaturesLength: {
get: function() {
return this._translucentFeaturesLength;
}
},
/**
* Total size of all GPU resources used by this batch texture.
*
* @memberof BatchTexture.prototype
* @type {number}
* @readonly
* @private
*/
byteLength: {
get: function() {
let memory = 0;
if (defined_default(this._pickTexture)) {
memory += this._pickTexture.sizeInBytes;
}
if (defined_default(this._batchTexture)) {
memory += this._batchTexture.sizeInBytes;
}
return memory;
}
},
/**
* Dimensions of the underlying batch texture.
*
* @memberof BatchTexture.prototype
* @type {Cartesian2}
* @readonly
* @private
*/
textureDimensions: {
get: function() {
return this._textureDimensions;
}
},
/**
* Size of each texture and distance from side to center of a texel in
* each direction. Stored as (stepX, centerX, stepY, centerY)
*
* @memberof BatchTexture.prototype
* @type {Cartesian4}
* @readonly
* @private
*/
textureStep: {
get: function() {
return this._textureStep;
}
},
/**
* The underlying texture used for styling. The texels are accessed
* by batch ID, and the value is the color of this feature after accounting
* for show/hide settings.
*
* @memberof BatchTexture.prototype
* @type {Texture}
* @readonly
* @private
*/
batchTexture: {
get: function() {
return this._batchTexture;
}
},
/**
* The default texture to use when there are no batch values
*
* @memberof BatchTexture.prototype
* @type {Texture}
* @readonly
* @private
*/
defaultTexture: {
get: function() {
return this._defaultTexture;
}
},
/**
* The underlying texture used for picking. The texels are accessed by
* batch ID, and the value is the pick color.
*
* @memberof BatchTexture.prototype
* @type {Texture}
* @readonly
* @private
*/
pickTexture: {
get: function() {
return this._pickTexture;
}
}
});
BatchTexture.DEFAULT_COLOR_VALUE = Color_default.WHITE;
BatchTexture.DEFAULT_SHOW_VALUE = true;
function getByteLength(batchTexture) {
const dimensions = batchTexture._textureDimensions;
return dimensions.x * dimensions.y * 4;
}
function getBatchValues(batchTexture) {
if (!defined_default(batchTexture._batchValues)) {
const byteLength = getByteLength(batchTexture);
const bytes = new Uint8Array(byteLength).fill(255);
batchTexture._batchValues = bytes;
}
return batchTexture._batchValues;
}
function getShowAlphaProperties(batchTexture) {
if (!defined_default(batchTexture._showAlphaProperties)) {
const byteLength = 2 * batchTexture._featuresLength;
const bytes = new Uint8Array(byteLength).fill(255);
batchTexture._showAlphaProperties = bytes;
}
return batchTexture._showAlphaProperties;
}
function checkBatchId(batchId, featuresLength) {
if (!defined_default(batchId) || batchId < 0 || batchId >= featuresLength) {
throw new DeveloperError_default(
`batchId is required and between zero and featuresLength - 1 (${featuresLength}` - +")."
);
}
}
BatchTexture.prototype.setShow = function(batchId, show) {
checkBatchId(batchId, this._featuresLength);
Check_default.typeOf.bool("show", show);
if (show && !defined_default(this._showAlphaProperties)) {
return;
}
const showAlphaProperties = getShowAlphaProperties(this);
const propertyOffset = batchId * 2;
const newShow = show ? 255 : 0;
if (showAlphaProperties[propertyOffset] !== newShow) {
showAlphaProperties[propertyOffset] = newShow;
const batchValues = getBatchValues(this);
const offset2 = batchId * 4 + 3;
batchValues[offset2] = show ? showAlphaProperties[propertyOffset + 1] : 0;
this._batchValuesDirty = true;
}
};
BatchTexture.prototype.setAllShow = function(show) {
Check_default.typeOf.bool("show", show);
const featuresLength = this._featuresLength;
for (let i = 0; i < featuresLength; ++i) {
this.setShow(i, show);
}
};
BatchTexture.prototype.getShow = function(batchId) {
checkBatchId(batchId, this._featuresLength);
if (!defined_default(this._showAlphaProperties)) {
return true;
}
const offset2 = batchId * 2;
return this._showAlphaProperties[offset2] === 255;
};
var scratchColorBytes = new Array(4);
BatchTexture.prototype.setColor = function(batchId, color) {
checkBatchId(batchId, this._featuresLength);
Check_default.typeOf.object("color", color);
if (Color_default.equals(color, BatchTexture.DEFAULT_COLOR_VALUE) && !defined_default(this._batchValues)) {
return;
}
const newColor = color.toBytes(scratchColorBytes);
const newAlpha = newColor[3];
const batchValues = getBatchValues(this);
const offset2 = batchId * 4;
const showAlphaProperties = getShowAlphaProperties(this);
const propertyOffset = batchId * 2;
if (batchValues[offset2] !== newColor[0] || batchValues[offset2 + 1] !== newColor[1] || batchValues[offset2 + 2] !== newColor[2] || showAlphaProperties[propertyOffset + 1] !== newAlpha) {
batchValues[offset2] = newColor[0];
batchValues[offset2 + 1] = newColor[1];
batchValues[offset2 + 2] = newColor[2];
const wasTranslucent = showAlphaProperties[propertyOffset + 1] !== 255;
const show = showAlphaProperties[propertyOffset] !== 0;
batchValues[offset2 + 3] = show ? newAlpha : 0;
showAlphaProperties[propertyOffset + 1] = newAlpha;
const isTranslucent = newAlpha !== 255;
if (isTranslucent && !wasTranslucent) {
++this._translucentFeaturesLength;
} else if (!isTranslucent && wasTranslucent) {
--this._translucentFeaturesLength;
}
this._batchValuesDirty = true;
if (defined_default(this._colorChangedCallback)) {
this._colorChangedCallback(batchId, color);
}
}
};
BatchTexture.prototype.setAllColor = function(color) {
Check_default.typeOf.object("color", color);
const featuresLength = this._featuresLength;
for (let i = 0; i < featuresLength; ++i) {
this.setColor(i, color);
}
};
BatchTexture.prototype.getColor = function(batchId, result) {
checkBatchId(batchId, this._featuresLength);
Check_default.typeOf.object("result", result);
if (!defined_default(this._batchValues)) {
return Color_default.clone(BatchTexture.DEFAULT_COLOR_VALUE, result);
}
const batchValues = this._batchValues;
const offset2 = batchId * 4;
const showAlphaProperties = this._showAlphaProperties;
const propertyOffset = batchId * 2;
return Color_default.fromBytes(
batchValues[offset2],
batchValues[offset2 + 1],
batchValues[offset2 + 2],
showAlphaProperties[propertyOffset + 1],
result
);
};
BatchTexture.prototype.getPickColor = function(batchId) {
checkBatchId(batchId, this._featuresLength);
return this._pickIds[batchId];
};
function createTexture2(batchTexture, context, bytes) {
const dimensions = batchTexture._textureDimensions;
return new Texture_default({
context,
pixelFormat: PixelFormat_default.RGBA,
pixelDatatype: PixelDatatype_default.UNSIGNED_BYTE,
source: {
width: dimensions.x,
height: dimensions.y,
arrayBufferView: bytes
},
flipY: false,
sampler: Sampler_default.NEAREST
});
}
function createPickTexture(batchTexture, context) {
const featuresLength = batchTexture._featuresLength;
if (!defined_default(batchTexture._pickTexture) && featuresLength > 0) {
const pickIds = batchTexture._pickIds;
const byteLength = getByteLength(batchTexture);
const bytes = new Uint8Array(byteLength);
const owner = batchTexture._owner;
const statistics2 = batchTexture._statistics;
for (let i = 0; i < featuresLength; ++i) {
const pickId = context.createPickId(owner.getFeature(i));
pickIds.push(pickId);
const pickColor = pickId.color;
const offset2 = i * 4;
bytes[offset2] = Color_default.floatToByte(pickColor.red);
bytes[offset2 + 1] = Color_default.floatToByte(pickColor.green);
bytes[offset2 + 2] = Color_default.floatToByte(pickColor.blue);
bytes[offset2 + 3] = Color_default.floatToByte(pickColor.alpha);
}
batchTexture._pickTexture = createTexture2(batchTexture, context, bytes);
if (defined_default(statistics2)) {
statistics2.batchTableByteLength += batchTexture._pickTexture.sizeInBytes;
}
}
}
function updateBatchTexture(batchTexture) {
const dimensions = batchTexture._textureDimensions;
batchTexture._batchTexture.copyFrom({
source: {
width: dimensions.x,
height: dimensions.y,
arrayBufferView: batchTexture._batchValues
}
});
}
BatchTexture.prototype.update = function(tileset, frameState) {
const context = frameState.context;
this._defaultTexture = context.defaultTexture;
const passes = frameState.passes;
if (passes.pick || passes.postProcess) {
createPickTexture(this, context);
}
if (this._batchValuesDirty) {
this._batchValuesDirty = false;
if (!defined_default(this._batchTexture)) {
this._batchTexture = createTexture2(this, context, this._batchValues);
if (defined_default(this._statistics)) {
this._statistics.batchTableByteLength += this._batchTexture.sizeInBytes;
}
}
updateBatchTexture(this);
}
};
BatchTexture.prototype.isDestroyed = function() {
return false;
};
BatchTexture.prototype.destroy = function() {
this._batchTexture = this._batchTexture && this._batchTexture.destroy();
this._pickTexture = this._pickTexture && this._pickTexture.destroy();
const pickIds = this._pickIds;
const length3 = pickIds.length;
for (let i = 0; i < length3; ++i) {
pickIds[i].destroy();
}
return destroyObject_default(this);
};
var BatchTexture_default = BatchTexture;
// packages/engine/Source/Scene/getBinaryAccessor.js
var ComponentsPerAttribute = {
SCALAR: 1,
VEC2: 2,
VEC3: 3,
VEC4: 4,
MAT2: 4,
MAT3: 9,
MAT4: 16
};
var ClassPerType = {
SCALAR: void 0,
VEC2: Cartesian2_default,
VEC3: Cartesian3_default,
VEC4: Cartesian4_default,
MAT2: Matrix2_default,
MAT3: Matrix3_default,
MAT4: Matrix4_default
};
function getBinaryAccessor(accessor) {
const componentType = accessor.componentType;
let componentDatatype;
if (typeof componentType === "string") {
componentDatatype = ComponentDatatype_default.fromName(componentType);
} else {
componentDatatype = componentType;
}
const componentsPerAttribute = ComponentsPerAttribute[accessor.type];
const classType = ClassPerType[accessor.type];
return {
componentsPerAttribute,
classType,
createArrayBufferView: function(buffer, byteOffset, length3) {
return ComponentDatatype_default.createArrayBufferView(
componentDatatype,
buffer,
byteOffset,
componentsPerAttribute * length3
);
}
};
}
var getBinaryAccessor_default = getBinaryAccessor;
// packages/engine/Source/Scene/BatchTableHierarchy.js
function BatchTableHierarchy(options) {
this._classes = void 0;
this._classIds = void 0;
this._classIndexes = void 0;
this._parentCounts = void 0;
this._parentIndexes = void 0;
this._parentIds = void 0;
this._byteLength = 0;
Check_default.typeOf.object("options.extension", options.extension);
initialize3(this, options.extension, options.binaryBody);
validateHierarchy(this);
}
Object.defineProperties(BatchTableHierarchy.prototype, {
byteLength: {
get: function() {
return this._byteLength;
}
}
});
function initialize3(hierarchy, hierarchyJson, binaryBody) {
let i;
let classId;
let binaryAccessor;
const instancesLength = hierarchyJson.instancesLength;
const classes = hierarchyJson.classes;
let classIds = hierarchyJson.classIds;
let parentCounts = hierarchyJson.parentCounts;
let parentIds = hierarchyJson.parentIds;
let parentIdsLength = instancesLength;
let byteLength = 0;
if (defined_default(classIds.byteOffset)) {
classIds.componentType = defaultValue_default(
classIds.componentType,
ComponentDatatype_default.UNSIGNED_SHORT
);
classIds.type = AttributeType_default.SCALAR;
binaryAccessor = getBinaryAccessor_default(classIds);
classIds = binaryAccessor.createArrayBufferView(
binaryBody.buffer,
binaryBody.byteOffset + classIds.byteOffset,
instancesLength
);
byteLength += classIds.byteLength;
}
let parentIndexes;
if (defined_default(parentCounts)) {
if (defined_default(parentCounts.byteOffset)) {
parentCounts.componentType = defaultValue_default(
parentCounts.componentType,
ComponentDatatype_default.UNSIGNED_SHORT
);
parentCounts.type = AttributeType_default.SCALAR;
binaryAccessor = getBinaryAccessor_default(parentCounts);
parentCounts = binaryAccessor.createArrayBufferView(
binaryBody.buffer,
binaryBody.byteOffset + parentCounts.byteOffset,
instancesLength
);
byteLength += parentCounts.byteLength;
}
parentIndexes = new Uint16Array(instancesLength);
parentIdsLength = 0;
for (i = 0; i < instancesLength; ++i) {
parentIndexes[i] = parentIdsLength;
parentIdsLength += parentCounts[i];
}
byteLength += parentIndexes.byteLength;
}
if (defined_default(parentIds) && defined_default(parentIds.byteOffset)) {
parentIds.componentType = defaultValue_default(
parentIds.componentType,
ComponentDatatype_default.UNSIGNED_SHORT
);
parentIds.type = AttributeType_default.SCALAR;
binaryAccessor = getBinaryAccessor_default(parentIds);
parentIds = binaryAccessor.createArrayBufferView(
binaryBody.buffer,
binaryBody.byteOffset + parentIds.byteOffset,
parentIdsLength
);
byteLength += parentIds.byteLength;
}
const classesLength = classes.length;
for (i = 0; i < classesLength; ++i) {
const classInstancesLength = classes[i].length;
const properties = classes[i].instances;
const binaryProperties = getBinaryProperties(
classInstancesLength,
properties,
binaryBody
);
byteLength += countBinaryPropertyMemory(binaryProperties);
classes[i].instances = combine_default(binaryProperties, properties);
}
const classCounts = new Array(classesLength).fill(0);
const classIndexes = new Uint16Array(instancesLength);
for (i = 0; i < instancesLength; ++i) {
classId = classIds[i];
classIndexes[i] = classCounts[classId];
++classCounts[classId];
}
byteLength += classIndexes.byteLength;
hierarchy._classes = classes;
hierarchy._classIds = classIds;
hierarchy._classIndexes = classIndexes;
hierarchy._parentCounts = parentCounts;
hierarchy._parentIndexes = parentIndexes;
hierarchy._parentIds = parentIds;
hierarchy._byteLength = byteLength;
}
function getBinaryProperties(featuresLength, properties, binaryBody) {
let binaryProperties;
for (const name in properties) {
if (properties.hasOwnProperty(name)) {
const property = properties[name];
const byteOffset = property.byteOffset;
if (defined_default(byteOffset)) {
const componentType = property.componentType;
const type = property.type;
if (!defined_default(componentType)) {
throw new RuntimeError_default("componentType is required.");
}
if (!defined_default(type)) {
throw new RuntimeError_default("type is required.");
}
if (!defined_default(binaryBody)) {
throw new RuntimeError_default(
`Property ${name} requires a batch table binary.`
);
}
const binaryAccessor = getBinaryAccessor_default(property);
const componentCount = binaryAccessor.componentsPerAttribute;
const classType = binaryAccessor.classType;
const typedArray = binaryAccessor.createArrayBufferView(
binaryBody.buffer,
binaryBody.byteOffset + byteOffset,
featuresLength
);
if (!defined_default(binaryProperties)) {
binaryProperties = {};
}
binaryProperties[name] = {
typedArray,
componentCount,
type: classType
};
}
}
}
return binaryProperties;
}
function countBinaryPropertyMemory(binaryProperties) {
let byteLength = 0;
for (const name in binaryProperties) {
if (binaryProperties.hasOwnProperty(name)) {
byteLength += binaryProperties[name].typedArray.byteLength;
}
}
return byteLength;
}
var scratchValidateStack = [];
function validateHierarchy(hierarchy) {
const stack = scratchValidateStack;
stack.length = 0;
const classIds = hierarchy._classIds;
const instancesLength = classIds.length;
for (let i = 0; i < instancesLength; ++i) {
validateInstance(hierarchy, i, stack);
}
}
function validateInstance(hierarchy, instanceIndex, stack) {
const parentCounts = hierarchy._parentCounts;
const parentIds = hierarchy._parentIds;
const parentIndexes = hierarchy._parentIndexes;
const classIds = hierarchy._classIds;
const instancesLength = classIds.length;
if (!defined_default(parentIds)) {
return;
}
if (instanceIndex >= instancesLength) {
throw new DeveloperError_default(
`Parent index ${instanceIndex} exceeds the total number of instances: ${instancesLength}`
);
}
if (stack.indexOf(instanceIndex) > -1) {
throw new DeveloperError_default(
"Circular dependency detected in the batch table hierarchy."
);
}
stack.push(instanceIndex);
const parentCount = defined_default(parentCounts) ? parentCounts[instanceIndex] : 1;
const parentIndex = defined_default(parentCounts) ? parentIndexes[instanceIndex] : instanceIndex;
for (let i = 0; i < parentCount; ++i) {
const parentId = parentIds[parentIndex + i];
if (parentId !== instanceIndex) {
validateInstance(hierarchy, parentId, stack);
}
}
stack.pop(instanceIndex);
}
var scratchVisited = [];
var scratchStack = [];
var marker = 0;
function traverseHierarchyMultipleParents(hierarchy, instanceIndex, endConditionCallback) {
const classIds = hierarchy._classIds;
const parentCounts = hierarchy._parentCounts;
const parentIds = hierarchy._parentIds;
const parentIndexes = hierarchy._parentIndexes;
const instancesLength = classIds.length;
const visited = scratchVisited;
visited.length = Math.max(visited.length, instancesLength);
const visitedMarker = ++marker;
const stack = scratchStack;
stack.length = 0;
stack.push(instanceIndex);
while (stack.length > 0) {
instanceIndex = stack.pop();
if (visited[instanceIndex] === visitedMarker) {
continue;
}
visited[instanceIndex] = visitedMarker;
const result = endConditionCallback(hierarchy, instanceIndex);
if (defined_default(result)) {
return result;
}
const parentCount = parentCounts[instanceIndex];
const parentIndex = parentIndexes[instanceIndex];
for (let i = 0; i < parentCount; ++i) {
const parentId = parentIds[parentIndex + i];
if (parentId !== instanceIndex) {
stack.push(parentId);
}
}
}
}
function traverseHierarchySingleParent(hierarchy, instanceIndex, endConditionCallback) {
let hasParent = true;
while (hasParent) {
const result = endConditionCallback(hierarchy, instanceIndex);
if (defined_default(result)) {
return result;
}
const parentId = hierarchy._parentIds[instanceIndex];
hasParent = parentId !== instanceIndex;
instanceIndex = parentId;
}
}
function traverseHierarchy(hierarchy, instanceIndex, endConditionCallback) {
const parentCounts = hierarchy._parentCounts;
const parentIds = hierarchy._parentIds;
if (!defined_default(parentIds)) {
return endConditionCallback(hierarchy, instanceIndex);
} else if (defined_default(parentCounts)) {
return traverseHierarchyMultipleParents(
hierarchy,
instanceIndex,
endConditionCallback
);
}
return traverseHierarchySingleParent(
hierarchy,
instanceIndex,
endConditionCallback
);
}
BatchTableHierarchy.prototype.hasProperty = function(batchId, propertyId) {
const result = traverseHierarchy(this, batchId, function(hierarchy, instanceIndex) {
const classId = hierarchy._classIds[instanceIndex];
const instances = hierarchy._classes[classId].instances;
if (defined_default(instances[propertyId])) {
return true;
}
});
return defined_default(result);
};
BatchTableHierarchy.prototype.propertyExists = function(propertyId) {
const classes = this._classes;
const classesLength = classes.length;
for (let i = 0; i < classesLength; ++i) {
const instances = classes[i].instances;
if (defined_default(instances[propertyId])) {
return true;
}
}
return false;
};
BatchTableHierarchy.prototype.getPropertyIds = function(batchId, results) {
results = defined_default(results) ? results : [];
results.length = 0;
traverseHierarchy(this, batchId, function(hierarchy, instanceIndex) {
const classId = hierarchy._classIds[instanceIndex];
const instances = hierarchy._classes[classId].instances;
for (const name in instances) {
if (instances.hasOwnProperty(name)) {
if (results.indexOf(name) === -1) {
results.push(name);
}
}
}
});
return results;
};
BatchTableHierarchy.prototype.getProperty = function(batchId, propertyId) {
return traverseHierarchy(this, batchId, function(hierarchy, instanceIndex) {
const classId = hierarchy._classIds[instanceIndex];
const instanceClass = hierarchy._classes[classId];
const indexInClass = hierarchy._classIndexes[instanceIndex];
const propertyValues = instanceClass.instances[propertyId];
if (defined_default(propertyValues)) {
if (defined_default(propertyValues.typedArray)) {
return getBinaryProperty(propertyValues, indexInClass);
}
return clone_default(propertyValues[indexInClass], true);
}
});
};
function getBinaryProperty(binaryProperty, index) {
const typedArray = binaryProperty.typedArray;
const componentCount = binaryProperty.componentCount;
if (componentCount === 1) {
return typedArray[index];
}
return binaryProperty.type.unpack(typedArray, index * componentCount);
}
BatchTableHierarchy.prototype.setProperty = function(batchId, propertyId, value) {
const result = traverseHierarchy(this, batchId, function(hierarchy, instanceIndex) {
const classId = hierarchy._classIds[instanceIndex];
const instanceClass = hierarchy._classes[classId];
const indexInClass = hierarchy._classIndexes[instanceIndex];
const propertyValues = instanceClass.instances[propertyId];
if (defined_default(propertyValues)) {
if (instanceIndex !== batchId) {
throw new DeveloperError_default(
`Inherited property "${propertyId}" is read-only.`
);
}
if (defined_default(propertyValues.typedArray)) {
setBinaryProperty(propertyValues, indexInClass, value);
} else {
propertyValues[indexInClass] = clone_default(value, true);
}
return true;
}
});
return defined_default(result);
};
function setBinaryProperty(binaryProperty, index, value) {
const typedArray = binaryProperty.typedArray;
const componentCount = binaryProperty.componentCount;
if (componentCount === 1) {
typedArray[index] = value;
} else {
binaryProperty.type.pack(value, typedArray, index * componentCount);
}
}
BatchTableHierarchy.prototype.isClass = function(batchId, className) {
const result = traverseHierarchy(this, batchId, function(hierarchy, instanceIndex) {
const classId = hierarchy._classIds[instanceIndex];
const instanceClass = hierarchy._classes[classId];
if (instanceClass.name === className) {
return true;
}
});
return defined_default(result);
};
BatchTableHierarchy.prototype.getClassName = function(batchId) {
const classId = this._classIds[batchId];
const instanceClass = this._classes[classId];
return instanceClass.name;
};
var BatchTableHierarchy_default = BatchTableHierarchy;
// packages/engine/Source/Scene/Cesium3DTileColorBlendMode.js
var Cesium3DTileColorBlendMode = {
/**
* Multiplies the source color by the feature color.
*
* @type {number}
* @constant
*/
HIGHLIGHT: 0,
/**
* Replaces the source color with the feature color.
*
* @type {number}
* @constant
*/
REPLACE: 1,
/**
* Blends the source color and feature color together.
*
* @type {number}
* @constant
*/
MIX: 2
};
var Cesium3DTileColorBlendMode_default = Object.freeze(Cesium3DTileColorBlendMode);
// packages/engine/Source/Scene/Cesium3DTileBatchTable.js
var DEFAULT_COLOR_VALUE = BatchTexture_default.DEFAULT_COLOR_VALUE;
var DEFAULT_SHOW_VALUE = BatchTexture_default.DEFAULT_SHOW_VALUE;
function Cesium3DTileBatchTable(content, featuresLength, batchTableJson, batchTableBinary, colorChangedCallback) {
this.featuresLength = featuresLength;
let extensions;
if (defined_default(batchTableJson)) {
extensions = batchTableJson.extensions;
}
this._extensions = defaultValue_default(extensions, {});
const properties = initializeProperties(batchTableJson);
this._properties = properties;
this._batchTableHierarchy = initializeHierarchy(
this,
batchTableJson,
batchTableBinary
);
const binaryProperties = getBinaryProperties2(
featuresLength,
properties,
batchTableBinary
);
this._binaryPropertiesByteLength = countBinaryPropertyMemory2(
binaryProperties
);
this._batchTableBinaryProperties = binaryProperties;
this._content = content;
this._batchTexture = new BatchTexture_default({
featuresLength,
colorChangedCallback,
owner: content,
statistics: content.tileset.statistics
});
}
Cesium3DTileBatchTable._deprecationWarning = deprecationWarning_default;
Object.defineProperties(Cesium3DTileBatchTable.prototype, {
/**
* Size of the batch table, including the batch table hierarchy's binary
* buffers and any binary properties. JSON data is not counted.
*
* @memberof Cesium3DTileBatchTable.prototype
* @type {number}
* @readonly
* @private
*/
batchTableByteLength: {
get: function() {
let totalByteLength = this._binaryPropertiesByteLength;
if (defined_default(this._batchTableHierarchy)) {
totalByteLength += this._batchTableHierarchy.byteLength;
}
totalByteLength += this._batchTexture.byteLength;
return totalByteLength;
}
}
});
function initializeProperties(jsonHeader) {
const properties = {};
if (!defined_default(jsonHeader)) {
return properties;
}
for (const propertyName in jsonHeader) {
if (jsonHeader.hasOwnProperty(propertyName) && propertyName !== "HIERARCHY" && // Deprecated HIERARCHY property
propertyName !== "extensions" && propertyName !== "extras") {
properties[propertyName] = clone_default(jsonHeader[propertyName], true);
}
}
return properties;
}
function initializeHierarchy(batchTable, jsonHeader, binaryBody) {
if (!defined_default(jsonHeader)) {
return;
}
let hierarchy = batchTable._extensions["3DTILES_batch_table_hierarchy"];
const legacyHierarchy = jsonHeader.HIERARCHY;
if (defined_default(legacyHierarchy)) {
Cesium3DTileBatchTable._deprecationWarning(
"batchTableHierarchyExtension",
"The batch table HIERARCHY property has been moved to an extension. Use extensions.3DTILES_batch_table_hierarchy instead."
);
batchTable._extensions["3DTILES_batch_table_hierarchy"] = legacyHierarchy;
hierarchy = legacyHierarchy;
}
if (!defined_default(hierarchy)) {
return;
}
return new BatchTableHierarchy_default({
extension: hierarchy,
binaryBody
});
}
function getBinaryProperties2(featuresLength, properties, binaryBody) {
let binaryProperties;
for (const name in properties) {
if (properties.hasOwnProperty(name)) {
const property = properties[name];
const byteOffset = property.byteOffset;
if (defined_default(byteOffset)) {
const componentType = property.componentType;
const type = property.type;
if (!defined_default(componentType)) {
throw new RuntimeError_default("componentType is required.");
}
if (!defined_default(type)) {
throw new RuntimeError_default("type is required.");
}
if (!defined_default(binaryBody)) {
throw new RuntimeError_default(
`Property ${name} requires a batch table binary.`
);
}
const binaryAccessor = getBinaryAccessor_default(property);
const componentCount = binaryAccessor.componentsPerAttribute;
const classType = binaryAccessor.classType;
const typedArray = binaryAccessor.createArrayBufferView(
binaryBody.buffer,
binaryBody.byteOffset + byteOffset,
featuresLength
);
if (!defined_default(binaryProperties)) {
binaryProperties = {};
}
binaryProperties[name] = {
typedArray,
componentCount,
type: classType
};
}
}
}
return binaryProperties;
}
function countBinaryPropertyMemory2(binaryProperties) {
if (!defined_default(binaryProperties)) {
return 0;
}
let byteLength = 0;
for (const name in binaryProperties) {
if (binaryProperties.hasOwnProperty(name)) {
byteLength += binaryProperties[name].typedArray.byteLength;
}
}
return byteLength;
}
Cesium3DTileBatchTable.getBinaryProperties = function(featuresLength, batchTableJson, batchTableBinary) {
return getBinaryProperties2(featuresLength, batchTableJson, batchTableBinary);
};
Cesium3DTileBatchTable.prototype.setShow = function(batchId, show) {
this._batchTexture.setShow(batchId, show);
};
Cesium3DTileBatchTable.prototype.setAllShow = function(show) {
this._batchTexture.setAllShow(show);
};
Cesium3DTileBatchTable.prototype.getShow = function(batchId) {
return this._batchTexture.getShow(batchId);
};
Cesium3DTileBatchTable.prototype.setColor = function(batchId, color) {
this._batchTexture.setColor(batchId, color);
};
Cesium3DTileBatchTable.prototype.setAllColor = function(color) {
this._batchTexture.setAllColor(color);
};
Cesium3DTileBatchTable.prototype.getColor = function(batchId, result) {
return this._batchTexture.getColor(batchId, result);
};
Cesium3DTileBatchTable.prototype.getPickColor = function(batchId) {
return this._batchTexture.getPickColor(batchId);
};
var scratchColor2 = new Color_default();
Cesium3DTileBatchTable.prototype.applyStyle = function(style) {
if (!defined_default(style)) {
this.setAllColor(DEFAULT_COLOR_VALUE);
this.setAllShow(DEFAULT_SHOW_VALUE);
return;
}
const content = this._content;
const length3 = this.featuresLength;
for (let i = 0; i < length3; ++i) {
const feature2 = content.getFeature(i);
const color = defined_default(style.color) ? defaultValue_default(
style.color.evaluateColor(feature2, scratchColor2),
DEFAULT_COLOR_VALUE
) : DEFAULT_COLOR_VALUE;
const show = defined_default(style.show) ? defaultValue_default(style.show.evaluate(feature2), DEFAULT_SHOW_VALUE) : DEFAULT_SHOW_VALUE;
this.setColor(i, color);
this.setShow(i, show);
}
};
function getBinaryProperty2(binaryProperty, index) {
const typedArray = binaryProperty.typedArray;
const componentCount = binaryProperty.componentCount;
if (componentCount === 1) {
return typedArray[index];
}
return binaryProperty.type.unpack(typedArray, index * componentCount);
}
function setBinaryProperty2(binaryProperty, index, value) {
const typedArray = binaryProperty.typedArray;
const componentCount = binaryProperty.componentCount;
if (componentCount === 1) {
typedArray[index] = value;
} else {
binaryProperty.type.pack(value, typedArray, index * componentCount);
}
}
function checkBatchId2(batchId, featuresLength) {
if (!defined_default(batchId) || batchId < 0 || batchId >= featuresLength) {
throw new DeveloperError_default(
`batchId is required and must be between zero and featuresLength - 1 (${featuresLength}` - +")."
);
}
}
Cesium3DTileBatchTable.prototype.isClass = function(batchId, className) {
checkBatchId2(batchId, this.featuresLength);
Check_default.typeOf.string("className", className);
const hierarchy = this._batchTableHierarchy;
if (!defined_default(hierarchy)) {
return false;
}
return hierarchy.isClass(batchId, className);
};
Cesium3DTileBatchTable.prototype.isExactClass = function(batchId, className) {
Check_default.typeOf.string("className", className);
return this.getExactClassName(batchId) === className;
};
Cesium3DTileBatchTable.prototype.getExactClassName = function(batchId) {
checkBatchId2(batchId, this.featuresLength);
const hierarchy = this._batchTableHierarchy;
if (!defined_default(hierarchy)) {
return void 0;
}
return hierarchy.getClassName(batchId);
};
Cesium3DTileBatchTable.prototype.hasProperty = function(batchId, name) {
checkBatchId2(batchId, this.featuresLength);
Check_default.typeOf.string("name", name);
return defined_default(this._properties[name]) || defined_default(this._batchTableHierarchy) && this._batchTableHierarchy.hasProperty(batchId, name);
};
Cesium3DTileBatchTable.prototype.hasPropertyBySemantic = function() {
return false;
};
Cesium3DTileBatchTable.prototype.getPropertyIds = function(batchId, results) {
checkBatchId2(batchId, this.featuresLength);
results = defined_default(results) ? results : [];
results.length = 0;
const scratchPropertyIds = Object.keys(this._properties);
results.push.apply(results, scratchPropertyIds);
if (defined_default(this._batchTableHierarchy)) {
results.push.apply(
results,
this._batchTableHierarchy.getPropertyIds(batchId, scratchPropertyIds)
);
}
return results;
};
Cesium3DTileBatchTable.prototype.getPropertyBySemantic = function(batchId, name) {
return void 0;
};
Cesium3DTileBatchTable.prototype.getProperty = function(batchId, name) {
checkBatchId2(batchId, this.featuresLength);
Check_default.typeOf.string("name", name);
if (defined_default(this._batchTableBinaryProperties)) {
const binaryProperty = this._batchTableBinaryProperties[name];
if (defined_default(binaryProperty)) {
return getBinaryProperty2(binaryProperty, batchId);
}
}
const propertyValues = this._properties[name];
if (defined_default(propertyValues)) {
return clone_default(propertyValues[batchId], true);
}
if (defined_default(this._batchTableHierarchy)) {
const hierarchyProperty = this._batchTableHierarchy.getProperty(
batchId,
name
);
if (defined_default(hierarchyProperty)) {
return hierarchyProperty;
}
}
return void 0;
};
Cesium3DTileBatchTable.prototype.setProperty = function(batchId, name, value) {
const featuresLength = this.featuresLength;
checkBatchId2(batchId, featuresLength);
Check_default.typeOf.string("name", name);
if (defined_default(this._batchTableBinaryProperties)) {
const binaryProperty = this._batchTableBinaryProperties[name];
if (defined_default(binaryProperty)) {
setBinaryProperty2(binaryProperty, batchId, value);
return;
}
}
if (defined_default(this._batchTableHierarchy)) {
if (this._batchTableHierarchy.setProperty(batchId, name, value)) {
return;
}
}
let propertyValues = this._properties[name];
if (!defined_default(propertyValues)) {
this._properties[name] = new Array(featuresLength);
propertyValues = this._properties[name];
}
propertyValues[batchId] = clone_default(value, true);
};
function getGlslComputeSt2(batchTable) {
if (batchTable._batchTexture.textureDimensions.y === 1) {
return "uniform vec4 tile_textureStep; \nvec2 computeSt(float batchId) \n{ \n float stepX = tile_textureStep.x; \n float centerX = tile_textureStep.y; \n return vec2(centerX + (batchId * stepX), 0.5); \n} \n";
}
return "uniform vec4 tile_textureStep; \nuniform vec2 tile_textureDimensions; \nvec2 computeSt(float batchId) \n{ \n float stepX = tile_textureStep.x; \n float centerX = tile_textureStep.y; \n float stepY = tile_textureStep.z; \n float centerY = tile_textureStep.w; \n float xId = mod(batchId, tile_textureDimensions.x); \n float yId = floor(batchId / tile_textureDimensions.x); \n return vec2(centerX + (xId * stepX), centerY + (yId * stepY)); \n} \n";
}
Cesium3DTileBatchTable.prototype.getVertexShaderCallback = function(handleTranslucent, batchIdAttributeName, diffuseAttributeOrUniformName) {
if (this.featuresLength === 0) {
return;
}
const that = this;
return function(source) {
const renamedSource = modifyDiffuse(
source,
diffuseAttributeOrUniformName,
false
);
let newMain;
if (ContextLimits_default.maximumVertexTextureImageUnits > 0) {
newMain = "";
if (handleTranslucent) {
newMain += "uniform bool tile_translucentCommand; \n";
}
newMain += `${"uniform sampler2D tile_batchTexture; \nout vec4 tile_featureColor; \nout vec2 tile_featureSt; \nvoid main() \n{ \n vec2 st = computeSt("}${batchIdAttributeName});
vec4 featureProperties = texture(tile_batchTexture, st);
tile_color(featureProperties);
float show = ceil(featureProperties.a);
gl_Position *= show;
`;
if (handleTranslucent) {
newMain += " bool isStyleTranslucent = (featureProperties.a != 1.0); \n if (czm_pass == czm_passTranslucent) \n { \n if (!isStyleTranslucent && !tile_translucentCommand) \n { \n gl_Position *= 0.0; \n } \n } \n else \n { \n if (isStyleTranslucent) \n { \n gl_Position *= 0.0; \n } \n } \n";
}
newMain += " tile_featureColor = featureProperties; \n tile_featureSt = st; \n}";
} else {
newMain = `${"out vec2 tile_featureSt; \nvoid main() \n{ \n tile_color(vec4(1.0)); \n tile_featureSt = computeSt("}${batchIdAttributeName});
}`;
}
return `${renamedSource}
${getGlslComputeSt2(that)}${newMain}`;
};
};
function getDefaultShader(source, applyHighlight) {
source = ShaderSource_default.replaceMain(source, "tile_main");
if (!applyHighlight) {
return `${source}void tile_color(vec4 tile_featureColor)
{
tile_main();
}
`;
}
return `${source}uniform float tile_colorBlend;
void tile_color(vec4 tile_featureColor)
{
tile_main();
tile_featureColor = czm_gammaCorrect(tile_featureColor);
out_FragColor.a *= tile_featureColor.a;
float highlight = ceil(tile_colorBlend);
out_FragColor.rgb *= mix(tile_featureColor.rgb, vec3(1.0), highlight);
}
`;
}
function replaceDiffuseTextureCalls(source, diffuseAttributeOrUniformName) {
const functionCall = `texture(${diffuseAttributeOrUniformName}`;
let fromIndex = 0;
let startIndex = source.indexOf(functionCall, fromIndex);
let endIndex;
while (startIndex > -1) {
let nestedLevel = 0;
for (let i = startIndex; i < source.length; ++i) {
const character = source.charAt(i);
if (character === "(") {
++nestedLevel;
} else if (character === ")") {
--nestedLevel;
if (nestedLevel === 0) {
endIndex = i + 1;
break;
}
}
}
const extractedFunction = source.slice(startIndex, endIndex);
const replacedFunction = `tile_diffuse_final(${extractedFunction}, tile_diffuse)`;
source = source.slice(0, startIndex) + replacedFunction + source.slice(endIndex);
fromIndex = startIndex + replacedFunction.length;
startIndex = source.indexOf(functionCall, fromIndex);
}
return source;
}
function modifyDiffuse(source, diffuseAttributeOrUniformName, applyHighlight) {
if (!defined_default(diffuseAttributeOrUniformName)) {
return getDefaultShader(source, applyHighlight);
}
let regex = new RegExp(
`(uniform|attribute|in)\\s+(vec[34]|sampler2D)\\s+${diffuseAttributeOrUniformName};`
);
const uniformMatch = source.match(regex);
if (!defined_default(uniformMatch)) {
return getDefaultShader(source, applyHighlight);
}
const declaration = uniformMatch[0];
const type = uniformMatch[2];
source = ShaderSource_default.replaceMain(source, "tile_main");
source = source.replace(declaration, "");
const finalDiffuseFunction = "bool isWhite(vec3 color) \n{ \n return all(greaterThan(color, vec3(1.0 - czm_epsilon3))); \n} \nvec4 tile_diffuse_final(vec4 sourceDiffuse, vec4 tileDiffuse) \n{ \n vec4 blendDiffuse = mix(sourceDiffuse, tileDiffuse, tile_colorBlend); \n vec4 diffuse = isWhite(tileDiffuse.rgb) ? sourceDiffuse : blendDiffuse; \n return vec4(diffuse.rgb, sourceDiffuse.a); \n} \n";
const highlight = " tile_featureColor = czm_gammaCorrect(tile_featureColor); \n out_FragColor.a *= tile_featureColor.a; \n float highlight = ceil(tile_colorBlend); \n out_FragColor.rgb *= mix(tile_featureColor.rgb, vec3(1.0), highlight); \n";
let setColor;
if (type === "vec3" || type === "vec4") {
const sourceDiffuse = type === "vec3" ? `vec4(${diffuseAttributeOrUniformName}, 1.0)` : diffuseAttributeOrUniformName;
const replaceDiffuse = type === "vec3" ? "tile_diffuse.xyz" : "tile_diffuse";
regex = new RegExp(diffuseAttributeOrUniformName, "g");
source = source.replace(regex, replaceDiffuse);
setColor = ` vec4 source = ${sourceDiffuse};
tile_diffuse = tile_diffuse_final(source, tile_featureColor);
tile_main();
`;
} else if (type === "sampler2D") {
source = replaceDiffuseTextureCalls(source, diffuseAttributeOrUniformName);
setColor = " tile_diffuse = tile_featureColor; \n tile_main(); \n";
}
source = `${"uniform float tile_colorBlend; \nvec4 tile_diffuse = vec4(1.0); \n"}${finalDiffuseFunction}${declaration}
${source}
void tile_color(vec4 tile_featureColor)
{
${setColor}`;
if (applyHighlight) {
source += highlight;
}
source += "} \n";
return source;
}
Cesium3DTileBatchTable.prototype.getFragmentShaderCallback = function(handleTranslucent, diffuseAttributeOrUniformName, hasPremultipliedAlpha) {
if (this.featuresLength === 0) {
return;
}
return function(source) {
source = modifyDiffuse(source, diffuseAttributeOrUniformName, true);
if (ContextLimits_default.maximumVertexTextureImageUnits > 0) {
source += "uniform sampler2D tile_pickTexture; \nin vec2 tile_featureSt; \nin vec4 tile_featureColor; \nvoid main() \n{ \n tile_color(tile_featureColor); \n";
if (hasPremultipliedAlpha) {
source += " out_FragColor.rgb *= out_FragColor.a; \n";
}
source += "}";
} else {
if (handleTranslucent) {
source += "uniform bool tile_translucentCommand; \n";
}
source += "uniform sampler2D tile_pickTexture; \nuniform sampler2D tile_batchTexture; \nin vec2 tile_featureSt; \nvoid main() \n{ \n vec4 featureProperties = texture(tile_batchTexture, tile_featureSt); \n if (featureProperties.a == 0.0) { \n discard; \n } \n";
if (handleTranslucent) {
source += " bool isStyleTranslucent = (featureProperties.a != 1.0); \n if (czm_pass == czm_passTranslucent) \n { \n if (!isStyleTranslucent && !tile_translucentCommand) \n { \n discard; \n } \n } \n else \n { \n if (isStyleTranslucent) \n { \n discard; \n } \n } \n";
}
source += " tile_color(featureProperties); \n";
if (hasPremultipliedAlpha) {
source += " out_FragColor.rgb *= out_FragColor.a; \n";
}
source += "} \n";
}
return source;
};
};
Cesium3DTileBatchTable.prototype.getClassificationFragmentShaderCallback = function() {
if (this.featuresLength === 0) {
return;
}
return function(source) {
source = ShaderSource_default.replaceMain(source, "tile_main");
if (ContextLimits_default.maximumVertexTextureImageUnits > 0) {
source += "uniform sampler2D tile_pickTexture;\nin vec2 tile_featureSt; \nin vec4 tile_featureColor; \nvoid main() \n{ \n tile_main(); \n out_FragColor = tile_featureColor; \n out_FragColor.rgb *= out_FragColor.a; \n}";
} else {
source += "uniform sampler2D tile_batchTexture; \nuniform sampler2D tile_pickTexture;\nin vec2 tile_featureSt; \nvoid main() \n{ \n tile_main(); \n vec4 featureProperties = texture(tile_batchTexture, tile_featureSt); \n if (featureProperties.a == 0.0) { \n discard; \n } \n out_FragColor = featureProperties; \n out_FragColor.rgb *= out_FragColor.a; \n} \n";
}
return source;
};
};
function getColorBlend(batchTable) {
const tileset = batchTable._content.tileset;
const colorBlendMode = tileset.colorBlendMode;
const colorBlendAmount = tileset.colorBlendAmount;
if (colorBlendMode === Cesium3DTileColorBlendMode_default.HIGHLIGHT) {
return 0;
}
if (colorBlendMode === Cesium3DTileColorBlendMode_default.REPLACE) {
return 1;
}
if (colorBlendMode === Cesium3DTileColorBlendMode_default.MIX) {
return Math_default.clamp(colorBlendAmount, Math_default.EPSILON4, 1);
}
throw new DeveloperError_default(`Invalid color blend mode "${colorBlendMode}".`);
}
Cesium3DTileBatchTable.prototype.getUniformMapCallback = function() {
if (this.featuresLength === 0) {
return;
}
const that = this;
return function(uniformMap2) {
const batchUniformMap = {
tile_batchTexture: function() {
return defaultValue_default(
that._batchTexture.batchTexture,
that._batchTexture.defaultTexture
);
},
tile_textureDimensions: function() {
return that._batchTexture.textureDimensions;
},
tile_textureStep: function() {
return that._batchTexture.textureStep;
},
tile_colorBlend: function() {
return getColorBlend(that);
},
tile_pickTexture: function() {
return that._batchTexture.pickTexture;
}
};
return combine_default(uniformMap2, batchUniformMap);
};
};
Cesium3DTileBatchTable.prototype.getPickId = function() {
return "texture(tile_pickTexture, tile_featureSt)";
};
var StyleCommandsNeeded = {
ALL_OPAQUE: 0,
ALL_TRANSLUCENT: 1,
OPAQUE_AND_TRANSLUCENT: 2
};
Cesium3DTileBatchTable.prototype.addDerivedCommands = function(frameState, commandStart) {
const commandList = frameState.commandList;
const commandEnd = commandList.length;
const tile = this._content._tile;
const finalResolution = tile._finalResolution;
const tileset = tile.tileset;
const bivariateVisibilityTest = tileset.isSkippingLevelOfDetail && tileset.hasMixedContent && frameState.context.stencilBuffer;
const styleCommandsNeeded = getStyleCommandsNeeded(this);
for (let i = commandStart; i < commandEnd; ++i) {
const command = commandList[i];
if (command.pass === Pass_default.COMPUTE) {
continue;
}
let derivedCommands = command.derivedCommands.tileset;
if (!defined_default(derivedCommands) || command.dirty) {
derivedCommands = {};
command.derivedCommands.tileset = derivedCommands;
derivedCommands.originalCommand = deriveCommand(command);
command.dirty = false;
}
const originalCommand = derivedCommands.originalCommand;
if (styleCommandsNeeded !== StyleCommandsNeeded.ALL_OPAQUE && command.pass !== Pass_default.TRANSLUCENT) {
if (!defined_default(derivedCommands.translucent)) {
derivedCommands.translucent = deriveTranslucentCommand(originalCommand);
}
}
if (styleCommandsNeeded !== StyleCommandsNeeded.ALL_TRANSLUCENT && command.pass !== Pass_default.TRANSLUCENT) {
if (!defined_default(derivedCommands.opaque)) {
derivedCommands.opaque = deriveOpaqueCommand(originalCommand);
}
if (bivariateVisibilityTest) {
if (!finalResolution) {
if (!defined_default(derivedCommands.zback)) {
derivedCommands.zback = deriveZBackfaceCommand(
frameState.context,
originalCommand
);
}
tileset._backfaceCommands.push(derivedCommands.zback);
}
if (!defined_default(derivedCommands.stencil) || tile._selectionDepth !== getLastSelectionDepth(derivedCommands.stencil)) {
if (command.renderState.depthMask) {
derivedCommands.stencil = deriveStencilCommand(
originalCommand,
tile._selectionDepth
);
} else {
derivedCommands.stencil = derivedCommands.opaque;
}
}
}
}
const opaqueCommand = bivariateVisibilityTest ? derivedCommands.stencil : derivedCommands.opaque;
const translucentCommand = derivedCommands.translucent;
if (command.pass !== Pass_default.TRANSLUCENT) {
if (styleCommandsNeeded === StyleCommandsNeeded.ALL_OPAQUE) {
commandList[i] = opaqueCommand;
}
if (styleCommandsNeeded === StyleCommandsNeeded.ALL_TRANSLUCENT) {
commandList[i] = translucentCommand;
}
if (styleCommandsNeeded === StyleCommandsNeeded.OPAQUE_AND_TRANSLUCENT) {
commandList[i] = opaqueCommand;
commandList.push(translucentCommand);
}
} else {
commandList[i] = originalCommand;
}
}
};
function getStyleCommandsNeeded(batchTable) {
const translucentFeaturesLength = batchTable._batchTexture.translucentFeaturesLength;
if (translucentFeaturesLength === 0) {
return StyleCommandsNeeded.ALL_OPAQUE;
} else if (translucentFeaturesLength === batchTable.featuresLength) {
return StyleCommandsNeeded.ALL_TRANSLUCENT;
}
return StyleCommandsNeeded.OPAQUE_AND_TRANSLUCENT;
}
function deriveCommand(command) {
const derivedCommand = DrawCommand_default.shallowClone(command);
const translucentCommand = derivedCommand.pass === Pass_default.TRANSLUCENT;
derivedCommand.uniformMap = defined_default(derivedCommand.uniformMap) ? derivedCommand.uniformMap : {};
derivedCommand.uniformMap.tile_translucentCommand = function() {
return translucentCommand;
};
return derivedCommand;
}
function deriveTranslucentCommand(command) {
const derivedCommand = DrawCommand_default.shallowClone(command);
derivedCommand.pass = Pass_default.TRANSLUCENT;
derivedCommand.renderState = getTranslucentRenderState(command.renderState);
return derivedCommand;
}
function deriveOpaqueCommand(command) {
const derivedCommand = DrawCommand_default.shallowClone(command);
derivedCommand.renderState = getOpaqueRenderState(command.renderState);
return derivedCommand;
}
function getLogDepthPolygonOffsetFragmentShaderProgram(context, shaderProgram) {
let shader = context.shaderCache.getDerivedShaderProgram(
shaderProgram,
"zBackfaceLogDepth"
);
if (!defined_default(shader)) {
const fs = shaderProgram.fragmentShaderSource.clone();
fs.defines = defined_default(fs.defines) ? fs.defines.slice(0) : [];
fs.defines.push("POLYGON_OFFSET");
fs.sources.unshift(
"#ifdef GL_OES_standard_derivatives\n#extension GL_OES_standard_derivatives : enable\n#endif\n"
);
shader = context.shaderCache.createDerivedShaderProgram(
shaderProgram,
"zBackfaceLogDepth",
{
vertexShaderSource: shaderProgram.vertexShaderSource,
fragmentShaderSource: fs,
attributeLocations: shaderProgram._attributeLocations
}
);
}
return shader;
}
function deriveZBackfaceCommand(context, command) {
const derivedCommand = DrawCommand_default.shallowClone(command);
const rs = clone_default(derivedCommand.renderState, true);
rs.cull.enabled = true;
rs.cull.face = CullFace_default.FRONT;
rs.colorMask = {
red: false,
green: false,
blue: false,
alpha: false
};
rs.polygonOffset = {
enabled: true,
factor: 5,
units: 5
};
rs.stencilTest = StencilConstants_default.setCesium3DTileBit();
rs.stencilMask = StencilConstants_default.CESIUM_3D_TILE_MASK;
derivedCommand.renderState = RenderState_default.fromCache(rs);
derivedCommand.castShadows = false;
derivedCommand.receiveShadows = false;
derivedCommand.uniformMap = clone_default(command.uniformMap);
const polygonOffset = new Cartesian2_default(5, 5);
derivedCommand.uniformMap.u_polygonOffset = function() {
return polygonOffset;
};
derivedCommand.shaderProgram = getLogDepthPolygonOffsetFragmentShaderProgram(
context,
command.shaderProgram
);
return derivedCommand;
}
function deriveStencilCommand(command, reference) {
const derivedCommand = DrawCommand_default.shallowClone(command);
const rs = clone_default(derivedCommand.renderState, true);
rs.stencilTest.enabled = true;
rs.stencilTest.mask = StencilConstants_default.SKIP_LOD_MASK;
rs.stencilTest.reference = StencilConstants_default.CESIUM_3D_TILE_MASK | reference << StencilConstants_default.SKIP_LOD_BIT_SHIFT;
rs.stencilTest.frontFunction = StencilFunction_default.GREATER_OR_EQUAL;
rs.stencilTest.frontOperation.zPass = StencilOperation_default.REPLACE;
rs.stencilTest.backFunction = StencilFunction_default.GREATER_OR_EQUAL;
rs.stencilTest.backOperation.zPass = StencilOperation_default.REPLACE;
rs.stencilMask = StencilConstants_default.CESIUM_3D_TILE_MASK | StencilConstants_default.SKIP_LOD_MASK;
derivedCommand.renderState = RenderState_default.fromCache(rs);
return derivedCommand;
}
function getLastSelectionDepth(stencilCommand) {
const reference = stencilCommand.renderState.stencilTest.reference;
return (reference & StencilConstants_default.SKIP_LOD_MASK) >>> StencilConstants_default.SKIP_LOD_BIT_SHIFT;
}
function getTranslucentRenderState(renderState) {
const rs = clone_default(renderState, true);
rs.cull.enabled = false;
rs.depthTest.enabled = true;
rs.depthMask = false;
rs.blending = BlendingState_default.ALPHA_BLEND;
rs.stencilTest = StencilConstants_default.setCesium3DTileBit();
rs.stencilMask = StencilConstants_default.CESIUM_3D_TILE_MASK;
return RenderState_default.fromCache(rs);
}
function getOpaqueRenderState(renderState) {
const rs = clone_default(renderState, true);
rs.stencilTest = StencilConstants_default.setCesium3DTileBit();
rs.stencilMask = StencilConstants_default.CESIUM_3D_TILE_MASK;
return RenderState_default.fromCache(rs);
}
Cesium3DTileBatchTable.prototype.update = function(tileset, frameState) {
this._batchTexture.update(tileset, frameState);
};
Cesium3DTileBatchTable.prototype.isDestroyed = function() {
return false;
};
Cesium3DTileBatchTable.prototype.destroy = function() {
this._batchTexture = this._batchTexture && this._batchTexture.destroy();
return destroyObject_default(this);
};
var Cesium3DTileBatchTable_default = Cesium3DTileBatchTable;
// packages/engine/Source/Scene/Vector3DTileBatch.js
function Vector3DTileBatch(options) {
this.offset = options.offset;
this.count = options.count;
this.color = options.color;
this.batchIds = options.batchIds;
}
var Vector3DTileBatch_default = Vector3DTileBatch;
// packages/engine/Source/Shaders/VectorTileVS.js
var VectorTileVS_default = "in vec3 position;\nin float a_batchId;\n\nuniform mat4 u_modifiedModelViewProjection;\n\nvoid main()\n{\n gl_Position = czm_depthClamp(u_modifiedModelViewProjection * vec4(position, 1.0));\n}\n";
// packages/engine/Source/Scene/Cesium3DTileFeature.js
function Cesium3DTileFeature(content, batchId) {
this._content = content;
this._batchId = batchId;
this._color = void 0;
}
Object.defineProperties(Cesium3DTileFeature.prototype, {
/**
* Gets or sets if the feature will be shown. This is set for all features
* when a style's show is evaluated.
*
* @memberof Cesium3DTileFeature.prototype
*
* @type {boolean}
*
* @default true
*/
show: {
get: function() {
return this._content.batchTable.getShow(this._batchId);
},
set: function(value) {
this._content.batchTable.setShow(this._batchId, value);
}
},
/**
* Gets or sets the highlight color multiplied with the feature's color. When
* this is white, the feature's color is not changed. This is set for all features
* when a style's color is evaluated.
*
* @memberof Cesium3DTileFeature.prototype
*
* @type {Color}
*
* @default {@link Color.WHITE}
*/
color: {
get: function() {
if (!defined_default(this._color)) {
this._color = new Color_default();
}
return this._content.batchTable.getColor(this._batchId, this._color);
},
set: function(value) {
this._content.batchTable.setColor(this._batchId, value);
}
},
/**
* Gets a typed array containing the ECEF positions of the polyline.
* Returns undefined if {@link Cesium3DTileset#vectorKeepDecodedPositions} is false
* or the feature is not a polyline in a vector tile.
*
* @memberof Cesium3DTileFeature.prototype
*
* @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.
*
* @type {Float64Array}
*/
polylinePositions: {
get: function() {
if (!defined_default(this._content.getPolylinePositions)) {
return void 0;
}
return this._content.getPolylinePositions(this._batchId);
}
},
/**
* Gets the content of the tile containing the feature.
*
* @memberof Cesium3DTileFeature.prototype
*
* @type {Cesium3DTileContent}
*
* @readonly
* @private
*/
content: {
get: function() {
return this._content;
}
},
/**
* Gets the tileset containing the feature.
*
* @memberof Cesium3DTileFeature.prototype
*
* @type {Cesium3DTileset}
*
* @readonly
*/
tileset: {
get: function() {
return this._content.tileset;
}
},
/**
* All objects returned by {@link Scene#pick} have a primitive
property. This returns
* the tileset containing the feature.
*
* @memberof Cesium3DTileFeature.prototype
*
* @type {Cesium3DTileset}
*
* @readonly
*/
primitive: {
get: function() {
return this._content.tileset;
}
},
/**
* Get the feature ID associated with this feature. For 3D Tiles 1.0, the
* batch ID is returned. For EXT_mesh_features, this is the feature ID from
* the selected feature ID set.
*
* @memberof Cesium3DTileFeature.prototype
*
* @type {number}
*
* @readonly
* @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.
*/
featureId: {
get: function() {
return this._batchId;
}
},
/**
* @private
*/
pickId: {
get: function() {
return this._content.batchTable.getPickColor(this._batchId);
}
}
});
Cesium3DTileFeature.prototype.hasProperty = function(name) {
return this._content.batchTable.hasProperty(this._batchId, name);
};
Cesium3DTileFeature.prototype.getPropertyIds = function(results) {
return this._content.batchTable.getPropertyIds(this._batchId, results);
};
Cesium3DTileFeature.prototype.getProperty = function(name) {
return this._content.batchTable.getProperty(this._batchId, name);
};
Cesium3DTileFeature.getPropertyInherited = function(content, batchId, name) {
const batchTable = content.batchTable;
if (defined_default(batchTable)) {
if (batchTable.hasPropertyBySemantic(batchId, name)) {
return batchTable.getPropertyBySemantic(batchId, name);
}
if (batchTable.hasProperty(batchId, name)) {
return batchTable.getProperty(batchId, name);
}
}
const contentMetadata = content.metadata;
if (defined_default(contentMetadata)) {
if (contentMetadata.hasPropertyBySemantic(name)) {
return contentMetadata.getPropertyBySemantic(name);
}
if (contentMetadata.hasProperty(name)) {
return contentMetadata.getProperty(name);
}
}
const tile = content.tile;
const tileMetadata = tile.metadata;
if (defined_default(tileMetadata)) {
if (tileMetadata.hasPropertyBySemantic(name)) {
return tileMetadata.getPropertyBySemantic(name);
}
if (tileMetadata.hasProperty(name)) {
return tileMetadata.getProperty(name);
}
}
let subtreeMetadata;
if (defined_default(tile.implicitSubtree)) {
subtreeMetadata = tile.implicitSubtree.metadata;
}
if (defined_default(subtreeMetadata)) {
if (subtreeMetadata.hasPropertyBySemantic(name)) {
return subtreeMetadata.getPropertyBySemantic(name);
}
if (subtreeMetadata.hasProperty(name)) {
return subtreeMetadata.getProperty(name);
}
}
const groupMetadata = defined_default(content.group) ? content.group.metadata : void 0;
if (defined_default(groupMetadata)) {
if (groupMetadata.hasPropertyBySemantic(name)) {
return groupMetadata.getPropertyBySemantic(name);
}
if (groupMetadata.hasProperty(name)) {
return groupMetadata.getProperty(name);
}
}
const tilesetMetadata = content.tileset.metadata;
if (defined_default(tilesetMetadata)) {
if (tilesetMetadata.hasPropertyBySemantic(name)) {
return tilesetMetadata.getPropertyBySemantic(name);
}
if (tilesetMetadata.hasProperty(name)) {
return tilesetMetadata.getProperty(name);
}
}
return void 0;
};
Cesium3DTileFeature.prototype.getPropertyInherited = function(name) {
return Cesium3DTileFeature.getPropertyInherited(
this._content,
this._batchId,
name
);
};
Cesium3DTileFeature.prototype.setProperty = function(name, value) {
this._content.batchTable.setProperty(this._batchId, name, value);
this._content.featurePropertiesDirty = true;
};
Cesium3DTileFeature.prototype.isExactClass = function(className) {
return this._content.batchTable.isExactClass(this._batchId, className);
};
Cesium3DTileFeature.prototype.isClass = function(className) {
return this._content.batchTable.isClass(this._batchId, className);
};
Cesium3DTileFeature.prototype.getExactClassName = function() {
return this._content.batchTable.getExactClassName(this._batchId);
};
var Cesium3DTileFeature_default = Cesium3DTileFeature;
// node_modules/jsep/dist/jsep.js
var Hooks = class {
/**
* @callback HookCallback
* @this {*|Jsep} this
* @param {Jsep} env
* @returns: void
*/
/**
* Adds the given callback to the list of callbacks for the given hook.
*
* The callback will be invoked when the hook it is registered for is run.
*
* One callback function can be registered to multiple hooks and the same hook multiple times.
*
* @param {string|object} name The name of the hook, or an object of callbacks keyed by name
* @param {HookCallback|boolean} callback The callback function which is given environment variables.
* @param {?boolean} [first=false] Will add the hook to the top of the list (defaults to the bottom)
* @public
*/
add(name, callback, first) {
if (typeof arguments[0] != "string") {
for (let name2 in arguments[0]) {
this.add(name2, arguments[0][name2], arguments[1]);
}
} else {
(Array.isArray(name) ? name : [name]).forEach(function(name2) {
this[name2] = this[name2] || [];
if (callback) {
this[name2][first ? "unshift" : "push"](callback);
}
}, this);
}
}
/**
* Runs a hook invoking all registered callbacks with the given environment variables.
*
* Callbacks will be invoked synchronously and in the order in which they were registered.
*
* @param {string} name The name of the hook.
* @param {Object1
.
*
* @memberof ImplicitAvailabilityBitstream.prototype
*
* @type {number}
* @readonly
* @private
*/
availableCount: {
get: function() {
return this._availableCount;
}
}
});
ImplicitAvailabilityBitstream.prototype.getBit = function(index) {
if (index < 0 || index >= this._lengthBits) {
throw new DeveloperError_default("Bit index out of bounds.");
}
if (defined_default(this._constant)) {
return this._constant;
}
const byteIndex = index >> 3;
const bitIndex = index % 8;
return (this._bitstream[byteIndex] >> bitIndex & 1) === 1;
};
var ImplicitAvailabilityBitstream_default = ImplicitAvailabilityBitstream;
// packages/engine/Source/Scene/ImplicitMetadataView.js
function ImplicitMetadataView(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const metadataTable = options.metadataTable;
const metadataClass = options.class;
const entityId = options.entityId;
const propertyTableJson = options.propertyTableJson;
Check_default.typeOf.object("options.metadataTable", metadataTable);
Check_default.typeOf.object("options.class", metadataClass);
Check_default.typeOf.number("options.entityId", entityId);
Check_default.typeOf.object("options.propertyTableJson", propertyTableJson);
this._class = metadataClass;
this._metadataTable = metadataTable;
this._entityId = entityId;
this._extensions = propertyTableJson.extensions;
this._extras = propertyTableJson.extras;
}
Object.defineProperties(ImplicitMetadataView.prototype, {
/**
* The class that properties conform to.
*
* @memberof ImplicitMetadataView.prototype
* @type {MetadataClass}
* @readonly
*/
class: {
get: function() {
return this._class;
}
},
/**
* Extra user-defined properties.
*
* @memberof ImplicitMetadataView.prototype
* @type {object}
* @readonly
*/
extras: {
get: function() {
return this._extras;
}
},
/**
* An object containing extensions.
*
* @memberof ImplicitMetadataView.prototype
* @type {object}
* @readonly
*/
extensions: {
get: function() {
return this._extensions;
}
}
});
ImplicitMetadataView.prototype.hasProperty = function(propertyId) {
return this._metadataTable.hasProperty(propertyId);
};
ImplicitMetadataView.prototype.hasPropertyBySemantic = function(semantic) {
return this._metadataTable.hasPropertyBySemantic(semantic);
};
ImplicitMetadataView.prototype.getPropertyIds = function(results) {
return this._metadataTable.getPropertyIds(results);
};
ImplicitMetadataView.prototype.getProperty = function(propertyId) {
return this._metadataTable.getProperty(this._entityId, propertyId);
};
ImplicitMetadataView.prototype.setProperty = function(propertyId, value) {
return this._metadataTable.setProperty(this._entityId, propertyId, value);
};
ImplicitMetadataView.prototype.getPropertyBySemantic = function(semantic) {
return this._metadataTable.getPropertyBySemantic(this._entityId, semantic);
};
ImplicitMetadataView.prototype.setPropertyBySemantic = function(semantic, value) {
return this._metadataTable.setPropertyBySemantic(
this._entityId,
semantic,
value
);
};
var ImplicitMetadataView_default = ImplicitMetadataView;
// packages/engine/Source/Scene/ImplicitSubdivisionScheme.js
var ImplicitSubdivisionScheme = {
/**
* A quadtree divides a parent tile into four children, split at the midpoint
* of the x and y dimensions of the bounding box
* @type {string}
* @constant
* @private
*/
QUADTREE: "QUADTREE",
/**
* An octree divides a parent tile into eight children, split at the midpoint
* of the x, y, and z dimensions of the bounding box.
* @type {string}
* @constant
* @private
*/
OCTREE: "OCTREE"
};
ImplicitSubdivisionScheme.getBranchingFactor = function(subdivisionScheme) {
switch (subdivisionScheme) {
case ImplicitSubdivisionScheme.OCTREE:
return 8;
case ImplicitSubdivisionScheme.QUADTREE:
return 4;
default:
throw new DeveloperError_default("subdivisionScheme is not a valid value.");
}
};
var ImplicitSubdivisionScheme_default = Object.freeze(ImplicitSubdivisionScheme);
// packages/engine/Source/Scene/MetadataEntity.js
function MetadataEntity() {
}
Object.defineProperties(MetadataEntity.prototype, {
/**
* The class that properties conform to.
*
* @memberof MetadataEntity.prototype
* @type {MetadataClass}
* @readonly
* @private
*/
class: {
// eslint-disable-next-line getter-return
get: function() {
DeveloperError_default.throwInstantiationError();
}
}
});
MetadataEntity.prototype.hasProperty = function(propertyId) {
DeveloperError_default.throwInstantiationError();
};
MetadataEntity.prototype.hasPropertyBySemantic = function(semantic) {
DeveloperError_default.throwInstantiationError();
};
MetadataEntity.prototype.getPropertyIds = function(results) {
DeveloperError_default.throwInstantiationError();
};
MetadataEntity.prototype.getProperty = function(propertyId) {
DeveloperError_default.throwInstantiationError();
};
MetadataEntity.prototype.setProperty = function(propertyId, value) {
DeveloperError_default.throwInstantiationError();
};
MetadataEntity.prototype.getPropertyBySemantic = function(semantic) {
DeveloperError_default.throwInstantiationError();
};
MetadataEntity.prototype.setPropertyBySemantic = function(semantic, value) {
DeveloperError_default.throwInstantiationError();
};
MetadataEntity.hasProperty = function(propertyId, properties, classDefinition) {
Check_default.typeOf.string("propertyId", propertyId);
Check_default.typeOf.object("properties", properties);
Check_default.typeOf.object("classDefinition", classDefinition);
if (defined_default(properties[propertyId])) {
return true;
}
const classProperties = classDefinition.properties;
if (!defined_default(classProperties)) {
return false;
}
const classProperty = classProperties[propertyId];
if (defined_default(classProperty) && defined_default(classProperty.default)) {
return true;
}
return false;
};
MetadataEntity.hasPropertyBySemantic = function(semantic, properties, classDefinition) {
Check_default.typeOf.string("semantic", semantic);
Check_default.typeOf.object("properties", properties);
Check_default.typeOf.object("classDefinition", classDefinition);
const propertiesBySemantic = classDefinition.propertiesBySemantic;
if (!defined_default(propertiesBySemantic)) {
return false;
}
const property = propertiesBySemantic[semantic];
return defined_default(property);
};
MetadataEntity.getPropertyIds = function(properties, classDefinition, results) {
Check_default.typeOf.object("properties", properties);
Check_default.typeOf.object("classDefinition", classDefinition);
results = defined_default(results) ? results : [];
results.length = 0;
for (const propertyId in properties) {
if (properties.hasOwnProperty(propertyId) && defined_default(properties[propertyId])) {
results.push(propertyId);
}
}
const classProperties = classDefinition.properties;
if (defined_default(classProperties)) {
for (const classPropertyId in classProperties) {
if (classProperties.hasOwnProperty(classPropertyId) && !defined_default(properties[classPropertyId]) && defined_default(classProperties[classPropertyId].default)) {
results.push(classPropertyId);
}
}
}
return results;
};
MetadataEntity.getProperty = function(propertyId, properties, classDefinition) {
Check_default.typeOf.string("propertyId", propertyId);
Check_default.typeOf.object("properties", properties);
Check_default.typeOf.object("classDefinition", classDefinition);
if (!defined_default(classDefinition.properties[propertyId])) {
throw new DeveloperError_default(`Class definition missing property ${propertyId}`);
}
const classProperty = classDefinition.properties[propertyId];
let value = properties[propertyId];
if (Array.isArray(value)) {
value = value.slice();
}
const enableNestedArrays = true;
value = classProperty.handleNoData(value);
if (!defined_default(value) && defined_default(classProperty.default)) {
value = clone_default(classProperty.default, true);
return classProperty.unpackVectorAndMatrixTypes(value, enableNestedArrays);
}
if (!defined_default(value)) {
return void 0;
}
value = classProperty.normalize(value);
value = classProperty.applyValueTransform(value);
return classProperty.unpackVectorAndMatrixTypes(value, enableNestedArrays);
};
MetadataEntity.setProperty = function(propertyId, value, properties, classDefinition) {
Check_default.typeOf.string("propertyId", propertyId);
Check_default.defined("value", value);
Check_default.typeOf.object("properties", properties);
Check_default.typeOf.object("classDefinition", classDefinition);
if (!defined_default(properties[propertyId])) {
return false;
}
if (Array.isArray(value)) {
value = value.slice();
}
let classProperty;
const classProperties = classDefinition.properties;
if (defined_default(classProperties)) {
classProperty = classProperties[propertyId];
}
const enableNestedArrays = true;
if (defined_default(classProperty)) {
value = classProperty.packVectorAndMatrixTypes(value, enableNestedArrays);
value = classProperty.unapplyValueTransform(value);
value = classProperty.unnormalize(value);
}
properties[propertyId] = value;
return true;
};
MetadataEntity.getPropertyBySemantic = function(semantic, properties, classDefinition) {
Check_default.typeOf.string("semantic", semantic);
Check_default.typeOf.object("properties", properties);
Check_default.typeOf.object("classDefinition", classDefinition);
const propertiesBySemantic = classDefinition.propertiesBySemantic;
if (!defined_default(propertiesBySemantic)) {
return void 0;
}
const property = propertiesBySemantic[semantic];
if (defined_default(property)) {
return MetadataEntity.getProperty(property.id, properties, classDefinition);
}
return void 0;
};
MetadataEntity.setPropertyBySemantic = function(semantic, value, properties, classDefinition) {
Check_default.typeOf.string("semantic", semantic);
Check_default.defined("value", value);
Check_default.typeOf.object("properties", properties);
Check_default.typeOf.object("classDefinition", classDefinition);
const propertiesBySemantic = classDefinition.propertiesBySemantic;
if (!defined_default(propertiesBySemantic)) {
return false;
}
const property = classDefinition.propertiesBySemantic[semantic];
if (defined_default(property)) {
return MetadataEntity.setProperty(
property.id,
value,
properties,
classDefinition
);
}
return false;
};
var MetadataEntity_default = MetadataEntity;
// packages/engine/Source/Scene/ImplicitSubtreeMetadata.js
function ImplicitSubtreeMetadata(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const subtreeMetadata = options.subtreeMetadata;
const metadataClass = options.class;
Check_default.typeOf.object("options.subtreeMetadata", subtreeMetadata);
Check_default.typeOf.object("options.class", metadataClass);
const properties = defined_default(subtreeMetadata.properties) ? subtreeMetadata.properties : {};
this._class = metadataClass;
this._properties = properties;
this._extras = subtreeMetadata.extras;
this._extensions = subtreeMetadata.extensions;
}
Object.defineProperties(ImplicitSubtreeMetadata.prototype, {
/**
* The class that properties conform to.
*
* @memberof ImplicitSubtreeMetadata.prototype
* @type {MetadataClass}
* @readonly
* @private
*/
class: {
get: function() {
return this._class;
}
},
/**
* Extra user-defined properties.
*
* @memberof ImplicitSubtreeMetadata.prototype
* @type {object}
* @readonly
* @private
*/
extras: {
get: function() {
return this._extras;
}
},
/**
* An object containing extensions.
*
* @memberof ImplicitSubtreeMetadata.prototype
* @type {object}
* @readonly
* @private
*/
extensions: {
get: function() {
return this._extensions;
}
}
});
ImplicitSubtreeMetadata.prototype.hasProperty = function(propertyId) {
return MetadataEntity_default.hasProperty(propertyId, this._properties, this._class);
};
ImplicitSubtreeMetadata.prototype.hasPropertyBySemantic = function(semantic) {
return MetadataEntity_default.hasPropertyBySemantic(
semantic,
this._properties,
this._class
);
};
ImplicitSubtreeMetadata.prototype.getPropertyIds = function(results) {
return MetadataEntity_default.getPropertyIds(this._properties, this._class, results);
};
ImplicitSubtreeMetadata.prototype.getProperty = function(propertyId) {
return MetadataEntity_default.getProperty(propertyId, this._properties, this._class);
};
ImplicitSubtreeMetadata.prototype.setProperty = function(propertyId, value) {
return MetadataEntity_default.setProperty(
propertyId,
value,
this._properties,
this._class
);
};
ImplicitSubtreeMetadata.prototype.getPropertyBySemantic = function(semantic) {
return MetadataEntity_default.getPropertyBySemantic(
semantic,
this._properties,
this._class
);
};
ImplicitSubtreeMetadata.prototype.setPropertyBySemantic = function(semantic, value) {
return MetadataEntity_default.setPropertyBySemantic(
semantic,
value,
this._properties,
this._class
);
};
var ImplicitSubtreeMetadata_default = ImplicitSubtreeMetadata;
// packages/engine/Source/Scene/MetadataComponentType.js
var MetadataComponentType = {
/**
* An 8-bit signed integer
*
* @type {string}
* @constant
*/
INT8: "INT8",
/**
* An 8-bit unsigned integer
*
* @type {string}
* @constant
*/
UINT8: "UINT8",
/**
* A 16-bit signed integer
*
* @type {string}
* @constant
*/
INT16: "INT16",
/**
* A 16-bit unsigned integer
*
* @type {string}
* @constant
*/
UINT16: "UINT16",
/**
* A 32-bit signed integer
*
* @type {string}
* @constant
*/
INT32: "INT32",
/**
* A 32-bit unsigned integer
*
* @type {string}
* @constant
*/
UINT32: "UINT32",
/**
* A 64-bit signed integer. This type requires BigInt support.
*
* @see FeatureDetection.supportsBigInt
*
* @type {string}
* @constant
*/
INT64: "INT64",
/**
* A 64-bit signed integer. This type requires BigInt support
*
* @see FeatureDetection.supportsBigInt
*
* @type {string}
* @constant
*/
UINT64: "UINT64",
/**
* A 32-bit (single precision) floating point number
*
* @type {string}
* @constant
*/
FLOAT32: "FLOAT32",
/**
* A 64-bit (double precision) floating point number
*
* @type {string}
* @constant
*/
FLOAT64: "FLOAT64"
};
MetadataComponentType.getMinimum = function(type) {
Check_default.typeOf.string("type", type);
switch (type) {
case MetadataComponentType.INT8:
return -128;
case MetadataComponentType.UINT8:
return 0;
case MetadataComponentType.INT16:
return -32768;
case MetadataComponentType.UINT16:
return 0;
case MetadataComponentType.INT32:
return -2147483648;
case MetadataComponentType.UINT32:
return 0;
case MetadataComponentType.INT64:
if (FeatureDetection_default.supportsBigInt()) {
return BigInt("-9223372036854775808");
}
return -Math.pow(2, 63);
case MetadataComponentType.UINT64:
if (FeatureDetection_default.supportsBigInt()) {
return BigInt(0);
}
return 0;
case MetadataComponentType.FLOAT32:
return -34028234663852886e22;
case MetadataComponentType.FLOAT64:
return -Number.MAX_VALUE;
}
};
MetadataComponentType.getMaximum = function(type) {
Check_default.typeOf.string("type", type);
switch (type) {
case MetadataComponentType.INT8:
return 127;
case MetadataComponentType.UINT8:
return 255;
case MetadataComponentType.INT16:
return 32767;
case MetadataComponentType.UINT16:
return 65535;
case MetadataComponentType.INT32:
return 2147483647;
case MetadataComponentType.UINT32:
return 4294967295;
case MetadataComponentType.INT64:
if (FeatureDetection_default.supportsBigInt()) {
return BigInt("9223372036854775807");
}
return Math.pow(2, 63) - 1;
case MetadataComponentType.UINT64:
if (FeatureDetection_default.supportsBigInt()) {
return BigInt("18446744073709551615");
}
return Math.pow(2, 64) - 1;
case MetadataComponentType.FLOAT32:
return 34028234663852886e22;
case MetadataComponentType.FLOAT64:
return Number.MAX_VALUE;
}
};
MetadataComponentType.isIntegerType = function(type) {
Check_default.typeOf.string("type", type);
switch (type) {
case MetadataComponentType.INT8:
case MetadataComponentType.UINT8:
case MetadataComponentType.INT16:
case MetadataComponentType.UINT16:
case MetadataComponentType.INT32:
case MetadataComponentType.UINT32:
case MetadataComponentType.INT64:
case MetadataComponentType.UINT64:
return true;
default:
return false;
}
};
MetadataComponentType.isUnsignedIntegerType = function(type) {
Check_default.typeOf.string("type", type);
switch (type) {
case MetadataComponentType.UINT8:
case MetadataComponentType.UINT16:
case MetadataComponentType.UINT32:
case MetadataComponentType.UINT64:
return true;
default:
return false;
}
};
MetadataComponentType.isVectorCompatible = function(type) {
Check_default.typeOf.string("type", type);
switch (type) {
case MetadataComponentType.INT8:
case MetadataComponentType.UINT8:
case MetadataComponentType.INT16:
case MetadataComponentType.UINT16:
case MetadataComponentType.INT32:
case MetadataComponentType.UINT32:
case MetadataComponentType.FLOAT32:
case MetadataComponentType.FLOAT64:
return true;
default:
return false;
}
};
MetadataComponentType.normalize = function(value, type) {
if (typeof value !== "number" && typeof value !== "bigint") {
throw new DeveloperError_default("value must be a number or a BigInt");
}
if (!MetadataComponentType.isIntegerType(type)) {
throw new DeveloperError_default("type must be an integer type");
}
return Math.max(
Number(value) / Number(MetadataComponentType.getMaximum(type)),
-1
);
};
MetadataComponentType.unnormalize = function(value, type) {
Check_default.typeOf.number("value", value);
if (!MetadataComponentType.isIntegerType(type)) {
throw new DeveloperError_default("type must be an integer type");
}
const max3 = MetadataComponentType.getMaximum(type);
const min3 = MetadataComponentType.isUnsignedIntegerType(type) ? 0 : -max3;
value = Math_default.sign(value) * Math.round(Math.abs(value) * Number(max3));
if ((type === MetadataComponentType.INT64 || type === MetadataComponentType.UINT64) && FeatureDetection_default.supportsBigInt()) {
value = BigInt(value);
}
if (value > max3) {
return max3;
}
if (value < min3) {
return min3;
}
return value;
};
MetadataComponentType.applyValueTransform = function(value, offset2, scale) {
return scale * value + offset2;
};
MetadataComponentType.unapplyValueTransform = function(value, offset2, scale) {
if (scale === 0) {
return 0;
}
return (value - offset2) / scale;
};
MetadataComponentType.getSizeInBytes = function(type) {
Check_default.typeOf.string("type", type);
switch (type) {
case MetadataComponentType.INT8:
case MetadataComponentType.UINT8:
return 1;
case MetadataComponentType.INT16:
case MetadataComponentType.UINT16:
return 2;
case MetadataComponentType.INT32:
case MetadataComponentType.UINT32:
return 4;
case MetadataComponentType.INT64:
case MetadataComponentType.UINT64:
return 8;
case MetadataComponentType.FLOAT32:
return 4;
case MetadataComponentType.FLOAT64:
return 8;
}
};
MetadataComponentType.fromComponentDatatype = function(componentDatatype) {
Check_default.typeOf.number("componentDatatype", componentDatatype);
switch (componentDatatype) {
case ComponentDatatype_default.BYTE:
return MetadataComponentType.INT8;
case ComponentDatatype_default.UNSIGNED_BYTE:
return MetadataComponentType.UINT8;
case ComponentDatatype_default.SHORT:
return MetadataComponentType.INT16;
case ComponentDatatype_default.UNSIGNED_SHORT:
return MetadataComponentType.UINT16;
case ComponentDatatype_default.INT:
return MetadataComponentType.INT32;
case ComponentDatatype_default.UNSIGNED_INT:
return MetadataComponentType.UINT32;
case ComponentDatatype_default.FLOAT:
return MetadataComponentType.FLOAT32;
case ComponentDatatype_default.DOUBLE:
return MetadataComponentType.FLOAT64;
}
};
MetadataComponentType.toComponentDatatype = function(type) {
Check_default.typeOf.string("type", type);
switch (type) {
case MetadataComponentType.INT8:
return ComponentDatatype_default.BYTE;
case MetadataComponentType.UINT8:
return ComponentDatatype_default.UNSIGNED_BYTE;
case MetadataComponentType.INT16:
return ComponentDatatype_default.SHORT;
case MetadataComponentType.UINT16:
return ComponentDatatype_default.UNSIGNED_SHORT;
case MetadataComponentType.INT32:
return ComponentDatatype_default.INT;
case MetadataComponentType.UINT32:
return ComponentDatatype_default.UNSIGNED_INT;
case MetadataComponentType.FLOAT32:
return ComponentDatatype_default.FLOAT;
case MetadataComponentType.FLOAT64:
return ComponentDatatype_default.DOUBLE;
}
};
var MetadataComponentType_default = Object.freeze(MetadataComponentType);
// packages/engine/Source/Scene/MetadataType.js
var MetadataType = {
/**
* A single component
*
* @type {string}
* @constant
*/
SCALAR: "SCALAR",
/**
* A vector with two components
*
* @type {string}
* @constant
*/
VEC2: "VEC2",
/**
* A vector with three components
*
* @type {string}
* @constant
*/
VEC3: "VEC3",
/**
* A vector with four components
*
* @type {string}
* @constant
*/
VEC4: "VEC4",
/**
* A 2x2 matrix, stored in column-major format.
*
* @type {string}
* @constant
*/
MAT2: "MAT2",
/**
* A 3x3 matrix, stored in column-major format.
*
* @type {string}
* @constant
*/
MAT3: "MAT3",
/**
* A 4x4 matrix, stored in column-major format.
*
* @type {string}
* @constant
*/
MAT4: "MAT4",
/**
* A boolean (true/false) value
*
* @type {string}
* @constant
*/
BOOLEAN: "BOOLEAN",
/**
* A UTF-8 encoded string value
*
* @type {string}
* @constant
*/
STRING: "STRING",
/**
* An enumerated value. This type is used in conjunction with a {@link MetadataEnum} to describe the valid values.
*
* @see MetadataEnum
*
* @type {string}
* @constant
*/
ENUM: "ENUM"
};
MetadataType.isVectorType = function(type) {
Check_default.typeOf.string("type", type);
switch (type) {
case MetadataType.VEC2:
case MetadataType.VEC3:
case MetadataType.VEC4:
return true;
default:
return false;
}
};
MetadataType.isMatrixType = function(type) {
Check_default.typeOf.string("type", type);
switch (type) {
case MetadataType.MAT2:
case MetadataType.MAT3:
case MetadataType.MAT4:
return true;
default:
return false;
}
};
MetadataType.getComponentCount = function(type) {
Check_default.typeOf.string("type", type);
switch (type) {
case MetadataType.SCALAR:
case MetadataType.STRING:
case MetadataType.ENUM:
case MetadataType.BOOLEAN:
return 1;
case MetadataType.VEC2:
return 2;
case MetadataType.VEC3:
return 3;
case MetadataType.VEC4:
return 4;
case MetadataType.MAT2:
return 4;
case MetadataType.MAT3:
return 9;
case MetadataType.MAT4:
return 16;
default:
throw new DeveloperError_default(`Invalid metadata type ${type}`);
}
};
MetadataType.getMathType = function(type) {
switch (type) {
case MetadataType.VEC2:
return Cartesian2_default;
case MetadataType.VEC3:
return Cartesian3_default;
case MetadataType.VEC4:
return Cartesian4_default;
case MetadataType.MAT2:
return Matrix2_default;
case MetadataType.MAT3:
return Matrix3_default;
case MetadataType.MAT4:
return Matrix4_default;
default:
return void 0;
}
};
var MetadataType_default = Object.freeze(MetadataType);
// packages/engine/Source/Scene/MetadataClassProperty.js
function MetadataClassProperty(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const id = options.id;
const type = options.type;
Check_default.typeOf.string("options.id", id);
Check_default.typeOf.string("options.type", type);
const componentType = options.componentType;
const enumType = options.enumType;
const normalized = defined_default(componentType) && MetadataComponentType_default.isIntegerType(componentType) && defaultValue_default(options.normalized, false);
this._id = id;
this._name = options.name;
this._description = options.description;
this._semantic = options.semantic;
this._isLegacyExtension = options.isLegacyExtension;
this._type = type;
this._componentType = componentType;
this._enumType = enumType;
this._valueType = defined_default(enumType) ? enumType.valueType : componentType;
this._isArray = defaultValue_default(options.isArray, false);
this._isVariableLengthArray = defaultValue_default(
options.isVariableLengthArray,
false
);
this._arrayLength = options.arrayLength;
this._min = clone_default(options.min, true);
this._max = clone_default(options.max, true);
this._normalized = normalized;
let offset2 = clone_default(options.offset, true);
let scale = clone_default(options.scale, true);
const hasValueTransform = defined_default(offset2) || defined_default(scale);
const enableNestedArrays = true;
if (!defined_default(offset2)) {
offset2 = this.expandConstant(0, enableNestedArrays);
}
if (!defined_default(scale)) {
scale = this.expandConstant(1, enableNestedArrays);
}
this._offset = offset2;
this._scale = scale;
this._hasValueTransform = hasValueTransform;
this._noData = clone_default(options.noData, true);
this._default = clone_default(options.default, true);
this._required = defaultValue_default(options.required, true);
this._extras = clone_default(options.extras, true);
this._extensions = clone_default(options.extensions, true);
}
MetadataClassProperty.fromJson = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const id = options.id;
const property = options.property;
Check_default.typeOf.string("options.id", id);
Check_default.typeOf.object("options.property", property);
Check_default.typeOf.string("options.property.type", property.type);
const isLegacyExtension = isLegacy(property);
const parsedType = parseType(property, options.enums);
let required;
if (!defined_default(isLegacyExtension)) {
required = false;
} else if (isLegacyExtension) {
required = defined_default(property.optional) ? !property.optional : true;
} else {
required = defaultValue_default(property.required, false);
}
return new MetadataClassProperty({
id,
type: parsedType.type,
componentType: parsedType.componentType,
enumType: parsedType.enumType,
isArray: parsedType.isArray,
isVariableLengthArray: parsedType.isVariableLengthArray,
arrayLength: parsedType.arrayLength,
normalized: property.normalized,
min: property.min,
max: property.max,
offset: property.offset,
scale: property.scale,
noData: property.noData,
default: property.default,
required,
name: property.name,
description: property.description,
semantic: property.semantic,
extras: property.extras,
extensions: property.extensions,
isLegacyExtension
});
};
Object.defineProperties(MetadataClassProperty.prototype, {
/**
* The ID of the property.
*
* @memberof MetadataClassProperty.prototype
* @type {string}
* @readonly
*/
id: {
get: function() {
return this._id;
}
},
/**
* The name of the property.
*
* @memberof MetadataClassProperty.prototype
* @type {string}
* @readonly
*/
name: {
get: function() {
return this._name;
}
},
/**
* The description of the property.
*
* @memberof MetadataClassProperty.prototype
* @type {string}
* @readonly
*/
description: {
get: function() {
return this._description;
}
},
/**
* The type of the property such as SCALAR, VEC2, VEC3
*
* @memberof MetadataClassProperty.prototype
* @type {MetadataType}
* @readonly
*/
type: {
get: function() {
return this._type;
}
},
/**
* The enum type of the property. Only defined when type is ENUM.
*
* @memberof MetadataClassProperty.prototype
* @type {MetadataEnum}
* @readonly
*/
enumType: {
get: function() {
return this._enumType;
}
},
/**
* The component type of the property. This includes integer
* (e.g. INT8 or UINT16), and floating point (FLOAT32 and FLOAT64) values
*
* @memberof MetadataClassProperty.prototype
* @type {MetadataComponentType}
* @readonly
*/
componentType: {
get: function() {
return this._componentType;
}
},
/**
* The datatype used for storing each component of the property. This
* is usually the same as componentType except for ENUM, where this
* returns an integer type
*
* @memberof MetadataClassProperty.prototype
* @type {MetadataComponentType}
* @readonly
* @private
*/
valueType: {
get: function() {
return this._valueType;
}
},
/**
* True if a property is an array (either fixed length or variable length),
* false otherwise.
*
* @memberof MetadataClassProperty.prototype
* @type {boolean}
* @readonly
*/
isArray: {
get: function() {
return this._isArray;
}
},
/**
* True if a property is a variable length array, false otherwise.
*
* @memberof MetadataClassProperty.prototype
* @type {boolean}
* @readonly
*/
isVariableLengthArray: {
get: function() {
return this._isVariableLengthArray;
}
},
/**
* The number of array elements. Only defined for fixed-size
* arrays.
*
* @memberof MetadataClassProperty.prototype
* @type {number}
* @readonly
*/
arrayLength: {
get: function() {
return this._arrayLength;
}
},
/**
* Whether the property is normalized.
*
* @memberof MetadataClassProperty.prototype
* @type {boolean}
* @readonly
*/
normalized: {
get: function() {
return this._normalized;
}
},
/**
* A number or an array of numbers storing the maximum allowable value of this property. Only defined when type is a numeric type.
*
* @memberof MetadataClassProperty.prototype
* @type {number|number[]|number[][]}
* @readonly
*/
max: {
get: function() {
return this._max;
}
},
/**
* A number or an array of numbers storing the minimum allowable value of this property. Only defined when type is a numeric type.
*
* @memberof MetadataClassProperty.prototype
* @type {number|number[]|number[][]}
* @readonly
*/
min: {
get: function() {
return this._min;
}
},
/**
* The no-data sentinel value that represents null values
*
* @memberof MetadataClassProperty.prototype
* @type {boolean|number|string|Array}
* @readonly
*/
noData: {
get: function() {
return this._noData;
}
},
/**
* A default value to use when an entity's property value is not defined.
*
* @memberof MetadataClassProperty.prototype
* @type {boolean|number|string|Array}
* @readonly
*/
default: {
get: function() {
return this._default;
}
},
/**
* Whether the property is required.
*
* @memberof MetadataClassProperty.prototype
* @type {boolean}
* @readonly
*/
required: {
get: function() {
return this._required;
}
},
/**
* An identifier that describes how this property should be interpreted.
*
* @memberof MetadataClassProperty.prototype
* @type {string}
* @readonly
*/
semantic: {
get: function() {
return this._semantic;
}
},
/**
* True if offset/scale should be applied. If both offset/scale were
* undefined, they default to identity so this property is set false
*
* @memberof MetadataClassProperty.prototype
* @type {boolean}
* @readonly
* @private
*/
hasValueTransform: {
get: function() {
return this._hasValueTransform;
}
},
/**
* The offset to be added to property values as part of the value transform.
*
* @memberof MetadataClassProperty.prototype
* @type {number|number[]|number[][]}
* @readonly
*/
offset: {
get: function() {
return this._offset;
}
},
/**
* The scale to be multiplied to property values as part of the value transform.
*
* @memberof MetadataClassProperty.prototype
* @type {number|number[]|number[][]}
* @readonly
*/
scale: {
get: function() {
return this._scale;
}
},
/**
* Extra user-defined properties.
*
* @memberof MetadataClassProperty.prototype
* @type {*}
* @readonly
*/
extras: {
get: function() {
return this._extras;
}
},
/**
* An object containing extensions.
*
* @memberof MetadataClassProperty.prototype
* @type {object}
* @readonly
*/
extensions: {
get: function() {
return this._extensions;
}
}
});
function isLegacy(property) {
if (property.type === "ARRAY") {
return true;
}
const type = property.type;
if (type === MetadataType_default.SCALAR || MetadataType_default.isMatrixType(type) || MetadataType_default.isVectorType(type)) {
return false;
}
if (defined_default(MetadataComponentType_default[type])) {
return true;
}
if (defined_default(property.noData) || defined_default(property.scale) || defined_default(property.offset) || defined_default(property.required) || defined_default(property.count) || defined_default(property.array)) {
return false;
}
if (defined_default(property.optional)) {
return false;
}
return void 0;
}
function parseType(property, enums) {
const type = property.type;
const componentType = property.componentType;
const isLegacyArray = type === "ARRAY";
let isArray;
let arrayLength;
let isVariableLengthArray;
if (isLegacyArray) {
isArray = true;
arrayLength = property.componentCount;
isVariableLengthArray = !defined_default(arrayLength);
} else if (property.array) {
isArray = true;
arrayLength = property.count;
isVariableLengthArray = !defined_default(property.count);
} else {
isArray = false;
arrayLength = void 0;
isVariableLengthArray = false;
}
let enumType;
if (defined_default(property.enumType)) {
enumType = enums[property.enumType];
}
if (type === MetadataType_default.ENUM) {
return {
type,
componentType: void 0,
enumType,
valueType: enumType.valueType,
isArray,
isVariableLengthArray,
arrayLength
};
}
if (isLegacyArray && componentType === MetadataType_default.ENUM) {
return {
type: componentType,
componentType: void 0,
enumType,
valueType: enumType.valueType,
isArray,
isVariableLengthArray,
arrayLength
};
}
if (type === MetadataType_default.SCALAR || MetadataType_default.isMatrixType(type) || MetadataType_default.isVectorType(type)) {
return {
type,
componentType,
enumType: void 0,
valueType: componentType,
isArray,
isVariableLengthArray,
arrayLength
};
}
if (type === MetadataType_default.BOOLEAN || type === MetadataType_default.STRING) {
return {
type,
componentType: void 0,
enumType: void 0,
valueType: void 0,
isArray,
isVariableLengthArray,
arrayLength
};
}
if (isLegacyArray && (componentType === MetadataType_default.BOOLEAN || componentType === MetadataType_default.STRING)) {
return {
type: componentType,
componentType: void 0,
enumType: void 0,
valueType: void 0,
isArray,
isVariableLengthArray,
arrayLength
};
}
if (defined_default(componentType) && defined_default(MetadataComponentType_default[componentType])) {
return {
type: MetadataType_default.SCALAR,
componentType,
enumType: void 0,
valueType: componentType,
isArray,
isVariableLengthArray,
arrayLength
};
}
if (defined_default(MetadataComponentType_default[type])) {
return {
type: MetadataType_default.SCALAR,
componentType: type,
enumType: void 0,
valueType: type,
isArray,
isVariableLengthArray,
arrayLength
};
}
throw new DeveloperError_default(
`unknown metadata type {type: ${type}, componentType: ${componentType})`
);
}
MetadataClassProperty.prototype.normalize = function(value) {
if (!this._normalized) {
return value;
}
return normalizeInPlace(
value,
this._valueType,
MetadataComponentType_default.normalize
);
};
MetadataClassProperty.prototype.unnormalize = function(value) {
if (!this._normalized) {
return value;
}
return normalizeInPlace(
value,
this._valueType,
MetadataComponentType_default.unnormalize
);
};
MetadataClassProperty.prototype.applyValueTransform = function(value) {
if (!this._hasValueTransform || this._isVariableLengthArray) {
return value;
}
return MetadataClassProperty.valueTransformInPlace(
value,
this._offset,
this._scale,
MetadataComponentType_default.applyValueTransform
);
};
MetadataClassProperty.prototype.unapplyValueTransform = function(value) {
if (!this._hasValueTransform || this._isVariableLengthArray) {
return value;
}
return MetadataClassProperty.valueTransformInPlace(
value,
this._offset,
this._scale,
MetadataComponentType_default.unapplyValueTransform
);
};
MetadataClassProperty.prototype.expandConstant = function(constant, enableNestedArrays) {
enableNestedArrays = defaultValue_default(enableNestedArrays, false);
const isArray = this._isArray;
const arrayLength = this._arrayLength;
const componentCount = MetadataType_default.getComponentCount(this._type);
const isNested = isArray && componentCount > 1;
if (!isArray && componentCount === 1) {
return constant;
}
if (!isArray) {
return new Array(componentCount).fill(constant);
}
if (!isNested) {
return new Array(arrayLength).fill(constant);
}
if (!enableNestedArrays) {
return new Array(this._arrayLength * componentCount).fill(constant);
}
const innerConstant = new Array(componentCount).fill(constant);
return new Array(this._arrayLength).fill(innerConstant);
};
MetadataClassProperty.prototype.handleNoData = function(value) {
const sentinel = this._noData;
if (!defined_default(sentinel)) {
return value;
}
if (arrayEquals(value, sentinel)) {
return void 0;
}
return value;
};
function arrayEquals(left, right) {
if (!Array.isArray(left)) {
return left === right;
}
if (!Array.isArray(right)) {
return false;
}
if (left.length !== right.length) {
return false;
}
for (let i = 0; i < left.length; i++) {
if (!arrayEquals(left[i], right[i])) {
return false;
}
}
return true;
}
MetadataClassProperty.prototype.unpackVectorAndMatrixTypes = function(value, enableNestedArrays) {
enableNestedArrays = defaultValue_default(enableNestedArrays, false);
const MathType = MetadataType_default.getMathType(this._type);
const isArray = this._isArray;
const componentCount = MetadataType_default.getComponentCount(this._type);
const isNested = isArray && componentCount > 1;
if (!defined_default(MathType)) {
return value;
}
if (enableNestedArrays && isNested) {
return value.map(function(x) {
return MathType.unpack(x);
});
}
if (isArray) {
return MathType.unpackArray(value);
}
return MathType.unpack(value);
};
MetadataClassProperty.prototype.packVectorAndMatrixTypes = function(value, enableNestedArrays) {
enableNestedArrays = defaultValue_default(enableNestedArrays, false);
const MathType = MetadataType_default.getMathType(this._type);
const isArray = this._isArray;
const componentCount = MetadataType_default.getComponentCount(this._type);
const isNested = isArray && componentCount > 1;
if (!defined_default(MathType)) {
return value;
}
if (enableNestedArrays && isNested) {
return value.map(function(x) {
return MathType.pack(x, []);
});
}
if (isArray) {
return MathType.packArray(value, []);
}
return MathType.pack(value, []);
};
MetadataClassProperty.prototype.validate = function(value) {
if (!defined_default(value) && defined_default(this._default)) {
return void 0;
}
if (this._required && !defined_default(value)) {
return `required property must have a value`;
}
if (this._isArray) {
return validateArray(this, value);
}
return validateSingleValue(this, value);
};
function validateArray(classProperty, value) {
if (!Array.isArray(value)) {
return `value ${value} must be an array`;
}
const length3 = value.length;
if (!classProperty._isVariableLengthArray && length3 !== classProperty._arrayLength) {
return "Array length does not match property.arrayLength";
}
for (let i = 0; i < length3; i++) {
const message = validateSingleValue(classProperty, value[i]);
if (defined_default(message)) {
return message;
}
}
}
function validateSingleValue(classProperty, value) {
const type = classProperty._type;
const componentType = classProperty._componentType;
const enumType = classProperty._enumType;
const normalized = classProperty._normalized;
if (MetadataType_default.isVectorType(type)) {
return validateVector(value, type, componentType);
} else if (MetadataType_default.isMatrixType(type)) {
return validateMatrix(value, type, componentType);
} else if (type === MetadataType_default.STRING) {
return validateString(value);
} else if (type === MetadataType_default.BOOLEAN) {
return validateBoolean(value);
} else if (type === MetadataType_default.ENUM) {
return validateEnum(value, enumType);
}
return validateScalar(value, componentType, normalized);
}
function validateVector(value, type, componentType) {
if (!MetadataComponentType_default.isVectorCompatible(componentType)) {
return `componentType ${componentType} is incompatible with vector type ${type}`;
}
if (type === MetadataType_default.VEC2 && !(value instanceof Cartesian2_default)) {
return `vector value ${value} must be a Cartesian2`;
}
if (type === MetadataType_default.VEC3 && !(value instanceof Cartesian3_default)) {
return `vector value ${value} must be a Cartesian3`;
}
if (type === MetadataType_default.VEC4 && !(value instanceof Cartesian4_default)) {
return `vector value ${value} must be a Cartesian4`;
}
}
function validateMatrix(value, type, componentType) {
if (!MetadataComponentType_default.isVectorCompatible(componentType)) {
return `componentType ${componentType} is incompatible with matrix type ${type}`;
}
if (type === MetadataType_default.MAT2 && !(value instanceof Matrix2_default)) {
return `matrix value ${value} must be a Matrix2`;
}
if (type === MetadataType_default.MAT3 && !(value instanceof Matrix3_default)) {
return `matrix value ${value} must be a Matrix3`;
}
if (type === MetadataType_default.MAT4 && !(value instanceof Matrix4_default)) {
return `matrix value ${value} must be a Matrix4`;
}
}
function validateString(value) {
if (typeof value !== "string") {
return getTypeErrorMessage(value, MetadataType_default.STRING);
}
}
function validateBoolean(value) {
if (typeof value !== "boolean") {
return getTypeErrorMessage(value, MetadataType_default.BOOLEAN);
}
}
function validateEnum(value, enumType) {
const javascriptType = typeof value;
if (defined_default(enumType)) {
if (javascriptType !== "string" || !defined_default(enumType.valuesByName[value])) {
return `value ${value} is not a valid enum name for ${enumType.id}`;
}
return;
}
}
function validateScalar(value, componentType, normalized) {
const javascriptType = typeof value;
switch (componentType) {
case MetadataComponentType_default.INT8:
case MetadataComponentType_default.UINT8:
case MetadataComponentType_default.INT16:
case MetadataComponentType_default.UINT16:
case MetadataComponentType_default.INT32:
case MetadataComponentType_default.UINT32:
case MetadataComponentType_default.FLOAT32:
case MetadataComponentType_default.FLOAT64:
if (javascriptType !== "number") {
return getTypeErrorMessage(value, componentType);
}
if (!isFinite(value)) {
return getNonFiniteErrorMessage(value, componentType);
}
return checkInRange(value, componentType, normalized);
case MetadataComponentType_default.INT64:
case MetadataComponentType_default.UINT64:
if (javascriptType !== "number" && javascriptType !== "bigint") {
return getTypeErrorMessage(value, componentType);
}
if (javascriptType === "number" && !isFinite(value)) {
return getNonFiniteErrorMessage(value, componentType);
}
return checkInRange(value, componentType, normalized);
}
}
function getTypeErrorMessage(value, type) {
return `value ${value} does not match type ${type}`;
}
function getOutOfRangeErrorMessage(value, type, normalized) {
let errorMessage = `value ${value} is out of range for type ${type}`;
if (normalized) {
errorMessage += " (normalized)";
}
return errorMessage;
}
function checkInRange(value, componentType, normalized) {
if (normalized) {
const min3 = MetadataComponentType_default.isUnsignedIntegerType(componentType) ? 0 : -1;
const max3 = 1;
if (value < min3 || value > max3) {
return getOutOfRangeErrorMessage(value, componentType, normalized);
}
return;
}
if (value < MetadataComponentType_default.getMinimum(componentType) || value > MetadataComponentType_default.getMaximum(componentType)) {
return getOutOfRangeErrorMessage(value, componentType, normalized);
}
}
function getNonFiniteErrorMessage(value, type) {
return `value ${value} of type ${type} must be finite`;
}
function normalizeInPlace(values, valueType, normalizeFunction) {
if (!Array.isArray(values)) {
return normalizeFunction(values, valueType);
}
for (let i = 0; i < values.length; i++) {
values[i] = normalizeInPlace(values[i], valueType, normalizeFunction);
}
return values;
}
MetadataClassProperty.valueTransformInPlace = function(values, offsets, scales, transformationFunction) {
if (!Array.isArray(values)) {
return transformationFunction(values, offsets, scales);
}
for (let i = 0; i < values.length; i++) {
values[i] = MetadataClassProperty.valueTransformInPlace(
values[i],
offsets[i],
scales[i],
transformationFunction
);
}
return values;
};
var MetadataClassProperty_default = MetadataClassProperty;
// packages/engine/Source/Scene/MetadataTableProperty.js
function MetadataTableProperty(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const count = options.count;
const property = options.property;
const classProperty = options.classProperty;
const bufferViews = options.bufferViews;
Check_default.typeOf.number.greaterThan("options.count", count, 0);
Check_default.typeOf.object("options.property", property);
Check_default.typeOf.object("options.classProperty", classProperty);
Check_default.typeOf.object("options.bufferViews", bufferViews);
const type = classProperty.type;
const isArray = classProperty.isArray;
const isVariableLengthArray = classProperty.isVariableLengthArray;
let valueType = classProperty.valueType;
const enumType = classProperty.enumType;
const hasStrings = type === MetadataType_default.STRING;
const hasBooleans = type === MetadataType_default.BOOLEAN;
let byteLength = 0;
let arrayOffsets;
if (isVariableLengthArray) {
let arrayOffsetType = defaultValue_default(
property.arrayOffsetType,
property.offsetType
);
arrayOffsetType = defaultValue_default(
MetadataComponentType_default[arrayOffsetType],
MetadataComponentType_default.UINT32
);
const arrayOffsetBufferView = defaultValue_default(
property.arrayOffsets,
property.arrayOffsetBufferView
);
arrayOffsets = new BufferView(
bufferViews[arrayOffsetBufferView],
arrayOffsetType,
count + 1
);
byteLength += arrayOffsets.typedArray.byteLength;
}
const vectorComponentCount = MetadataType_default.getComponentCount(type);
let arrayComponentCount;
if (isVariableLengthArray) {
arrayComponentCount = arrayOffsets.get(count) - arrayOffsets.get(0);
} else if (isArray) {
arrayComponentCount = count * classProperty.arrayLength;
} else {
arrayComponentCount = count;
}
const componentCount = vectorComponentCount * arrayComponentCount;
let stringOffsets;
if (hasStrings) {
let stringOffsetType = defaultValue_default(
property.stringOffsetType,
property.offsetType
);
stringOffsetType = defaultValue_default(
MetadataComponentType_default[stringOffsetType],
MetadataComponentType_default.UINT32
);
const stringOffsetBufferView = defaultValue_default(
property.stringOffsets,
property.stringOffsetBufferView
);
stringOffsets = new BufferView(
bufferViews[stringOffsetBufferView],
stringOffsetType,
componentCount + 1
);
byteLength += stringOffsets.typedArray.byteLength;
}
if (hasStrings || hasBooleans) {
valueType = MetadataComponentType_default.UINT8;
}
let valueCount;
if (hasStrings) {
valueCount = stringOffsets.get(componentCount) - stringOffsets.get(0);
} else if (hasBooleans) {
valueCount = Math.ceil(componentCount / 8);
} else {
valueCount = componentCount;
}
const valuesBufferView = defaultValue_default(property.values, property.bufferView);
const values = new BufferView(
bufferViews[valuesBufferView],
valueType,
valueCount
);
byteLength += values.typedArray.byteLength;
let offset2 = property.offset;
let scale = property.scale;
const hasValueTransform = classProperty.hasValueTransform || defined_default(offset2) || defined_default(scale);
offset2 = defaultValue_default(offset2, classProperty.offset);
scale = defaultValue_default(scale, classProperty.scale);
offset2 = flatten(offset2);
scale = flatten(scale);
let getValueFunction;
let setValueFunction;
const that = this;
if (hasStrings) {
getValueFunction = function(index) {
return getString(index, that._values, that._stringOffsets);
};
} else if (hasBooleans) {
getValueFunction = function(index) {
return getBoolean(index, that._values);
};
setValueFunction = function(index, value) {
setBoolean(index, that._values, value);
};
} else if (defined_default(enumType)) {
getValueFunction = function(index) {
const integer = that._values.get(index);
return enumType.namesByValue[integer];
};
setValueFunction = function(index, value) {
const integer = enumType.valuesByName[value];
that._values.set(index, integer);
};
} else {
getValueFunction = function(index) {
return that._values.get(index);
};
setValueFunction = function(index, value) {
that._values.set(index, value);
};
}
this._arrayOffsets = arrayOffsets;
this._stringOffsets = stringOffsets;
this._values = values;
this._classProperty = classProperty;
this._count = count;
this._vectorComponentCount = vectorComponentCount;
this._min = property.min;
this._max = property.max;
this._offset = offset2;
this._scale = scale;
this._hasValueTransform = hasValueTransform;
this._getValue = getValueFunction;
this._setValue = setValueFunction;
this._unpackedValues = void 0;
this._extras = property.extras;
this._extensions = property.extensions;
this._byteLength = byteLength;
}
Object.defineProperties(MetadataTableProperty.prototype, {
/**
* True if offset/scale should be applied. If both offset/scale were
* undefined, they default to identity so this property is set false
*
* @memberof MetadataClassProperty.prototype
* @type {boolean}
* @readonly
* @private
*/
hasValueTransform: {
get: function() {
return this._hasValueTransform;
}
},
/**
* The offset to be added to property values as part of the value transform.
*
* @memberof MetadataClassProperty.prototype
* @type {number|number[]|number[][]}
* @readonly
* @private
*/
offset: {
get: function() {
return this._offset;
}
},
/**
* The scale to be multiplied to property values as part of the value transform.
*
* @memberof MetadataClassProperty.prototype
* @type {number|number[]|number[][]}
* @readonly
* @private
*/
scale: {
get: function() {
return this._scale;
}
},
/**
* Extra user-defined properties.
*
* @memberof MetadataTableProperty.prototype
* @type {*}
* @readonly
* @private
*/
extras: {
get: function() {
return this._extras;
}
},
/**
* An object containing extensions.
*
* @memberof MetadataTableProperty.prototype
* @type {*}
* @readonly
* @private
*/
extensions: {
get: function() {
return this._extensions;
}
},
/**
* Size of all typed arrays used by this table property
*
* @memberof MetadataTableProperty.prototype
* @type {Normal}
* @readonly
* @private
*/
byteLength: {
get: function() {
return this._byteLength;
}
}
});
MetadataTableProperty.prototype.get = function(index) {
checkIndex(this, index);
let value = get(this, index);
value = this._classProperty.handleNoData(value);
if (!defined_default(value)) {
value = this._classProperty.default;
return this._classProperty.unpackVectorAndMatrixTypes(value);
}
value = this._classProperty.normalize(value);
value = applyValueTransform(this, value);
return this._classProperty.unpackVectorAndMatrixTypes(value);
};
MetadataTableProperty.prototype.set = function(index, value) {
const classProperty = this._classProperty;
Check_default.defined("value", value);
checkIndex(this, index);
const errorMessage = classProperty.validate(value);
if (defined_default(errorMessage)) {
throw new DeveloperError_default(errorMessage);
}
value = classProperty.packVectorAndMatrixTypes(value);
value = unapplyValueTransform(this, value);
value = classProperty.unnormalize(value);
set(this, index, value);
};
MetadataTableProperty.prototype.getTypedArray = function() {
if (defined_default(this._values)) {
return this._values.typedArray;
}
return void 0;
};
function flatten(values) {
if (!Array.isArray(values)) {
return values;
}
const result = [];
for (let i = 0; i < values.length; i++) {
const value = values[i];
if (Array.isArray(value)) {
result.push.apply(result, value);
} else {
result.push(value);
}
}
return result;
}
function checkIndex(table2, index) {
const count = table2._count;
if (!defined_default(index) || index < 0 || index >= count) {
const maximumIndex = count - 1;
throw new DeveloperError_default(
`index is required and between zero and count - 1. Actual value: ${maximumIndex}`
);
}
}
function get(property, index) {
if (requiresUnpackForGet(property)) {
unpackProperty(property);
}
const classProperty = property._classProperty;
const isArray = classProperty.isArray;
const type = classProperty.type;
const componentCount = MetadataType_default.getComponentCount(type);
if (defined_default(property._unpackedValues)) {
const value = property._unpackedValues[index];
if (isArray) {
return clone_default(value, true);
}
return value;
}
if (!isArray && componentCount === 1) {
return property._getValue(index);
}
return getArrayValues(property, classProperty, index);
}
function getArrayValues(property, classProperty, index) {
let offset2;
let length3;
if (classProperty.isVariableLengthArray) {
offset2 = property._arrayOffsets.get(index);
length3 = property._arrayOffsets.get(index + 1) - offset2;
const componentCount = MetadataType_default.getComponentCount(classProperty.type);
offset2 *= componentCount;
length3 *= componentCount;
} else {
const arrayLength = defaultValue_default(classProperty.arrayLength, 1);
const componentCount = arrayLength * property._vectorComponentCount;
offset2 = index * componentCount;
length3 = componentCount;
}
const values = new Array(length3);
for (let i = 0; i < length3; i++) {
values[i] = property._getValue(offset2 + i);
}
return values;
}
function set(property, index, value) {
if (requiresUnpackForSet(property, index, value)) {
unpackProperty(property);
}
const classProperty = property._classProperty;
const isArray = classProperty.isArray;
const type = classProperty.type;
const componentCount = MetadataType_default.getComponentCount(type);
if (defined_default(property._unpackedValues)) {
if (classProperty.isArray) {
value = clone_default(value, true);
}
property._unpackedValues[index] = value;
return;
}
if (!isArray && componentCount === 1) {
property._setValue(index, value);
return;
}
let offset2;
let length3;
if (classProperty.isVariableLengthArray) {
offset2 = property._arrayOffsets.get(index);
length3 = property._arrayOffsets.get(index + 1) - offset2;
} else {
const arrayLength = defaultValue_default(classProperty.arrayLength, 1);
const componentCount2 = arrayLength * property._vectorComponentCount;
offset2 = index * componentCount2;
length3 = componentCount2;
}
for (let i = 0; i < length3; ++i) {
property._setValue(offset2 + i, value[i]);
}
}
function getString(index, values, stringOffsets) {
const stringByteOffset = stringOffsets.get(index);
const stringByteLength = stringOffsets.get(index + 1) - stringByteOffset;
return getStringFromTypedArray_default(
values.typedArray,
stringByteOffset,
stringByteLength
);
}
function getBoolean(index, values) {
const byteIndex = index >> 3;
const bitIndex = index % 8;
return (values.typedArray[byteIndex] >> bitIndex & 1) === 1;
}
function setBoolean(index, values, value) {
const byteIndex = index >> 3;
const bitIndex = index % 8;
if (value) {
values.typedArray[byteIndex] |= 1 << bitIndex;
} else {
values.typedArray[byteIndex] &= ~(1 << bitIndex);
}
}
function getInt64NumberFallback(index, values) {
const dataView = values.dataView;
const byteOffset = index * 8;
let value = 0;
const isNegative = (dataView.getUint8(byteOffset + 7) & 128) > 0;
let carrying = true;
for (let i = 0; i < 8; ++i) {
let byte = dataView.getUint8(byteOffset + i);
if (isNegative) {
if (carrying) {
if (byte !== 0) {
byte = ~(byte - 1) & 255;
carrying = false;
}
} else {
byte = ~byte & 255;
}
}
value += byte * Math.pow(256, i);
}
if (isNegative) {
value = -value;
}
return value;
}
function getInt64BigIntFallback(index, values) {
const dataView = values.dataView;
const byteOffset = index * 8;
let value = BigInt(0);
const isNegative = (dataView.getUint8(byteOffset + 7) & 128) > 0;
let carrying = true;
for (let i = 0; i < 8; ++i) {
let byte = dataView.getUint8(byteOffset + i);
if (isNegative) {
if (carrying) {
if (byte !== 0) {
byte = ~(byte - 1) & 255;
carrying = false;
}
} else {
byte = ~byte & 255;
}
}
value += BigInt(byte) * (BigInt(1) << BigInt(i * 8));
}
if (isNegative) {
value = -value;
}
return value;
}
function getUint64NumberFallback(index, values) {
const dataView = values.dataView;
const byteOffset = index * 8;
const left = dataView.getUint32(byteOffset, true);
const right = dataView.getUint32(byteOffset + 4, true);
const value = left + 4294967296 * right;
return value;
}
function getUint64BigIntFallback(index, values) {
const dataView = values.dataView;
const byteOffset = index * 8;
const left = BigInt(dataView.getUint32(byteOffset, true));
const right = BigInt(dataView.getUint32(byteOffset + 4, true));
const value = left + BigInt(4294967296) * right;
return value;
}
function getComponentDatatype(componentType) {
switch (componentType) {
case MetadataComponentType_default.INT8:
return ComponentDatatype_default.BYTE;
case MetadataComponentType_default.UINT8:
return ComponentDatatype_default.UNSIGNED_BYTE;
case MetadataComponentType_default.INT16:
return ComponentDatatype_default.SHORT;
case MetadataComponentType_default.UINT16:
return ComponentDatatype_default.UNSIGNED_SHORT;
case MetadataComponentType_default.INT32:
return ComponentDatatype_default.INT;
case MetadataComponentType_default.UINT32:
return ComponentDatatype_default.UNSIGNED_INT;
case MetadataComponentType_default.FLOAT32:
return ComponentDatatype_default.FLOAT;
case MetadataComponentType_default.FLOAT64:
return ComponentDatatype_default.DOUBLE;
}
}
function requiresUnpackForGet(property) {
if (defined_default(property._unpackedValues)) {
return false;
}
const classProperty = property._classProperty;
const type = classProperty.type;
const valueType = classProperty.valueType;
if (type === MetadataType_default.STRING) {
return true;
}
if (valueType === MetadataComponentType_default.INT64 && !FeatureDetection_default.supportsBigInt64Array()) {
return true;
}
if (valueType === MetadataComponentType_default.UINT64 && !FeatureDetection_default.supportsBigUint64Array()) {
return true;
}
return false;
}
function requiresUnpackForSet(property, index, value) {
if (requiresUnpackForGet(property)) {
return true;
}
const arrayOffsets = property._arrayOffsets;
if (defined_default(arrayOffsets)) {
const oldLength = arrayOffsets.get(index + 1) - arrayOffsets.get(index);
const newLength = value.length;
if (oldLength !== newLength) {
return true;
}
}
return false;
}
function unpackProperty(property) {
property._unpackedValues = unpackValues(property);
property._arrayOffsets = void 0;
property._stringOffsets = void 0;
property._values = void 0;
}
function unpackValues(property) {
const count = property._count;
const unpackedValues = new Array(count);
const classProperty = property._classProperty;
const isArray = classProperty.isArray;
const type = classProperty.type;
const componentCount = MetadataType_default.getComponentCount(type);
if (!isArray && componentCount === 1) {
for (let i = 0; i < count; ++i) {
unpackedValues[i] = property._getValue(i);
}
return unpackedValues;
}
for (let i = 0; i < count; i++) {
unpackedValues[i] = getArrayValues(property, classProperty, i);
}
return unpackedValues;
}
function applyValueTransform(property, value) {
const classProperty = property._classProperty;
const isVariableLengthArray = classProperty.isVariableLengthArray;
if (!property._hasValueTransform || isVariableLengthArray) {
return value;
}
return MetadataClassProperty_default.valueTransformInPlace(
value,
property._offset,
property._scale,
MetadataComponentType_default.applyValueTransform
);
}
function unapplyValueTransform(property, value) {
const classProperty = property._classProperty;
const isVariableLengthArray = classProperty.isVariableLengthArray;
if (!property._hasValueTransform || isVariableLengthArray) {
return value;
}
return MetadataClassProperty_default.valueTransformInPlace(
value,
property._offset,
property._scale,
MetadataComponentType_default.unapplyValueTransform
);
}
function BufferView(bufferView, componentType, length3) {
const that = this;
let typedArray;
let getFunction;
let setFunction;
if (componentType === MetadataComponentType_default.INT64) {
if (!FeatureDetection_default.supportsBigInt()) {
oneTimeWarning_default(
"INT64 type is not fully supported on this platform. Values greater than 2^53 - 1 or less than -(2^53 - 1) may lose precision when read."
);
typedArray = new Uint8Array(
bufferView.buffer,
bufferView.byteOffset,
length3 * 8
);
getFunction = function(index) {
return getInt64NumberFallback(index, that);
};
} else if (!FeatureDetection_default.supportsBigInt64Array()) {
typedArray = new Uint8Array(
bufferView.buffer,
bufferView.byteOffset,
length3 * 8
);
getFunction = function(index) {
return getInt64BigIntFallback(index, that);
};
} else {
typedArray = new BigInt64Array(
bufferView.buffer,
bufferView.byteOffset,
length3
);
setFunction = function(index, value) {
that.typedArray[index] = BigInt(value);
};
}
} else if (componentType === MetadataComponentType_default.UINT64) {
if (!FeatureDetection_default.supportsBigInt()) {
oneTimeWarning_default(
"UINT64 type is not fully supported on this platform. Values greater than 2^53 - 1 may lose precision when read."
);
typedArray = new Uint8Array(
bufferView.buffer,
bufferView.byteOffset,
length3 * 8
);
getFunction = function(index) {
return getUint64NumberFallback(index, that);
};
} else if (!FeatureDetection_default.supportsBigUint64Array()) {
typedArray = new Uint8Array(
bufferView.buffer,
bufferView.byteOffset,
length3 * 8
);
getFunction = function(index) {
return getUint64BigIntFallback(index, that);
};
} else {
typedArray = new BigUint64Array(
bufferView.buffer,
bufferView.byteOffset,
length3
);
setFunction = function(index, value) {
that.typedArray[index] = BigInt(value);
};
}
} else {
const componentDatatype = getComponentDatatype(componentType);
typedArray = ComponentDatatype_default.createArrayBufferView(
componentDatatype,
bufferView.buffer,
bufferView.byteOffset,
length3
);
setFunction = function(index, value) {
that.typedArray[index] = value;
};
}
if (!defined_default(getFunction)) {
getFunction = function(index) {
return that.typedArray[index];
};
}
this.typedArray = typedArray;
this.dataView = new DataView(typedArray.buffer, typedArray.byteOffset);
this.get = getFunction;
this.set = setFunction;
this._componentType = componentType;
}
var MetadataTableProperty_default = MetadataTableProperty;
// packages/engine/Source/Scene/MetadataTable.js
function MetadataTable(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const count = options.count;
const metadataClass = options.class;
Check_default.typeOf.number.greaterThan("options.count", count, 0);
Check_default.typeOf.object("options.class", metadataClass);
let byteLength = 0;
const properties = {};
if (defined_default(options.properties)) {
for (const propertyId in options.properties) {
if (options.properties.hasOwnProperty(propertyId)) {
const property = new MetadataTableProperty_default({
count,
property: options.properties[propertyId],
classProperty: metadataClass.properties[propertyId],
bufferViews: options.bufferViews
});
properties[propertyId] = property;
byteLength += property.byteLength;
}
}
}
this._count = count;
this._class = metadataClass;
this._properties = properties;
this._byteLength = byteLength;
}
Object.defineProperties(MetadataTable.prototype, {
/**
* The number of entities in the table.
*
* @memberof MetadataTable.prototype
* @type {number}
* @readonly
* @private
*/
count: {
get: function() {
return this._count;
}
},
/**
* The class that properties conform to.
*
* @memberof MetadataTable.prototype
* @type {MetadataClass}
* @readonly
* @private
*/
class: {
get: function() {
return this._class;
}
},
/**
* The size of all typed arrays used in this table.
*
* @memberof MetadataTable.prototype
* @type {number}
* @readonly
* @private
*/
byteLength: {
get: function() {
return this._byteLength;
}
}
});
MetadataTable.prototype.hasProperty = function(propertyId) {
return MetadataEntity_default.hasProperty(propertyId, this._properties, this._class);
};
MetadataTable.prototype.hasPropertyBySemantic = function(semantic) {
return MetadataEntity_default.hasPropertyBySemantic(
semantic,
this._properties,
this._class
);
};
MetadataTable.prototype.getPropertyIds = function(results) {
return MetadataEntity_default.getPropertyIds(this._properties, this._class, results);
};
MetadataTable.prototype.getProperty = function(index, propertyId) {
Check_default.typeOf.string("propertyId", propertyId);
const property = this._properties[propertyId];
let value;
if (defined_default(property)) {
value = property.get(index);
} else {
value = getDefault(this._class, propertyId);
}
return value;
};
MetadataTable.prototype.setProperty = function(index, propertyId, value) {
Check_default.typeOf.string("propertyId", propertyId);
const property = this._properties[propertyId];
if (defined_default(property)) {
property.set(index, value);
return true;
}
return false;
};
MetadataTable.prototype.getPropertyBySemantic = function(index, semantic) {
Check_default.typeOf.string("semantic", semantic);
let property;
const propertiesBySemantic = this._class.propertiesBySemantic;
if (defined_default(propertiesBySemantic)) {
property = propertiesBySemantic[semantic];
}
if (defined_default(property)) {
return this.getProperty(index, property.id);
}
return void 0;
};
MetadataTable.prototype.setPropertyBySemantic = function(index, semantic, value) {
Check_default.typeOf.string("semantic", semantic);
let property;
const propertiesBySemantic = this._class.propertiesBySemantic;
if (defined_default(propertiesBySemantic)) {
property = propertiesBySemantic[semantic];
}
if (defined_default(property)) {
return this.setProperty(index, property.id, value);
}
return false;
};
MetadataTable.prototype.getPropertyTypedArray = function(propertyId) {
Check_default.typeOf.string("propertyId", propertyId);
const property = this._properties[propertyId];
if (defined_default(property)) {
return property.getTypedArray();
}
return void 0;
};
MetadataTable.prototype.getPropertyTypedArrayBySemantic = function(semantic) {
Check_default.typeOf.string("semantic", semantic);
let property;
const propertiesBySemantic = this._class.propertiesBySemantic;
if (defined_default(propertiesBySemantic)) {
property = propertiesBySemantic[semantic];
}
if (defined_default(property)) {
return this.getPropertyTypedArray(property.id);
}
return void 0;
};
function getDefault(classDefinition, propertyId) {
const classProperties = classDefinition.properties;
if (!defined_default(classProperties)) {
return void 0;
}
const classProperty = classProperties[propertyId];
if (defined_default(classProperty) && defined_default(classProperty.default)) {
let value = classProperty.default;
if (classProperty.isArray) {
value = clone_default(value, true);
}
value = classProperty.normalize(value);
return classProperty.unpackVectorAndMatrixTypes(value);
}
}
var MetadataTable_default = MetadataTable;
// packages/engine/Source/Scene/ResourceLoader.js
function ResourceLoader() {
}
Object.defineProperties(ResourceLoader.prototype, {
/**
* The cache key of the resource.
*
* @memberof ResourceLoader.prototype
*
* @type {string}
* @readonly
* @private
*/
cacheKey: {
// eslint-disable-next-line getter-return
get: function() {
DeveloperError_default.throwInstantiationError();
}
}
});
ResourceLoader.prototype.load = function() {
DeveloperError_default.throwInstantiationError();
};
ResourceLoader.prototype.unload = function() {
};
ResourceLoader.prototype.process = function(frameState) {
return false;
};
ResourceLoader.prototype.getError = function(errorMessage, error) {
Check_default.typeOf.string("errorMessage", errorMessage);
if (defined_default(error) && defined_default(error.message)) {
errorMessage += `
${error.message}`;
}
const runtimeError = new RuntimeError_default(errorMessage);
if (defined_default(error)) {
runtimeError.stack = `Original stack:
${error.stack}
Handler stack:
${runtimeError.stack}`;
}
return runtimeError;
};
ResourceLoader.prototype.isDestroyed = function() {
return false;
};
ResourceLoader.prototype.destroy = function() {
this.unload();
return destroyObject_default(this);
};
var ResourceLoader_default = ResourceLoader;
// packages/engine/Source/Scene/ResourceLoaderState.js
var ResourceLoaderState = {
/**
* The resource has not yet been loaded.
*
* @type {number}
* @constant
* @private
*/
UNLOADED: 0,
/**
* The resource is loading. In this state, external resources are fetched as needed.
*
* @type {number}
* @constant
* @private
*/
LOADING: 1,
/**
* The resource has finished loading, but requires further processing.
*
* @type {number}
* @constant
* @private
*/
LOADED: 2,
/**
* The resource is processing. GPU resources are allocated in this state as needed.
*
* @type {Number}
* @constant
* @private
*/
PROCESSING: 3,
/**
* The resource has finished loading and processing; the results are ready to be used.
*
* @type {number}
* @constant
* @private
*/
READY: 4,
/**
* The resource loading or processing has failed due to an error.
*
* @type {number}
* @constant
* @private
*/
FAILED: 5
};
var ResourceLoaderState_default = Object.freeze(ResourceLoaderState);
// packages/engine/Source/Scene/BufferLoader.js
function BufferLoader(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const typedArray = options.typedArray;
const resource = options.resource;
const cacheKey = options.cacheKey;
if (defined_default(typedArray) === defined_default(resource)) {
throw new DeveloperError_default(
"One of options.typedArray and options.resource must be defined."
);
}
this._typedArray = typedArray;
this._resource = resource;
this._cacheKey = cacheKey;
this._state = ResourceLoaderState_default.UNLOADED;
this._promise = void 0;
}
if (defined_default(Object.create)) {
BufferLoader.prototype = Object.create(ResourceLoader_default.prototype);
BufferLoader.prototype.constructor = BufferLoader;
}
Object.defineProperties(BufferLoader.prototype, {
/**
* The cache key of the resource.
*
* @memberof BufferLoader.prototype
*
* @type {string}
* @readonly
* @private
*/
cacheKey: {
get: function() {
return this._cacheKey;
}
},
/**
* The typed array containing the embedded buffer contents.
*
* @memberof BufferLoader.prototype
*
* @type {Uint8Array}
* @readonly
* @private
*/
typedArray: {
get: function() {
return this._typedArray;
}
}
});
BufferLoader.prototype.load = async function() {
if (defined_default(this._promise)) {
return this._promise;
}
if (defined_default(this._typedArray)) {
this._promise = Promise.resolve(this);
return this._promise;
}
this._promise = loadExternalBuffer(this);
return this._promise;
};
async function loadExternalBuffer(bufferLoader) {
const resource = bufferLoader._resource;
bufferLoader._state = ResourceLoaderState_default.LOADING;
try {
const arrayBuffer = await BufferLoader._fetchArrayBuffer(resource);
if (bufferLoader.isDestroyed()) {
return;
}
bufferLoader._typedArray = new Uint8Array(arrayBuffer);
bufferLoader._state = ResourceLoaderState_default.READY;
return bufferLoader;
} catch (error) {
if (bufferLoader.isDestroyed()) {
return;
}
bufferLoader._state = ResourceLoaderState_default.FAILED;
const errorMessage = `Failed to load external buffer: ${resource.url}`;
throw bufferLoader.getError(errorMessage, error);
}
}
BufferLoader._fetchArrayBuffer = function(resource) {
return resource.fetchArrayBuffer();
};
BufferLoader.prototype.unload = function() {
this._typedArray = void 0;
};
var BufferLoader_default = BufferLoader;
// node_modules/meshoptimizer/meshopt_encoder.module.js
var MeshoptEncoder = function() {
"use strict";
var wasm = "B9h79tEBBBENQ9gEUEU9gEUB9gBB9gVUUUUUEU9gDUUEU9gLUUUUEU9gVUUUUUB9gLUUUUB9gIUUUEU9gD99UE99I8ayDILEVLEVLOOOOORRVBWWBEdddLVE9wEIIVIEBEOWEUEC+g/KEKR/QIhO9tw9t9vv95DBh9f9f939h79t9f9j9h229f9jT9vv7BB8a9tw79o9v9wT9fw9u9j9v9kw9WwvTw949C919m9mwvBE8f9tw79o9v9wT9fw9u9j9v9kw9WwvTw949C919m9mwv9C9v919u9kBDe9tw79o9v9wT9fw9u9j9v9kw9WwvTw949Wwv79p9v9uBIy9tw79o9v9wT9fw9u9j9v9kw69u9kw949C919m9mwvBL8e9tw79o9v9wT9fw9u9j9v9kw69u9kw949C919m9mwv9C9v919u9kBV8a9tw79o9v9wT9fw9u9j9v9kw69u9kw949Wwv79p9v9uBOe9tw79o9v9wT9fw9u9j9v9kw69u9kw949Twg91w9u9jwBRA9tw79o9v9wT9fw9u9j9v9kw69u9kw949Twg91w9u9jw9C9v919u9kBWl9tw79o9v9wT9fw9u9j9v9kws9p2Twv9P9jTBdk9tw79o9v9wT9fw9u9j9v9kws9p2Twv9R919hTBQl9tw79o9v9wT9fw9u9j9v9kws9p2Twvt949wBKe9tw79o9v9wT9f9v9wT9p9t9p96w9WwvTw94j9h9j9owBpA9tw79o9v9wT9f9v9wT9p9t9p96w9WwvTw94j9h9j9ow9TTv9p9wBSA9tw79o9v9wT9f9v9wT9p9t9p96w9WwvTw94swT9j9o9Sw9t9h9wBZL79iv9rBhdWEBCEKDxcQ+1tyDBK/hKEyU8jJJJJBCJO9rGV8kJJJJBCBHODNALCEFAE0MBABCBrB+Q+KJJBC+gEv86BBAVCJDFCBCJDZ+TJJJB8aDNAItMBAVCJDFADALZmJJJB8aKABAEFHRABCEFHWAVALFCBCBCJDAL9rALCfE0eZ+TJJJB8aAVAVCJDFALZmJJJBHdCJ/ABAL9uHEDNDNALtMBAEC/wfBgGECJDAECJD6eHQCBHKINAKAI9PMEAdCJLFCBCJDZ+TJJJB8aAQAIAK9rAKAQFAI6eGXCSFGECL4CIFCD4HMADAKAL2FHpDNDNDNDNDNAEC9wgGStMBCBHZCEHhApHoAWHaXEKDNAXtMBCBHaCEHhApHcINAdAaFrBBHxAcHECBHOINAdCJLFAOFAErBBGqAx9rGxCETAxCkTCk91CR4786BBAEALFHEAqHxAOCEFGOAX9HMBKARAW9rAM6MIAWCBAMZ+TJJJBGEtMIAEAMFHWAcCEFHcAaCEFGaAL6HhAaAL9HMBXVKKARAW9rAM6MOAWCBAMZ+TJJJB8aCEHEINAWGxAMFHWALAEGOsMLDNARAW9rAM6MBAOCEFHEAWCBAMZ+TJJJB8aAxMEKKCBHWAOAL6MOXIKINDNAXtMBAdAZFrBBHxCBHEAoHOINAdCJLFAEFAOrBBGqAx9rGxCETAxCkTCk91CR4786BBAOALFHOAqHxAECEFGEAX9HMBKKARAa9rAM6MEARAaCBAMZ+TJJJBGlAMFGW9rCk6MDCBHkAdCJLFHcINAdCJLFAkFHyCWH8aCZHaCEHqINDNDNAqCE9HMBCUHOAyrBBMECBHODNINAOGECSsMEAECEFHOAcAEFCEFrBBtMBKKCUCBAECS6eHOXEKAqCETC/+fffEgHOCUAqTCU7CfEgHxCBHEINAOAxAcAEFrBB9NFHOAECEFGECZ9HMBKKAOAaAOAa6GEeHaAqA8aAEeH8aAqCETGqCW6MBKDNDNDNDNA8aCUFpDIEBKAlAkCO4FGEAErBBCDCIA8aCLseAkCI4COgTv86BBA8aCW9HMEAWAy8pBB83BBAWCWFAyCWF8pBB83BBAWCZFHWXDKAlAkCO4FGEAErBBCEAkCI4COgTv86BBKDNCWA8a9tGeMBINAWCB86BBAWCEFHWXBKKCUA8aTCU7HqCBH3AcH5INA5HEAeHxCBHOINAErBBGaAqAaAqCfEgGy6eAOCfEgA8aTvHOAECEFHEAxCUFGxMBKAWAO86BBA5AeFH5AWCEFHWA3AeFG3CZ6MBKCBHEINDNAcAEFrBBGOAy6MBAWAO86BBAWCEFHWKAECEFGECZ9HMBKKDNAkCZFGkAS9PMBAcCZFHcARAW9rCl0MEKKAkAS6MEAWtMEAoCEFHoAZCEFGZAL6HhAWHaAZALsMIXBKKCBHWAhCEgtMEXLKCBHWAhCEgMIKAdApAXCUFAL2FALZmJJJB8aAXAKFHKAWMBKCBHOXDKCBHOARAW9rCAALALCA6e6MEDNALC8f0MBAWCBCAAL9rGEZ+TJJJBAEFHWKAWAdCJDFALZmJJJBALFAB9rHOXEKCBHOKAVCJOF8kJJJJBAOK9HEEUAECAAECA0eABCJ/ABAE9uC/wfBgGDCJDADCJD6eGDFCUFAD9uAE2ADCL4CIFCD4ADv2FCEFKMBCBABbD+Q+KJJBK/YSE3U8jJJJJBC/AE9rGL8kJJJJBCBHVDNAICI9uGOChFAE0MBABCBYDn+KJJBGVC/gEv86BBALC/ABFCfECJEZ+TJJJB8aALCuFGR9CU83IBALC8wFGW9CU83IBALCYFGd9CU83IBALCAFGQ9CU83IBALCkFGK9CU83IBALCZFGX9CU83IBAL9CU83IWAL9CU83IBABAEFC9wFHMABCEFGpAOFHEDNAItMBCMCSAVCB9KGSeHZAVCE9IHhCBHoCBHaCBHcCBHxCBHqINDNAEAM9NMBCBHVXIKAqCUFHVADAcCDTFGOYDBHlAOCWFYDBHkAOCLFYDBHyCBH8aDNDNINALC/ABFAVCSgCITFGOYDLHeDNDNDNAOYDBGOAl9HMBAeAysMEKDNAOAy9HMBAeAk9HMBA8aCEFH8aXEKAOAk9HMEAeAl9HMEA8aCDFH8aKA8aC870MDAxCUFHVADA8aCIgCX2GOC+Y1JJBFYDBAcFCDTFYDBHeADAOCn1JJBFYDBAcFCDTFYDBHkADAOC+Q1JJBFYDBAcFCDTFYDBHlCBHODNINDNALAVCSgCDTFYDBAe9HMBAOHyXDKCUHyAVCUFHVAOCEFGOCZ9HMBKKAyCB9KAyAZ9IgGVCU7AeAosGOgH3DNDNDNDNDNAyCBCSAOeAVeGVCS9HMBAhMBAeAeAaAeCEFAasGVeGaCEFsMECMCSAVeHVKApAVA8aCDTC/wEgv86BBAVCS9HMEAeAa9rGVCETAVC8f917HVINAEAVCfB0CRTAVCfBgv86BBAECEFHEAVCJE6HOAVCR4HVAOtMBKAeHaXDKCpHVApA8aCDTCpv86BBAeHaKAVtMBAVAZ9IMEKALAxCDTFAebDBAxCEFCSgHxKAoA3FHoALC/ABFAqCITFGVAkbDLAVAebDBALC/ABFAqCEFCSgGVCITFGOAebDLAOAlbDBAVCEFHOXIKAVCUFHVA8aCLFG8aC/AB9HMBKKDNADCEAkAosCETAyAoseCX2GVC+Q1JJBFYDBAcFCDTFYDBGltADAVCn1JJBFYDBAcFCDTFYDBG8aCEsgADAVC+Y1JJBFYDBAcFCDTFYDBGyCDsgAoCB9HgASgG5CE9HMBAR9CU83IBAW9CU83IBAd9CU83IBAQ9CU83IBAK9CU83IBAX9CU83IBAL9CU83IWAL9CU83IBCBHoKCBHeAxCUFGVHODNINDNALAOCSgCDTFYDBA8a9HMBAeHkXDKCUHkAOCUFHOAeCEFGeCZ9HMBKKCBHODNINDNALAVCSgCDTFYDBAy9HMBAOHeXDKCUHeAVCUFHVAOCEFGOCZ9HMBKKAoAlAosG8eFH3DNDNAkCM0MBAkCEFHkXEKCBCSA8aA3sGVeHkA3AVFH3KDNDNAeCM0MBAeCEFHeXEKCBCSAyA3sGVeHeA3AVFH3KC9+CUA8eeH8fAeAkCLTvHOCBHVDNDNDNINAVCJ1JJBFrBBAOCfEgsMEAVCEFGVCZ9HMBXDKKAlAo9HAVCM0vA5vMBApAVC/wEv86BBXEKApA8f86BBAEAO86BBAECEFHEKDNA8eMBAlAa9rGVCETAVC8f917HVINAEAVCfB0GOCRTAVCfBgv86BBAVCR4HVAECEFHEAOMBKAlHaKDNAkCS9HMBA8aAa9rGVCETAVC8f917HVINAEAVCfB0GOCRTAVCfBgv86BBAVCR4HVAECEFHEAOMBKA8aHaKDNAeCS9HMBAyAa9rGVCETAVC8f917HVINAEAVCfB0GOCRTAVCfBgv86BBAVCR4HVAECEFHEAOMBKAyHaKALAxCDTFAlbDBAxCEFCSgHVDNDNAkpZBEEEEEEEEEEEEEEBEKALAVCDTFA8abDBAxCDFCSgHVKDNDNAepZBEEEEEEEEEEEEEEBEKALAVCDTFAybDBAVCEFCSgHVKALC/ABFAqCITFGOAlbDLAOA8abDBALC/ABFAqCEFCSgCITFGOA8abDLAOAybDBALC/ABFAqCDFCSgCITFGOAybDLAOAlbDBAqCIFHOAVHxA3HoKApCEFHpAOCSgHqAcCIFGcAI6MBKKCBHVAEAM0MBCBHVINAEAVFAVCJ1JJBFrBB86BBAVCEFGVCZ9HMBKAEAB9rAVFHVKALC/AEF8kJJJJBAVKzEEUCBHDDNINADCEFGDC8f0MECEADTAE6MBKKADCRFCfEgCR9uCI2CDFABCI9u2ChFKMBCBABbDn+KJJBK+cDEWU8jJJJJBCZ9rHLCBHVDNAICVFAE0MBCBHOABCBrBn+KJJBC/QEv86BBAL9CB83IWABCEFHRABAEFC98FHWDNAItMBCBHdINDNARAW6MBCBSKADAdCDTFYDBGQALCWFAOAQALCWFAOCDTFYDB9rGEAEC8f91GEFAE7C507GOCDTFGKYDB9rGEC8e91C9+gAECDT7AOvHEINARAECfB0GVCRTAECfBgv86BBAECR4HEARCEFHRAVMBKAKAQbDBAdCEFGdAI9HMBKKCBHVARAW0MBARCBbBBARAB9rCLFHVKAVKbEEUCBHDDNINADCEFGDC8f0MECEADTAE6MBKKADCWFCfEgCR9uAB2CVFK+DVLI99DUI99LUDNAEtMBCUADCETCUFTCU7+yHVDNDNCUAICUFTCU7+yGOjBBBzmGR+LjBBB9P9dtMBAR+oHWXEKCJJJJ94HWKCBHICBHdINALCLFiDBGRjBBBBjBBJzALiDBGQ+LAR+LmALCWFiDBGK+LmGR+VARjBBBB9beGRnHXAQARnHRALCXFiDBHQDNDNAKjBBBB9gtMBAXHKXEKjBBJzAR+L+TGKAK+MAXjBBBB9geHKjBBJzAX+L+TGXAX+MARjBBBB9geHRKDNDNAQjBBJ+/AQjBBJ+/9geGXjBBJzAXjBBJz9feAVnjBBBzjBBB+/AQjBBBB9gemGQ+LjBBB9P9dtMBAQ+oHMXEKCJJJJ94HMKDNDNAKjBBJ+/AKjBBJ+/9geGQjBBJzAQjBBJz9feAOnjBBBzjBBB+/AKjBBBB9gemGQ+LjBBB9P9dtMBAQ+oHpXEKCJJJJ94HpKDNDNARjBBJ+/ARjBBJ+/9geGQjBBJzAQjBBJz9feAOnjBBBzjBBB+/ARjBBBB9gemGR+LjBBB9P9dtMBAR+oHSXEKCJJJJ94HSKDNDNADCL9HMBABAdFGZAS86BBAZCIFAM86BBAZCDFAW86BBAZCEFAp86BBXEKABAIFGZAS87EBAZCOFAM87EBAZCLFAW87EBAZCDFAp87EBKALCZFHLAICWFHIAdCLFHdAECUFGEMBKKK/KLLD99EUD99EUDNAEtMBDNDNCUAICUFTCU7+yGVjBBBzmGO+LjBBB9P9dtMBAO+oHIXEKCJJJJ94HIKAIC/8fIgHRINABCOFCICDALCLFiDB+LALiDB+L9eGIALCWFiDB+LALAICDTFiDB+L9eeGIALCXFiDB+LALAICDTFiDB+L9eeGIARv87EBDNDNALAICEFCIgCDTFiDBj/zL+1znjBBJ+/jBBJzALAICDTFiDBjBBBB9deGOnGWjBBJ+/AWjBBJ+/9geGdjBBJzAdjBBJz9feAVnjBBBzjBBB+/AWjBBBB9gemGW+LjBBB9P9dtMBAW+oHQXEKCJJJJ94HQKABAQ87EBDNDNAOALAICDFCIgCDTFiDBj/zL+1znnGWjBBJ+/AWjBBJ+/9geGdjBBJzAdjBBJz9feAVnjBBBzjBBB+/AWjBBBB9gemGW+LjBBB9P9dtMBAW+oHQXEKCJJJJ94HQKABCDFAQ87EBDNDNAOALAICUFCIgCDTFiDBj/zL+1znnGOjBBJ+/AOjBBJ+/9geGWjBBJzAWjBBJz9feAVnjBBBzjBBB+/AOjBBBB9gemGO+LjBBB9P9dtMBAO+oHIXEKCJJJJ94HIKABCLFAI87EBABCWFHBALCZFHLAECUFGEMBKKK+7DDWUE998jJJJJBCZ9rGV8kJJJJBDNAEtMBADCL6MBCEAI9rHOADCD4GDCEADCE0eHRADCDTHWCBHdINC+cUHDALHIARHQINAIiDBAVCXFZ+XJJJB8aAVYDXGKADADAK9IeHDAICLFHIAQCUFGQMBKAOADFGICkTHKCBHDCBAI9rHXARHIINDNDNALADFiDBGMAXZ+WJJJBjBBBzjBBB+/AMjBBBB9gemGM+LjBBB9P9dtMBAM+oHQXEKCJJJJ94HQKABADFAQCfffRgAKvbDBADCLFHDAICUFGIMBKABAWFHBALAWFHLAdCEFGdAE9HMBKKAVCZF8kJJJJBK/tKDcUI998jJJJJBC+QD9rGV8kJJJJBAVC+oEFCBC/kBZ+TJJJB8aCBHODNADtMBCBHOAItMBDNABAE9HMBAVCUADCDTGOADCffffI0eCBYD1+KJJBhJJJJBBGEbD+oEAVCEbD1DAEABAOZmJJJB8aKAVC+YEFCWFCBbDBAV9CB83I+YEAVC+YEFAEADAIAVC+oEFZ+NJJJBCUAICDTGRAICffffI0eGWCBYD1+KJJBhJJJJBBHOAVC+oEFAVYD1DGdCDTFAObDBAVAdCEFGQbD1DAOAVYD+YEGKARZmJJJBHXAVC+oEFAQCDTFADCI9uGMCBYD1+KJJBhJJJJBBGObDBAVAdCDFGRbD1DAOCBAMZ+TJJJBHpAVC+oEFARCDTFAWCBYD1+KJJBhJJJJBBGSbDBAVAdCIFGQbD1DAXHOASHRINARALiDBALAOYDBGWCWAWCW6eCDTFC/EBFiDBmuDBAOCLFHOARCLFHRAICUFGIMBKAVC+oEFAQCDTFCUAMCDTADCffff970eCBYD1+KJJBhJJJJBBGQbDBAVAdCLFbD1DDNADCI6MBAMCEAMCE0eHIAEHOAQHRINARASAOYDBCDTFiDBASAOCLFYDBCDTFiDBmASAOCWFYDBCDTFiDBmuDBAOCXFHOARCLFHRAICUFGIMBKKAVC/MBFHZAVYD+cEHhAVYD+gEHoAVHOCBHWCBHRCBHaCEHcINAOHxCIHqAEARCI2GlCDTFGOCWFYDBHkAOYDBHDABAaCX2FGICLFAOCLFYDBGdbDBAIADbDBAICWFAkbDBApARFCE86BBAZAkbDWAZAdbDLAZADbDBAQARCDTFCBbDBDNAWtMBCIHqAxHIINDNAIYDBGOADsMBAOAdsMBAOAksMBAZAqCDTFAObDBAqCEFHqKAICLFHIAWCUFGWMBKKAaCEFHaAXADCDTFGOAOYDBCUFbDBAXAdCDTFGOAOYDBCUFbDBAXAkCDTFGOAOYDBCUFbDBCBHWINAoAhAEAWAlFCDTFYDBCDTGIFYDBCDTFGkHOAKAIFGdYDBGDHIDNADtMBDNINAOYDBARsMEAOCLFHOAICUFGItMDXBKKAOADCDTAkFC98FYDBbDBAdAdYDBCUFbDBKAWCEFGWCI9HMBKDNDNDNAqtMBCUHRjBBBBHyCBHOINASAZAOCDTFYDBCDTGIFGWiDBH8aAWALCBAOCEFGdAOCS0eCDTFiDBALAXAIFYDBGOCWAOCW6eCDTFC/EBFiDBmGeuDBDNAKAIFYDBGWtMBAeA8a+THeAoAhAIFYDBCDTFHOAWCDTHIINAQAOYDBGWCDTFGDAeADiDBmG8auDBA8aAyAyA8a9dGDeHyAWARADeHRAOCLFHOAIC98FGIMBKKAdHOAdAq9HMBKARCU9HMEKAcAM9PMEINDNApAcFrBBMBAcHRXDKAMAcCEFGc9HMBXDKKAqCZAqCZ6eHWAZHOAxHZARCU9HMEKKAVYD1DHOKAOCDTAVC+oEFFC98FHRDNINAOtMEARYDBCBYD+E+KJJBh+BJJJBBARC98FHRAOCUFHOXBKKAVC+QDF8kJJJJBK/uLEVUCUAICDTGVAICffffI0eGOCBYD1+KJJBhJJJJBBHRALALYD9gGWCDTFARbDBALAWCEFbD9gABARbDBAOCBYD1+KJJBhJJJJBBHRALALYD9gGOCDTFARbDBALAOCEFbD9gABARbDLCUADCDTADCffffI0eCBYD1+KJJBhJJJJBBHRALALYD9gGOCDTFARbDBALAOCEFbD9gABARbDWABYDBCBAVZ+TJJJB8aADCI9uHWDNADtMBABYDBHOAEHLADHRINAOALYDBCDTFGVAVYDBCEFbDBALCLFHLARCUFGRMBKKDNAItMBABYDBHLABYDLHRCBHVAIHOINARAVbDBARCLFHRALYDBAVFHVALCLFHLAOCUFGOMBKKDNADCI6MBAWCEAWCE0eHdABYDLHRABYDWHVCBHLINAECWFYDBHOAECLFYDBHDARAEYDBCDTFGWAWYDBGWCEFbDBAVAWCDTFALbDBARADCDTFGDADYDBGDCEFbDBAVADCDTFALbDBARAOCDTFGOAOYDBGOCEFbDBAVAOCDTFALbDBAECXFHEAdALCEFGL9HMBKKDNAItMBABYDLHEABYDBHLINAEAEYDBALYDB9rbDBALCLFHLAECLFHEAICUFGIMBKKKqBABAEADAIC+01JJBZ+MJJJBKqBABAEADAIC+c+JJJBZ+MJJJBK9dEEUABCfEAICDTZ+TJJJBHLCBHIDNADtMBINDNALAEYDBCDTFGBYDBCU9HMBABAIbDBAICEFHIKAECLFHEADCUFGDMBKKAIK9TEIUCBCBYD+M+KJJBGEABCIFC98gFGBbD+M+KJJBDNDNABzBCZTGD9NMBCUHIABAD9rCffIFCZ4NBCUsMEKAEHIKAIK/lEEEUDNDNAEABvCIgtMBABHIXEKDNDNADCZ9PMBABHIXEKABHIINAIAEYDBbDBAICLFAECLFYDBbDBAICWFAECWFYDBbDBAICXFAECXFYDBbDBAICZFHIAECZFHEADC9wFGDCS0MBKKADCL6MBINAIAEYDBbDBAECLFHEAICLFHIADC98FGDCI0MBKKDNADtMBINAIAErBB86BBAICEFHIAECEFHEADCUFGDMBKKABK/AEEDUDNDNABCIgtMBABHIXEKAECfEgC+B+C+EW2HLDNDNADCZ9PMBABHIXEKABHIINAIALbDBAICXFALbDBAICWFALbDBAICLFALbDBAICZFHIADC9wFGDCS0MBKKADCL6MBINAIALbDBAICLFHIADC98FGDCI0MBKKDNADtMBINAIAE86BBAICEFHIADCUFGDMBKKABK9TEIUCBCBYD+M+KJJBGEABCIFC98gFGBbD+M+KJJBDNDNABzBCZTGD9NMBCUHIABAD9rCffIFCZ4NBCUsMEKAEHIKAIK9+EIUzBHEDNDNCBYD+M+KJJBGDAECZTGI9NMBCUHEADAI9rCffIFCZ4NBCUsMEKADHEKCBABAE9rCIFC98gCBYD+M+KJJBFGDbD+M+KJJBDNADzBCZTGE9NMBADAE9rCffIFCZ4NB8aKKXBABAEZ+YJJJBK+BEEIUDNAB+8GDCl4GICfEgGLCfEsMBDNALMBDNABjBBBB9cMBAECBbDBABSKABjBBJ9fnAEZ+XJJJBHBAEAEYDBCNFbDBABSKAEAICfEgC+CUFbDBADCfff+D94gCJJJ/4Iv++HBKABK+gEBDNDNAECJE9IMBABjBBBUnHBDNAECfE9PMBAEC+BUFHEXDKABjBBBUnHBAECPDAECPD6eC+C9+FHEXEKAEC+BU9KMBABjBBJXnHBDNAEC+b9+9NMBAEC/mBFHEXEKABjBBJXnHBAEC+299AEC+2990eC/MEFHEKABAEClTCJJJ/8IF++nKK+eDDBCJWK+EDB4+H9W9n94+p+Gw+J9o+YE9pBBBBBBEBBBDBBBEBBBDBBBBBBBDBBBBBBBEBBBBBBB+L29Hz/69+9Kz/n/76z/RG97z/Z/O9Xz8j/b85z/+/U9Yz/B/K9hz+2/z9dz9E+L9Mz59a8kz+R/t3z+a+Zyz79ohz/J4++8++y+d9v8+BBBB9S+49+z8r+Hbz9m9m/m8+l/Z/O8+/8+pg89Q/X+j878r+Hq8++m+b/E87BBBBBBJzBBJzBBJz+e/v/n8++y+dSz9I/h/68+XD/r8+/H0838+/w+nOzBBBB+wv9o8+UF888+9I/h/68+9C9g/l89/N/M9M89/d8kO8+BBBBF+8Tz9M836zs+2azl/Zpzz818ez9E+LXz/u98f8+819e/68+BC+EQKXEBBBDBBBAwBB";
var wasmpack = new Uint8Array([32, 0, 65, 2, 1, 106, 34, 33, 3, 128, 11, 4, 13, 64, 6, 253, 10, 7, 15, 116, 127, 5, 8, 12, 40, 16, 19, 54, 20, 9, 27, 255, 113, 17, 42, 67, 24, 23, 146, 148, 18, 14, 22, 45, 70, 69, 56, 114, 101, 21, 25, 63, 75, 136, 108, 28, 118, 29, 73, 115]);
if (typeof WebAssembly !== "object") {
return {
supported: false
};
}
var instance;
var promise = WebAssembly.instantiate(unpack(wasm), {}).then(function(result) {
instance = result.instance;
instance.exports.__wasm_call_ctors();
instance.exports.meshopt_encodeVertexVersion(0);
instance.exports.meshopt_encodeIndexVersion(1);
});
function unpack(data) {
var result = new Uint8Array(data.length);
for (var i = 0; i < data.length; ++i) {
var ch = data.charCodeAt(i);
result[i] = ch > 96 ? ch - 71 : ch > 64 ? ch - 65 : ch > 47 ? ch + 4 : ch > 46 ? 63 : 62;
}
var write = 0;
for (var i = 0; i < data.length; ++i) {
result[write++] = result[i] < 60 ? wasmpack[result[i]] : (result[i] - 60) * 64 + result[++i];
}
return result.buffer.slice(0, write);
}
function assert(cond) {
if (!cond) {
throw new Error("Assertion failed");
}
}
function bytes(view) {
return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
}
function reorder(indices2, vertices, optf) {
var sbrk = instance.exports.sbrk;
var ip = sbrk(indices2.length * 4);
var rp = sbrk(vertices * 4);
var heap = new Uint8Array(instance.exports.memory.buffer);
var indices8 = bytes(indices2);
heap.set(indices8, ip);
if (optf) {
optf(ip, ip, indices2.length, vertices);
}
var unique = instance.exports.meshopt_optimizeVertexFetchRemap(rp, ip, indices2.length, vertices);
heap = new Uint8Array(instance.exports.memory.buffer);
var remap = new Uint32Array(vertices);
new Uint8Array(remap.buffer).set(heap.subarray(rp, rp + vertices * 4));
indices8.set(heap.subarray(ip, ip + indices2.length * 4));
sbrk(ip - sbrk(0));
for (var i = 0; i < indices2.length; ++i)
indices2[i] = remap[indices2[i]];
return [remap, unique];
}
function encode(fun, bound, source, count, size) {
var sbrk = instance.exports.sbrk;
var tp = sbrk(bound);
var sp = sbrk(count * size);
var heap = new Uint8Array(instance.exports.memory.buffer);
heap.set(bytes(source), sp);
var res = fun(tp, bound, sp, count, size);
var target = new Uint8Array(res);
target.set(heap.subarray(tp, tp + res));
sbrk(tp - sbrk(0));
return target;
}
function maxindex(source) {
var result = 0;
for (var i = 0; i < source.length; ++i) {
var index = source[i];
result = result < index ? index : result;
}
return result;
}
function index32(source, size) {
assert(size == 2 || size == 4);
if (size == 4) {
return new Uint32Array(source.buffer, source.byteOffset, source.byteLength / 4);
} else {
var view = new Uint16Array(source.buffer, source.byteOffset, source.byteLength / 2);
return new Uint32Array(view);
}
}
function filter(fun, source, count, stride, bits, insize) {
var sbrk = instance.exports.sbrk;
var tp = sbrk(count * stride);
var sp = sbrk(count * insize);
var heap = new Uint8Array(instance.exports.memory.buffer);
heap.set(bytes(source), sp);
fun(tp, count, stride, bits, sp);
var target = new Uint8Array(count * stride);
target.set(heap.subarray(tp, tp + count * stride));
sbrk(tp - sbrk(0));
return target;
}
return {
ready: promise,
supported: true,
reorderMesh: function(indices2, triangles, optsize) {
var optf = triangles ? optsize ? instance.exports.meshopt_optimizeVertexCacheStrip : instance.exports.meshopt_optimizeVertexCache : void 0;
return reorder(indices2, maxindex(indices2) + 1, optf);
},
encodeVertexBuffer: function(source, count, size) {
assert(size > 0 && size <= 256);
assert(size % 4 == 0);
var bound = instance.exports.meshopt_encodeVertexBufferBound(count, size);
return encode(instance.exports.meshopt_encodeVertexBuffer, bound, source, count, size);
},
encodeIndexBuffer: function(source, count, size) {
assert(size == 2 || size == 4);
assert(count % 3 == 0);
var indices2 = index32(source, size);
var bound = instance.exports.meshopt_encodeIndexBufferBound(count, maxindex(indices2) + 1);
return encode(instance.exports.meshopt_encodeIndexBuffer, bound, indices2, count, 4);
},
encodeIndexSequence: function(source, count, size) {
assert(size == 2 || size == 4);
var indices2 = index32(source, size);
var bound = instance.exports.meshopt_encodeIndexSequenceBound(count, maxindex(indices2) + 1);
return encode(instance.exports.meshopt_encodeIndexSequence, bound, indices2, count, 4);
},
encodeGltfBuffer: function(source, count, size, mode2) {
var table2 = {
ATTRIBUTES: this.encodeVertexBuffer,
TRIANGLES: this.encodeIndexBuffer,
INDICES: this.encodeIndexSequence
};
assert(table2[mode2]);
return table2[mode2](source, count, size);
},
encodeFilterOct: function(source, count, stride, bits) {
assert(stride == 4 || stride == 8);
assert(bits >= 1 && bits <= 16);
return filter(instance.exports.meshopt_encodeFilterOct, source, count, stride, bits, 16);
},
encodeFilterQuat: function(source, count, stride, bits) {
assert(stride == 8);
assert(bits >= 4 && bits <= 16);
return filter(instance.exports.meshopt_encodeFilterQuat, source, count, stride, bits, 16);
},
encodeFilterExp: function(source, count, stride, bits) {
assert(stride > 0 && stride % 4 == 0);
assert(bits >= 1 && bits <= 24);
return filter(instance.exports.meshopt_encodeFilterExp, source, count, stride, bits, stride);
}
};
}();
// node_modules/meshoptimizer/meshopt_decoder.module.js
var MeshoptDecoder = function() {
"use strict";
var wasm_base = "B9h79tEBBBE8fV9gBB9gVUUUUUEU9gIUUUB9gEUEU9gIUUUEUIKQBEEEDDDILLVIEBEOWEUEC+Q/IEKR/LEdO9tw9t9vv95DBh9f9f939h79t9f9j9h229f9jT9vv7BB8a9tw79o9v9wT9f9kw9j9v9kw9WwvTw949C919m9mwvBEy9tw79o9v9wT9f9kw9j9v9kw69u9kw949C919m9mwvBDe9tw79o9v9wT9f9kw9j9v9kw69u9kw949Twg91w9u9jwBIl9tw79o9v9wT9f9kw9j9v9kws9p2Twv9P9jTBLk9tw79o9v9wT9f9kw9j9v9kws9p2Twv9R919hTBVl9tw79o9v9wT9f9kw9j9v9kws9p2Twvt949wBOL79iv9rBRQ+p8yQDBK/3SEZU8jJJJJBCJ/EB9rGV8kJJJJBC9+HODNADCEFAL0MBCUHOAIrBBC+gE9HMBAVAIALFGRAD9rADZ1JJJBHWCJ/ABAD9uHOAICEFHLDNADtMBAOC/wfBgGOCJDAOCJD6eHdCBHQINAQAE9PMEAdAEAQ9rAQAdFAE6eGKCSFGOCL4CIFCD4HXDNDNDNDNAOC9wgGMtMBCBHpCEHSAWCJDFHZALHhINARAh9rAX6MIDNARAhAXFGL9rCk6MBCZHOINAWCJ/CBFAOGIFGOC9wFHoDNDNDNDNDNAhAIC9wFGaCO4FrBBAaCI4COg4CIgpLBEDIBKAo9CB83IBAoCWF9CB83IBXIKAoALrBLALrBBGaCO4GcAcCIsGce86BBAOCgFALCLFAcFGorBBAaCL4CIgGcAcCIsGce86BBAOCvFAoAcFGorBBAaCD4CIgGcAcCIsGce86BBAOC7FAoAcFGorBBAaCIgGaAaCIsGae86BBAOCTFAoAaFGarBBALrBEGoCO4GcAcCIsGce86BBAOC91FAaAcFGarBBAoCL4CIgGcAcCIsGce86BBAOC4FAaAcFGarBBAoCD4CIgGcAcCIsGce86BBAOC93FAaAcFGarBBAoCIgGoAoCIsGoe86BBAOC94FAaAoFGarBBALrBDGoCO4GcAcCIsGce86BBAOC95FAaAcFGarBBAoCL4CIgGcAcCIsGce86BBAOC96FAaAcFGarBBAoCD4CIgGcAcCIsGce86BBAOC97FAaAcFGarBBAoCIgGoAoCIsGoe86BBAOC98FAaAoFGorBBALrBIGLCO4GaAaCIsGae86BBAOC99FAoAaFGorBBALCL4CIgGaAaCIsGae86BBAOC9+FAoAaFGorBBALCD4CIgGaAaCIsGae86BBAOCUFAoAaFGOrBBALCIgGLALCIsGLe86BBAOALFHLXDKAoALrBWALrBBGaCL4GcAcCSsGce86BBAOCgFALCWFAcFGorBBAaCSgGaAaCSsGae86BBAOCvFAoAaFGorBBALrBEGaCL4GcAcCSsGce86BBAOC7FAoAcFGorBBAaCSgGaAaCSsGae86BBAOCTFAoAaFGorBBALrBDGaCL4GcAcCSsGce86BBAOC91FAoAcFGorBBAaCSgGaAaCSsGae86BBAOC4FAoAaFGorBBALrBIGaCL4GcAcCSsGce86BBAOC93FAoAcFGorBBAaCSgGaAaCSsGae86BBAOC94FAoAaFGorBBALrBLGaCL4GcAcCSsGce86BBAOC95FAoAcFGorBBAaCSgGaAaCSsGae86BBAOC96FAoAaFGorBBALrBVGaCL4GcAcCSsGce86BBAOC97FAoAcFGorBBAaCSgGaAaCSsGae86BBAOC98FAoAaFGorBBALrBOGaCL4GcAcCSsGce86BBAOC99FAoAcFGorBBAaCSgGaAaCSsGae86BBAOC9+FAoAaFGorBBALrBRGLCL4GaAaCSsGae86BBAOCUFAoAaFGOrBBALCSgGLALCSsGLe86BBAOALFHLXEKAoAL8pBB83BBAoCWFALCWF8pBB83BBALCZFHLKDNAIAM9PMBAICZFHOARAL9rCl0MEKKAIAM6MIALtMIDNAKtMBAWApFrBBHoCBHOAZHIINAIAWCJ/CBFAOFrBBGaCE4CBAaCEg9r7AoFGo86BBAIADFHIAOCEFGOAK9HMBKKAZCEFHZApCEFGpAD6HSALHhApAD9HMEXVKKCBHLASCEgMDXIKALAXAD2FHcDNAKtMBCBHhCEHSAWCJDFHMINARAL9rAX6MIALtMDALAXFHLAWAhFrBBHoCBHOAMHIINAIAWCJ/CBFAOFrBBGaCE4CBAaCEg9r7AoFGo86BBAIADFHIAOCEFGOAK9HMBKAMCEFHMAhCEFGhAD6HSAhAD9HMBKAcHLXIKCBHOCEHSINARAL9rAX6MDALtMEALAXFHLAOCEFGOAD6HSADAO9HMBKAcHLXDKCBHLASCEgtMEKC9+HOXIKABAQAD2FAWCJDFAKAD2Z1JJJB8aAWAWCJDFAKCUFAD2FADZ1JJJB8aAKAQFHQALMBKC9+HOXEKCBC99ARAL9rADCAADCA0eseHOKAVCJ/EBF8kJJJJBAOK/YZEhU8jJJJJBC/AE9rGV8kJJJJBC9+HODNAECI9uGRChFAL0MBCUHOAIrBBGWC/wEgC/gE9HMBAWCSgGdCE0MBAVC/ABFCfECJEZ+JJJJB8aAVCuF9CU83IBAVC8wF9CU83IBAVCYF9CU83IBAVCAF9CU83IBAVCkF9CU83IBAVCZF9CU83IBAV9CU83IWAV9CU83IBAIALFC9wFHQAICEFGWARFHODNAEtMBCMCSAdCEseHKCBHXCBHMCBHdCBHICBHLINDNAOAQ9NMBC9+HOXIKDNDNAWrBBGRC/vE0MBAVC/ABFALARCL4CU7FCSgCITFGpYDLHSApYDBHZDNARCSgGpAK9PMBAVAIARCU7FCSgCDTFYDBAXApeHRAptHpDNDNADCD9HMBABAdCETFGhAZ87EBAhCDFAS87EBAhCLFAR87EBXEKABAdCDTFGhAZbDBAhCLFASbDBAhCWFARbDBKAXApFHXAVC/ABFALCITFGhARbDBAhASbDLAVAICDTFARbDBAVC/ABFALCEFCSgGLCITFGhAZbDBAhARbDLAIApFHIALCEFHLXDKDNDNApCSsMBAMApFApC987FCEFHMXEKAOCEFHRAO8sBBGpCfEgHhDNDNApCU9MMBARHOXEKAOCVFHOAhCfBgHhCRHpDNINAR8sBBGoCfBgApTAhvHhAoCU9KMEARCEFHRApCRFGpC8j9HMBXDKKARCEFHOKAhCE4CBAhCEg9r7AMFHMKDNDNADCD9HMBABAdCETFGRAZ87EBARCDFAS87EBARCLFAM87EBXEKABAdCDTFGRAZbDBARCLFASbDBARCWFAMbDBKAVC/ABFALCITFGRAMbDBARASbDLAVAICDTFAMbDBAVC/ABFALCEFCSgGLCITFGRAZbDBARAMbDLAICEFHIALCEFHLXEKDNARCPE0MBAXCEFGoAVAIAQARCSgFrBBGpCL49rCSgCDTFYDBApCZ6GheHRAVAIAp9rCSgCDTFYDBAoAhFGSApCSgGoeHpAotHoDNDNADCD9HMBABAdCETFGZAX87EBAZCDFAR87EBAZCLFAp87EBXEKABAdCDTFGZAXbDBAZCLFARbDBAZCWFApbDBKAVAICDTFAXbDBAVC/ABFALCITFGZARbDBAZAXbDLAVAICEFGICSgCDTFARbDBAVC/ABFALCEFCSgCITFGZApbDBAZARbDLAVAIAhFCSgGICDTFApbDBAVC/ABFALCDFCSgGLCITFGRAXbDBARApbDLALCEFHLAIAoFHIASAoFHXXEKAXCBAOrBBGZeGaARC/+EsGRFHSAZCSgHcAZCL4HxDNDNAZCS0MBASCEFHoXEKASHoAVAIAx9rCSgCDTFYDBHSKDNDNAcMBAoCEFHXXEKAoHXAVAIAZ9rCSgCDTFYDBHoKDNDNARtMBAOCEFHRXEKAOCDFHRAO8sBEGhCfEgHpDNAhCU9KMBAOCOFHaApCfBgHpCRHODNINAR8sBBGhCfBgAOTApvHpAhCU9KMEARCEFHRAOCRFGOC8j9HMBKAaHRXEKARCEFHRKApCE4CBApCEg9r7AMFGMHaKDNDNAxCSsMBARHpXEKARCEFHpAR8sBBGOCfEgHhDNAOCU9KMBARCVFHSAhCfBgHhCRHODNINAp8sBBGRCfBgAOTAhvHhARCU9KMEApCEFHpAOCRFGOC8j9HMBKASHpXEKApCEFHpKAhCE4CBAhCEg9r7AMFGMHSKDNDNAcCSsMBApHOXEKApCEFHOAp8sBBGRCfEgHhDNARCU9KMBApCVFHoAhCfBgHhCRHRDNINAO8sBBGpCfBgARTAhvHhApCU9KMEAOCEFHOARCRFGRC8j9HMBKAoHOXEKAOCEFHOKAhCE4CBAhCEg9r7AMFGMHoKDNDNADCD9HMBABAdCETFGRAa87EBARCDFAS87EBARCLFAo87EBXEKABAdCDTFGRAabDBARCLFASbDBARCWFAobDBKAVC/ABFALCITFGRASbDBARAabDLAVAICDTFAabDBAVC/ABFALCEFCSgCITFGRAobDBARASbDLAVAICEFGICSgCDTFASbDBAVC/ABFALCDFCSgCITFGRAabDBARAobDLAVAIAZCZ6AxCSsvFGICSgCDTFAobDBAIActAcCSsvFHIALCIFHLKAWCEFHWALCSgHLAICSgHIAdCIFGdAE6MBKKCBC99AOAQseHOKAVC/AEF8kJJJJBAOK+LLEVU8jJJJJBCZ9rHVC9+HODNAECVFAL0MBCUHOAIrBBC/+EgC/QE9HMBAV9CB83IWAICEFHRAIALFC98FHWDNAEtMBDNADCDsMBCBHdINDNARAW6MBC9+SKARCEFHOAR8sBBGLCfEgHIDNDNALCU9MMBAOHRXEKARCVFHRAICfBgHICRHLDNINAO8sBBGDCfBgALTAIvHIADCU9KMEAOCEFHOALCRFGLC8j9HMBXDKKAOCEFHRKABAdCDTFAICD4CBAICE4CEg9r7AVCWFAICEgCDTvGOYDBFGLbDBAOALbDBAdCEFGdAE9HMBXDKKCBHdINDNARAW6MBC9+SKARCEFHOAR8sBBGLCfEgHIDNDNALCU9MMBAOHRXEKARCVFHRAICfBgHICRHLDNINAO8sBBGDCfBgALTAIvHIADCU9KMEAOCEFHOALCRFGLC8j9HMBXDKKAOCEFHRKABAdCETFAICD4CBAICE4CEg9r7AVCWFAICEgCDTvGOYDBFGL87EBAOALbDBAdCEFGdAE9HMBKKCBC99ARAWseHOKAOK+lVOEUE99DUD99EUD99DNDNADCL9HMBAEtMEINDNDNABCDFGD8sBB+yAB8sBBGI+yGL+L+TABCEFGV8sBBGO+yGR+L+TGWjBB/+9CAWAWnjBBBBAWAWjBBBB9gGdeGQ+MGKAQAICB9IeALmGWAWnAKAQAOCB9IeARmGQAQnmm+R+VGLnjBBBzjBBB+/AdemGR+LjBBB9P9dtMBAR+oHIXEKCJJJJ94HIKADAI86BBDNDNAQALnjBBBzjBBB+/AQjBBBB9gemGQ+LjBBB9P9dtMBAQ+oHDXEKCJJJJ94HDKAVAD86BBDNDNAWALnjBBBzjBBB+/AWjBBBB9gemGW+LjBBB9P9dtMBAW+oHDXEKCJJJJ94HDKABAD86BBABCLFHBAECUFGEMBXDKKAEtMBINDNDNABCLFGD8uEB+yAB8uEBGI+yGL+L+TABCDFGV8uEBGO+yGR+L+TGWjB/+fsAWAWnjBBBBAWAWjBBBB9gGdeGQ+MGKAQAICB9IeALmGWAWnAKAQAOCB9IeARmGQAQnmm+R+VGLnjBBBzjBBB+/AdemGR+LjBBB9P9dtMBAR+oHIXEKCJJJJ94HIKADAI87EBDNDNAQALnjBBBzjBBB+/AQjBBBB9gemGQ+LjBBB9P9dtMBAQ+oHDXEKCJJJJ94HDKAVAD87EBDNDNAWALnjBBBzjBBB+/AWjBBBB9gemGW+LjBBB9P9dtMBAW+oHDXEKCJJJJ94HDKABAD87EBABCWFHBAECUFGEMBKKK/SILIUI99IUE99DNAEtMBCBHIABHLINDNDNj/zL81zALCOF8uEBGVCIv+y+VGOAL8uEB+ynGRjB/+fsnjBBBzjBBB+/ARjBBBB9gemGW+LjBBB9P9dtMBAW+oHdXEKCJJJJ94HdKALCLF8uEBHQALCDF8uEBHKABAVCEFCIgAIvCETFAd87EBDNDNAOAK+ynGWjB/+fsnjBBBzjBBB+/AWjBBBB9gemGX+LjBBB9P9dtMBAX+oHKXEKCJJJJ94HKKABAVCDFCIgAIvCETFAK87EBDNDNAOAQ+ynGOjB/+fsnjBBBzjBBB+/AOjBBBB9gemGX+LjBBB9P9dtMBAX+oHQXEKCJJJJ94HQKABAVCUFCIgAIvCETFAQ87EBDNDNjBBJzARARn+TAWAWn+TAOAOn+TGRjBBBBARjBBBB9ge+RjB/+fsnjBBBzmGR+LjBBB9P9dtMBAR+oHQXEKCJJJJ94HQKABAVCIgAIvCETFAQ87EBALCWFHLAICLFHIAECUFGEMBKKK9MBDNADCD4AE2GEtMBINABABYDBGDCWTCW91+yADCE91CJJJ/8IFCJJJ98g++nuDBABCLFHBAECUFGEMBKKK9TEIUCBCBYDJ1JJBGEABCIFC98gFGBbDJ1JJBDNDNABzBCZTGD9NMBCUHIABAD9rCffIFCZ4NBCUsMEKAEHIKAIK/lEEEUDNDNAEABvCIgtMBABHIXEKDNDNADCZ9PMBABHIXEKABHIINAIAEYDBbDBAICLFAECLFYDBbDBAICWFAECWFYDBbDBAICXFAECXFYDBbDBAICZFHIAECZFHEADC9wFGDCS0MBKKADCL6MBINAIAEYDBbDBAECLFHEAICLFHIADC98FGDCI0MBKKDNADtMBINAIAErBB86BBAICEFHIAECEFHEADCUFGDMBKKABK/AEEDUDNDNABCIgtMBABHIXEKAECfEgC+B+C+EW2HLDNDNADCZ9PMBABHIXEKABHIINAIALbDBAICXFALbDBAICWFALbDBAICLFALbDBAICZFHIADC9wFGDCS0MBKKADCL6MBINAIALbDBAICLFHIADC98FGDCI0MBKKDNADtMBINAIAE86BBAICEFHIADCUFGDMBKKABKKKEBCJWKLZ9kBB";
var wasm_simd = "B9h79tEBBBEkL9gBB9gVUUUUUEU9gIUUUB9gEUEUIKQBBEBEEDDDILVE9wEEEVIEBEOWEUEC+Q/aEKR/LEdO9tw9t9vv95DBh9f9f939h79t9f9j9h229f9jT9vv7BB8a9tw79o9v9wT9f9kw9j9v9kw9WwvTw949C919m9mwvBDy9tw79o9v9wT9f9kw9j9v9kw69u9kw949C919m9mwvBLe9tw79o9v9wT9f9kw9j9v9kw69u9kw949Twg91w9u9jwBVl9tw79o9v9wT9f9kw9j9v9kws9p2Twv9P9jTBOk9tw79o9v9wT9f9kw9j9v9kws9p2Twv9R919hTBRl9tw79o9v9wT9f9kw9j9v9kws9p2Twvt949wBWL79iv9rBdQ/T9TQLBZIK9+EVU8jJJJJBCZ9rHBCBHEINCBHDCBHIINABCWFADFAICJUAEAD4CEgGLe86BBAIALFHIADCEFGDCW9HMBKAEC+Q+YJJBFAI86BBAECITC+Q1JJBFAB8pIW83IBAECEFGECJD9HMBKK/H8jLhUD97EUO978jJJJJBCJ/KB9rGV8kJJJJBC9+HODNADCEFAL0MBCUHOAIrBBC+gE9HMBAVAIALFGRAD9rAD/8QBBCJ/ABAD9uHOAICEFHLDNADtMBAOC/wfBgGOCJDAOCJD6eHWCBHdINAdAE9PMEAWAEAd9rAdAWFAE6eGQCSFGOC9wgGKCI2HXAKCETHMAOCL4CIFCD4HpABAdAD2FHSCBHZDNINCEHhALHoCBHaDNINARAo9rAp6MIAVCJ/CBFAaAK2FHcAoApFHLCBHIDNAKC/AB6MBARAL9rC/gB6MBCBHOINAcAOFHIDNDNDNDNDNAoAOCO4FrBBGxCIgpLBEDIBKAIPXBBBBBBBBBBBBBBBBPKLBXIKAIALPBBLALPBBBGqCLP+MEAqPMBZEhDoIaLcVxOqRlGqCDP+MEAqPMBZEhDoIaLcVxOqRlPXIIIIIIIIIIIIIIIIP9OGlPXIIIIIIIIIIIIIIIIP8jGqP5B9CJf/8/4/w/g/AB9+9Cu1+nGkCITC+Q1JJBFPBIBAkC+Q+YJJBFPBBBGyAyPMBBBBBBBBBBBBBBBBAqP5E9CJf/8/4/w/g/AB9+9Cu1+nGkCITC+Q1JJBFPBIBP9uPMBEDILVORZhoacxqlPpAlAqP9SPKLBALCLFAyPqBFAkC+Q+YJJBFrBBFHLXDKAIALPBBWALPBBBGqCLP+MEAqPMBZEhDoIaLcVxOqRlPXSSSSSSSSSSSSSSSSP9OGlPXSSSSSSSSSSSSSSSSP8jGqP5B9CJf/8/4/w/g/AB9+9Cu1+nGkCITC+Q1JJBFPBIBAkC+Q+YJJBFPBBBGyAyPMBBBBBBBBBBBBBBBBAqP5E9CJf/8/4/w/g/AB9+9Cu1+nGkCITC+Q1JJBFPBIBP9uPMBEDILVORZhoacxqlPpAlAqP9SPKLBALCWFAyPqBFAkC+Q+YJJBFrBBFHLXEKAIALPBBBPKLBALCZFHLKDNDNDNDNDNAxCD4CIgpLBEDIBKAIPXBBBBBBBBBBBBBBBBPKLZXIKAIALPBBLALPBBBGqCLP+MEAqPMBZEhDoIaLcVxOqRlGqCDP+MEAqPMBZEhDoIaLcVxOqRlPXIIIIIIIIIIIIIIIIP9OGlPXIIIIIIIIIIIIIIIIP8jGqP5B9CJf/8/4/w/g/AB9+9Cu1+nGkCITC+Q1JJBFPBIBAkC+Q+YJJBFPBBBGyAyPMBBBBBBBBBBBBBBBBAqP5E9CJf/8/4/w/g/AB9+9Cu1+nGkCITC+Q1JJBFPBIBP9uPMBEDILVORZhoacxqlPpAlAqP9SPKLZALCLFAyPqBFAkC+Q+YJJBFrBBFHLXDKAIALPBBWALPBBBGqCLP+MEAqPMBZEhDoIaLcVxOqRlPXSSSSSSSSSSSSSSSSP9OGlPXSSSSSSSSSSSSSSSSP8jGqP5B9CJf/8/4/w/g/AB9+9Cu1+nGkCITC+Q1JJBFPBIBAkC+Q+YJJBFPBBBGyAyPMBBBBBBBBBBBBBBBBAqP5E9CJf/8/4/w/g/AB9+9Cu1+nGkCITC+Q1JJBFPBIBP9uPMBEDILVORZhoacxqlPpAlAqP9SPKLZALCWFAyPqBFAkC+Q+YJJBFrBBFHLXEKAIALPBBBPKLZALCZFHLKDNDNDNDNDNAxCL4CIgpLBEDIBKAIPXBBBBBBBBBBBBBBBBPKLAXIKAIALPBBLALPBBBGqCLP+MEAqPMBZEhDoIaLcVxOqRlGqCDP+MEAqPMBZEhDoIaLcVxOqRlPXIIIIIIIIIIIIIIIIP9OGlPXIIIIIIIIIIIIIIIIP8jGqP5B9CJf/8/4/w/g/AB9+9Cu1+nGkCITC+Q1JJBFPBIBAkC+Q+YJJBFPBBBGyAyPMBBBBBBBBBBBBBBBBAqP5E9CJf/8/4/w/g/AB9+9Cu1+nGkCITC+Q1JJBFPBIBP9uPMBEDILVORZhoacxqlPpAlAqP9SPKLAALCLFAyPqBFAkC+Q+YJJBFrBBFHLXDKAIALPBBWALPBBBGqCLP+MEAqPMBZEhDoIaLcVxOqRlPXSSSSSSSSSSSSSSSSP9OGlPXSSSSSSSSSSSSSSSSP8jGqP5B9CJf/8/4/w/g/AB9+9Cu1+nGkCITC+Q1JJBFPBIBAkC+Q+YJJBFPBBBGyAyPMBBBBBBBBBBBBBBBBAqP5E9CJf/8/4/w/g/AB9+9Cu1+nGkCITC+Q1JJBFPBIBP9uPMBEDILVORZhoacxqlPpAlAqP9SPKLAALCWFAyPqBFAkC+Q+YJJBFrBBFHLXEKAIALPBBBPKLAALCZFHLKDNDNDNDNDNAxCO4pLBEDIBKAIPXBBBBBBBBBBBBBBBBPKL8wXIKAIALPBBLALPBBBGqCLP+MEAqPMBZEhDoIaLcVxOqRlGqCDP+MEAqPMBZEhDoIaLcVxOqRlPXIIIIIIIIIIIIIIIIP9OGlPXIIIIIIIIIIIIIIIIP8jGqP5B9CJf/8/4/w/g/AB9+9Cu1+nGxCITC+Q1JJBFPBIBAxC+Q+YJJBFPBBBGyAyPMBBBBBBBBBBBBBBBBAqP5E9CJf/8/4/w/g/AB9+9Cu1+nGxCITC+Q1JJBFPBIBP9uPMBEDILVORZhoacxqlPpAlAqP9SPKL8wALCLFAyPqBFAxC+Q+YJJBFrBBFHLXDKAIALPBBWALPBBBGqCLP+MEAqPMBZEhDoIaLcVxOqRlPXSSSSSSSSSSSSSSSSP9OGlPXSSSSSSSSSSSSSSSSP8jGqP5B9CJf/8/4/w/g/AB9+9Cu1+nGxCITC+Q1JJBFPBIBAxC+Q+YJJBFPBBBGyAyPMBBBBBBBBBBBBBBBBAqP5E9CJf/8/4/w/g/AB9+9Cu1+nGxCITC+Q1JJBFPBIBP9uPMBEDILVORZhoacxqlPpAlAqP9SPKL8wALCWFAyPqBFAxC+Q+YJJBFrBBFHLXEKAIALPBBBPKL8wALCZFHLKAOC/ABFHIAOCJEFAK0MEAIHOARAL9rC/fB0MBKKDNDNAIAK9PMBAICI4HOINARAL9rCk6MDAcAIFHxDNDNDNDNDNAoAICO4FrBBAOCOg4CIgpLBEDIBKAxPXBBBBBBBBBBBBBBBBPKLBXIKAxALPBBLALPBBBGqCLP+MEAqPMBZEhDoIaLcVxOqRlGqCDP+MEAqPMBZEhDoIaLcVxOqRlPXIIIIIIIIIIIIIIIIP9OGlPXIIIIIIIIIIIIIIIIP8jGqP5B9CJf/8/4/w/g/AB9+9Cu1+nGkCITC+Q1JJBFPBIBAkC+Q+YJJBFPBBBGyAyPMBBBBBBBBBBBBBBBBAqP5E9CJf/8/4/w/g/AB9+9Cu1+nGkCITC+Q1JJBFPBIBP9uPMBEDILVORZhoacxqlPpAlAqP9SPKLBALCLFAyPqBFAkC+Q+YJJBFrBBFHLXDKAxALPBBWALPBBBGqCLP+MEAqPMBZEhDoIaLcVxOqRlPXSSSSSSSSSSSSSSSSP9OGlPXSSSSSSSSSSSSSSSSP8jGqP5B9CJf/8/4/w/g/AB9+9Cu1+nGkCITC+Q1JJBFPBIBAkC+Q+YJJBFPBBBGyAyPMBBBBBBBBBBBBBBBBAqP5E9CJf/8/4/w/g/AB9+9Cu1+nGkCITC+Q1JJBFPBIBP9uPMBEDILVORZhoacxqlPpAlAqP9SPKLBALCWFAyPqBFAkC+Q+YJJBFrBBFHLXEKAxALPBBBPKLBALCZFHLKAOCDFHOAICZFGIAK6MBKKALtMBAaCI6HhALHoAaCEFGOHaAOCLsMDXEKKCBHLAhCEgMDKDNAKtMBAVCJDFAZFHIAVAZFPBDBHyCBHxINAIAVCJ/CBFAxFGOPBLBGlCEP9tAlPXEEEEEEEEEEEEEEEEGqP9OP9hP9RGlAOAKFPBLBG8aCEP9tA8aAqP9OP9hP9RG8aPMBZEhDoIaLcVxOqRlGeAOAMFPBLBG3CEP9tA3AqP9OP9hP9RG3AOAXFPBLBG5CEP9tA5AqP9OP9hP9RG5PMBZEhDoIaLcVxOqRlG8ePMBEZhDIoaLVcxORqlGqAqPMBEDIBEDIBEDIBEDIAyP9uGyP9aDBBAIADFGOAyAqAqPMLVORLVORLVORLVORP9uGyP9aDBBAOADFGOAyAqAqPMWdQKWdQKWdQKWdQKP9uGyP9aDBBAOADFGOAyAqAqPMXMpSXMpSXMpSXMpSP9uGyP9aDBBAOADFGOAyAeA8ePMWdkyQK8aeXM35pS8e8fGqAqPMBEDIBEDIBEDIBEDIP9uGyP9aDBBAOADFGOAyAqAqPMLVORLVORLVORLVORP9uGyP9aDBBAOADFGOAyAqAqPMWdQKWdQKWdQKWdQKP9uGyP9aDBBAOADFGOAyAqAqPMXMpSXMpSXMpSXMpSP9uGyP9aDBBAOADFGOAyAlA8aPMWkdyQ8aKeX3M5p8eS8fGlA3A5PMWkdyQ8aKeX3M5p8eS8fG8aPMBEZhDIoaLVcxORqlGqAqPMBEDIBEDIBEDIBEDIP9uGyP9aDBBAOADFGOAyAqAqPMLVORLVORLVORLVORP9uGyP9aDBBAOADFGOAyAqAqPMWdQKWdQKWdQKWdQKP9uGyP9aDBBAOADFGOAyAqAqPMXMpSXMpSXMpSXMpSP9uGyP9aDBBAOADFGOAyAlA8aPMWdkyQK8aeXM35pS8e8fGqAqPMBEDIBEDIBEDIBEDIP9uGyP9aDBBAOADFGOAyAqAqPMLVORLVORLVORLVORP9uGyP9aDBBAOADFGOAyAqAqPMWdQKWdQKWdQKWdQKP9uGyP9aDBBAOADFGOAyAqAqPMXMpSXMpSXMpSXMpSP9uGyP9aDBBAOADFHIAxCZFGxAK6MBKKAZCLFGZAD6MBKASAVCJDFAQAD2/8QBBAVAVCJDFAQCUFAD2FAD/8QBBAQAdFHdC9+HOALMEXIKKC9+HOXEKCBC99ARAL9rADCAADCA0eseHOKAVCJ/KBF8kJJJJBAOKWBZ+BJJJBK/UZEhU8jJJJJBC/AE9rGV8kJJJJBC9+HODNAECI9uGRChFAL0MBCUHOAIrBBGWC/wEgC/gE9HMBAWCSgGdCE0MBAVC/ABFCfECJE/8KBAVCuF9CU83IBAVC8wF9CU83IBAVCYF9CU83IBAVCAF9CU83IBAVCkF9CU83IBAVCZF9CU83IBAV9CU83IWAV9CU83IBAIALFC9wFHQAICEFGWARFHODNAEtMBCMCSAdCEseHKCBHXCBHMCBHdCBHICBHLINDNAOAQ9NMBC9+HOXIKDNDNAWrBBGRC/vE0MBAVC/ABFALARCL4CU7FCSgCITFGpYDLHSApYDBHZDNARCSgGpAK9PMBAVAIARCU7FCSgCDTFYDBAXApeHRAptHpDNDNADCD9HMBABAdCETFGhAZ87EBAhCDFAS87EBAhCLFAR87EBXEKABAdCDTFGhAZbDBAhCLFASbDBAhCWFARbDBKAXApFHXAVC/ABFALCITFGhARbDBAhASbDLAVAICDTFARbDBAVC/ABFALCEFCSgGLCITFGhAZbDBAhARbDLAIApFHIALCEFHLXDKDNDNApCSsMBAMApFApC987FCEFHMXEKAOCEFHRAO8sBBGpCfEgHhDNDNApCU9MMBARHOXEKAOCVFHOAhCfBgHhCRHpDNINAR8sBBGoCfBgApTAhvHhAoCU9KMEARCEFHRApCRFGpC8j9HMBXDKKARCEFHOKAhCE4CBAhCEg9r7AMFHMKDNDNADCD9HMBABAdCETFGRAZ87EBARCDFAS87EBARCLFAM87EBXEKABAdCDTFGRAZbDBARCLFASbDBARCWFAMbDBKAVC/ABFALCITFGRAMbDBARASbDLAVAICDTFAMbDBAVC/ABFALCEFCSgGLCITFGRAZbDBARAMbDLAICEFHIALCEFHLXEKDNARCPE0MBAXCEFGoAVAIAQARCSgFrBBGpCL49rCSgCDTFYDBApCZ6GheHRAVAIAp9rCSgCDTFYDBAoAhFGSApCSgGoeHpAotHoDNDNADCD9HMBABAdCETFGZAX87EBAZCDFAR87EBAZCLFAp87EBXEKABAdCDTFGZAXbDBAZCLFARbDBAZCWFApbDBKAVAICDTFAXbDBAVC/ABFALCITFGZARbDBAZAXbDLAVAICEFGICSgCDTFARbDBAVC/ABFALCEFCSgCITFGZApbDBAZARbDLAVAIAhFCSgGICDTFApbDBAVC/ABFALCDFCSgGLCITFGRAXbDBARApbDLALCEFHLAIAoFHIASAoFHXXEKAXCBAOrBBGZeGaARC/+EsGRFHSAZCSgHcAZCL4HxDNDNAZCS0MBASCEFHoXEKASHoAVAIAx9rCSgCDTFYDBHSKDNDNAcMBAoCEFHXXEKAoHXAVAIAZ9rCSgCDTFYDBHoKDNDNARtMBAOCEFHRXEKAOCDFHRAO8sBEGhCfEgHpDNAhCU9KMBAOCOFHaApCfBgHpCRHODNINAR8sBBGhCfBgAOTApvHpAhCU9KMEARCEFHRAOCRFGOC8j9HMBKAaHRXEKARCEFHRKApCE4CBApCEg9r7AMFGMHaKDNDNAxCSsMBARHpXEKARCEFHpAR8sBBGOCfEgHhDNAOCU9KMBARCVFHSAhCfBgHhCRHODNINAp8sBBGRCfBgAOTAhvHhARCU9KMEApCEFHpAOCRFGOC8j9HMBKASHpXEKApCEFHpKAhCE4CBAhCEg9r7AMFGMHSKDNDNAcCSsMBApHOXEKApCEFHOAp8sBBGRCfEgHhDNARCU9KMBApCVFHoAhCfBgHhCRHRDNINAO8sBBGpCfBgARTAhvHhApCU9KMEAOCEFHOARCRFGRC8j9HMBKAoHOXEKAOCEFHOKAhCE4CBAhCEg9r7AMFGMHoKDNDNADCD9HMBABAdCETFGRAa87EBARCDFAS87EBARCLFAo87EBXEKABAdCDTFGRAabDBARCLFASbDBARCWFAobDBKAVC/ABFALCITFGRASbDBARAabDLAVAICDTFAabDBAVC/ABFALCEFCSgCITFGRAobDBARASbDLAVAICEFGICSgCDTFASbDBAVC/ABFALCDFCSgCITFGRAabDBARAobDLAVAIAZCZ6AxCSsvFGICSgCDTFAobDBAIActAcCSsvFHIALCIFHLKAWCEFHWALCSgHLAICSgHIAdCIFGdAE6MBKKCBC99AOAQseHOKAVC/AEF8kJJJJBAOK+LLEVU8jJJJJBCZ9rHVC9+HODNAECVFAL0MBCUHOAIrBBC/+EgC/QE9HMBAV9CB83IWAICEFHRAIALFC98FHWDNAEtMBDNADCDsMBCBHdINDNARAW6MBC9+SKARCEFHOAR8sBBGLCfEgHIDNDNALCU9MMBAOHRXEKARCVFHRAICfBgHICRHLDNINAO8sBBGDCfBgALTAIvHIADCU9KMEAOCEFHOALCRFGLC8j9HMBXDKKAOCEFHRKABAdCDTFAICD4CBAICE4CEg9r7AVCWFAICEgCDTvGOYDBFGLbDBAOALbDBAdCEFGdAE9HMBXDKKCBHdINDNARAW6MBC9+SKARCEFHOAR8sBBGLCfEgHIDNDNALCU9MMBAOHRXEKARCVFHRAICfBgHICRHLDNINAO8sBBGDCfBgALTAIvHIADCU9KMEAOCEFHOALCRFGLC8j9HMBXDKKAOCEFHRKABAdCETFAICD4CBAICE4CEg9r7AVCWFAICEgCDTvGOYDBFGL87EBAOALbDBAdCEFGdAE9HMBKKCBC99ARAWseHOKAOK+epLIUO97EUE978jJJJJBCA9rHIDNDNADCL9HMBDNAEC98gGLtMBCBHVABHDINADADPBBBGOCkP+rECkP+sEP/6EGRAOCWP+rECkP+sEP/6EARP/gEAOCZP+rECkP+sEP/6EGWP/gEP/kEP/lEGdPXBBBBBBBBBBBBBBBBP+2EGQARPXBBBJBBBJBBBJBBBJGKP9OP9RP/kEGRPXBB/+9CBB/+9CBB/+9CBB/+9CARARP/mEAdAdP/mEAWAQAWAKP9OP9RP/kEGRARP/mEP/kEP/kEP/jEP/nEGWP/mEPXBBN0BBN0BBN0BBN0GQP/kEPXfBBBfBBBfBBBfBBBP9OAOPXBBBfBBBfBBBfBBBfP9OP9QARAWP/mEAQP/kECWP+rEPXBfBBBfBBBfBBBfBBP9OP9QAdAWP/mEAQP/kECZP+rEPXBBfBBBfBBBfBBBfBP9OP9QPKBBADCZFHDAVCLFGVAL6MBKKALAE9PMEAIAECIgGVCDTGDvCBCZAD9r/8KBAIABALCDTFGLAD/8QBBDNAVtMBAIAIPBLBGOCkP+rECkP+sEP/6EGRAOCWP+rECkP+sEP/6EARP/gEAOCZP+rECkP+sEP/6EGWP/gEP/kEP/lEGdPXBBBBBBBBBBBBBBBBP+2EGQARPXBBBJBBBJBBBJBBBJGKP9OP9RP/kEGRPXBB/+9CBB/+9CBB/+9CBB/+9CARARP/mEAdAdP/mEAWAQAWAKP9OP9RP/kEGRARP/mEP/kEP/kEP/jEP/nEGWP/mEPXBBN0BBN0BBN0BBN0GQP/kEPXfBBBfBBBfBBBfBBBP9OAOPXBBBfBBBfBBBfBBBfP9OP9QARAWP/mEAQP/kECWP+rEPXBfBBBfBBBfBBBfBBP9OP9QAdAWP/mEAQP/kECZP+rEPXBBfBBBfBBBfBBBfBP9OP9QPKLBKALAIAD/8QBBSKDNAEC98gGXtMBCBHVABHDINADCZFGLALPBBBGOPXBBBBBBffBBBBBBffGKP9OADPBBBGdAOPMLVORXMpScxql358e8fPXfUBBfUBBfUBBfUBBP9OP/6EAdAOPMBEDIWdQKZhoaky8aeGOCZP+sEP/6EGRP/gEAOCZP+rECZP+sEP/6EGWP/gEP/kEP/lEGOPXB/+fsB/+fsB/+fsB/+fsAWAOPXBBBBBBBBBBBBBBBBP+2EGQAWPXBBBJBBBJBBBJBBBJGMP9OP9RP/kEGWAWP/mEAOAOP/mEARAQARAMP9OP9RP/kEGOAOP/mEP/kEP/kEP/jEP/nEGRP/mEPXBBN0BBN0BBN0BBN0GQP/kECZP+rEAWARP/mEAQP/kEPXffBBffBBffBBffBBP9OP9QGWAOARP/mEAQP/kEPXffBBffBBffBBffBBP9OGOPMWdkyQK8aeXM35pS8e8fP9QPKBBADAdAKP9OAWAOPMBEZhDIoaLVcxORqlP9QPKBBADCAFHDAVCLFGVAX6MBKKAXAE9PMBAIAECIgGVCITGDFCBCAAD9r/8KBAIABAXCITFGLAD/8QBBDNAVtMBAIAIPBLZGOPXBBBBBBffBBBBBBffGKP9OAIPBLBGdAOPMLVORXMpScxql358e8fPXfUBBfUBBfUBBfUBBP9OP/6EAdAOPMBEDIWdQKZhoaky8aeGOCZP+sEP/6EGRP/gEAOCZP+rECZP+sEP/6EGWP/gEP/kEP/lEGOPXB/+fsB/+fsB/+fsB/+fsAWAOPXBBBBBBBBBBBBBBBBP+2EGQAWPXBBBJBBBJBBBJBBBJGMP9OP9RP/kEGWAWP/mEAOAOP/mEARAQARAMP9OP9RP/kEGOAOP/mEP/kEP/kEP/jEP/nEGRP/mEPXBBN0BBN0BBN0BBN0GQP/kECZP+rEAWARP/mEAQP/kEPXffBBffBBffBBffBBP9OP9QGWAOARP/mEAQP/kEPXffBBffBBffBBffBBP9OGOPMWdkyQK8aeXM35pS8e8fP9QPKLZAIAdAKP9OAWAOPMBEZhDIoaLVcxORqlP9QPKLBKALAIAD/8QBBKK/4WLLUE97EUV978jJJJJBC8w9rHIDNAEC98gGLtMBCBHVABHOINAIAOPBBBGRAOCZFGWPBBBGdPMLVORXMpScxql358e8fGQCZP+sEGKCLP+rEPKLBAOPXBBJzBBJzBBJzBBJzPX/zL81z/zL81z/zL81z/zL81zAKPXIBBBIBBBIBBBIBBBP9QP/6EP/nEGKARAdPMBEDIWdQKZhoaky8aeGRCZP+rECZP+sEP/6EP/mEGdAdP/mEAKARCZP+sEP/6EP/mEGXAXP/mEAKAQCZP+rECZP+sEP/6EP/mEGQAQP/mEP/kEP/kEP/lEPXBBBBBBBBBBBBBBBBP+4EP/jEPXB/+fsB/+fsB/+fsB/+fsGKP/mEPXBBN0BBN0BBN0BBN0GRP/kEPXffBBffBBffBBffBBGMP9OAXAKP/mEARP/kECZP+rEP9QGXAQAKP/mEARP/kECZP+rEAdAKP/mEARP/kEAMP9OP9QGKPMBEZhDIoaLVcxORqlGRP5BAIPBLBPeB+t+J83IBAOCWFARP5EAIPBLBPeE+t+J83IBAWAXAKPMWdkyQK8aeXM35pS8e8fGKP5BAIPBLBPeD+t+J83IBAOCkFAKP5EAIPBLBPeI+t+J83IBAOCAFHOAVCLFGVAL6MBKKDNALAE9PMBAIAECIgGVCITGOFCBCAAO9r/8KBAIABALCITFGWAO/8QBBDNAVtMBAIAIPBLBGRAIPBLZGdPMLVORXMpScxql358e8fGQCZP+sEGKCLP+rEPKLAAIPXBBJzBBJzBBJzBBJzPX/zL81z/zL81z/zL81z/zL81zAKPXIBBBIBBBIBBBIBBBP9QP/6EP/nEGKARAdPMBEDIWdQKZhoaky8aeGRCZP+rECZP+sEP/6EP/mEGdAdP/mEAKARCZP+sEP/6EP/mEGXAXP/mEAKAQCZP+rECZP+sEP/6EP/mEGQAQP/mEP/kEP/kEP/lEPXBBBBBBBBBBBBBBBBP+4EP/jEPXB/+fsB/+fsB/+fsB/+fsGKP/mEPXBBN0BBN0BBN0BBN0GRP/kEPXffBBffBBffBBffBBGMP9OAXAKP/mEARP/kECZP+rEP9QGXAQAKP/mEARP/kECZP+rEAdAKP/mEARP/kEAMP9OP9QGKPMBEZhDIoaLVcxORqlGRP5BAIPBLAPeB+t+J83IBAIARP5EAIPBLAPeE+t+J83IWAIAXAKPMWdkyQK8aeXM35pS8e8fGKP5BAIPBLAPeD+t+J83IZAIAKP5EAIPBLAPeI+t+J83IkKAWAIAO/8QBBKK+pDDIUE978jJJJJBC/AB9rHIDNADCD4AE2GLC98gGVtMBCBHDABHEINAEAEPBBBGOCWP+rECWP+sEP/6EAOCEP+sEPXBBJzBBJzBBJzBBJzP+uEPXBBJfBBJfBBJfBBJfP9OP/mEPKBBAECZFHEADCLFGDAV6MBKKDNAVAL9PMBAIALCIgGDCDTGEvCBC/ABAE9r/8KBAIABAVCDTFGVAE/8QBBDNADtMBAIAIPBLBGOCWP+rECWP+sEP/6EAOCEP+sEPXBBJzBBJzBBJzBBJzP+uEPXBBJfBBJfBBJfBBJfP9OP/mEPKLBKAVAIAE/8QBBKK9TEIUCBCBYDJ1JJBGEABCIFC98gFGBbDJ1JJBDNDNABzBCZTGD9NMBCUHIABAD9rCffIFCZ4NBCUsMEKAEHIKAIKKKEBCJWKLZ9tBB";
var detector = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 3, 2, 0, 0, 5, 3, 1, 0, 1, 12, 1, 0, 10, 22, 2, 12, 0, 65, 0, 65, 0, 65, 0, 252, 10, 0, 0, 11, 7, 0, 65, 0, 253, 15, 26, 11]);
var wasmpack = new Uint8Array([32, 0, 65, 2, 1, 106, 34, 33, 3, 128, 11, 4, 13, 64, 6, 253, 10, 7, 15, 116, 127, 5, 8, 12, 40, 16, 19, 54, 20, 9, 27, 255, 113, 17, 42, 67, 24, 23, 146, 148, 18, 14, 22, 45, 70, 69, 56, 114, 101, 21, 25, 63, 75, 136, 108, 28, 118, 29, 73, 115]);
if (typeof WebAssembly !== "object") {
return {
supported: false
};
}
var wasm = wasm_base;
if (WebAssembly.validate(detector)) {
wasm = wasm_simd;
}
var instance;
var promise = WebAssembly.instantiate(unpack(wasm), {}).then(function(result) {
instance = result.instance;
instance.exports.__wasm_call_ctors();
});
function unpack(data) {
var result = new Uint8Array(data.length);
for (var i = 0; i < data.length; ++i) {
var ch = data.charCodeAt(i);
result[i] = ch > 96 ? ch - 71 : ch > 64 ? ch - 65 : ch > 47 ? ch + 4 : ch > 46 ? 63 : 62;
}
var write = 0;
for (var i = 0; i < data.length; ++i) {
result[write++] = result[i] < 60 ? wasmpack[result[i]] : (result[i] - 60) * 64 + result[++i];
}
return result.buffer.slice(0, write);
}
function decode(fun, target, count, size, source, filter) {
var sbrk = instance.exports.sbrk;
var count4 = count + 3 & ~3;
var tp = sbrk(count4 * size);
var sp = sbrk(source.length);
var heap = new Uint8Array(instance.exports.memory.buffer);
heap.set(source, sp);
var res = fun(tp, count, size, sp, source.length);
if (res == 0 && filter) {
filter(tp, count4, size);
}
target.set(heap.subarray(tp, tp + count * size));
sbrk(tp - sbrk(0));
if (res != 0) {
throw new Error("Malformed buffer data: " + res);
}
}
;
var filters = {
// legacy index-based enums for glTF
0: "",
1: "meshopt_decodeFilterOct",
2: "meshopt_decodeFilterQuat",
3: "meshopt_decodeFilterExp",
// string-based enums for glTF
NONE: "",
OCTAHEDRAL: "meshopt_decodeFilterOct",
QUATERNION: "meshopt_decodeFilterQuat",
EXPONENTIAL: "meshopt_decodeFilterExp"
};
var decoders = {
// legacy index-based enums for glTF
0: "meshopt_decodeVertexBuffer",
1: "meshopt_decodeIndexBuffer",
2: "meshopt_decodeIndexSequence",
// string-based enums for glTF
ATTRIBUTES: "meshopt_decodeVertexBuffer",
TRIANGLES: "meshopt_decodeIndexBuffer",
INDICES: "meshopt_decodeIndexSequence"
};
return {
ready: promise,
supported: true,
decodeVertexBuffer: function(target, count, size, source, filter) {
decode(instance.exports.meshopt_decodeVertexBuffer, target, count, size, source, instance.exports[filters[filter]]);
},
decodeIndexBuffer: function(target, count, size, source) {
decode(instance.exports.meshopt_decodeIndexBuffer, target, count, size, source);
},
decodeIndexSequence: function(target, count, size, source) {
decode(instance.exports.meshopt_decodeIndexSequence, target, count, size, source);
},
decodeGltfBuffer: function(target, count, size, source, mode2, filter) {
decode(instance.exports[decoders[mode2]], target, count, size, source, instance.exports[filters[filter]]);
}
};
}();
// node_modules/meshoptimizer/meshopt_simplifier.module.js
var MeshoptSimplifier = function() {
"use strict";
var wasm = "B9h79tEBBBECd9gEUEU9gEUB9gBB9gQUUUUUUU99UUEU9gVUUUUUB9gLUUUUE999gIUUUE999gLUUUUEU9gIUUUEUIMXDILVORBWWBEWLVE9wEIIVIEBEOWEUECJ/JEKR7OO9tw9t9vv95DBh9f9f939h79t9f9j9h229f9jT9vv7BBZ9tw79o9v9wT9f79p9t9w29p9m95BEx9tw79o9v9wT9f79p9t9w29p9m959T9j9h2wBLA9tw79o9v9wT9f9v9wT9p9t9p96w9WwvTw94swT9j9o9Sw9t9h9wBVL79iv9rBOdWEBCEKDdQQ+stXDBK/48yIkUp99hU8jJJJJBCJ/BB9rGQ8kJJJJBAQCkFCBC/kBZ1JJJB8aCUALCDTGKALCffffI0eGXCBYD/s1JJBhJJJJBBHMAQCkFAQYD94GpCDTFAMbDBAQAMbDWAQApCEFbD94AXCBYD/s1JJBhJJJJBBHSAQCkFAQYD94GpCDTFASbDBAQASbDXAQApCEFbD94CUADCITADCffffE0eCBYD/s1JJBhJJJJBBHZAQCkFAQYD94GpCDTFAZbDBAQAZbDZAQApCEFbD94AQCWFAEADALCBZ+CJJJBAXCBYD/s1JJBhJJJJBBHhAQCkFAQYD94GpCDTFAhbDBAQApCEFbD94AXCBYD/s1JJBhJJJJBBHoAQCkFAQYD94GpCDTFAobDBAQApCEFbD94ALCD4ALFHaCEHcINAcGpCETHcApAa6MBKCBHxCUApCDTGaApCffffI0eCBYD/s1JJBhJJJJBBHcAQCkFAQYD94GqCDTFAcbDBAQAqCEFbD94AcCfEAaZ1JJJBHlDNALtMBAVCD4HkApCUFHqINAIAxAk2CDTFGyYDLGpCh4Ap7C+f+B+dd2AyYDBGpCh4Ap7C/d/o+b8j27AyYDWGpCh4Ap7C+3f/n8n27HaCBHpDNDNINAlAaAqgGaCDTFG8aYDBGcCUsMEAIAcAk2CDTFAyCXZ+LJJJBtMDApCEFGpAaFHaApAq9NMBXDKKA8aAxbDBAxHcKAhAxCDTFAcbDBAxCEFGxAL9HMBKCBHpAoHcINAcApbDBAcCLFHcALApCEFGp9HMBKCBHpAhHcAoHaINDNApAcYDBGqsMBAaAoAqCDTFGqYDBbDBAqApbDBKAcCLFHcAaCLFHaALApCEFGp9HMBKKCBHaALCBYD/s1JJBhJJJJBBHyAQCkFAQYD94GpCDTFAybDBAQApCEFbD94AXCBYD/s1JJBhJJJJBBHpAQCkFAQYD94GcCDTFApbDBAQAcCEFbD94AXCBYD/s1JJBhJJJJBBHcAQCkFAQYD94GqCDTFAcbDBAQAqCEFbD94ApCfEAKZ1JJJBHeAcCfEAKZ1JJJBH3DNALtMBAZCWFH5INDNAMAaCDTGpFYDBG8etMBAZASApFYDBCITFH8fA3ApFHAAeApFHxCBHkINDNDNA8fAkCITFYDBGlAa9HMBAxAabDBAAAabDBXEKDNAMAlCDTGKFYDBGHtMBAZASAKFYDBCITGpFYDBAasMEAHCUFH8aA5ApFHcCBHpINA8aApsMEApCEFHpAcYDBHqAcCWFHcAqAa9HMBKApAH6MEKA3AKFGpAaAlApYDBCUsebDBAxAlAaAxYDBCUsebDBKAkCEFGkA8e9HMBKKAaCEFGaAL9HMBKAhHcAoHaA3HqAeHkCBHpINDNDNApAcYDBG8a9HMBDNApAaYDBG8a9HMBAkYDBH8aDNAqYDBGlCU9HMBA8aCU9HMBAyApFCB86BBXIKAyApFHxDNApAlsMBApA8asMBAxCE86BBXIKAxCL86BBXDKDNApAoA8aCDTGlFYDB9HMBDNAqYDBGxCUsMBApAxsMBAkYDBGKCUsMBApAKsMBA3AlFYDBG8eCUsMBA8eA8asMBAeAlFYDBGlCUsMBAlA8asMBDNAhAxCDTFYDBAhAlCDTFYDB9HMBAhAKCDTFYDBAhA8eCDTFYDB9HMBAyApFCD86BBXLKAyApFCL86BBXIKAyApFCL86BBXDKAyApFCL86BBXEKAyApFAyA8aFrBB86BBKAcCLFHcAaCLFHaAqCLFHqAkCLFHkALApCEFGp9HMBKAWCEgtMBAyHpALHcINDNAprBBCE9HMBApCL86BBKApCEFHpAcCUFGcMBKKCBHkCUALCX2ALC/V+q/V+qE0eCBYD/s1JJBhJJJJBBHMAQCkFAQYD94GpCDTFAMbDBAQApCEFbD94AMAIALAVZ+DJJJB8aCUALC8s2GcALC/d/o/F8u0eCBYD/s1JJBhJJJJBBHpAQCkFAQYD94GaCDTFApbDBAQAaCEFbD94ApCBAcZ1JJJBHZDNADtMBAEHcINDNAMAcCLFYDBG8aCX2FGpiDBAMAcYDBGlCX2FGaiDBGG+TG8jAMAcCWFYDBGxCX2FGqCLFiDBAaCLFiDBG8k+TG8lnAqiDBAG+TG8mApCLFiDBA8k+TG8nn+TGYAYnA8nAqCWFiDBAaCWFiDBG8p+TGinA8lApCWFiDBA8p+TG8nn+TG8lA8lnA8nA8mnAiA8jn+TG8jA8jnmm+RG8mjBBBB9etMBAYA8m+VHYA8jA8m+VH8jA8lA8m+VH8lKAZAhAlCDTFYDBC8s2FGpA8lA8m+RG8mA8lnnG8nApiDBmuDBApA8jA8mA8jnG8rnGiApiDLmuDLApAYA8mAYnG8snGrApiDWmuDWApA8rA8lnG8rApiDXmuDXApA8sA8lnG8uApiDZmuDZApA8sA8jnG8sApiDcmuDcApA8lA8mAYA8pnA8lAGnA8kA8jnmm+MG8knGGnG8lApiDkmuDkApA8jAGnG8jApiD3muD3ApAYAGnGYApiDAmuDAApAGA8knGGApiD8kmuD8kApA8mApiDYmuDYAZAhA8aCDTFYDBC8s2FGpA8nApiDBmuDBApAiApiDLmuDLApArApiDWmuDWApA8rApiDXmuDXApA8uApiDZmuDZApA8sApiDcmuDcApA8lApiDkmuDkApA8jApiD3muD3ApAYApiDAmuDAApAGApiD8kmuD8kApA8mApiDYmuDYAZAhAxCDTFYDBC8s2FGpA8nApiDBmuDBApAiApiDLmuDLApArApiDWmuDWApA8rApiDXmuDXApA8uApiDZmuDZApA8sApiDcmuDcApA8lApiDkmuDkApA8jApiD3muD3ApAYApiDAmuDAApAGApiD8kmuD8kApA8mApiDYmuDYAcCXFHcAkCIFGkAD6MBKCBH8aAEHxINCBHcINAyAEAcC+81JJBFYDBGlA8aFCDTFYDBGaFrBBHpDNDNAyAxAcFYDBGqFrBBGkC99FCfEgCPE0MBApCEsMBApCD9HMEKDNAkCUFCfEgCE0MBAeAqCDTFYDBAa9HMEKDNApCUFCfEgCE0MBA3AaCDTFYDBAq9HMEKDNAkCV2ApFC+g1JJBFrBBtMBAhAaCDTFYDBAhAqCDTFYDB0MEKjBBACjBBJzApCEseH8mAkCEsHKAEAlCDTC+81JJBFYDBA8aFCDTFYDBHlDNAMAaCX2FGpCWFiDBAMAqCX2FGkCWFiDBG8k+TG8lA8lnApiDBAkiDBG8p+TG8jA8jnApCLFiDBAkCLFiDBG8n+TGYAYnmm+RGGjBBBB9etMBA8lAG+VH8lAYAG+VHYA8jAG+VH8jKjBBACA8mAKeH8sDNAMAlCX2FGpiDWA8k+TG8mA8lA8mA8lnApiDBA8p+TGrA8jnAYApiDLA8n+TG8rnmmGin+TG8mA8mnArA8jAin+TG8lA8lnA8rAYAin+TG8jA8jnmm+RGYjBBBB9etMBA8mAY+VH8mA8jAY+VH8jA8lAY+VH8lKAZAhAqCDTFYDBC8s2FGpA8lA8sAGnGYA8lnnGiApiDBmuDBApA8jAYA8jnG8snGrApiDLmuDLApA8mAYA8mnGGnG8rApiDWmuDWApA8sA8lnG8sApiDXmuDXApAGA8lnG8uApiDZmuDZApAGA8jnG8vApiDcmuDcApA8lAYA8mA8knA8lA8pnA8nA8jnmm+MG8knGGnG8lApiDkmuDkApA8jAGnG8jApiD3muD3ApA8mAGnG8mApiDAmuDAApAGA8knGGApiD8kmuD8kApAYApiDYmuDYAZAhAaCDTFYDBC8s2FGpAiApiDBmuDBApArApiDLmuDLApA8rApiDWmuDWApA8sApiDXmuDXApA8uApiDZmuDZApA8vApiDcmuDcApA8lApiDkmuDkApA8jApiD3muD3ApA8mApiDAmuDAApAGApiD8kmuD8kApAYApiDYmuDYKAcCLFGcCX9HMBKAxCXFHxA8aCIFG8aAD6MBKKDNABAEsMBABAEADCDTZ+HJJJB8aKCUADCX2ADC/V+q/V+qE0eCBYD/s1JJBhJJJJBBHAAQCkFAQYD94GpCDTFAAbDBAQApCEFbD94CUADCDTADCffffI0eCBYD/s1JJBhJJJJBBH5AQCkFAQYD94GpCDTFA5bDBAQApCEFbD94AXCBYD/s1JJBhJJJJBBHIAQCkFAQYD94GpCDTFAIbDBAQApCEFbD94ALCBYD/s1JJBhJJJJBBH8wAQCkFAQYD94GpCDTFA8wbDBAQApCEFbD94jBBBBHrDNADAO9NMBARARnH8sAACWFH8xAQYDZH8yAQYDXH8zAQYDWH80jBBBBHrINAQCWFABADGSALAhZ+CJJJBCBHHABHxCBHKINCBHpINDNAhAxApFYDBGaCDTGEFYDBGkAhABApC+81JJBFYDBAKFCDTFYDBGcCDTFYDBG8asMBAyAcFrBBGlCV2AyAaFrBBGqFC/Q1JJBFrBBGDAqCV2AlFG8eC/Q1JJBFrBBG8fvCfEgtMBDNA8eC+g1JJBFrBBtMBA8aAk0MEKDNAqAl9HMBAqCUFCfEgCE0MBAeAEFYDBAc9HMEKAAAHCX2FGqAcAaA8fCfEgGkebDLAqAaAcAkebDBAqADA8fgCfEgCB9HbDWAHCEFHHKApCLFGpCX9HMBKAxCXFHxAKCIFGKAS6MBKDNDNAHtMBAAHcAHH8aINAcCWFGljBBBBjBBJzAZAhAcYDBGaCDTFYDBC8s2FGpiDYG8l+VA8ljBBBB9beApiDWAMAcCLFGEYDBGqCX2FGkCWFiDBG8lnApiDZAkiDBG8jnApiDAmG8mA8mmmA8lnApiDLAkCLFiDBG8mnApiDcA8lnApiD3mG8lA8lmmA8mnApiDBA8jnApiDXA8mnApiDkmG8lA8lmmA8jnApiD8kmmm+LnGYjBBBBjBBJzAZAhAqAaAlYDBGkeGlCDTFYDBC8s2FGpiDYG8l+VA8ljBBBB9beApiDWAMAaAqAkeGxCX2FGkCWFiDBG8lnApiDZAkiDBG8jnApiDAmG8mA8mmmA8lnApiDLAkCLFiDBG8mnApiDcA8lnApiD3mG8lA8lmmA8mnApiDBA8jnApiDXA8mnApiDkmG8lA8lmmA8jnApiD8kmmm+LnG8lAYA8l9fGpeuDBAEAqAxApebDBAcAaAlApebDBAcCXFHcA8aCUFG8aMBKAQCJEFCBCJ/ABZ1JJJB8aA8xHpAHHcINAQCJEFApYDBCo4C/8zgFGaAaYDBCEFbDBApCXFHpAcCUFGcMBKCBHpCBHcINAQCJEFApFGaYDBHqAaAcbDBAqAcFHcApCLFGpCJ/AB9HMBKCBHpA8xHcINAQCJEFAcYDBCo4C/8zgFGaAaYDBGaCEFbDBA5AaCDTFApbDBAcCXFHcAHApCEFGp9HMBKASAO9rGaCI9uH81DNALtMBCBHpAIHcINAcApbDBAcCLFHcALApCEFGp9HMBKKCBHbA8wCBALZ1JJJBH83AaCo9uHuA81CE4H85CBH86CBHKDNINAAA5AKCDTFYDBCX2FGxiDWG8jA8s9eMEA86A819PMEjffUUH8lDNA85AH9PMBAAA5A85CDTFYDBCX2FiDWjBB/AznH8lKDNA8jA8l9etMBA86Au0MDKDNA83AhAxYDLG87CDTG88FYDBGaFG89rBBA83AhAxYDBGECDTG8+FYDBGzFGNrBBvMBDNA80AzCDTGpFYDBGqtMBA8yA8zApFYDBCITFHpAMAaCX2FG8eCWFHDA8eCLFHXAMAzCX2FG8fCWFHVA8fCLFHWCBHcCEHlDNINDNAIApYDBCDTFYDBGkAasMBAIApCLFYDBCDTFYDBG8aAasMBAMA8aCX2FG8aiDBAMAkCX2FGkiDBG8m+TG8lAWiDBAkCLFiDBGY+TGGnA8fiDBA8m+TG8kA8aCLFiDBAY+TG8jn+TA8lAXiDBAY+TG8pnA8eiDBA8m+TG8nA8jn+TnA8jAViDBAkCWFiDBGY+TGinAGA8aCWFiDBAY+TG8mn+TA8jADiDBAY+TGYnA8pA8mn+TnA8mA8knAiA8ln+TA8mA8nnAYA8ln+TnmmjBBBB9dMDKApCWFHpAcCEFGcAq6HlAqAc9HMBKKAlCEgtMBA85CEFH85XEKAxCWFHqAZAaC8s2FGpAZAzC8s2FGciDBApiDBmuDBApAciDLApiDLmuDLApAciDWApiDWmuDWApAciDXApiDXmuDXApAciDZApiDZmuDZApAciDcApiDcmuDcApAciDkApiDkmuDkApAciD3ApiD3muD3ApAciDAApiDAmuDAApAciD8kApiD8kmuD8kApAciDYApiDYmuDYDNDNDNDNAyAEFGcrBBC9+FpDEBDKAEHpINAIApCDTGpFAabDBAoApFYDBGpAE9HMBXIKKAoA88FYDBHpAoA8+FYDBHEAIA8+FA87bDBApH87KAIAECDTFA87bDBKANCE86BBA89CE86BBAqiDBG8lArArA8l9deHrAbCEFHbCECDAcrBBCEseA86FH86KAKCEFGKAH9HMBKKAbtMBDNALtMBCBHcAeHpINDNApYDBGaCUsMBDNAcAIAaCDTGqFYDBGa9HMBAeAqFYDBHaKApAabDBKApCLFHpALAcCEFGc9HMBKCBHcA3HpINDNApYDBGaCUsMBDNAcAIAaCDTGqFYDBGa9HMBA3AqFYDBHaKApAabDBKApCLFHpALAcCEFGc9HMBKKCBHDABHpCBHkINDNAIApYDBCDTFYDBGcAIApCLFYDBCDTFYDBGasMBAcAIApCWFYDBCDTFYDBGqsMBAaAqsMBABADCDTFG8aAcbDBA8aCLFAabDBA8aCWFAqbDBADCIFHDKApCXFHpAkCIFGkAS9PMDXBKKASHDXDKADAO0MBKKDNAdtMBAdAr+RuDBKAQYD94GpCDTAQCkFFC98FHhDNINAptMEAhYDBCBYD/w1JJBh+BJJJBBAhC98FHhApCUFHpXBKKAQCJ/BBF8kJJJJBADK/PLEOUABYDBCBAICDTZ1JJJB8aADCI9uHVDNADtMBABYDBHODNALtMBAEHRADHWINAOALARYDBCDTFYDBCDTFGdAdYDBCEFbDBARCLFHRAWCUFGWMBXDKKAEHRADHWINAOARYDBCDTFGdAdYDBCEFbDBARCLFHRAWCUFGWMBKKDNAItMBABYDBHRABYDLHWCBHdAIHOINAWAdbDBAWCLFHWARYDBAdFHdARCLFHRAOCUFGOMBKKDNADCI6MBAVCEAVCE0eHQABYDLHVABYDWHRINAECWFYDBHWAECLFYDBHdAEYDBHODNALtMBALAWCDTFYDBHWALAdCDTFYDBHdALAOCDTFYDBHOKARAVAOCDTFGDYDBCITFAdbDBARADYDBCITFAWbDLADADYDBCEFbDBARAVAdCDTFGDYDBCITFAWbDBARADYDBCITFAObDLADADYDBCEFbDBARAVAWCDTFGWYDBCITFAObDBARAWYDBCITFAdbDLAWAWYDBCEFbDBAECXFHEAQCUFGQMBKKDNAItMBABYDLHRABYDBHWINARARYDBAWYDB9rbDBAWCLFHWARCLFHRAICUFGIMBKKK+3LDOUV998jJJJJBCA9rGLCZFCWFCBYD11JJBbDBALCB8pDJ1JJB83IZALCWFCBYDn1JJBbDBALCB8pD+M1JJB83IBDNADtMBAICD4HVDNABtMBAVCDTHOCBHRAEHWINABARCX2FGIAEARAV2CDTFGdiDBuDBAIAdiDLuDLAIAdiDWuDWCBHIINALCZFAIFGdAWAIFiDBGQAdiDBGKAKAQ9eeuDBALAIFGdAQAdiDBGKAKAQ9deuDBAICLFGICX9HMBKAWAOFHWARCEFGRAD9HMBXDKKAVCDTHRCBHWINCBHIINALCZFAIFGdAEAIFiDBGQAdiDBGKAKAQ9eeuDBALAIFGdAQAdiDBGKAKAQ9deuDBAICLFGICX9HMBKAEARFHEAWCEFGWAD9HMBKKALiDBALiDZGK+TjBBBB+XGQALiDLALiDcGX+TGMAMAQ9deGQALiDWALiDkGM+TGpApAQ9deHpDNABtMBADtMBjBBBBjBBJzAp+VApjBBBB9beHQINABAQABiDBAK+TnuDBABCLFGIAQAIiDBAX+TnuDBABCWFGIAQAIiDBAM+TnuDBABCXFHBADCUFGDMBKKApK+qDIDUI99DUCBHI8jJJJJBCA9rGLCZFCWFCBYD11JJBbDBALCB8pDJ1JJB83IZALCWFCBYDn1JJBbDBALCB8pD+M1JJB83IBDNDNAEMBjBBJfHVjBBJfHOjBBJfHRXEKADCD4CDTHWINCBHDINALCZFADFGdABADFiDBGOAdiDBGRARAO9eeuDBALADFGdAOAdiDBGRARAO9deuDBADCLFGDCX9HMBKABAWFHBAICEFGIAE9HMBKALiDWALiDk+THRALiDLALiDc+THOALiDBALiDZ+THVKAVjBBBB+XGVAOAOAV9deGOARARAO9deK9dEEUABCfEAICDTZ1JJJBHLCBHIDNADtMBINDNALAEYDBCDTFGBYDBCU9HMBABAIbDBAICEFHIKAECLFHEADCUFGDMBKKAIK9TEIUCBCBYD/01JJBGEABCIFC98gFGBbD/01JJBDNDNABzBCZTGD9NMBCUHIABAD9rCffIFCZ4NBCUsMEKAEHIKAIK/lEEEUDNDNAEABvCIgtMBABHIXEKDNDNADCZ9PMBABHIXEKABHIINAIAEYDBbDBAICLFAECLFYDBbDBAICWFAECWFYDBbDBAICXFAECXFYDBbDBAICZFHIAECZFHEADC9wFGDCS0MBKKADCL6MBINAIAEYDBbDBAECLFHEAICLFHIADC98FGDCI0MBKKDNADtMBINAIAErBB86BBAICEFHIAECEFHEADCUFGDMBKKABK/AEEDUDNDNABCIgtMBABHIXEKAECfEgC+B+C+EW2HLDNDNADCZ9PMBABHIXEKABHIINAIALbDBAICXFALbDBAICWFALbDBAICLFALbDBAICZFHIADC9wFGDCS0MBKKADCL6MBINAIALbDBAICLFHIADC98FGDCI0MBKKDNADtMBINAIAE86BBAICEFHIADCUFGDMBKKABK9TEIUCBCBYD/01JJBGEABCIFC98gFGBbD/01JJBDNDNABzBCZTGD9NMBCUHIABAD9rCffIFCZ4NBCUsMEKAEHIKAIK9+EIUzBHEDNDNCBYD/01JJBGDAECZTGI9NMBCUHEADAI9rCffIFCZ4NBCUsMEKADHEKCBABAE9rCIFC98gCBYD/01JJBFGDbD/01JJBDNADzBCZTGE9NMBADAE9rCffIFCZ4NB8aKK6EIUCBHIDNADtMBDNINABrBBGLAErBBGV9HMEAECEFHEABCEFHBADCUFGDMBXDKKALAV9rHIKAIKK+CEDBCJWK9pffUUffUUffUUffUfffUfffUfBBBBBBBBEEEBEEBEBBEEEBEBBBBBEBEBBBBBEBBBDBBBBBBBBBBBBBBBEEEEEBEBBBBBEBBBBBEEBBBBBBC/sWKXEBBBDBBBJ9kBB";
var wasmpack = new Uint8Array([32, 0, 65, 2, 1, 106, 34, 33, 3, 128, 11, 4, 13, 64, 6, 253, 10, 7, 15, 116, 127, 5, 8, 12, 40, 16, 19, 54, 20, 9, 27, 255, 113, 17, 42, 67, 24, 23, 146, 148, 18, 14, 22, 45, 70, 69, 56, 114, 101, 21, 25, 63, 75, 136, 108, 28, 118, 29, 73, 115]);
if (typeof WebAssembly !== "object") {
return {
supported: false
};
}
var instance;
var promise = WebAssembly.instantiate(unpack(wasm), {}).then(function(result) {
instance = result.instance;
instance.exports.__wasm_call_ctors();
});
function unpack(data) {
var result = new Uint8Array(data.length);
for (var i = 0; i < data.length; ++i) {
var ch = data.charCodeAt(i);
result[i] = ch > 96 ? ch - 71 : ch > 64 ? ch - 65 : ch > 47 ? ch + 4 : ch > 46 ? 63 : 62;
}
var write = 0;
for (var i = 0; i < data.length; ++i) {
result[write++] = result[i] < 60 ? wasmpack[result[i]] : (result[i] - 60) * 64 + result[++i];
}
return result.buffer.slice(0, write);
}
function assert(cond) {
if (!cond) {
throw new Error("Assertion failed");
}
}
function bytes(view) {
return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
}
function reorder(indices2, vertices) {
var sbrk = instance.exports.sbrk;
var ip = sbrk(indices2.length * 4);
var rp = sbrk(vertices * 4);
var heap = new Uint8Array(instance.exports.memory.buffer);
var indices8 = bytes(indices2);
heap.set(indices8, ip);
var unique = instance.exports.meshopt_optimizeVertexFetchRemap(rp, ip, indices2.length, vertices);
heap = new Uint8Array(instance.exports.memory.buffer);
var remap = new Uint32Array(vertices);
new Uint8Array(remap.buffer).set(heap.subarray(rp, rp + vertices * 4));
indices8.set(heap.subarray(ip, ip + indices2.length * 4));
sbrk(ip - sbrk(0));
for (var i = 0; i < indices2.length; ++i)
indices2[i] = remap[indices2[i]];
return [remap, unique];
}
function maxindex(source) {
var result = 0;
for (var i = 0; i < source.length; ++i) {
var index = source[i];
result = result < index ? index : result;
}
return result;
}
function simplify(fun, indices2, index_count, vertex_positions, vertex_count, vertex_positions_stride, target_index_count, target_error, options) {
var sbrk = instance.exports.sbrk;
var te = sbrk(4);
var ti = sbrk(index_count * 4);
var sp = sbrk(vertex_count * vertex_positions_stride);
var si = sbrk(index_count * 4);
var heap = new Uint8Array(instance.exports.memory.buffer);
heap.set(bytes(vertex_positions), sp);
heap.set(bytes(indices2), si);
var result = fun(ti, si, index_count, sp, vertex_count, vertex_positions_stride, target_index_count, target_error, options, te);
heap = new Uint8Array(instance.exports.memory.buffer);
var target = new Uint32Array(result);
bytes(target).set(heap.subarray(ti, ti + result * 4));
var error = new Float32Array(1);
bytes(error).set(heap.subarray(te, te + 4));
sbrk(te - sbrk(0));
return [target, error[0]];
}
function simplifyScale(fun, vertex_positions, vertex_count, vertex_positions_stride) {
var sbrk = instance.exports.sbrk;
var sp = sbrk(vertex_count * vertex_positions_stride);
var heap = new Uint8Array(instance.exports.memory.buffer);
heap.set(bytes(vertex_positions), sp);
var result = fun(sp, vertex_count, vertex_positions_stride);
sbrk(sp - sbrk(0));
return result;
}
var simplifyOptions = {
LockBorder: 1
};
return {
ready: promise,
supported: true,
compactMesh: function(indices2) {
assert(indices2 instanceof Uint32Array || indices2 instanceof Int32Array || indices2 instanceof Uint16Array || indices2 instanceof Int16Array);
assert(indices2.length % 3 == 0);
var indices32 = indices2.BYTES_PER_ELEMENT == 4 ? indices2 : new Uint32Array(indices2);
return reorder(indices32, maxindex(indices2) + 1);
},
simplify: function(indices2, vertex_positions, vertex_positions_stride, target_index_count, target_error, flags) {
assert(indices2 instanceof Uint32Array || indices2 instanceof Int32Array || indices2 instanceof Uint16Array || indices2 instanceof Int16Array);
assert(indices2.length % 3 == 0);
assert(vertex_positions instanceof Float32Array);
assert(vertex_positions.length % vertex_positions_stride == 0);
assert(vertex_positions_stride >= 3);
assert(target_index_count % 3 == 0);
var options = 0;
for (var i = 0; i < (flags ? flags.length : 0); ++i) {
options |= simplifyOptions[flags[i]];
}
var indices32 = indices2.BYTES_PER_ELEMENT == 4 ? indices2 : new Uint32Array(indices2);
var result = simplify(instance.exports.meshopt_simplify, indices32, indices2.length, vertex_positions, vertex_positions.length, vertex_positions_stride * 4, target_index_count, target_error, options);
result[0] = indices2 instanceof Uint32Array ? result[0] : new indices2.constructor(result[0]);
return result;
},
getScale: function(vertex_positions, vertex_positions_stride) {
assert(vertex_positions instanceof Float32Array);
assert(vertex_positions.length % vertex_positions_stride == 0);
return simplifyScale(instance.exports.meshopt_simplifyScale, vertex_positions, vertex_positions.length, vertex_positions_stride * 4);
}
};
}();
// packages/engine/Source/Scene/GltfBufferViewLoader.js
function GltfBufferViewLoader(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const resourceCache = options.resourceCache;
const gltf = options.gltf;
const bufferViewId = options.bufferViewId;
const gltfResource = options.gltfResource;
const baseResource2 = options.baseResource;
const cacheKey = options.cacheKey;
Check_default.typeOf.func("options.resourceCache", resourceCache);
Check_default.typeOf.object("options.gltf", gltf);
Check_default.typeOf.number("options.bufferViewId", bufferViewId);
Check_default.typeOf.object("options.gltfResource", gltfResource);
Check_default.typeOf.object("options.baseResource", baseResource2);
const bufferView = gltf.bufferViews[bufferViewId];
let bufferId = bufferView.buffer;
let byteOffset = bufferView.byteOffset;
let byteLength = bufferView.byteLength;
let hasMeshopt = false;
let meshoptByteStride;
let meshoptCount;
let meshoptMode;
let meshoptFilter;
if (hasExtension_default(bufferView, "EXT_meshopt_compression")) {
const meshopt = bufferView.extensions.EXT_meshopt_compression;
bufferId = meshopt.buffer;
byteOffset = defaultValue_default(meshopt.byteOffset, 0);
byteLength = meshopt.byteLength;
hasMeshopt = true;
meshoptByteStride = meshopt.byteStride;
meshoptCount = meshopt.count;
meshoptMode = meshopt.mode;
meshoptFilter = defaultValue_default(meshopt.filter, "NONE");
}
const buffer = gltf.buffers[bufferId];
this._hasMeshopt = hasMeshopt;
this._meshoptByteStride = meshoptByteStride;
this._meshoptCount = meshoptCount;
this._meshoptMode = meshoptMode;
this._meshoptFilter = meshoptFilter;
this._resourceCache = resourceCache;
this._gltfResource = gltfResource;
this._baseResource = baseResource2;
this._buffer = buffer;
this._bufferId = bufferId;
this._byteOffset = byteOffset;
this._byteLength = byteLength;
this._cacheKey = cacheKey;
this._bufferLoader = void 0;
this._typedArray = void 0;
this._state = ResourceLoaderState_default.UNLOADED;
this._promise = void 0;
}
if (defined_default(Object.create)) {
GltfBufferViewLoader.prototype = Object.create(ResourceLoader_default.prototype);
GltfBufferViewLoader.prototype.constructor = GltfBufferViewLoader;
}
Object.defineProperties(GltfBufferViewLoader.prototype, {
/**
* The cache key of the resource.
*
* @memberof GltfBufferViewLoader.prototype
*
* @type {string}
* @readonly
* @private
*/
cacheKey: {
get: function() {
return this._cacheKey;
}
},
/**
* The typed array containing buffer view data.
*
* @memberof GltfBufferViewLoader.prototype
*
* @type {Uint8Array}
* @readonly
* @private
*/
typedArray: {
get: function() {
return this._typedArray;
}
}
});
async function loadResources(loader) {
try {
const bufferLoader = getBufferLoader(loader);
loader._bufferLoader = bufferLoader;
await bufferLoader.load();
if (loader.isDestroyed()) {
return;
}
const bufferTypedArray = bufferLoader.typedArray;
const bufferViewTypedArray = new Uint8Array(
bufferTypedArray.buffer,
bufferTypedArray.byteOffset + loader._byteOffset,
loader._byteLength
);
loader.unload();
loader._typedArray = bufferViewTypedArray;
if (loader._hasMeshopt) {
const count = loader._meshoptCount;
const byteStride = loader._meshoptByteStride;
const result = new Uint8Array(count * byteStride);
MeshoptDecoder.decodeGltfBuffer(
result,
count,
byteStride,
loader._typedArray,
loader._meshoptMode,
loader._meshoptFilter
);
loader._typedArray = result;
}
loader._state = ResourceLoaderState_default.READY;
return loader;
} catch (error) {
if (loader.isDestroyed()) {
return;
}
loader.unload();
loader._state = ResourceLoaderState_default.FAILED;
const errorMessage = "Failed to load buffer view";
throw loader.getError(errorMessage, error);
}
}
GltfBufferViewLoader.prototype.load = async function() {
if (defined_default(this._promise)) {
return this._promise;
}
this._state = ResourceLoaderState_default.LOADING;
this._promise = loadResources(this);
return this._promise;
};
function getBufferLoader(bufferViewLoader) {
const resourceCache = bufferViewLoader._resourceCache;
const buffer = bufferViewLoader._buffer;
if (defined_default(buffer.uri)) {
const baseResource2 = bufferViewLoader._baseResource;
const resource = baseResource2.getDerivedResource({
url: buffer.uri
});
return resourceCache.getExternalBufferLoader({
resource
});
}
return resourceCache.getEmbeddedBufferLoader({
parentResource: bufferViewLoader._gltfResource,
bufferId: bufferViewLoader._bufferId
});
}
GltfBufferViewLoader.prototype.unload = function() {
if (defined_default(this._bufferLoader) && !this._bufferLoader.isDestroyed()) {
this._resourceCache.unload(this._bufferLoader);
}
this._bufferLoader = void 0;
this._typedArray = void 0;
};
var GltfBufferViewLoader_default = GltfBufferViewLoader;
// packages/engine/Source/Scene/DracoLoader.js
function DracoLoader() {
}
DracoLoader._maxDecodingConcurrency = Math.max(
FeatureDetection_default.hardwareConcurrency - 1,
1
);
DracoLoader._decoderTaskProcessor = void 0;
DracoLoader._taskProcessorReady = false;
DracoLoader._getDecoderTaskProcessor = function() {
if (!defined_default(DracoLoader._decoderTaskProcessor)) {
const processor = new TaskProcessor_default(
"decodeDraco",
DracoLoader._maxDecodingConcurrency
);
processor.initWebAssemblyModule({
modulePath: "ThirdParty/Workers/draco_decoder_nodejs.js",
wasmBinaryFile: "ThirdParty/draco_decoder.wasm"
}).then(function() {
DracoLoader._taskProcessorReady = true;
});
DracoLoader._decoderTaskProcessor = processor;
}
return DracoLoader._decoderTaskProcessor;
};
DracoLoader.decodePointCloud = function(parameters) {
const decoderTaskProcessor = DracoLoader._getDecoderTaskProcessor();
if (!DracoLoader._taskProcessorReady) {
return;
}
return decoderTaskProcessor.scheduleTask(parameters, [
parameters.buffer.buffer
]);
};
DracoLoader.decodeBufferView = function(options) {
const decoderTaskProcessor = DracoLoader._getDecoderTaskProcessor();
if (!DracoLoader._taskProcessorReady) {
return;
}
return decoderTaskProcessor.scheduleTask(options, [options.array.buffer]);
};
var DracoLoader_default = DracoLoader;
// packages/engine/Source/Scene/GltfDracoLoader.js
function GltfDracoLoader(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const resourceCache = options.resourceCache;
const gltf = options.gltf;
const draco = options.draco;
const gltfResource = options.gltfResource;
const baseResource2 = options.baseResource;
const cacheKey = options.cacheKey;
Check_default.typeOf.func("options.resourceCache", resourceCache);
Check_default.typeOf.object("options.gltf", gltf);
Check_default.typeOf.object("options.draco", draco);
Check_default.typeOf.object("options.gltfResource", gltfResource);
Check_default.typeOf.object("options.baseResource", baseResource2);
this._resourceCache = resourceCache;
this._gltfResource = gltfResource;
this._baseResource = baseResource2;
this._gltf = gltf;
this._draco = draco;
this._cacheKey = cacheKey;
this._bufferViewLoader = void 0;
this._bufferViewTypedArray = void 0;
this._decodePromise = void 0;
this._decodedData = void 0;
this._state = ResourceLoaderState_default.UNLOADED;
this._promise = void 0;
this._dracoError = void 0;
}
if (defined_default(Object.create)) {
GltfDracoLoader.prototype = Object.create(ResourceLoader_default.prototype);
GltfDracoLoader.prototype.constructor = GltfDracoLoader;
}
Object.defineProperties(GltfDracoLoader.prototype, {
/**
* The cache key of the resource.
*
* @memberof GltfDracoLoader.prototype
*
* @type {string}
* @readonly
* @private
*/
cacheKey: {
get: function() {
return this._cacheKey;
}
},
/**
* The decoded data.
*
* @memberof GltfDracoLoader.prototype
*
* @type {object}
* @readonly
* @private
*/
decodedData: {
get: function() {
return this._decodedData;
}
}
});
async function loadResources2(loader) {
const resourceCache = loader._resourceCache;
try {
const bufferViewLoader = resourceCache.getBufferViewLoader({
gltf: loader._gltf,
bufferViewId: loader._draco.bufferView,
gltfResource: loader._gltfResource,
baseResource: loader._baseResource
});
loader._bufferViewLoader = bufferViewLoader;
await bufferViewLoader.load();
if (loader.isDestroyed()) {
return;
}
loader._bufferViewTypedArray = bufferViewLoader.typedArray;
loader._state = ResourceLoaderState_default.PROCESSING;
return loader;
} catch (error) {
if (loader.isDestroyed()) {
return;
}
handleError(loader, error);
}
}
GltfDracoLoader.prototype.load = async function() {
if (defined_default(this._promise)) {
return this._promise;
}
this._state = ResourceLoaderState_default.LOADING;
this._promise = loadResources2(this);
return this._promise;
};
function handleError(dracoLoader, error) {
dracoLoader.unload();
dracoLoader._state = ResourceLoaderState_default.FAILED;
const errorMessage = "Failed to load Draco";
throw dracoLoader.getError(errorMessage, error);
}
async function processDecode(loader, decodePromise) {
try {
const results = await decodePromise;
if (loader.isDestroyed()) {
return;
}
loader.unload();
loader._decodedData = {
indices: results.indexArray,
vertexAttributes: results.attributeData
};
loader._state = ResourceLoaderState_default.READY;
return loader._baseResource;
} catch (error) {
if (loader.isDestroyed()) {
return;
}
loader._dracoError = error;
}
}
GltfDracoLoader.prototype.process = function(frameState) {
Check_default.typeOf.object("frameState", frameState);
if (this._state === ResourceLoaderState_default.READY) {
return true;
}
if (this._state !== ResourceLoaderState_default.PROCESSING) {
return false;
}
if (defined_default(this._dracoError)) {
handleError(this, this._dracoError);
}
if (!defined_default(this._bufferViewTypedArray)) {
return false;
}
if (defined_default(this._decodePromise)) {
return false;
}
const draco = this._draco;
const gltf = this._gltf;
const bufferViews = gltf.bufferViews;
const bufferViewId = draco.bufferView;
const bufferView = bufferViews[bufferViewId];
const compressedAttributes = draco.attributes;
const decodeOptions = {
// Need to make a copy of the typed array otherwise the underlying
// ArrayBuffer may be accessed on both the worker and the main thread. This
// leads to errors such as "ArrayBuffer at index 0 is already detached".
// PERFORMANCE_IDEA: Look into SharedArrayBuffer to get around this.
array: new Uint8Array(this._bufferViewTypedArray),
bufferView,
compressedAttributes,
dequantizeInShader: true
};
const decodePromise = DracoLoader_default.decodeBufferView(decodeOptions);
if (!defined_default(decodePromise)) {
return false;
}
this._decodePromise = processDecode(this, decodePromise);
};
GltfDracoLoader.prototype.unload = function() {
if (defined_default(this._bufferViewLoader)) {
this._resourceCache.unload(this._bufferViewLoader);
}
this._bufferViewLoader = void 0;
this._bufferViewTypedArray = void 0;
this._decodedData = void 0;
this._gltf = void 0;
};
var GltfDracoLoader_default = GltfDracoLoader;
// packages/engine/Source/Core/loadImageFromTypedArray.js
function loadImageFromTypedArray(options) {
const uint8Array = options.uint8Array;
const format = options.format;
const request = options.request;
const flipY = defaultValue_default(options.flipY, false);
const skipColorSpaceConversion = defaultValue_default(
options.skipColorSpaceConversion,
false
);
Check_default.typeOf.object("uint8Array", uint8Array);
Check_default.typeOf.string("format", format);
const blob = new Blob([uint8Array], {
type: format
});
let blobUrl;
return Resource_default.supportsImageBitmapOptions().then(function(result) {
if (result) {
return Promise.resolve(
Resource_default.createImageBitmapFromBlob(blob, {
flipY,
premultiplyAlpha: false,
skipColorSpaceConversion
})
);
}
blobUrl = window.URL.createObjectURL(blob);
const resource = new Resource_default({
url: blobUrl,
request
});
return resource.fetchImage({
flipY,
skipColorSpaceConversion
});
}).then(function(result) {
if (defined_default(blobUrl)) {
window.URL.revokeObjectURL(blobUrl);
}
return result;
}).catch(function(error) {
if (defined_default(blobUrl)) {
window.URL.revokeObjectURL(blobUrl);
}
return Promise.reject(error);
});
}
var loadImageFromTypedArray_default = loadImageFromTypedArray;
// packages/engine/Source/Scene/GltfImageLoader.js
function GltfImageLoader(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const resourceCache = options.resourceCache;
const gltf = options.gltf;
const imageId = options.imageId;
const gltfResource = options.gltfResource;
const baseResource2 = options.baseResource;
const cacheKey = options.cacheKey;
Check_default.typeOf.func("options.resourceCache", resourceCache);
Check_default.typeOf.object("options.gltf", gltf);
Check_default.typeOf.number("options.imageId", imageId);
Check_default.typeOf.object("options.gltfResource", gltfResource);
Check_default.typeOf.object("options.baseResource", baseResource2);
const image = gltf.images[imageId];
const bufferViewId = image.bufferView;
const uri = image.uri;
this._resourceCache = resourceCache;
this._gltfResource = gltfResource;
this._baseResource = baseResource2;
this._gltf = gltf;
this._bufferViewId = bufferViewId;
this._uri = uri;
this._cacheKey = cacheKey;
this._bufferViewLoader = void 0;
this._image = void 0;
this._mipLevels = void 0;
this._state = ResourceLoaderState_default.UNLOADED;
this._promise = void 0;
}
if (defined_default(Object.create)) {
GltfImageLoader.prototype = Object.create(ResourceLoader_default.prototype);
GltfImageLoader.prototype.constructor = GltfImageLoader;
}
Object.defineProperties(GltfImageLoader.prototype, {
/**
* The cache key of the resource.
*
* @memberof GltfImageLoader.prototype
*
* @type {string}
* @readonly
* @private
*/
cacheKey: {
get: function() {
return this._cacheKey;
}
},
/**
* The image.
*
* @memberof GltfImageLoader.prototype
*
* @type {Image|ImageBitmap|CompressedTextureBuffer}
* @readonly
* @private
*/
image: {
get: function() {
return this._image;
}
},
/**
* The mip levels. Only defined for KTX2 files containing mip levels.
*
* @memberof GltfImageLoader.prototype
*
* @type {Uint8Array[]}
* @readonly
* @private
*/
mipLevels: {
get: function() {
return this._mipLevels;
}
}
});
GltfImageLoader.prototype.load = function() {
if (defined_default(this._promise)) {
return this._promise;
}
if (defined_default(this._bufferViewId)) {
this._promise = loadFromBufferView(this);
return this._promise;
}
this._promise = loadFromUri(this);
return this._promise;
};
function getImageAndMipLevels(image) {
let mipLevels;
if (Array.isArray(image)) {
mipLevels = image.slice(1, image.length).map(function(mipLevel) {
return mipLevel.bufferView;
});
image = image[0];
}
return {
image,
mipLevels
};
}
async function loadFromBufferView(imageLoader) {
imageLoader._state = ResourceLoaderState_default.LOADING;
const resourceCache = imageLoader._resourceCache;
try {
const bufferViewLoader = resourceCache.getBufferViewLoader({
gltf: imageLoader._gltf,
bufferViewId: imageLoader._bufferViewId,
gltfResource: imageLoader._gltfResource,
baseResource: imageLoader._baseResource
});
imageLoader._bufferViewLoader = bufferViewLoader;
await bufferViewLoader.load();
if (imageLoader.isDestroyed()) {
return;
}
const typedArray = bufferViewLoader.typedArray;
const image = await loadImageFromBufferTypedArray(typedArray);
if (imageLoader.isDestroyed()) {
return;
}
const imageAndMipLevels = getImageAndMipLevels(image);
imageLoader.unload();
imageLoader._image = imageAndMipLevels.image;
imageLoader._mipLevels = imageAndMipLevels.mipLevels;
imageLoader._state = ResourceLoaderState_default.READY;
return imageLoader;
} catch (error) {
if (imageLoader.isDestroyed()) {
return;
}
return handleError2(imageLoader, error, "Failed to load embedded image");
}
}
async function loadFromUri(imageLoader) {
imageLoader._state = ResourceLoaderState_default.LOADING;
const baseResource2 = imageLoader._baseResource;
const uri = imageLoader._uri;
const resource = baseResource2.getDerivedResource({
url: uri
});
try {
const image = await loadImageFromUri(resource);
if (imageLoader.isDestroyed()) {
return;
}
const imageAndMipLevels = getImageAndMipLevels(image);
imageLoader.unload();
imageLoader._image = imageAndMipLevels.image;
imageLoader._mipLevels = imageAndMipLevels.mipLevels;
imageLoader._state = ResourceLoaderState_default.READY;
return imageLoader;
} catch (error) {
if (imageLoader.isDestroyed()) {
return;
}
return handleError2(imageLoader, error, `Failed to load image: ${uri}`);
}
}
function handleError2(imageLoader, error, errorMessage) {
imageLoader.unload();
imageLoader._state = ResourceLoaderState_default.FAILED;
return Promise.reject(imageLoader.getError(errorMessage, error));
}
function getMimeTypeFromTypedArray(typedArray) {
const header = typedArray.subarray(0, 2);
const webpHeaderRIFFChars = typedArray.subarray(0, 4);
const webpHeaderWEBPChars = typedArray.subarray(8, 12);
if (header[0] === 255 && header[1] === 216) {
return "image/jpeg";
} else if (header[0] === 137 && header[1] === 80) {
return "image/png";
} else if (header[0] === 171 && header[1] === 75) {
return "image/ktx2";
} else if (
// See https://developers.google.com/speed/webp/docs/riff_container#webp_file_header
webpHeaderRIFFChars[0] === 82 && webpHeaderRIFFChars[1] === 73 && webpHeaderRIFFChars[2] === 70 && webpHeaderRIFFChars[3] === 70 && webpHeaderWEBPChars[0] === 87 && webpHeaderWEBPChars[1] === 69 && webpHeaderWEBPChars[2] === 66 && webpHeaderWEBPChars[3] === 80
) {
return "image/webp";
}
throw new RuntimeError_default("Image format is not recognized");
}
async function loadImageFromBufferTypedArray(typedArray) {
const mimeType = getMimeTypeFromTypedArray(typedArray);
if (mimeType === "image/ktx2") {
const ktxBuffer = new Uint8Array(typedArray);
return loadKTX2_default(ktxBuffer);
}
return GltfImageLoader._loadImageFromTypedArray({
uint8Array: typedArray,
format: mimeType,
flipY: false,
skipColorSpaceConversion: true
});
}
var ktx2Regex2 = /(^data:image\/ktx2)|(\.ktx2$)/i;
function loadImageFromUri(resource) {
const uri = resource.getUrlComponent(false, true);
if (ktx2Regex2.test(uri)) {
return loadKTX2_default(resource);
}
return resource.fetchImage({
skipColorSpaceConversion: true,
preferImageBitmap: true
});
}
GltfImageLoader.prototype.unload = function() {
if (defined_default(this._bufferViewLoader) && !this._bufferViewLoader.isDestroyed()) {
this._resourceCache.unload(this._bufferViewLoader);
}
this._bufferViewLoader = void 0;
this._uri = void 0;
this._image = void 0;
this._mipLevels = void 0;
this._gltf = void 0;
};
GltfImageLoader._loadImageFromTypedArray = loadImageFromTypedArray_default;
var GltfImageLoader_default = GltfImageLoader;
// packages/engine/Source/Scene/JobType.js
var JobType = {
TEXTURE: 0,
PROGRAM: 1,
BUFFER: 2,
NUMBER_OF_JOB_TYPES: 3
};
var JobType_default = Object.freeze(JobType);
// packages/engine/Source/Scene/GltfIndexBufferLoader.js
function GltfIndexBufferLoader(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const resourceCache = options.resourceCache;
const gltf = options.gltf;
const accessorId = options.accessorId;
const gltfResource = options.gltfResource;
const baseResource2 = options.baseResource;
const draco = options.draco;
const cacheKey = options.cacheKey;
const asynchronous = defaultValue_default(options.asynchronous, true);
const loadBuffer = defaultValue_default(options.loadBuffer, false);
const loadTypedArray = defaultValue_default(options.loadTypedArray, false);
Check_default.typeOf.func("options.resourceCache", resourceCache);
Check_default.typeOf.object("options.gltf", gltf);
Check_default.typeOf.number("options.accessorId", accessorId);
Check_default.typeOf.object("options.gltfResource", gltfResource);
Check_default.typeOf.object("options.baseResource", baseResource2);
if (!loadBuffer && !loadTypedArray) {
throw new DeveloperError_default(
"At least one of loadBuffer and loadTypedArray must be true."
);
}
const indexDatatype = gltf.accessors[accessorId].componentType;
this._resourceCache = resourceCache;
this._gltfResource = gltfResource;
this._baseResource = baseResource2;
this._gltf = gltf;
this._accessorId = accessorId;
this._indexDatatype = indexDatatype;
this._draco = draco;
this._cacheKey = cacheKey;
this._asynchronous = asynchronous;
this._loadBuffer = loadBuffer;
this._loadTypedArray = loadTypedArray;
this._bufferViewLoader = void 0;
this._dracoLoader = void 0;
this._typedArray = void 0;
this._buffer = void 0;
this._state = ResourceLoaderState_default.UNLOADED;
this._promise = void 0;
}
if (defined_default(Object.create)) {
GltfIndexBufferLoader.prototype = Object.create(ResourceLoader_default.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 loadBuffer
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 loadTypedArray
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;
}
}
});
var scratchIndexBufferJob = new CreateIndexBufferJob();
GltfIndexBufferLoader.prototype.load = async function() {
if (defined_default(this._promise)) {
return this._promise;
}
if (defined_default(this._draco)) {
this._promise = loadFromDraco(this);
return this._promise;
}
this._promise = loadFromBufferView2(this);
return this._promise;
};
async function loadFromDraco(indexBufferLoader) {
indexBufferLoader._state = ResourceLoaderState_default.LOADING;
const resourceCache = indexBufferLoader._resourceCache;
try {
const dracoLoader = resourceCache.getDracoLoader({
gltf: indexBufferLoader._gltf,
draco: indexBufferLoader._draco,
gltfResource: indexBufferLoader._gltfResource,
baseResource: indexBufferLoader._baseResource
});
indexBufferLoader._dracoLoader = dracoLoader;
await dracoLoader.load();
if (indexBufferLoader.isDestroyed()) {
return;
}
indexBufferLoader._state = ResourceLoaderState_default.LOADED;
return indexBufferLoader;
} catch (error) {
if (indexBufferLoader.isDestroyed()) {
return;
}
handleError3(indexBufferLoader, error);
}
}
async function loadFromBufferView2(indexBufferLoader) {
const gltf = indexBufferLoader._gltf;
const accessorId = indexBufferLoader._accessorId;
const accessor = gltf.accessors[accessorId];
const bufferViewId = accessor.bufferView;
indexBufferLoader._state = ResourceLoaderState_default.LOADING;
const resourceCache = indexBufferLoader._resourceCache;
try {
const bufferViewLoader = resourceCache.getBufferViewLoader({
gltf,
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_default.PROCESSING;
return indexBufferLoader;
} catch (error) {
if (indexBufferLoader.isDestroyed()) {
return;
}
handleError3(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_default.getSizeInBytes(indexDatatype);
let arrayBuffer = bufferViewTypedArray.buffer;
let byteOffset = bufferViewTypedArray.byteOffset + accessor.byteOffset;
if (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_default(
"index-buffer-unaligned",
`The index array is not aligned to a ${indexSize}-byte boundary.`
);
}
let typedArray;
if (indexDatatype === IndexDatatype_default.UNSIGNED_BYTE) {
typedArray = new Uint8Array(arrayBuffer, byteOffset, count);
} else if (indexDatatype === IndexDatatype_default.UNSIGNED_SHORT) {
typedArray = new Uint16Array(arrayBuffer, byteOffset, count);
} else if (indexDatatype === IndexDatatype_default.UNSIGNED_INT) {
typedArray = new Uint32Array(arrayBuffer, byteOffset, count);
}
return typedArray;
}
function handleError3(indexBufferLoader, error) {
indexBufferLoader.unload();
indexBufferLoader._state = ResourceLoaderState_default.FAILED;
const errorMessage = "Failed to load index buffer";
throw indexBufferLoader.getError(errorMessage, error);
}
function CreateIndexBufferJob() {
this.typedArray = void 0;
this.indexDatatype = void 0;
this.context = void 0;
this.buffer = void 0;
}
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_default.createIndexBuffer({
typedArray,
context,
usage: BufferUsage_default.STATIC_DRAW,
indexDatatype
});
buffer.vertexArrayDestroyable = false;
return buffer;
}
GltfIndexBufferLoader.prototype.process = function(frameState) {
Check_default.typeOf.object("frameState", frameState);
if (this._state === ResourceLoaderState_default.READY) {
return true;
}
if (this._state !== ResourceLoaderState_default.LOADED && this._state !== ResourceLoaderState_default.PROCESSING) {
return false;
}
let typedArray = this._typedArray;
let indexDatatype = this._indexDatatype;
if (defined_default(this._dracoLoader)) {
try {
const ready = this._dracoLoader.process(frameState);
if (ready) {
const dracoLoader = this._dracoLoader;
typedArray = dracoLoader.decodedData.indices.typedArray;
this._typedArray = typedArray;
indexDatatype = ComponentDatatype_default.fromTypedArray(typedArray);
this._indexDatatype = indexDatatype;
}
} catch (error) {
handleError3(this, error);
}
}
if (!defined_default(typedArray)) {
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_default.BUFFER)) {
return false;
}
buffer = indexBufferJob.buffer;
} else if (this._loadBuffer) {
buffer = createIndexBuffer(typedArray, indexDatatype, frameState.context);
}
this.unload();
this._buffer = buffer;
this._typedArray = this._loadTypedArray ? typedArray : void 0;
this._state = ResourceLoaderState_default.READY;
this._resourceCache.statistics.addGeometryLoader(this);
return true;
};
GltfIndexBufferLoader.prototype.unload = function() {
if (defined_default(this._buffer)) {
this._buffer.destroy();
}
const resourceCache = this._resourceCache;
if (defined_default(this._bufferViewLoader) && !this._bufferViewLoader.isDestroyed()) {
resourceCache.unload(this._bufferViewLoader);
}
if (defined_default(this._dracoLoader)) {
resourceCache.unload(this._dracoLoader);
}
this._bufferViewLoader = void 0;
this._dracoLoader = void 0;
this._typedArray = void 0;
this._buffer = void 0;
this._gltf = void 0;
};
var GltfIndexBufferLoader_default = GltfIndexBufferLoader;
// packages/engine/Source/Scene/GltfPipeline/addToArray.js
function addToArray(array, element, checkDuplicates) {
checkDuplicates = defaultValue_default(checkDuplicates, false);
if (checkDuplicates) {
const index = array.indexOf(element);
if (index > -1) {
return index;
}
}
array.push(element);
return array.length - 1;
}
var addToArray_default = addToArray;
// packages/engine/Source/Scene/GltfPipeline/usesExtension.js
function usesExtension(gltf, extension) {
return defined_default(gltf.extensionsUsed) && gltf.extensionsUsed.indexOf(extension) >= 0;
}
var usesExtension_default = usesExtension;
// packages/engine/Source/Scene/GltfPipeline/ForEach.js
function ForEach() {
}
ForEach.objectLegacy = function(objects, handler) {
if (defined_default(objects)) {
for (const objectId in objects) {
if (Object.prototype.hasOwnProperty.call(objects, objectId)) {
const object2 = objects[objectId];
const value = handler(object2, objectId);
if (defined_default(value)) {
return value;
}
}
}
}
};
ForEach.object = function(arrayOfObjects, handler) {
if (defined_default(arrayOfObjects)) {
const length3 = arrayOfObjects.length;
for (let i = 0; i < length3; i++) {
const object2 = arrayOfObjects[i];
const value = handler(object2, i);
if (defined_default(value)) {
return value;
}
}
}
};
ForEach.topLevel = function(gltf, name, handler) {
const gltfProperty = gltf[name];
if (defined_default(gltfProperty) && !Array.isArray(gltfProperty)) {
return ForEach.objectLegacy(gltfProperty, handler);
}
return ForEach.object(gltfProperty, handler);
};
ForEach.accessor = function(gltf, handler) {
return ForEach.topLevel(gltf, "accessors", handler);
};
ForEach.accessorWithSemantic = function(gltf, semantic, handler) {
const visited = {};
return ForEach.mesh(gltf, function(mesh) {
return ForEach.meshPrimitive(mesh, function(primitive) {
const valueForEach = ForEach.meshPrimitiveAttribute(
primitive,
function(accessorId, attributeSemantic) {
if (attributeSemantic.indexOf(semantic) === 0 && !defined_default(visited[accessorId])) {
visited[accessorId] = true;
const value = handler(accessorId);
if (defined_default(value)) {
return value;
}
}
}
);
if (defined_default(valueForEach)) {
return valueForEach;
}
return ForEach.meshPrimitiveTarget(primitive, function(target) {
return ForEach.meshPrimitiveTargetAttribute(
target,
function(accessorId, attributeSemantic) {
if (attributeSemantic.indexOf(semantic) === 0 && !defined_default(visited[accessorId])) {
visited[accessorId] = true;
const value = handler(accessorId);
if (defined_default(value)) {
return value;
}
}
}
);
});
});
});
};
ForEach.accessorContainingVertexAttributeData = function(gltf, handler) {
const visited = {};
return ForEach.mesh(gltf, function(mesh) {
return ForEach.meshPrimitive(mesh, function(primitive) {
const valueForEach = ForEach.meshPrimitiveAttribute(
primitive,
function(accessorId) {
if (!defined_default(visited[accessorId])) {
visited[accessorId] = true;
const value = handler(accessorId);
if (defined_default(value)) {
return value;
}
}
}
);
if (defined_default(valueForEach)) {
return valueForEach;
}
return ForEach.meshPrimitiveTarget(primitive, function(target) {
return ForEach.meshPrimitiveTargetAttribute(
target,
function(accessorId) {
if (!defined_default(visited[accessorId])) {
visited[accessorId] = true;
const value = handler(accessorId);
if (defined_default(value)) {
return value;
}
}
}
);
});
});
});
};
ForEach.accessorContainingIndexData = function(gltf, handler) {
const visited = {};
return ForEach.mesh(gltf, function(mesh) {
return ForEach.meshPrimitive(mesh, function(primitive) {
const indices2 = primitive.indices;
if (defined_default(indices2) && !defined_default(visited[indices2])) {
visited[indices2] = true;
const value = handler(indices2);
if (defined_default(value)) {
return value;
}
}
});
});
};
ForEach.animation = function(gltf, handler) {
return ForEach.topLevel(gltf, "animations", handler);
};
ForEach.animationChannel = function(animation, handler) {
const channels = animation.channels;
return ForEach.object(channels, handler);
};
ForEach.animationSampler = function(animation, handler) {
const samplers = animation.samplers;
return ForEach.object(samplers, handler);
};
ForEach.buffer = function(gltf, handler) {
return ForEach.topLevel(gltf, "buffers", handler);
};
ForEach.bufferView = function(gltf, handler) {
return ForEach.topLevel(gltf, "bufferViews", handler);
};
ForEach.camera = function(gltf, handler) {
return ForEach.topLevel(gltf, "cameras", handler);
};
ForEach.image = function(gltf, handler) {
return ForEach.topLevel(gltf, "images", handler);
};
ForEach.material = function(gltf, handler) {
return ForEach.topLevel(gltf, "materials", handler);
};
ForEach.materialValue = function(material, handler) {
let values = material.values;
if (defined_default(material.extensions) && defined_default(material.extensions.KHR_techniques_webgl)) {
values = material.extensions.KHR_techniques_webgl.values;
}
for (const name in values) {
if (Object.prototype.hasOwnProperty.call(values, name)) {
const value = handler(values[name], name);
if (defined_default(value)) {
return value;
}
}
}
};
ForEach.mesh = function(gltf, handler) {
return ForEach.topLevel(gltf, "meshes", handler);
};
ForEach.meshPrimitive = function(mesh, handler) {
const primitives = mesh.primitives;
if (defined_default(primitives)) {
const primitivesLength = primitives.length;
for (let i = 0; i < primitivesLength; i++) {
const primitive = primitives[i];
const value = handler(primitive, i);
if (defined_default(value)) {
return value;
}
}
}
};
ForEach.meshPrimitiveAttribute = function(primitive, handler) {
const attributes = primitive.attributes;
for (const semantic in attributes) {
if (Object.prototype.hasOwnProperty.call(attributes, semantic)) {
const value = handler(attributes[semantic], semantic);
if (defined_default(value)) {
return value;
}
}
}
};
ForEach.meshPrimitiveTarget = function(primitive, handler) {
const targets = primitive.targets;
if (defined_default(targets)) {
const length3 = targets.length;
for (let i = 0; i < length3; ++i) {
const value = handler(targets[i], i);
if (defined_default(value)) {
return value;
}
}
}
};
ForEach.meshPrimitiveTargetAttribute = function(target, handler) {
for (const semantic in target) {
if (Object.prototype.hasOwnProperty.call(target, semantic)) {
const accessorId = target[semantic];
const value = handler(accessorId, semantic);
if (defined_default(value)) {
return value;
}
}
}
};
ForEach.node = function(gltf, handler) {
return ForEach.topLevel(gltf, "nodes", handler);
};
ForEach.nodeInTree = function(gltf, nodeIds, handler) {
const nodes = gltf.nodes;
if (defined_default(nodes)) {
const length3 = nodeIds.length;
for (let i = 0; i < length3; i++) {
const nodeId = nodeIds[i];
const node = nodes[nodeId];
if (defined_default(node)) {
let value = handler(node, nodeId);
if (defined_default(value)) {
return value;
}
const children = node.children;
if (defined_default(children)) {
value = ForEach.nodeInTree(gltf, children, handler);
if (defined_default(value)) {
return value;
}
}
}
}
}
};
ForEach.nodeInScene = function(gltf, scene, handler) {
const sceneNodeIds = scene.nodes;
if (defined_default(sceneNodeIds)) {
return ForEach.nodeInTree(gltf, sceneNodeIds, handler);
}
};
ForEach.program = function(gltf, handler) {
if (usesExtension_default(gltf, "KHR_techniques_webgl")) {
return ForEach.object(
gltf.extensions.KHR_techniques_webgl.programs,
handler
);
}
return ForEach.topLevel(gltf, "programs", handler);
};
ForEach.sampler = function(gltf, handler) {
return ForEach.topLevel(gltf, "samplers", handler);
};
ForEach.scene = function(gltf, handler) {
return ForEach.topLevel(gltf, "scenes", handler);
};
ForEach.shader = function(gltf, handler) {
if (usesExtension_default(gltf, "KHR_techniques_webgl")) {
return ForEach.object(
gltf.extensions.KHR_techniques_webgl.shaders,
handler
);
}
return ForEach.topLevel(gltf, "shaders", handler);
};
ForEach.skin = function(gltf, handler) {
return ForEach.topLevel(gltf, "skins", handler);
};
ForEach.skinJoint = function(skin, handler) {
const joints = skin.joints;
if (defined_default(joints)) {
const jointsLength = joints.length;
for (let i = 0; i < jointsLength; i++) {
const joint = joints[i];
const value = handler(joint);
if (defined_default(value)) {
return value;
}
}
}
};
ForEach.techniqueAttribute = function(technique, handler) {
const attributes = technique.attributes;
for (const attributeName in attributes) {
if (Object.prototype.hasOwnProperty.call(attributes, attributeName)) {
const value = handler(attributes[attributeName], attributeName);
if (defined_default(value)) {
return value;
}
}
}
};
ForEach.techniqueUniform = function(technique, handler) {
const uniforms = technique.uniforms;
for (const uniformName in uniforms) {
if (Object.prototype.hasOwnProperty.call(uniforms, uniformName)) {
const value = handler(uniforms[uniformName], uniformName);
if (defined_default(value)) {
return value;
}
}
}
};
ForEach.techniqueParameter = function(technique, handler) {
const parameters = technique.parameters;
for (const parameterName in parameters) {
if (Object.prototype.hasOwnProperty.call(parameters, parameterName)) {
const value = handler(parameters[parameterName], parameterName);
if (defined_default(value)) {
return value;
}
}
}
};
ForEach.technique = function(gltf, handler) {
if (usesExtension_default(gltf, "KHR_techniques_webgl")) {
return ForEach.object(
gltf.extensions.KHR_techniques_webgl.techniques,
handler
);
}
return ForEach.topLevel(gltf, "techniques", handler);
};
ForEach.texture = function(gltf, handler) {
return ForEach.topLevel(gltf, "textures", handler);
};
var ForEach_default = ForEach;
// packages/engine/Source/Scene/GltfPipeline/numberOfComponentsForType.js
function numberOfComponentsForType(type) {
switch (type) {
case "SCALAR":
return 1;
case "VEC2":
return 2;
case "VEC3":
return 3;
case "VEC4":
case "MAT2":
return 4;
case "MAT3":
return 9;
case "MAT4":
return 16;
}
}
var numberOfComponentsForType_default = numberOfComponentsForType;
// packages/engine/Source/Scene/GltfPipeline/getAccessorByteStride.js
function getAccessorByteStride(gltf, accessor) {
const bufferViewId = accessor.bufferView;
if (defined_default(bufferViewId)) {
const bufferView = gltf.bufferViews[bufferViewId];
if (defined_default(bufferView.byteStride) && bufferView.byteStride > 0) {
return bufferView.byteStride;
}
}
return ComponentDatatype_default.getSizeInBytes(accessor.componentType) * numberOfComponentsForType_default(accessor.type);
}
var getAccessorByteStride_default = getAccessorByteStride;
// packages/engine/Source/Scene/GltfPipeline/addDefaults.js
function addDefaults(gltf) {
ForEach_default.accessor(gltf, function(accessor) {
if (defined_default(accessor.bufferView)) {
accessor.byteOffset = defaultValue_default(accessor.byteOffset, 0);
}
});
ForEach_default.bufferView(gltf, function(bufferView) {
if (defined_default(bufferView.buffer)) {
bufferView.byteOffset = defaultValue_default(bufferView.byteOffset, 0);
}
});
ForEach_default.mesh(gltf, function(mesh) {
ForEach_default.meshPrimitive(mesh, function(primitive) {
primitive.mode = defaultValue_default(primitive.mode, WebGLConstants_default.TRIANGLES);
if (!defined_default(primitive.material)) {
if (!defined_default(gltf.materials)) {
gltf.materials = [];
}
const defaultMaterial4 = {
name: "default"
};
primitive.material = addToArray_default(gltf.materials, defaultMaterial4);
}
});
});
ForEach_default.accessorContainingVertexAttributeData(gltf, function(accessorId) {
const accessor = gltf.accessors[accessorId];
const bufferViewId = accessor.bufferView;
accessor.normalized = defaultValue_default(accessor.normalized, false);
if (defined_default(bufferViewId)) {
const bufferView = gltf.bufferViews[bufferViewId];
bufferView.byteStride = getAccessorByteStride_default(gltf, accessor);
bufferView.target = WebGLConstants_default.ARRAY_BUFFER;
}
});
ForEach_default.accessorContainingIndexData(gltf, function(accessorId) {
const accessor = gltf.accessors[accessorId];
const bufferViewId = accessor.bufferView;
if (defined_default(bufferViewId)) {
const bufferView = gltf.bufferViews[bufferViewId];
bufferView.target = WebGLConstants_default.ELEMENT_ARRAY_BUFFER;
}
});
ForEach_default.material(gltf, function(material) {
const extensions = defaultValue_default(
material.extensions,
defaultValue_default.EMPTY_OBJECT
);
const materialsCommon = extensions.KHR_materials_common;
if (defined_default(materialsCommon)) {
const technique = materialsCommon.technique;
const values = defined_default(materialsCommon.values) ? materialsCommon.values : {};
materialsCommon.values = values;
values.ambient = defined_default(values.ambient) ? values.ambient : [0, 0, 0, 1];
values.emission = defined_default(values.emission) ? values.emission : [0, 0, 0, 1];
values.transparency = defaultValue_default(values.transparency, 1);
if (technique !== "CONSTANT") {
values.diffuse = defined_default(values.diffuse) ? values.diffuse : [0, 0, 0, 1];
if (technique !== "LAMBERT") {
values.specular = defined_default(values.specular) ? values.specular : [0, 0, 0, 1];
values.shininess = defaultValue_default(values.shininess, 0);
}
}
materialsCommon.transparent = defaultValue_default(
materialsCommon.transparent,
false
);
materialsCommon.doubleSided = defaultValue_default(
materialsCommon.doubleSided,
false
);
return;
}
material.emissiveFactor = defaultValue_default(
material.emissiveFactor,
[0, 0, 0]
);
material.alphaMode = defaultValue_default(material.alphaMode, "OPAQUE");
material.doubleSided = defaultValue_default(material.doubleSided, false);
if (material.alphaMode === "MASK") {
material.alphaCutoff = defaultValue_default(material.alphaCutoff, 0.5);
}
const techniquesExtension = extensions.KHR_techniques_webgl;
if (defined_default(techniquesExtension)) {
ForEach_default.materialValue(material, function(materialValue) {
if (defined_default(materialValue.index)) {
addTextureDefaults(materialValue);
}
});
}
addTextureDefaults(material.emissiveTexture);
addTextureDefaults(material.normalTexture);
addTextureDefaults(material.occlusionTexture);
const pbrMetallicRoughness = material.pbrMetallicRoughness;
if (defined_default(pbrMetallicRoughness)) {
pbrMetallicRoughness.baseColorFactor = defaultValue_default(
pbrMetallicRoughness.baseColorFactor,
[1, 1, 1, 1]
);
pbrMetallicRoughness.metallicFactor = defaultValue_default(
pbrMetallicRoughness.metallicFactor,
1
);
pbrMetallicRoughness.roughnessFactor = defaultValue_default(
pbrMetallicRoughness.roughnessFactor,
1
);
addTextureDefaults(pbrMetallicRoughness.baseColorTexture);
addTextureDefaults(pbrMetallicRoughness.metallicRoughnessTexture);
}
const pbrSpecularGlossiness = extensions.KHR_materials_pbrSpecularGlossiness;
if (defined_default(pbrSpecularGlossiness)) {
pbrSpecularGlossiness.diffuseFactor = defaultValue_default(
pbrSpecularGlossiness.diffuseFactor,
[1, 1, 1, 1]
);
pbrSpecularGlossiness.specularFactor = defaultValue_default(
pbrSpecularGlossiness.specularFactor,
[1, 1, 1]
);
pbrSpecularGlossiness.glossinessFactor = defaultValue_default(
pbrSpecularGlossiness.glossinessFactor,
1
);
addTextureDefaults(pbrSpecularGlossiness.specularGlossinessTexture);
}
});
ForEach_default.animation(gltf, function(animation) {
ForEach_default.animationSampler(animation, function(sampler) {
sampler.interpolation = defaultValue_default(sampler.interpolation, "LINEAR");
});
});
const animatedNodes = getAnimatedNodes(gltf);
ForEach_default.node(gltf, function(node, id) {
const animated = defined_default(animatedNodes[id]);
if (animated || defined_default(node.translation) || defined_default(node.rotation) || defined_default(node.scale)) {
node.translation = defaultValue_default(node.translation, [0, 0, 0]);
node.rotation = defaultValue_default(node.rotation, [0, 0, 0, 1]);
node.scale = defaultValue_default(node.scale, [1, 1, 1]);
} else {
node.matrix = defaultValue_default(
node.matrix,
[
1,
0,
0,
0,
0,
1,
0,
0,
0,
0,
1,
0,
0,
0,
0,
1
]
);
}
});
ForEach_default.sampler(gltf, function(sampler) {
sampler.wrapS = defaultValue_default(sampler.wrapS, WebGLConstants_default.REPEAT);
sampler.wrapT = defaultValue_default(sampler.wrapT, WebGLConstants_default.REPEAT);
});
if (defined_default(gltf.scenes) && !defined_default(gltf.scene)) {
gltf.scene = 0;
}
return gltf;
}
function getAnimatedNodes(gltf) {
const nodes = {};
ForEach_default.animation(gltf, function(animation) {
ForEach_default.animationChannel(animation, function(channel) {
const target = channel.target;
const nodeId = target.node;
const path = target.path;
if (path === "translation" || path === "rotation" || path === "scale") {
nodes[nodeId] = true;
}
});
});
return nodes;
}
function addTextureDefaults(texture) {
if (defined_default(texture)) {
texture.texCoord = defaultValue_default(texture.texCoord, 0);
}
}
var addDefaults_default = addDefaults;
// packages/engine/Source/Scene/GltfPipeline/addPipelineExtras.js
function addPipelineExtras(gltf) {
ForEach_default.shader(gltf, function(shader) {
addExtras(shader);
});
ForEach_default.buffer(gltf, function(buffer) {
addExtras(buffer);
});
ForEach_default.image(gltf, function(image) {
addExtras(image);
});
addExtras(gltf);
return gltf;
}
function addExtras(object2) {
object2.extras = defined_default(object2.extras) ? object2.extras : {};
object2.extras._pipeline = defined_default(object2.extras._pipeline) ? object2.extras._pipeline : {};
}
var addPipelineExtras_default = addPipelineExtras;
// packages/engine/Source/Scene/GltfPipeline/removeExtensionsRequired.js
function removeExtensionsRequired(gltf, extension) {
const extensionsRequired = gltf.extensionsRequired;
if (defined_default(extensionsRequired)) {
const index = extensionsRequired.indexOf(extension);
if (index >= 0) {
extensionsRequired.splice(index, 1);
}
if (extensionsRequired.length === 0) {
delete gltf.extensionsRequired;
}
}
}
var removeExtensionsRequired_default = removeExtensionsRequired;
// packages/engine/Source/Scene/GltfPipeline/removeExtensionsUsed.js
function removeExtensionsUsed(gltf, extension) {
const extensionsUsed = gltf.extensionsUsed;
if (defined_default(extensionsUsed)) {
const index = extensionsUsed.indexOf(extension);
if (index >= 0) {
extensionsUsed.splice(index, 1);
}
removeExtensionsRequired_default(gltf, extension);
if (extensionsUsed.length === 0) {
delete gltf.extensionsUsed;
}
}
}
var removeExtensionsUsed_default = removeExtensionsUsed;
// packages/engine/Source/Scene/GltfPipeline/parseGlb.js
var sizeOfUint323 = 4;
function parseGlb(glb) {
const magic = getMagic_default(glb);
if (magic !== "glTF") {
throw new RuntimeError_default("File is not valid binary glTF");
}
const header = readHeader(glb, 0, 5);
const version2 = header[1];
if (version2 !== 1 && version2 !== 2) {
throw new RuntimeError_default("Binary glTF version is not 1 or 2");
}
if (version2 === 1) {
return parseGlbVersion1(glb, header);
}
return parseGlbVersion2(glb, header);
}
function readHeader(glb, byteOffset, count) {
const dataView = new DataView(glb.buffer);
const header = new Array(count);
for (let i = 0; i < count; ++i) {
header[i] = dataView.getUint32(
glb.byteOffset + byteOffset + i * sizeOfUint323,
true
);
}
return header;
}
function parseGlbVersion1(glb, header) {
const length3 = header[2];
const contentLength = header[3];
const contentFormat = header[4];
if (contentFormat !== 0) {
throw new RuntimeError_default("Binary glTF scene format is not JSON");
}
const jsonStart = 20;
const binaryStart = jsonStart + contentLength;
const contentString = getStringFromTypedArray_default(glb, jsonStart, contentLength);
const gltf = JSON.parse(contentString);
addPipelineExtras_default(gltf);
const binaryBuffer = glb.subarray(binaryStart, length3);
const buffers = gltf.buffers;
if (defined_default(buffers) && Object.keys(buffers).length > 0) {
const binaryGltfBuffer = defaultValue_default(
buffers.binary_glTF,
buffers.KHR_binary_glTF
);
if (defined_default(binaryGltfBuffer)) {
binaryGltfBuffer.extras._pipeline.source = binaryBuffer;
delete binaryGltfBuffer.uri;
}
}
removeExtensionsUsed_default(gltf, "KHR_binary_glTF");
return gltf;
}
function parseGlbVersion2(glb, header) {
const length3 = header[2];
let byteOffset = 12;
let gltf;
let binaryBuffer;
while (byteOffset < length3) {
const chunkHeader = readHeader(glb, byteOffset, 2);
const chunkLength = chunkHeader[0];
const chunkType = chunkHeader[1];
byteOffset += 8;
const chunkBuffer = glb.subarray(byteOffset, byteOffset + chunkLength);
byteOffset += chunkLength;
if (chunkType === 1313821514) {
const jsonString = getStringFromTypedArray_default(chunkBuffer);
gltf = JSON.parse(jsonString);
addPipelineExtras_default(gltf);
} else if (chunkType === 5130562) {
binaryBuffer = chunkBuffer;
}
}
if (defined_default(gltf) && defined_default(binaryBuffer)) {
const buffers = gltf.buffers;
if (defined_default(buffers) && buffers.length > 0) {
const buffer = buffers[0];
buffer.extras._pipeline.source = binaryBuffer;
}
}
return gltf;
}
var parseGlb_default = parseGlb;
// packages/engine/Source/Scene/GltfPipeline/removePipelineExtras.js
function removePipelineExtras(gltf) {
ForEach_default.shader(gltf, function(shader) {
removeExtras(shader);
});
ForEach_default.buffer(gltf, function(buffer) {
removeExtras(buffer);
});
ForEach_default.image(gltf, function(image) {
removeExtras(image);
});
removeExtras(gltf);
return gltf;
}
function removeExtras(object2) {
if (!defined_default(object2.extras)) {
return;
}
if (defined_default(object2.extras._pipeline)) {
delete object2.extras._pipeline;
}
if (Object.keys(object2.extras).length === 0) {
delete object2.extras;
}
}
var removePipelineExtras_default = removePipelineExtras;
// packages/engine/Source/Scene/GltfPipeline/addExtensionsUsed.js
function addExtensionsUsed(gltf, extension) {
let extensionsUsed = gltf.extensionsUsed;
if (!defined_default(extensionsUsed)) {
extensionsUsed = [];
gltf.extensionsUsed = extensionsUsed;
}
addToArray_default(extensionsUsed, extension, true);
}
var addExtensionsUsed_default = addExtensionsUsed;
// packages/engine/Source/Scene/GltfPipeline/getComponentReader.js
function getComponentReader(componentType) {
switch (componentType) {
case ComponentDatatype_default.BYTE:
return function(dataView, byteOffset, numberOfComponents, componentTypeByteLength, result) {
for (let i = 0; i < numberOfComponents; ++i) {
result[i] = dataView.getInt8(
byteOffset + i * componentTypeByteLength
);
}
};
case ComponentDatatype_default.UNSIGNED_BYTE:
return function(dataView, byteOffset, numberOfComponents, componentTypeByteLength, result) {
for (let i = 0; i < numberOfComponents; ++i) {
result[i] = dataView.getUint8(
byteOffset + i * componentTypeByteLength
);
}
};
case ComponentDatatype_default.SHORT:
return function(dataView, byteOffset, numberOfComponents, componentTypeByteLength, result) {
for (let i = 0; i < numberOfComponents; ++i) {
result[i] = dataView.getInt16(
byteOffset + i * componentTypeByteLength,
true
);
}
};
case ComponentDatatype_default.UNSIGNED_SHORT:
return function(dataView, byteOffset, numberOfComponents, componentTypeByteLength, result) {
for (let i = 0; i < numberOfComponents; ++i) {
result[i] = dataView.getUint16(
byteOffset + i * componentTypeByteLength,
true
);
}
};
case ComponentDatatype_default.INT:
return function(dataView, byteOffset, numberOfComponents, componentTypeByteLength, result) {
for (let i = 0; i < numberOfComponents; ++i) {
result[i] = dataView.getInt32(
byteOffset + i * componentTypeByteLength,
true
);
}
};
case ComponentDatatype_default.UNSIGNED_INT:
return function(dataView, byteOffset, numberOfComponents, componentTypeByteLength, result) {
for (let i = 0; i < numberOfComponents; ++i) {
result[i] = dataView.getUint32(
byteOffset + i * componentTypeByteLength,
true
);
}
};
case ComponentDatatype_default.FLOAT:
return function(dataView, byteOffset, numberOfComponents, componentTypeByteLength, result) {
for (let i = 0; i < numberOfComponents; ++i) {
result[i] = dataView.getFloat32(
byteOffset + i * componentTypeByteLength,
true
);
}
};
case ComponentDatatype_default.DOUBLE:
return function(dataView, byteOffset, numberOfComponents, componentTypeByteLength, result) {
for (let i = 0; i < numberOfComponents; ++i) {
result[i] = dataView.getFloat64(
byteOffset + i * componentTypeByteLength,
true
);
}
};
}
}
var getComponentReader_default = getComponentReader;
// packages/engine/Source/Scene/GltfPipeline/findAccessorMinMax.js
function findAccessorMinMax(gltf, accessor) {
const bufferViews = gltf.bufferViews;
const buffers = gltf.buffers;
const bufferViewId = accessor.bufferView;
const numberOfComponents = numberOfComponentsForType_default(accessor.type);
if (!defined_default(accessor.bufferView)) {
return {
min: new Array(numberOfComponents).fill(0),
max: new Array(numberOfComponents).fill(0)
};
}
const min3 = new Array(numberOfComponents).fill(Number.POSITIVE_INFINITY);
const max3 = new Array(numberOfComponents).fill(Number.NEGATIVE_INFINITY);
const bufferView = bufferViews[bufferViewId];
const bufferId = bufferView.buffer;
const buffer = buffers[bufferId];
const source = buffer.extras._pipeline.source;
const count = accessor.count;
const byteStride = getAccessorByteStride_default(gltf, accessor);
let byteOffset = accessor.byteOffset + bufferView.byteOffset + source.byteOffset;
const componentType = accessor.componentType;
const componentTypeByteLength = ComponentDatatype_default.getSizeInBytes(componentType);
const dataView = new DataView(source.buffer);
const components = new Array(numberOfComponents);
const componentReader = getComponentReader_default(componentType);
for (let i = 0; i < count; i++) {
componentReader(
dataView,
byteOffset,
numberOfComponents,
componentTypeByteLength,
components
);
for (let j = 0; j < numberOfComponents; j++) {
const value = components[j];
min3[j] = Math.min(min3[j], value);
max3[j] = Math.max(max3[j], value);
}
byteOffset += byteStride;
}
return {
min: min3,
max: max3
};
}
var findAccessorMinMax_default = findAccessorMinMax;
// packages/engine/Source/Scene/GltfPipeline/moveTechniqueRenderStates.js
var defaultBlendEquation = [WebGLConstants_default.FUNC_ADD, WebGLConstants_default.FUNC_ADD];
var defaultBlendFactors = [
WebGLConstants_default.ONE,
WebGLConstants_default.ZERO,
WebGLConstants_default.ONE,
WebGLConstants_default.ZERO
];
function isStateEnabled(renderStates, state) {
const enabled = renderStates.enable;
if (!defined_default(enabled)) {
return false;
}
return enabled.indexOf(state) > -1;
}
var supportedBlendFactors = [
WebGLConstants_default.ZERO,
WebGLConstants_default.ONE,
WebGLConstants_default.SRC_COLOR,
WebGLConstants_default.ONE_MINUS_SRC_COLOR,
WebGLConstants_default.SRC_ALPHA,
WebGLConstants_default.ONE_MINUS_SRC_ALPHA,
WebGLConstants_default.DST_ALPHA,
WebGLConstants_default.ONE_MINUS_DST_ALPHA,
WebGLConstants_default.DST_COLOR,
WebGLConstants_default.ONE_MINUS_DST_COLOR
];
function getSupportedBlendFactors(value, defaultValue2) {
if (!defined_default(value)) {
return defaultValue2;
}
for (let i = 0; i < 4; i++) {
if (supportedBlendFactors.indexOf(value[i]) === -1) {
return defaultValue2;
}
}
return value;
}
function moveTechniqueRenderStates(gltf) {
const blendingForTechnique = {};
const materialPropertiesForTechnique = {};
const techniquesLegacy = gltf.techniques;
if (!defined_default(techniquesLegacy)) {
return gltf;
}
ForEach_default.technique(gltf, function(techniqueLegacy, techniqueIndex) {
const renderStates = techniqueLegacy.states;
if (defined_default(renderStates)) {
const materialProperties = materialPropertiesForTechnique[techniqueIndex] = {};
if (isStateEnabled(renderStates, WebGLConstants_default.BLEND)) {
materialProperties.alphaMode = "BLEND";
const blendFunctions = renderStates.functions;
if (defined_default(blendFunctions) && (defined_default(blendFunctions.blendEquationSeparate) || defined_default(blendFunctions.blendFuncSeparate))) {
blendingForTechnique[techniqueIndex] = {
blendEquation: defaultValue_default(
blendFunctions.blendEquationSeparate,
defaultBlendEquation
),
blendFactors: getSupportedBlendFactors(
blendFunctions.blendFuncSeparate,
defaultBlendFactors
)
};
}
}
if (!isStateEnabled(renderStates, WebGLConstants_default.CULL_FACE)) {
materialProperties.doubleSided = true;
}
delete techniqueLegacy.states;
}
});
if (Object.keys(blendingForTechnique).length > 0) {
if (!defined_default(gltf.extensions)) {
gltf.extensions = {};
}
addExtensionsUsed_default(gltf, "KHR_blend");
}
ForEach_default.material(gltf, function(material) {
if (defined_default(material.technique)) {
const materialProperties = materialPropertiesForTechnique[material.technique];
ForEach_default.objectLegacy(materialProperties, function(value, property) {
material[property] = value;
});
const blending = blendingForTechnique[material.technique];
if (defined_default(blending)) {
if (!defined_default(material.extensions)) {
material.extensions = {};
}
material.extensions.KHR_blend = blending;
}
}
});
return gltf;
}
var moveTechniqueRenderStates_default = moveTechniqueRenderStates;
// packages/engine/Source/Scene/GltfPipeline/addExtensionsRequired.js
function addExtensionsRequired(gltf, extension) {
let extensionsRequired = gltf.extensionsRequired;
if (!defined_default(extensionsRequired)) {
extensionsRequired = [];
gltf.extensionsRequired = extensionsRequired;
}
addToArray_default(extensionsRequired, extension, true);
addExtensionsUsed_default(gltf, extension);
}
var addExtensionsRequired_default = addExtensionsRequired;
// packages/engine/Source/Scene/GltfPipeline/moveTechniquesToExtension.js
function moveTechniquesToExtension(gltf) {
const techniquesLegacy = gltf.techniques;
const mappedUniforms = {};
const updatedTechniqueIndices = {};
const seenPrograms = {};
if (defined_default(techniquesLegacy)) {
const extension = {
programs: [],
shaders: [],
techniques: []
};
const glExtensions = gltf.glExtensionsUsed;
delete gltf.glExtensionsUsed;
ForEach_default.technique(gltf, function(techniqueLegacy, techniqueId) {
const technique = {
name: techniqueLegacy.name,
program: void 0,
attributes: {},
uniforms: {}
};
let parameterLegacy;
ForEach_default.techniqueAttribute(
techniqueLegacy,
function(parameterName, attributeName) {
parameterLegacy = techniqueLegacy.parameters[parameterName];
technique.attributes[attributeName] = {
semantic: parameterLegacy.semantic
};
}
);
ForEach_default.techniqueUniform(
techniqueLegacy,
function(parameterName, uniformName) {
parameterLegacy = techniqueLegacy.parameters[parameterName];
technique.uniforms[uniformName] = {
count: parameterLegacy.count,
node: parameterLegacy.node,
type: parameterLegacy.type,
semantic: parameterLegacy.semantic,
value: parameterLegacy.value
};
if (!defined_default(mappedUniforms[techniqueId])) {
mappedUniforms[techniqueId] = {};
}
mappedUniforms[techniqueId][parameterName] = uniformName;
}
);
if (!defined_default(seenPrograms[techniqueLegacy.program])) {
const programLegacy = gltf.programs[techniqueLegacy.program];
const program = {
name: programLegacy.name,
fragmentShader: void 0,
vertexShader: void 0,
glExtensions
};
const fs = gltf.shaders[programLegacy.fragmentShader];
program.fragmentShader = addToArray_default(extension.shaders, fs, true);
const vs = gltf.shaders[programLegacy.vertexShader];
program.vertexShader = addToArray_default(extension.shaders, vs, true);
technique.program = addToArray_default(extension.programs, program);
seenPrograms[techniqueLegacy.program] = technique.program;
} else {
technique.program = seenPrograms[techniqueLegacy.program];
}
updatedTechniqueIndices[techniqueId] = addToArray_default(
extension.techniques,
technique
);
});
if (extension.techniques.length > 0) {
if (!defined_default(gltf.extensions)) {
gltf.extensions = {};
}
gltf.extensions.KHR_techniques_webgl = extension;
addExtensionsUsed_default(gltf, "KHR_techniques_webgl");
addExtensionsRequired_default(gltf, "KHR_techniques_webgl");
}
}
ForEach_default.material(gltf, function(material) {
if (defined_default(material.technique)) {
const materialExtension = {
technique: updatedTechniqueIndices[material.technique]
};
ForEach_default.objectLegacy(material.values, function(value, parameterName) {
if (!defined_default(materialExtension.values)) {
materialExtension.values = {};
}
const uniformName = mappedUniforms[material.technique][parameterName];
if (defined_default(uniformName)) {
materialExtension.values[uniformName] = value;
}
});
if (!defined_default(material.extensions)) {
material.extensions = {};
}
material.extensions.KHR_techniques_webgl = materialExtension;
}
delete material.technique;
delete material.values;
});
delete gltf.techniques;
delete gltf.programs;
delete gltf.shaders;
return gltf;
}
var moveTechniquesToExtension_default = moveTechniquesToExtension;
// packages/engine/Source/Scene/GltfPipeline/forEachTextureInMaterial.js
function forEachTextureInMaterial(material, handler) {
Check_default.typeOf.object("material", material);
Check_default.defined("handler", handler);
const pbrMetallicRoughness = material.pbrMetallicRoughness;
if (defined_default(pbrMetallicRoughness)) {
if (defined_default(pbrMetallicRoughness.baseColorTexture)) {
const textureInfo = pbrMetallicRoughness.baseColorTexture;
const value2 = handler(textureInfo.index, textureInfo);
if (defined_default(value2)) {
return value2;
}
}
if (defined_default(pbrMetallicRoughness.metallicRoughnessTexture)) {
const textureInfo = pbrMetallicRoughness.metallicRoughnessTexture;
const value2 = handler(textureInfo.index, textureInfo);
if (defined_default(value2)) {
return value2;
}
}
}
if (defined_default(material.extensions)) {
const pbrSpecularGlossiness = material.extensions.KHR_materials_pbrSpecularGlossiness;
if (defined_default(pbrSpecularGlossiness)) {
if (defined_default(pbrSpecularGlossiness.diffuseTexture)) {
const textureInfo = pbrSpecularGlossiness.diffuseTexture;
const value2 = handler(textureInfo.index, textureInfo);
if (defined_default(value2)) {
return value2;
}
}
if (defined_default(pbrSpecularGlossiness.specularGlossinessTexture)) {
const textureInfo = pbrSpecularGlossiness.specularGlossinessTexture;
const value2 = handler(textureInfo.index, textureInfo);
if (defined_default(value2)) {
return value2;
}
}
}
const materialsCommon = material.extensions.KHR_materials_common;
if (defined_default(materialsCommon) && defined_default(materialsCommon.values)) {
const diffuse = materialsCommon.values.diffuse;
const ambient = materialsCommon.values.ambient;
const emission = materialsCommon.values.emission;
const specular = materialsCommon.values.specular;
if (defined_default(diffuse) && defined_default(diffuse.index)) {
const value2 = handler(diffuse.index, diffuse);
if (defined_default(value2)) {
return value2;
}
}
if (defined_default(ambient) && defined_default(ambient.index)) {
const value2 = handler(ambient.index, ambient);
if (defined_default(value2)) {
return value2;
}
}
if (defined_default(emission) && defined_default(emission.index)) {
const value2 = handler(emission.index, emission);
if (defined_default(value2)) {
return value2;
}
}
if (defined_default(specular) && defined_default(specular.index)) {
const value2 = handler(specular.index, specular);
if (defined_default(value2)) {
return value2;
}
}
}
}
const value = ForEach_default.materialValue(material, function(materialValue) {
if (defined_default(materialValue.index)) {
const value2 = handler(materialValue.index, materialValue);
if (defined_default(value2)) {
return value2;
}
}
});
if (defined_default(value)) {
return value;
}
if (defined_default(material.emissiveTexture)) {
const textureInfo = material.emissiveTexture;
const value2 = handler(textureInfo.index, textureInfo);
if (defined_default(value2)) {
return value2;
}
}
if (defined_default(material.normalTexture)) {
const textureInfo = material.normalTexture;
const value2 = handler(textureInfo.index, textureInfo);
if (defined_default(value2)) {
return value2;
}
}
if (defined_default(material.occlusionTexture)) {
const textureInfo = material.occlusionTexture;
const value2 = handler(textureInfo.index, textureInfo);
if (defined_default(value2)) {
return value2;
}
}
}
var forEachTextureInMaterial_default = forEachTextureInMaterial;
// packages/engine/Source/Scene/GltfPipeline/removeUnusedElements.js
var allElementTypes = [
"mesh",
"node",
"material",
"accessor",
"bufferView",
"buffer",
"texture",
"sampler",
"image"
];
function removeUnusedElements(gltf, elementTypes) {
elementTypes = defaultValue_default(elementTypes, allElementTypes);
allElementTypes.forEach(function(type) {
if (elementTypes.indexOf(type) > -1) {
removeUnusedElementsByType(gltf, type);
}
});
return gltf;
}
var TypeToGltfElementName = {
accessor: "accessors",
buffer: "buffers",
bufferView: "bufferViews",
image: "images",
node: "nodes",
material: "materials",
mesh: "meshes",
sampler: "samplers",
texture: "textures"
};
function removeUnusedElementsByType(gltf, type) {
const name = TypeToGltfElementName[type];
const arrayOfObjects = gltf[name];
if (defined_default(arrayOfObjects)) {
let removed = 0;
const usedIds = getListOfElementsIdsInUse[type](gltf);
const length3 = arrayOfObjects.length;
for (let i = 0; i < length3; ++i) {
if (!usedIds[i]) {
Remove[type](gltf, i - removed);
removed++;
}
}
}
}
function Remove() {
}
Remove.accessor = function(gltf, accessorId) {
const accessors = gltf.accessors;
accessors.splice(accessorId, 1);
ForEach_default.mesh(gltf, function(mesh) {
ForEach_default.meshPrimitive(mesh, function(primitive) {
ForEach_default.meshPrimitiveAttribute(
primitive,
function(attributeAccessorId, semantic) {
if (attributeAccessorId > accessorId) {
primitive.attributes[semantic]--;
}
}
);
ForEach_default.meshPrimitiveTarget(primitive, function(target) {
ForEach_default.meshPrimitiveTargetAttribute(
target,
function(attributeAccessorId, semantic) {
if (attributeAccessorId > accessorId) {
target[semantic]--;
}
}
);
});
const indices2 = primitive.indices;
if (defined_default(indices2) && indices2 > accessorId) {
primitive.indices--;
}
});
});
ForEach_default.skin(gltf, function(skin) {
if (defined_default(skin.inverseBindMatrices) && skin.inverseBindMatrices > accessorId) {
skin.inverseBindMatrices--;
}
});
ForEach_default.animation(gltf, function(animation) {
ForEach_default.animationSampler(animation, function(sampler) {
if (defined_default(sampler.input) && sampler.input > accessorId) {
sampler.input--;
}
if (defined_default(sampler.output) && sampler.output > accessorId) {
sampler.output--;
}
});
});
};
Remove.buffer = function(gltf, bufferId) {
const buffers = gltf.buffers;
buffers.splice(bufferId, 1);
ForEach_default.bufferView(gltf, function(bufferView) {
if (defined_default(bufferView.buffer) && bufferView.buffer > bufferId) {
bufferView.buffer--;
}
if (defined_default(bufferView.extensions) && defined_default(bufferView.extensions.EXT_meshopt_compression)) {
bufferView.extensions.EXT_meshopt_compression.buffer--;
}
});
};
Remove.bufferView = function(gltf, bufferViewId) {
const bufferViews = gltf.bufferViews;
bufferViews.splice(bufferViewId, 1);
ForEach_default.accessor(gltf, function(accessor) {
if (defined_default(accessor.bufferView) && accessor.bufferView > bufferViewId) {
accessor.bufferView--;
}
});
ForEach_default.shader(gltf, function(shader) {
if (defined_default(shader.bufferView) && shader.bufferView > bufferViewId) {
shader.bufferView--;
}
});
ForEach_default.image(gltf, function(image) {
if (defined_default(image.bufferView) && image.bufferView > bufferViewId) {
image.bufferView--;
}
});
if (usesExtension_default(gltf, "KHR_draco_mesh_compression")) {
ForEach_default.mesh(gltf, function(mesh) {
ForEach_default.meshPrimitive(mesh, function(primitive) {
if (defined_default(primitive.extensions) && defined_default(primitive.extensions.KHR_draco_mesh_compression)) {
if (primitive.extensions.KHR_draco_mesh_compression.bufferView > bufferViewId) {
primitive.extensions.KHR_draco_mesh_compression.bufferView--;
}
}
});
});
}
if (usesExtension_default(gltf, "EXT_feature_metadata")) {
const extension = gltf.extensions.EXT_feature_metadata;
const featureTables = extension.featureTables;
for (const featureTableId in featureTables) {
if (featureTables.hasOwnProperty(featureTableId)) {
const featureTable = featureTables[featureTableId];
const properties = featureTable.properties;
if (defined_default(properties)) {
for (const propertyId in properties) {
if (properties.hasOwnProperty(propertyId)) {
const property = properties[propertyId];
if (defined_default(property.bufferView) && property.bufferView > bufferViewId) {
property.bufferView--;
}
if (defined_default(property.arrayOffsetBufferView) && property.arrayOffsetBufferView > bufferViewId) {
property.arrayOffsetBufferView--;
}
if (defined_default(property.stringOffsetBufferView) && property.stringOffsetBufferView > bufferViewId) {
property.stringOffsetBufferView--;
}
}
}
}
}
}
}
if (usesExtension_default(gltf, "EXT_structural_metadata")) {
const extension = gltf.extensions.EXT_structural_metadata;
const propertyTables = extension.propertyTables;
if (defined_default(propertyTables)) {
const propertyTablesLength = propertyTables.length;
for (let i = 0; i < propertyTablesLength; ++i) {
const propertyTable = propertyTables[i];
const properties = propertyTable.properties;
for (const propertyId in properties) {
if (properties.hasOwnProperty(propertyId)) {
const property = properties[propertyId];
if (defined_default(property.values) && property.values > bufferViewId) {
property.values--;
}
if (defined_default(property.arrayOffsets) && property.arrayOffsets > bufferViewId) {
property.arrayOffsets--;
}
if (defined_default(property.stringOffsets) && property.stringOffsets > bufferViewId) {
property.stringOffsets--;
}
}
}
}
}
}
};
Remove.image = function(gltf, imageId) {
const images = gltf.images;
images.splice(imageId, 1);
ForEach_default.texture(gltf, function(texture) {
if (defined_default(texture.source)) {
if (texture.source > imageId) {
--texture.source;
}
}
const ext = texture.extensions;
if (defined_default(ext) && defined_default(ext.EXT_texture_webp) && ext.EXT_texture_webp.source > imageId) {
--texture.extensions.EXT_texture_webp.source;
} else if (defined_default(ext) && defined_default(ext.KHR_texture_basisu) && ext.KHR_texture_basisu.source > imageId) {
--texture.extensions.KHR_texture_basisu.source;
}
});
};
Remove.mesh = function(gltf, meshId) {
const meshes = gltf.meshes;
meshes.splice(meshId, 1);
ForEach_default.node(gltf, function(node) {
if (defined_default(node.mesh)) {
if (node.mesh > meshId) {
node.mesh--;
} else if (node.mesh === meshId) {
delete node.mesh;
}
}
});
};
Remove.node = function(gltf, nodeId) {
const nodes = gltf.nodes;
nodes.splice(nodeId, 1);
ForEach_default.skin(gltf, function(skin) {
if (defined_default(skin.skeleton) && skin.skeleton > nodeId) {
skin.skeleton--;
}
skin.joints = skin.joints.map(function(x) {
return x > nodeId ? x - 1 : x;
});
});
ForEach_default.animation(gltf, function(animation) {
ForEach_default.animationChannel(animation, function(channel) {
if (defined_default(channel.target) && defined_default(channel.target.node) && channel.target.node > nodeId) {
channel.target.node--;
}
});
});
ForEach_default.technique(gltf, function(technique) {
ForEach_default.techniqueUniform(technique, function(uniform) {
if (defined_default(uniform.node) && uniform.node > nodeId) {
uniform.node--;
}
});
});
ForEach_default.node(gltf, function(node) {
if (!defined_default(node.children)) {
return;
}
node.children = node.children.filter(function(x) {
return x !== nodeId;
}).map(function(x) {
return x > nodeId ? x - 1 : x;
});
});
ForEach_default.scene(gltf, function(scene) {
scene.nodes = scene.nodes.filter(function(x) {
return x !== nodeId;
}).map(function(x) {
return x > nodeId ? x - 1 : x;
});
});
};
Remove.material = function(gltf, materialId) {
const materials = gltf.materials;
materials.splice(materialId, 1);
ForEach_default.mesh(gltf, function(mesh) {
ForEach_default.meshPrimitive(mesh, function(primitive) {
if (defined_default(primitive.material) && primitive.material > materialId) {
primitive.material--;
}
});
});
};
Remove.sampler = function(gltf, samplerId) {
const samplers = gltf.samplers;
samplers.splice(samplerId, 1);
ForEach_default.texture(gltf, function(texture) {
if (defined_default(texture.sampler)) {
if (texture.sampler > samplerId) {
--texture.sampler;
}
}
});
};
Remove.texture = function(gltf, textureId) {
const textures = gltf.textures;
textures.splice(textureId, 1);
ForEach_default.material(gltf, function(material) {
forEachTextureInMaterial_default(material, function(textureIndex, textureInfo) {
if (textureInfo.index > textureId) {
--textureInfo.index;
}
});
});
if (usesExtension_default(gltf, "EXT_feature_metadata")) {
ForEach_default.mesh(gltf, function(mesh) {
ForEach_default.meshPrimitive(mesh, function(primitive) {
const extensions = primitive.extensions;
if (defined_default(extensions) && defined_default(extensions.EXT_feature_metadata)) {
const extension2 = extensions.EXT_feature_metadata;
const featureIdTextures = extension2.featureIdTextures;
if (defined_default(featureIdTextures)) {
const featureIdTexturesLength = featureIdTextures.length;
for (let i = 0; i < featureIdTexturesLength; ++i) {
const featureIdTexture = featureIdTextures[i];
const textureInfo = featureIdTexture.featureIds.texture;
if (textureInfo.index > textureId) {
--textureInfo.index;
}
}
}
}
});
});
const extension = gltf.extensions.EXT_feature_metadata;
const featureTextures = extension.featureTextures;
for (const featureTextureId in featureTextures) {
if (featureTextures.hasOwnProperty(featureTextureId)) {
const featureTexture = featureTextures[featureTextureId];
const properties = featureTexture.properties;
if (defined_default(properties)) {
for (const propertyId in properties) {
if (properties.hasOwnProperty(propertyId)) {
const property = properties[propertyId];
const textureInfo = property.texture;
if (textureInfo.index > textureId) {
--textureInfo.index;
}
}
}
}
}
}
}
if (usesExtension_default(gltf, "EXT_mesh_features")) {
ForEach_default.mesh(gltf, function(mesh) {
ForEach_default.meshPrimitive(mesh, function(primitive) {
const extensions = primitive.extensions;
if (defined_default(extensions) && defined_default(extensions.EXT_mesh_features)) {
const extension = extensions.EXT_mesh_features;
const featureIds = extension.featureIds;
if (defined_default(featureIds)) {
const featureIdsLength = featureIds.length;
for (let i = 0; i < featureIdsLength; ++i) {
const featureId = featureIds[i];
if (defined_default(featureId.texture)) {
if (featureId.texture.index > textureId) {
--featureId.texture.index;
}
}
}
}
}
});
});
}
if (usesExtension_default(gltf, "EXT_structural_metadata")) {
const extension = gltf.extensions.EXT_structural_metadata;
const propertyTextures = extension.propertyTextures;
if (defined_default(propertyTextures)) {
const propertyTexturesLength = propertyTextures.length;
for (let i = 0; i < propertyTexturesLength; ++i) {
const propertyTexture = propertyTextures[i];
const properties = propertyTexture.properties;
for (const propertyId in properties) {
if (properties.hasOwnProperty(propertyId)) {
const property = properties[propertyId];
if (property.index > textureId) {
--property.index;
}
}
}
}
}
}
};
function getListOfElementsIdsInUse() {
}
getListOfElementsIdsInUse.accessor = function(gltf) {
const usedAccessorIds = {};
ForEach_default.mesh(gltf, function(mesh) {
ForEach_default.meshPrimitive(mesh, function(primitive) {
ForEach_default.meshPrimitiveAttribute(primitive, function(accessorId) {
usedAccessorIds[accessorId] = true;
});
ForEach_default.meshPrimitiveTarget(primitive, function(target) {
ForEach_default.meshPrimitiveTargetAttribute(target, function(accessorId) {
usedAccessorIds[accessorId] = true;
});
});
const indices2 = primitive.indices;
if (defined_default(indices2)) {
usedAccessorIds[indices2] = true;
}
});
});
ForEach_default.skin(gltf, function(skin) {
if (defined_default(skin.inverseBindMatrices)) {
usedAccessorIds[skin.inverseBindMatrices] = true;
}
});
ForEach_default.animation(gltf, function(animation) {
ForEach_default.animationSampler(animation, function(sampler) {
if (defined_default(sampler.input)) {
usedAccessorIds[sampler.input] = true;
}
if (defined_default(sampler.output)) {
usedAccessorIds[sampler.output] = true;
}
});
});
if (usesExtension_default(gltf, "EXT_mesh_gpu_instancing")) {
ForEach_default.node(gltf, function(node) {
if (defined_default(node.extensions) && defined_default(node.extensions.EXT_mesh_gpu_instancing)) {
Object.keys(node.extensions.EXT_mesh_gpu_instancing.attributes).forEach(
function(key) {
const attributeAccessorId = node.extensions.EXT_mesh_gpu_instancing.attributes[key];
usedAccessorIds[attributeAccessorId] = true;
}
);
}
});
}
return usedAccessorIds;
};
getListOfElementsIdsInUse.buffer = function(gltf) {
const usedBufferIds = {};
ForEach_default.bufferView(gltf, function(bufferView) {
if (defined_default(bufferView.buffer)) {
usedBufferIds[bufferView.buffer] = true;
}
if (defined_default(bufferView.extensions) && defined_default(bufferView.extensions.EXT_meshopt_compression)) {
usedBufferIds[bufferView.extensions.EXT_meshopt_compression.buffer] = true;
}
});
return usedBufferIds;
};
getListOfElementsIdsInUse.bufferView = function(gltf) {
const usedBufferViewIds = {};
ForEach_default.accessor(gltf, function(accessor) {
if (defined_default(accessor.bufferView)) {
usedBufferViewIds[accessor.bufferView] = true;
}
});
ForEach_default.shader(gltf, function(shader) {
if (defined_default(shader.bufferView)) {
usedBufferViewIds[shader.bufferView] = true;
}
});
ForEach_default.image(gltf, function(image) {
if (defined_default(image.bufferView)) {
usedBufferViewIds[image.bufferView] = true;
}
});
if (usesExtension_default(gltf, "KHR_draco_mesh_compression")) {
ForEach_default.mesh(gltf, function(mesh) {
ForEach_default.meshPrimitive(mesh, function(primitive) {
if (defined_default(primitive.extensions) && defined_default(primitive.extensions.KHR_draco_mesh_compression)) {
usedBufferViewIds[primitive.extensions.KHR_draco_mesh_compression.bufferView] = true;
}
});
});
}
if (usesExtension_default(gltf, "EXT_feature_metadata")) {
const extension = gltf.extensions.EXT_feature_metadata;
const featureTables = extension.featureTables;
for (const featureTableId in featureTables) {
if (featureTables.hasOwnProperty(featureTableId)) {
const featureTable = featureTables[featureTableId];
const properties = featureTable.properties;
if (defined_default(properties)) {
for (const propertyId in properties) {
if (properties.hasOwnProperty(propertyId)) {
const property = properties[propertyId];
if (defined_default(property.bufferView)) {
usedBufferViewIds[property.bufferView] = true;
}
if (defined_default(property.arrayOffsetBufferView)) {
usedBufferViewIds[property.arrayOffsetBufferView] = true;
}
if (defined_default(property.stringOffsetBufferView)) {
usedBufferViewIds[property.stringOffsetBufferView] = true;
}
}
}
}
}
}
}
if (usesExtension_default(gltf, "EXT_structural_metadata")) {
const extension = gltf.extensions.EXT_structural_metadata;
const propertyTables = extension.propertyTables;
if (defined_default(propertyTables)) {
const propertyTablesLength = propertyTables.length;
for (let i = 0; i < propertyTablesLength; ++i) {
const propertyTable = propertyTables[i];
const properties = propertyTable.properties;
for (const propertyId in properties) {
if (properties.hasOwnProperty(propertyId)) {
const property = properties[propertyId];
if (defined_default(property.values)) {
usedBufferViewIds[property.values] = true;
}
if (defined_default(property.arrayOffsets)) {
usedBufferViewIds[property.arrayOffsets] = true;
}
if (defined_default(property.stringOffsets)) {
usedBufferViewIds[property.stringOffsets] = true;
}
}
}
}
}
}
return usedBufferViewIds;
};
getListOfElementsIdsInUse.image = function(gltf) {
const usedImageIds = {};
ForEach_default.texture(gltf, function(texture) {
if (defined_default(texture.source)) {
usedImageIds[texture.source] = true;
}
if (defined_default(texture.extensions) && defined_default(texture.extensions.EXT_texture_webp)) {
usedImageIds[texture.extensions.EXT_texture_webp.source] = true;
} else if (defined_default(texture.extensions) && defined_default(texture.extensions.KHR_texture_basisu)) {
usedImageIds[texture.extensions.KHR_texture_basisu.source] = true;
}
});
return usedImageIds;
};
getListOfElementsIdsInUse.mesh = function(gltf) {
const usedMeshIds = {};
ForEach_default.node(gltf, function(node) {
if (defined_default(node.mesh && defined_default(gltf.meshes))) {
const mesh = gltf.meshes[node.mesh];
if (defined_default(mesh) && defined_default(mesh.primitives) && mesh.primitives.length > 0) {
usedMeshIds[node.mesh] = true;
}
}
});
return usedMeshIds;
};
function nodeIsEmpty(gltf, nodeId, usedNodeIds) {
const node = gltf.nodes[nodeId];
if (defined_default(node.mesh) || defined_default(node.camera) || defined_default(node.skin) || defined_default(node.weights) || defined_default(node.extras) || defined_default(node.extensions) && Object.keys(node.extensions).length !== 0 || defined_default(usedNodeIds[nodeId])) {
return false;
}
return !defined_default(node.children) || node.children.filter(function(n) {
return !nodeIsEmpty(gltf, n, usedNodeIds);
}).length === 0;
}
getListOfElementsIdsInUse.node = function(gltf) {
const usedNodeIds = {};
ForEach_default.skin(gltf, function(skin) {
if (defined_default(skin.skeleton)) {
usedNodeIds[skin.skeleton] = true;
}
ForEach_default.skinJoint(skin, function(joint) {
usedNodeIds[joint] = true;
});
});
ForEach_default.animation(gltf, function(animation) {
ForEach_default.animationChannel(animation, function(channel) {
if (defined_default(channel.target) && defined_default(channel.target.node)) {
usedNodeIds[channel.target.node] = true;
}
});
});
ForEach_default.technique(gltf, function(technique) {
ForEach_default.techniqueUniform(technique, function(uniform) {
if (defined_default(uniform.node)) {
usedNodeIds[uniform.node] = true;
}
});
});
ForEach_default.node(gltf, function(node, nodeId) {
if (!nodeIsEmpty(gltf, nodeId, usedNodeIds)) {
usedNodeIds[nodeId] = true;
}
});
return usedNodeIds;
};
getListOfElementsIdsInUse.material = function(gltf) {
const usedMaterialIds = {};
ForEach_default.mesh(gltf, function(mesh) {
ForEach_default.meshPrimitive(mesh, function(primitive) {
if (defined_default(primitive.material)) {
usedMaterialIds[primitive.material] = true;
}
});
});
return usedMaterialIds;
};
getListOfElementsIdsInUse.texture = function(gltf) {
const usedTextureIds = {};
ForEach_default.material(gltf, function(material) {
forEachTextureInMaterial_default(material, function(textureId) {
usedTextureIds[textureId] = true;
});
});
if (usesExtension_default(gltf, "EXT_feature_metadata")) {
ForEach_default.mesh(gltf, function(mesh) {
ForEach_default.meshPrimitive(mesh, function(primitive) {
const extensions = primitive.extensions;
if (defined_default(extensions) && defined_default(extensions.EXT_feature_metadata)) {
const extension2 = extensions.EXT_feature_metadata;
const featureIdTextures = extension2.featureIdTextures;
if (defined_default(featureIdTextures)) {
const featureIdTexturesLength = featureIdTextures.length;
for (let i = 0; i < featureIdTexturesLength; ++i) {
const featureIdTexture = featureIdTextures[i];
const textureInfo = featureIdTexture.featureIds.texture;
usedTextureIds[textureInfo.index] = true;
}
}
}
});
});
const extension = gltf.extensions.EXT_feature_metadata;
const featureTextures = extension.featureTextures;
for (const featureTextureId in featureTextures) {
if (featureTextures.hasOwnProperty(featureTextureId)) {
const featureTexture = featureTextures[featureTextureId];
const properties = featureTexture.properties;
if (defined_default(properties)) {
for (const propertyId in properties) {
if (properties.hasOwnProperty(propertyId)) {
const property = properties[propertyId];
const textureInfo = property.texture;
usedTextureIds[textureInfo.index] = true;
}
}
}
}
}
}
if (usesExtension_default(gltf, "EXT_mesh_features")) {
ForEach_default.mesh(gltf, function(mesh) {
ForEach_default.meshPrimitive(mesh, function(primitive) {
const extensions = primitive.extensions;
if (defined_default(extensions) && defined_default(extensions.EXT_mesh_features)) {
const extension = extensions.EXT_mesh_features;
const featureIds = extension.featureIds;
if (defined_default(featureIds)) {
const featureIdsLength = featureIds.length;
for (let i = 0; i < featureIdsLength; ++i) {
const featureId = featureIds[i];
if (defined_default(featureId.texture)) {
usedTextureIds[featureId.texture.index] = true;
}
}
}
}
});
});
}
if (usesExtension_default(gltf, "EXT_structural_metadata")) {
const extension = gltf.extensions.EXT_structural_metadata;
const propertyTextures = extension.propertyTextures;
if (defined_default(propertyTextures)) {
const propertyTexturesLength = propertyTextures.length;
for (let i = 0; i < propertyTexturesLength; ++i) {
const propertyTexture = propertyTextures[i];
const properties = propertyTexture.properties;
for (const propertyId in properties) {
if (properties.hasOwnProperty(propertyId)) {
const property = properties[propertyId];
usedTextureIds[property.index] = true;
}
}
}
}
}
return usedTextureIds;
};
getListOfElementsIdsInUse.sampler = function(gltf) {
const usedSamplerIds = {};
ForEach_default.texture(gltf, function(texture) {
if (defined_default(texture.sampler)) {
usedSamplerIds[texture.sampler] = true;
}
});
return usedSamplerIds;
};
var removeUnusedElements_default = removeUnusedElements;
// packages/engine/Source/Scene/GltfPipeline/addBuffer.js
function addBuffer(gltf, buffer) {
const newBuffer = {
byteLength: buffer.length,
extras: {
_pipeline: {
source: buffer
}
}
};
const bufferId = addToArray_default(gltf.buffers, newBuffer);
const bufferView = {
buffer: bufferId,
byteOffset: 0,
byteLength: buffer.length
};
return addToArray_default(gltf.bufferViews, bufferView);
}
var addBuffer_default = addBuffer;
// packages/engine/Source/Scene/GltfPipeline/readAccessorPacked.js
function readAccessorPacked(gltf, accessor) {
const byteStride = getAccessorByteStride_default(gltf, accessor);
const componentTypeByteLength = ComponentDatatype_default.getSizeInBytes(
accessor.componentType
);
const numberOfComponents = numberOfComponentsForType_default(accessor.type);
const count = accessor.count;
const values = new Array(numberOfComponents * count);
if (!defined_default(accessor.bufferView)) {
return values.fill(0);
}
const bufferView = gltf.bufferViews[accessor.bufferView];
const source = gltf.buffers[bufferView.buffer].extras._pipeline.source;
let byteOffset = accessor.byteOffset + bufferView.byteOffset + source.byteOffset;
const dataView = new DataView(source.buffer);
const components = new Array(numberOfComponents);
const componentReader = getComponentReader_default(accessor.componentType);
for (let i = 0; i < count; ++i) {
componentReader(
dataView,
byteOffset,
numberOfComponents,
componentTypeByteLength,
components
);
for (let j = 0; j < numberOfComponents; ++j) {
values[i * numberOfComponents + j] = components[j];
}
byteOffset += byteStride;
}
return values;
}
var readAccessorPacked_default = readAccessorPacked;
// packages/engine/Source/Scene/GltfPipeline/updateAccessorComponentTypes.js
function updateAccessorComponentTypes(gltf) {
let componentType;
ForEach_default.accessorWithSemantic(gltf, "JOINTS_0", function(accessorId) {
const accessor = gltf.accessors[accessorId];
componentType = accessor.componentType;
if (componentType === WebGLConstants_default.BYTE) {
convertType(gltf, accessor, ComponentDatatype_default.UNSIGNED_BYTE);
} else if (componentType !== WebGLConstants_default.UNSIGNED_BYTE && componentType !== WebGLConstants_default.UNSIGNED_SHORT) {
convertType(gltf, accessor, ComponentDatatype_default.UNSIGNED_SHORT);
}
});
ForEach_default.accessorWithSemantic(gltf, "WEIGHTS_0", function(accessorId) {
const accessor = gltf.accessors[accessorId];
componentType = accessor.componentType;
if (componentType === WebGLConstants_default.BYTE) {
convertType(gltf, accessor, ComponentDatatype_default.UNSIGNED_BYTE);
} else if (componentType === WebGLConstants_default.SHORT) {
convertType(gltf, accessor, ComponentDatatype_default.UNSIGNED_SHORT);
}
});
return gltf;
}
function convertType(gltf, accessor, updatedComponentType) {
const typedArray = ComponentDatatype_default.createTypedArray(
updatedComponentType,
readAccessorPacked_default(gltf, accessor)
);
const newBuffer = new Uint8Array(typedArray.buffer);
accessor.bufferView = addBuffer_default(gltf, newBuffer);
accessor.componentType = updatedComponentType;
accessor.byteOffset = 0;
}
var updateAccessorComponentTypes_default = updateAccessorComponentTypes;
// packages/engine/Source/Scene/GltfPipeline/removeExtension.js
function removeExtension(gltf, extension) {
removeExtensionsUsed_default(gltf, extension);
if (extension === "CESIUM_RTC") {
removeCesiumRTC(gltf);
}
return removeExtensionAndTraverse(gltf, extension);
}
function removeCesiumRTC(gltf) {
ForEach_default.technique(gltf, function(technique) {
ForEach_default.techniqueUniform(technique, function(uniform) {
if (uniform.semantic === "CESIUM_RTC_MODELVIEW") {
uniform.semantic = "MODELVIEW";
}
});
});
}
function removeExtensionAndTraverse(object2, extension) {
if (Array.isArray(object2)) {
const length3 = object2.length;
for (let i = 0; i < length3; ++i) {
removeExtensionAndTraverse(object2[i], extension);
}
} else if (object2 !== null && typeof object2 === "object" && object2.constructor === Object) {
const extensions = object2.extensions;
let extensionData;
if (defined_default(extensions)) {
extensionData = extensions[extension];
if (defined_default(extensionData)) {
delete extensions[extension];
if (Object.keys(extensions).length === 0) {
delete object2.extensions;
}
}
}
for (const key in object2) {
if (Object.prototype.hasOwnProperty.call(object2, key)) {
removeExtensionAndTraverse(object2[key], extension);
}
}
return extensionData;
}
}
var removeExtension_default = removeExtension;
// packages/engine/Source/Scene/GltfPipeline/updateVersion.js
var updateFunctions = {
0.8: glTF08to10,
"1.0": glTF10to20,
"2.0": void 0
};
function updateVersion(gltf, options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const targetVersion = options.targetVersion;
let version2 = gltf.version;
gltf.asset = defaultValue_default(gltf.asset, {
version: "1.0"
});
gltf.asset.version = defaultValue_default(gltf.asset.version, "1.0");
version2 = defaultValue_default(version2, gltf.asset.version).toString();
if (!Object.prototype.hasOwnProperty.call(updateFunctions, version2)) {
if (defined_default(version2)) {
version2 = version2.substring(0, 3);
}
if (!Object.prototype.hasOwnProperty.call(updateFunctions, version2)) {
version2 = "1.0";
}
}
let updateFunction = updateFunctions[version2];
while (defined_default(updateFunction)) {
if (version2 === targetVersion) {
break;
}
updateFunction(gltf, options);
version2 = gltf.asset.version;
updateFunction = updateFunctions[version2];
}
if (!options.keepLegacyExtensions) {
convertTechniquesToPbr(gltf);
convertMaterialsCommonToPbr(gltf);
}
return gltf;
}
function updateInstanceTechniques(gltf) {
const materials = gltf.materials;
for (const materialId in materials) {
if (Object.prototype.hasOwnProperty.call(materials, materialId)) {
const material = materials[materialId];
const instanceTechnique = material.instanceTechnique;
if (defined_default(instanceTechnique)) {
material.technique = instanceTechnique.technique;
material.values = instanceTechnique.values;
delete material.instanceTechnique;
}
}
}
}
function setPrimitiveModes(gltf) {
const meshes = gltf.meshes;
for (const meshId in meshes) {
if (Object.prototype.hasOwnProperty.call(meshes, meshId)) {
const mesh = meshes[meshId];
const primitives = mesh.primitives;
if (defined_default(primitives)) {
const primitivesLength = primitives.length;
for (let i = 0; i < primitivesLength; ++i) {
const primitive = primitives[i];
const defaultMode = defaultValue_default(
primitive.primitive,
WebGLConstants_default.TRIANGLES
);
primitive.mode = defaultValue_default(primitive.mode, defaultMode);
delete primitive.primitive;
}
}
}
}
}
function updateNodes(gltf) {
const nodes = gltf.nodes;
const axis = new Cartesian3_default();
const quat = new Quaternion_default();
for (const nodeId in nodes) {
if (Object.prototype.hasOwnProperty.call(nodes, nodeId)) {
const node = nodes[nodeId];
if (defined_default(node.rotation)) {
const rotation = node.rotation;
Cartesian3_default.fromArray(rotation, 0, axis);
Quaternion_default.fromAxisAngle(axis, rotation[3], quat);
node.rotation = [quat.x, quat.y, quat.z, quat.w];
}
const instanceSkin = node.instanceSkin;
if (defined_default(instanceSkin)) {
node.skeletons = instanceSkin.skeletons;
node.skin = instanceSkin.skin;
node.meshes = instanceSkin.meshes;
delete node.instanceSkin;
}
}
}
}
function updateAnimations(gltf) {
const animations = gltf.animations;
const accessors = gltf.accessors;
const bufferViews = gltf.bufferViews;
const buffers = gltf.buffers;
const updatedAccessors = {};
const axis = new Cartesian3_default();
const quat = new Quaternion_default();
for (const animationId in animations) {
if (Object.prototype.hasOwnProperty.call(animations, animationId)) {
const animation = animations[animationId];
const channels = animation.channels;
const parameters = animation.parameters;
const samplers = animation.samplers;
if (defined_default(channels)) {
const channelsLength = channels.length;
for (let i = 0; i < channelsLength; ++i) {
const channel = channels[i];
if (channel.target.path === "rotation") {
const accessorId = parameters[samplers[channel.sampler].output];
if (defined_default(updatedAccessors[accessorId])) {
continue;
}
updatedAccessors[accessorId] = true;
const accessor = accessors[accessorId];
const bufferView = bufferViews[accessor.bufferView];
const buffer = buffers[bufferView.buffer];
const source = buffer.extras._pipeline.source;
const byteOffset = source.byteOffset + bufferView.byteOffset + accessor.byteOffset;
const componentType = accessor.componentType;
const count = accessor.count;
const componentsLength = numberOfComponentsForType_default(accessor.type);
const length3 = accessor.count * componentsLength;
const typedArray = ComponentDatatype_default.createArrayBufferView(
componentType,
source.buffer,
byteOffset,
length3
);
for (let j = 0; j < count; j++) {
const offset2 = j * componentsLength;
Cartesian3_default.unpack(typedArray, offset2, axis);
const angle = typedArray[offset2 + 3];
Quaternion_default.fromAxisAngle(axis, angle, quat);
Quaternion_default.pack(quat, typedArray, offset2);
}
}
}
}
}
}
}
function removeTechniquePasses(gltf) {
const techniques = gltf.techniques;
for (const techniqueId in techniques) {
if (Object.prototype.hasOwnProperty.call(techniques, techniqueId)) {
const technique = techniques[techniqueId];
const passes = technique.passes;
if (defined_default(passes)) {
const passName = defaultValue_default(technique.pass, "defaultPass");
if (Object.prototype.hasOwnProperty.call(passes, passName)) {
const pass = passes[passName];
const instanceProgram = pass.instanceProgram;
technique.attributes = defaultValue_default(
technique.attributes,
instanceProgram.attributes
);
technique.program = defaultValue_default(
technique.program,
instanceProgram.program
);
technique.uniforms = defaultValue_default(
technique.uniforms,
instanceProgram.uniforms
);
technique.states = defaultValue_default(technique.states, pass.states);
}
delete technique.passes;
delete technique.pass;
}
}
}
}
function glTF08to10(gltf) {
if (!defined_default(gltf.asset)) {
gltf.asset = {};
}
const asset = gltf.asset;
asset.version = "1.0";
if (typeof asset.profile === "string") {
const split = asset.profile.split(" ");
asset.profile = {
api: split[0],
version: split[1]
};
} else {
asset.profile = {};
}
if (defined_default(gltf.version)) {
delete gltf.version;
}
updateInstanceTechniques(gltf);
setPrimitiveModes(gltf);
updateNodes(gltf);
updateAnimations(gltf);
removeTechniquePasses(gltf);
if (defined_default(gltf.allExtensions)) {
gltf.extensionsUsed = gltf.allExtensions;
delete gltf.allExtensions;
}
if (defined_default(gltf.lights)) {
const extensions = defaultValue_default(gltf.extensions, {});
gltf.extensions = extensions;
const materialsCommon = defaultValue_default(extensions.KHR_materials_common, {});
extensions.KHR_materials_common = materialsCommon;
materialsCommon.lights = gltf.lights;
delete gltf.lights;
addExtensionsUsed_default(gltf, "KHR_materials_common");
}
}
function removeAnimationSamplersIndirection(gltf) {
const animations = gltf.animations;
for (const animationId in animations) {
if (Object.prototype.hasOwnProperty.call(animations, animationId)) {
const animation = animations[animationId];
const parameters = animation.parameters;
if (defined_default(parameters)) {
const samplers = animation.samplers;
for (const samplerId in samplers) {
if (Object.prototype.hasOwnProperty.call(samplers, samplerId)) {
const sampler = samplers[samplerId];
sampler.input = parameters[sampler.input];
sampler.output = parameters[sampler.output];
}
}
delete animation.parameters;
}
}
}
}
function objectToArray(object2, mapping) {
const array = [];
for (const id in object2) {
if (Object.prototype.hasOwnProperty.call(object2, id)) {
const value = object2[id];
mapping[id] = array.length;
array.push(value);
if (!defined_default(value.name)) {
value.name = id;
}
}
}
return array;
}
function objectsToArrays(gltf) {
let i;
const globalMapping = {
accessors: {},
animations: {},
buffers: {},
bufferViews: {},
cameras: {},
images: {},
materials: {},
meshes: {},
nodes: {},
programs: {},
samplers: {},
scenes: {},
shaders: {},
skins: {},
textures: {},
techniques: {}
};
let jointName;
const jointNameToId = {};
const nodes = gltf.nodes;
for (const id in nodes) {
if (Object.prototype.hasOwnProperty.call(nodes, id)) {
jointName = nodes[id].jointName;
if (defined_default(jointName)) {
jointNameToId[jointName] = id;
}
}
}
for (const topLevelId in gltf) {
if (Object.prototype.hasOwnProperty.call(gltf, topLevelId) && defined_default(globalMapping[topLevelId])) {
const objectMapping = {};
const object2 = gltf[topLevelId];
gltf[topLevelId] = objectToArray(object2, objectMapping);
globalMapping[topLevelId] = objectMapping;
}
}
for (jointName in jointNameToId) {
if (Object.prototype.hasOwnProperty.call(jointNameToId, jointName)) {
jointNameToId[jointName] = globalMapping.nodes[jointNameToId[jointName]];
}
}
if (defined_default(gltf.scene)) {
gltf.scene = globalMapping.scenes[gltf.scene];
}
ForEach_default.bufferView(gltf, function(bufferView) {
if (defined_default(bufferView.buffer)) {
bufferView.buffer = globalMapping.buffers[bufferView.buffer];
}
});
ForEach_default.accessor(gltf, function(accessor) {
if (defined_default(accessor.bufferView)) {
accessor.bufferView = globalMapping.bufferViews[accessor.bufferView];
}
});
ForEach_default.shader(gltf, function(shader) {
const extensions = shader.extensions;
if (defined_default(extensions)) {
const binaryGltf = extensions.KHR_binary_glTF;
if (defined_default(binaryGltf)) {
shader.bufferView = globalMapping.bufferViews[binaryGltf.bufferView];
delete extensions.KHR_binary_glTF;
}
if (Object.keys(extensions).length === 0) {
delete shader.extensions;
}
}
});
ForEach_default.program(gltf, function(program) {
if (defined_default(program.vertexShader)) {
program.vertexShader = globalMapping.shaders[program.vertexShader];
}
if (defined_default(program.fragmentShader)) {
program.fragmentShader = globalMapping.shaders[program.fragmentShader];
}
});
ForEach_default.technique(gltf, function(technique) {
if (defined_default(technique.program)) {
technique.program = globalMapping.programs[technique.program];
}
ForEach_default.techniqueParameter(technique, function(parameter) {
if (defined_default(parameter.node)) {
parameter.node = globalMapping.nodes[parameter.node];
}
const value = parameter.value;
if (typeof value === "string") {
parameter.value = {
index: globalMapping.textures[value]
};
}
});
});
ForEach_default.mesh(gltf, function(mesh) {
ForEach_default.meshPrimitive(mesh, function(primitive) {
if (defined_default(primitive.indices)) {
primitive.indices = globalMapping.accessors[primitive.indices];
}
ForEach_default.meshPrimitiveAttribute(
primitive,
function(accessorId, semantic) {
primitive.attributes[semantic] = globalMapping.accessors[accessorId];
}
);
if (defined_default(primitive.material)) {
primitive.material = globalMapping.materials[primitive.material];
}
});
});
ForEach_default.node(gltf, function(node) {
let children = node.children;
if (defined_default(children)) {
const childrenLength = children.length;
for (i = 0; i < childrenLength; ++i) {
children[i] = globalMapping.nodes[children[i]];
}
}
if (defined_default(node.meshes)) {
const meshes = node.meshes;
const meshesLength = meshes.length;
if (meshesLength > 0) {
node.mesh = globalMapping.meshes[meshes[0]];
for (i = 1; i < meshesLength; ++i) {
const meshNode = {
mesh: globalMapping.meshes[meshes[i]]
};
const meshNodeId = addToArray_default(gltf.nodes, meshNode);
if (!defined_default(children)) {
children = [];
node.children = children;
}
children.push(meshNodeId);
}
}
delete node.meshes;
}
if (defined_default(node.camera)) {
node.camera = globalMapping.cameras[node.camera];
}
if (defined_default(node.skin)) {
node.skin = globalMapping.skins[node.skin];
}
if (defined_default(node.skeletons)) {
const skeletons = node.skeletons;
const skeletonsLength = skeletons.length;
if (skeletonsLength > 0 && defined_default(node.skin)) {
const skin = gltf.skins[node.skin];
skin.skeleton = globalMapping.nodes[skeletons[0]];
}
delete node.skeletons;
}
if (defined_default(node.jointName)) {
delete node.jointName;
}
});
ForEach_default.skin(gltf, function(skin) {
if (defined_default(skin.inverseBindMatrices)) {
skin.inverseBindMatrices = globalMapping.accessors[skin.inverseBindMatrices];
}
const jointNames = skin.jointNames;
if (defined_default(jointNames)) {
const joints = [];
const jointNamesLength = jointNames.length;
for (i = 0; i < jointNamesLength; ++i) {
joints[i] = jointNameToId[jointNames[i]];
}
skin.joints = joints;
delete skin.jointNames;
}
});
ForEach_default.scene(gltf, function(scene) {
const sceneNodes = scene.nodes;
if (defined_default(sceneNodes)) {
const sceneNodesLength = sceneNodes.length;
for (i = 0; i < sceneNodesLength; ++i) {
sceneNodes[i] = globalMapping.nodes[sceneNodes[i]];
}
}
});
ForEach_default.animation(gltf, function(animation) {
const samplerMapping = {};
animation.samplers = objectToArray(animation.samplers, samplerMapping);
ForEach_default.animationSampler(animation, function(sampler) {
sampler.input = globalMapping.accessors[sampler.input];
sampler.output = globalMapping.accessors[sampler.output];
});
ForEach_default.animationChannel(animation, function(channel) {
channel.sampler = samplerMapping[channel.sampler];
const target = channel.target;
if (defined_default(target)) {
target.node = globalMapping.nodes[target.id];
delete target.id;
}
});
});
ForEach_default.material(gltf, function(material) {
if (defined_default(material.technique)) {
material.technique = globalMapping.techniques[material.technique];
}
ForEach_default.materialValue(material, function(value, name) {
if (typeof value === "string") {
material.values[name] = {
index: globalMapping.textures[value]
};
}
});
const extensions = material.extensions;
if (defined_default(extensions)) {
const materialsCommon = extensions.KHR_materials_common;
if (defined_default(materialsCommon) && defined_default(materialsCommon.values)) {
ForEach_default.materialValue(materialsCommon, function(value, name) {
if (typeof value === "string") {
materialsCommon.values[name] = {
index: globalMapping.textures[value]
};
}
});
}
}
});
ForEach_default.image(gltf, function(image) {
const extensions = image.extensions;
if (defined_default(extensions)) {
const binaryGltf = extensions.KHR_binary_glTF;
if (defined_default(binaryGltf)) {
image.bufferView = globalMapping.bufferViews[binaryGltf.bufferView];
image.mimeType = binaryGltf.mimeType;
delete extensions.KHR_binary_glTF;
}
if (Object.keys(extensions).length === 0) {
delete image.extensions;
}
}
});
ForEach_default.texture(gltf, function(texture) {
if (defined_default(texture.sampler)) {
texture.sampler = globalMapping.samplers[texture.sampler];
}
if (defined_default(texture.source)) {
texture.source = globalMapping.images[texture.source];
}
});
}
function removeAnimationSamplerNames(gltf) {
ForEach_default.animation(gltf, function(animation) {
ForEach_default.animationSampler(animation, function(sampler) {
delete sampler.name;
});
});
}
function removeEmptyArrays(gltf) {
for (const topLevelId in gltf) {
if (Object.prototype.hasOwnProperty.call(gltf, topLevelId)) {
const array = gltf[topLevelId];
if (Array.isArray(array) && array.length === 0) {
delete gltf[topLevelId];
}
}
}
ForEach_default.node(gltf, function(node) {
if (defined_default(node.children) && node.children.length === 0) {
delete node.children;
}
});
}
function stripAsset(gltf) {
const asset = gltf.asset;
delete asset.profile;
delete asset.premultipliedAlpha;
}
var knownExtensions = {
CESIUM_RTC: true,
KHR_materials_common: true,
WEB3D_quantized_attributes: true
};
function requireKnownExtensions(gltf) {
const extensionsUsed = gltf.extensionsUsed;
gltf.extensionsRequired = defaultValue_default(gltf.extensionsRequired, []);
if (defined_default(extensionsUsed)) {
const extensionsUsedLength = extensionsUsed.length;
for (let i = 0; i < extensionsUsedLength; ++i) {
const extension = extensionsUsed[i];
if (defined_default(knownExtensions[extension])) {
gltf.extensionsRequired.push(extension);
}
}
}
}
function removeBufferType(gltf) {
ForEach_default.buffer(gltf, function(buffer) {
delete buffer.type;
});
}
function removeTextureProperties(gltf) {
ForEach_default.texture(gltf, function(texture) {
delete texture.format;
delete texture.internalFormat;
delete texture.target;
delete texture.type;
});
}
function requireAttributeSetIndex(gltf) {
ForEach_default.mesh(gltf, function(mesh) {
ForEach_default.meshPrimitive(mesh, function(primitive) {
ForEach_default.meshPrimitiveAttribute(
primitive,
function(accessorId, semantic) {
if (semantic === "TEXCOORD") {
primitive.attributes.TEXCOORD_0 = accessorId;
} else if (semantic === "COLOR") {
primitive.attributes.COLOR_0 = accessorId;
}
}
);
delete primitive.attributes.TEXCOORD;
delete primitive.attributes.COLOR;
});
});
ForEach_default.technique(gltf, function(technique) {
ForEach_default.techniqueParameter(technique, function(parameter) {
const semantic = parameter.semantic;
if (defined_default(semantic)) {
if (semantic === "TEXCOORD") {
parameter.semantic = "TEXCOORD_0";
} else if (semantic === "COLOR") {
parameter.semantic = "COLOR_0";
}
}
});
});
}
var knownSemantics = {
POSITION: true,
NORMAL: true,
TANGENT: true
};
var indexedSemantics = {
COLOR: "COLOR",
JOINT: "JOINTS",
JOINTS: "JOINTS",
TEXCOORD: "TEXCOORD",
WEIGHT: "WEIGHTS",
WEIGHTS: "WEIGHTS"
};
function underscoreApplicationSpecificSemantics(gltf) {
const mappedSemantics = {};
ForEach_default.mesh(gltf, function(mesh) {
ForEach_default.meshPrimitive(mesh, function(primitive) {
ForEach_default.meshPrimitiveAttribute(
primitive,
function(accessorId, semantic) {
if (semantic.charAt(0) !== "_") {
const setIndex = semantic.search(/_[0-9]+/g);
let strippedSemantic = semantic;
let suffix = "_0";
if (setIndex >= 0) {
strippedSemantic = semantic.substring(0, setIndex);
suffix = semantic.substring(setIndex);
}
let newSemantic;
const indexedSemantic = indexedSemantics[strippedSemantic];
if (defined_default(indexedSemantic)) {
newSemantic = indexedSemantic + suffix;
mappedSemantics[semantic] = newSemantic;
} else if (!defined_default(knownSemantics[strippedSemantic])) {
newSemantic = `_${semantic}`;
mappedSemantics[semantic] = newSemantic;
}
}
}
);
for (const semantic in mappedSemantics) {
if (Object.prototype.hasOwnProperty.call(mappedSemantics, semantic)) {
const mappedSemantic = mappedSemantics[semantic];
const accessorId = primitive.attributes[semantic];
if (defined_default(accessorId)) {
delete primitive.attributes[semantic];
primitive.attributes[mappedSemantic] = accessorId;
}
}
}
});
});
ForEach_default.technique(gltf, function(technique) {
ForEach_default.techniqueParameter(technique, function(parameter) {
const mappedSemantic = mappedSemantics[parameter.semantic];
if (defined_default(mappedSemantic)) {
parameter.semantic = mappedSemantic;
}
});
});
}
function clampCameraParameters(gltf) {
ForEach_default.camera(gltf, function(camera) {
const perspective = camera.perspective;
if (defined_default(perspective)) {
const aspectRatio = perspective.aspectRatio;
if (defined_default(aspectRatio) && aspectRatio === 0) {
delete perspective.aspectRatio;
}
const yfov = perspective.yfov;
if (defined_default(yfov) && yfov === 0) {
perspective.yfov = 1;
}
}
});
}
function computeAccessorByteStride(gltf, accessor) {
return defined_default(accessor.byteStride) && accessor.byteStride !== 0 ? accessor.byteStride : getAccessorByteStride_default(gltf, accessor);
}
function requireByteLength(gltf) {
ForEach_default.buffer(gltf, function(buffer) {
if (!defined_default(buffer.byteLength)) {
buffer.byteLength = buffer.extras._pipeline.source.length;
}
});
ForEach_default.accessor(gltf, function(accessor) {
const bufferViewId = accessor.bufferView;
if (defined_default(bufferViewId)) {
const bufferView = gltf.bufferViews[bufferViewId];
const accessorByteStride = computeAccessorByteStride(gltf, accessor);
const accessorByteEnd = accessor.byteOffset + accessor.count * accessorByteStride;
bufferView.byteLength = Math.max(
defaultValue_default(bufferView.byteLength, 0),
accessorByteEnd
);
}
});
}
function moveByteStrideToBufferView(gltf) {
let i;
let j;
let bufferView;
const bufferViews = gltf.bufferViews;
const bufferViewHasVertexAttributes = {};
ForEach_default.accessorContainingVertexAttributeData(gltf, function(accessorId) {
const accessor = gltf.accessors[accessorId];
if (defined_default(accessor.bufferView)) {
bufferViewHasVertexAttributes[accessor.bufferView] = true;
}
});
const bufferViewMap = {};
ForEach_default.accessor(gltf, function(accessor) {
if (defined_default(accessor.bufferView)) {
bufferViewMap[accessor.bufferView] = defaultValue_default(
bufferViewMap[accessor.bufferView],
[]
);
bufferViewMap[accessor.bufferView].push(accessor);
}
});
for (const bufferViewId in bufferViewMap) {
if (Object.prototype.hasOwnProperty.call(bufferViewMap, bufferViewId)) {
bufferView = bufferViews[bufferViewId];
const accessors = bufferViewMap[bufferViewId];
accessors.sort(function(a3, b) {
return a3.byteOffset - b.byteOffset;
});
let currentByteOffset = 0;
let currentIndex = 0;
const accessorsLength = accessors.length;
for (i = 0; i < accessorsLength; ++i) {
let accessor = accessors[i];
const accessorByteStride = computeAccessorByteStride(gltf, accessor);
const accessorByteOffset = accessor.byteOffset;
const accessorByteLength = accessor.count * accessorByteStride;
delete accessor.byteStride;
const hasNextAccessor = i < accessorsLength - 1;
const nextAccessorByteStride = hasNextAccessor ? computeAccessorByteStride(gltf, accessors[i + 1]) : void 0;
if (accessorByteStride !== nextAccessorByteStride) {
const newBufferView = clone_default(bufferView, true);
if (bufferViewHasVertexAttributes[bufferViewId]) {
newBufferView.byteStride = accessorByteStride;
}
newBufferView.byteOffset += currentByteOffset;
newBufferView.byteLength = accessorByteOffset + accessorByteLength - currentByteOffset;
const newBufferViewId = addToArray_default(bufferViews, newBufferView);
for (j = currentIndex; j <= i; ++j) {
accessor = accessors[j];
accessor.bufferView = newBufferViewId;
accessor.byteOffset = accessor.byteOffset - currentByteOffset;
}
currentByteOffset = hasNextAccessor ? accessors[i + 1].byteOffset : void 0;
currentIndex = i + 1;
}
}
}
}
removeUnusedElements_default(gltf, ["accessor", "bufferView", "buffer"]);
}
function requirePositionAccessorMinMax(gltf) {
ForEach_default.accessorWithSemantic(gltf, "POSITION", function(accessorId) {
const accessor = gltf.accessors[accessorId];
if (!defined_default(accessor.min) || !defined_default(accessor.max)) {
const minMax = findAccessorMinMax_default(gltf, accessor);
accessor.min = minMax.min;
accessor.max = minMax.max;
}
});
}
function isNodeEmpty(node) {
return (!defined_default(node.children) || node.children.length === 0) && (!defined_default(node.meshes) || node.meshes.length === 0) && !defined_default(node.camera) && !defined_default(node.skin) && !defined_default(node.skeletons) && !defined_default(node.jointName) && (!defined_default(node.translation) || Cartesian3_default.fromArray(node.translation).equals(Cartesian3_default.ZERO)) && (!defined_default(node.scale) || Cartesian3_default.fromArray(node.scale).equals(new Cartesian3_default(1, 1, 1))) && (!defined_default(node.rotation) || Cartesian4_default.fromArray(node.rotation).equals(
new Cartesian4_default(0, 0, 0, 1)
)) && (!defined_default(node.matrix) || Matrix4_default.fromColumnMajorArray(node.matrix).equals(Matrix4_default.IDENTITY)) && !defined_default(node.extensions) && !defined_default(node.extras);
}
function deleteNode(gltf, nodeId) {
ForEach_default.scene(gltf, function(scene) {
const sceneNodes = scene.nodes;
if (defined_default(sceneNodes)) {
const sceneNodesLength = sceneNodes.length;
for (let i = sceneNodesLength; i >= 0; --i) {
if (sceneNodes[i] === nodeId) {
sceneNodes.splice(i, 1);
return;
}
}
}
});
ForEach_default.node(gltf, function(parentNode, parentNodeId) {
if (defined_default(parentNode.children)) {
const index = parentNode.children.indexOf(nodeId);
if (index > -1) {
parentNode.children.splice(index, 1);
if (isNodeEmpty(parentNode)) {
deleteNode(gltf, parentNodeId);
}
}
}
});
delete gltf.nodes[nodeId];
}
function removeEmptyNodes(gltf) {
ForEach_default.node(gltf, function(node, nodeId) {
if (isNodeEmpty(node)) {
deleteNode(gltf, nodeId);
}
});
return gltf;
}
function requireAnimationAccessorMinMax(gltf) {
ForEach_default.animation(gltf, function(animation) {
ForEach_default.animationSampler(animation, function(sampler) {
const accessor = gltf.accessors[sampler.input];
if (!defined_default(accessor.min) || !defined_default(accessor.max)) {
const minMax = findAccessorMinMax_default(gltf, accessor);
accessor.min = minMax.min;
accessor.max = minMax.max;
}
});
});
}
function validatePresentAccessorMinMax(gltf) {
ForEach_default.accessor(gltf, function(accessor) {
if (defined_default(accessor.min) || defined_default(accessor.max)) {
const minMax = findAccessorMinMax_default(gltf, accessor);
if (defined_default(accessor.min)) {
accessor.min = minMax.min;
}
if (defined_default(accessor.max)) {
accessor.max = minMax.max;
}
}
});
}
function glTF10to20(gltf) {
gltf.asset = defaultValue_default(gltf.asset, {});
gltf.asset.version = "2.0";
updateInstanceTechniques(gltf);
removeAnimationSamplersIndirection(gltf);
removeEmptyNodes(gltf);
objectsToArrays(gltf);
removeAnimationSamplerNames(gltf);
stripAsset(gltf);
requireKnownExtensions(gltf);
requireByteLength(gltf);
moveByteStrideToBufferView(gltf);
requirePositionAccessorMinMax(gltf);
requireAnimationAccessorMinMax(gltf);
validatePresentAccessorMinMax(gltf);
removeBufferType(gltf);
removeTextureProperties(gltf);
requireAttributeSetIndex(gltf);
underscoreApplicationSpecificSemantics(gltf);
updateAccessorComponentTypes_default(gltf);
clampCameraParameters(gltf);
moveTechniqueRenderStates_default(gltf);
moveTechniquesToExtension_default(gltf);
removeEmptyArrays(gltf);
}
var baseColorTextureNames = ["u_tex", "u_diffuse", "u_emission"];
var baseColorFactorNames = ["u_diffuse"];
function initializePbrMaterial(material) {
material.pbrMetallicRoughness = defined_default(material.pbrMetallicRoughness) ? material.pbrMetallicRoughness : {};
material.pbrMetallicRoughness.roughnessFactor = 1;
material.pbrMetallicRoughness.metallicFactor = 0;
}
function isTexture(value) {
return defined_default(value.index);
}
function isVec4(value) {
return Array.isArray(value) && value.length === 4;
}
function srgbToLinear(srgb) {
const linear = new Array(4);
linear[3] = srgb[3];
for (let i = 0; i < 3; i++) {
const c = srgb[i];
if (c <= 0.04045) {
linear[i] = srgb[i] * 0.07739938080495357;
} else {
linear[i] = Math.pow(
// eslint-disable-next-line no-loss-of-precision
(c + 0.055) * 0.9478672985781991,
2.4
);
}
}
return linear;
}
function convertTechniquesToPbr(gltf) {
ForEach_default.material(gltf, function(material) {
ForEach_default.materialValue(material, function(value, name) {
if (baseColorTextureNames.indexOf(name) !== -1 && isTexture(value)) {
initializePbrMaterial(material);
material.pbrMetallicRoughness.baseColorTexture = value;
} else if (baseColorFactorNames.indexOf(name) !== -1 && isVec4(value)) {
initializePbrMaterial(material);
material.pbrMetallicRoughness.baseColorFactor = srgbToLinear(value);
}
});
});
removeExtension_default(gltf, "KHR_techniques_webgl");
removeExtension_default(gltf, "KHR_blend");
}
function convertMaterialsCommonToPbr(gltf) {
ForEach_default.material(gltf, function(material) {
const materialsCommon = defaultValue_default(
material.extensions,
defaultValue_default.EMPTY_OBJECT
).KHR_materials_common;
if (defined_default(materialsCommon)) {
const technique = materialsCommon.technique;
if (technique === "CONSTANT") {
addExtensionsUsed_default(gltf, "KHR_materials_unlit");
material.extensions = defined_default(material.extensions) ? material.extensions : {};
material.extensions["KHR_materials_unlit"] = {};
}
const values = defined_default(materialsCommon.values) ? materialsCommon.values : {};
const ambient = values.ambient;
const diffuse = values.diffuse;
const emission = values.emission;
const transparency = values.transparency;
const doubleSided = materialsCommon.doubleSided;
const transparent = materialsCommon.transparent;
initializePbrMaterial(material);
if (defined_default(ambient)) {
if (isVec4(ambient)) {
material.emissiveFactor = ambient.slice(0, 3);
} else if (isTexture(ambient)) {
material.emissiveTexture = ambient;
}
}
if (defined_default(diffuse)) {
if (isVec4(diffuse)) {
material.pbrMetallicRoughness.baseColorFactor = srgbToLinear(diffuse);
} else if (isTexture(diffuse)) {
material.pbrMetallicRoughness.baseColorTexture = diffuse;
}
}
if (defined_default(doubleSided)) {
material.doubleSided = doubleSided;
}
if (defined_default(emission)) {
if (isVec4(emission)) {
material.emissiveFactor = emission.slice(0, 3);
} else if (isTexture(emission)) {
material.emissiveTexture = emission;
}
}
if (defined_default(transparency)) {
if (defined_default(material.pbrMetallicRoughness.baseColorFactor)) {
material.pbrMetallicRoughness.baseColorFactor[3] *= transparency;
} else {
material.pbrMetallicRoughness.baseColorFactor = [
1,
1,
1,
transparency
];
}
}
if (defined_default(transparent)) {
material.alphaMode = transparent ? "BLEND" : "OPAQUE";
}
}
});
removeExtension_default(gltf, "KHR_materials_common");
}
var updateVersion_default = updateVersion;
// packages/engine/Source/Scene/VertexAttributeSemantic.js
var VertexAttributeSemantic = {
/**
* Per-vertex position.
*
* @type {string}
* @constant
*/
POSITION: "POSITION",
/**
* Per-vertex normal.
*
* @type {string}
* @constant
*/
NORMAL: "NORMAL",
/**
* Per-vertex tangent.
*
* @type {string}
* @constant
*/
TANGENT: "TANGENT",
/**
* Per-vertex texture coordinates.
*
* @type {string}
* @constant
*/
TEXCOORD: "TEXCOORD",
/**
* Per-vertex color.
*
* @type {string}
* @constant
*/
COLOR: "COLOR",
/**
* Per-vertex joint IDs for skinning.
*
* @type {string}
* @constant
*/
JOINTS: "JOINTS",
/**
* Per-vertex joint weights for skinning.
*
* @type {string}
* @constant
*/
WEIGHTS: "WEIGHTS",
/**
* Per-vertex feature ID.
*
* @type {string}
* @constant
*/
FEATURE_ID: "_FEATURE_ID"
};
function semanticToVariableName(semantic) {
switch (semantic) {
case VertexAttributeSemantic.POSITION:
return "positionMC";
case VertexAttributeSemantic.NORMAL:
return "normalMC";
case VertexAttributeSemantic.TANGENT:
return "tangentMC";
case VertexAttributeSemantic.TEXCOORD:
return "texCoord";
case VertexAttributeSemantic.COLOR:
return "color";
case VertexAttributeSemantic.JOINTS:
return "joints";
case VertexAttributeSemantic.WEIGHTS:
return "weights";
case VertexAttributeSemantic.FEATURE_ID:
return "featureId";
default:
throw new DeveloperError_default("semantic is not a valid value.");
}
}
VertexAttributeSemantic.hasSetIndex = function(semantic) {
Check_default.typeOf.string("semantic", semantic);
switch (semantic) {
case VertexAttributeSemantic.POSITION:
case VertexAttributeSemantic.NORMAL:
case VertexAttributeSemantic.TANGENT:
return false;
case VertexAttributeSemantic.TEXCOORD:
case VertexAttributeSemantic.COLOR:
case VertexAttributeSemantic.JOINTS:
case VertexAttributeSemantic.WEIGHTS:
case VertexAttributeSemantic.FEATURE_ID:
return true;
default:
throw new DeveloperError_default("semantic is not a valid value.");
}
};
VertexAttributeSemantic.fromGltfSemantic = function(gltfSemantic) {
Check_default.typeOf.string("gltfSemantic", gltfSemantic);
let semantic = gltfSemantic;
const setIndexRegex = /^(\w+)_\d+$/;
const setIndexMatch = setIndexRegex.exec(gltfSemantic);
if (setIndexMatch !== null) {
semantic = setIndexMatch[1];
}
switch (semantic) {
case "POSITION":
return VertexAttributeSemantic.POSITION;
case "NORMAL":
return VertexAttributeSemantic.NORMAL;
case "TANGENT":
return VertexAttributeSemantic.TANGENT;
case "TEXCOORD":
return VertexAttributeSemantic.TEXCOORD;
case "COLOR":
return VertexAttributeSemantic.COLOR;
case "JOINTS":
return VertexAttributeSemantic.JOINTS;
case "WEIGHTS":
return VertexAttributeSemantic.WEIGHTS;
case "_FEATURE_ID":
return VertexAttributeSemantic.FEATURE_ID;
}
return void 0;
};
VertexAttributeSemantic.fromPntsSemantic = function(pntsSemantic) {
Check_default.typeOf.string("pntsSemantic", pntsSemantic);
switch (pntsSemantic) {
case "POSITION":
case "POSITION_QUANTIZED":
return VertexAttributeSemantic.POSITION;
case "RGBA":
case "RGB":
case "RGB565":
return VertexAttributeSemantic.COLOR;
case "NORMAL":
case "NORMAL_OCT16P":
return VertexAttributeSemantic.NORMAL;
case "BATCH_ID":
return VertexAttributeSemantic.FEATURE_ID;
default:
throw new DeveloperError_default("pntsSemantic is not a valid value.");
}
};
VertexAttributeSemantic.getGlslType = function(semantic) {
Check_default.typeOf.string("semantic", semantic);
switch (semantic) {
case VertexAttributeSemantic.POSITION:
case VertexAttributeSemantic.NORMAL:
case VertexAttributeSemantic.TANGENT:
return "vec3";
case VertexAttributeSemantic.TEXCOORD:
return "vec2";
case VertexAttributeSemantic.COLOR:
return "vec4";
case VertexAttributeSemantic.JOINTS:
return "ivec4";
case VertexAttributeSemantic.WEIGHTS:
return "vec4";
case VertexAttributeSemantic.FEATURE_ID:
return "int";
default:
throw new DeveloperError_default("semantic is not a valid value.");
}
};
VertexAttributeSemantic.getVariableName = function(semantic, setIndex) {
Check_default.typeOf.string("semantic", semantic);
let variableName = semanticToVariableName(semantic);
if (defined_default(setIndex)) {
variableName += `_${setIndex}`;
}
return variableName;
};
var VertexAttributeSemantic_default = Object.freeze(VertexAttributeSemantic);
// packages/engine/Source/Scene/Model/ModelUtility.js
function ModelUtility() {
}
ModelUtility.getError = function(type, path, error) {
let message = `Failed to load ${type}: ${path}`;
if (defined_default(error) && defined_default(error.message)) {
message += `
${error.message}`;
}
const runtimeError = new RuntimeError_default(message);
if (defined_default(error)) {
runtimeError.stack = `Original stack:
${error.stack}
Handler stack:
${runtimeError.stack}`;
}
return runtimeError;
};
ModelUtility.getNodeTransform = function(node) {
if (defined_default(node.matrix)) {
return node.matrix;
}
return Matrix4_default.fromTranslationQuaternionRotationScale(
defined_default(node.translation) ? node.translation : Cartesian3_default.ZERO,
defined_default(node.rotation) ? node.rotation : Quaternion_default.IDENTITY,
defined_default(node.scale) ? node.scale : Cartesian3_default.ONE
);
};
ModelUtility.getAttributeBySemantic = function(object2, semantic, setIndex) {
const attributes = object2.attributes;
const attributesLength = attributes.length;
for (let i = 0; i < attributesLength; ++i) {
const attribute = attributes[i];
const matchesSetIndex = defined_default(setIndex) ? attribute.setIndex === setIndex : true;
if (attribute.semantic === semantic && matchesSetIndex) {
return attribute;
}
}
return void 0;
};
ModelUtility.getAttributeByName = function(object2, name) {
const attributes = object2.attributes;
const attributesLength = attributes.length;
for (let i = 0; i < attributesLength; ++i) {
const attribute = attributes[i];
if (attribute.name === name) {
return attribute;
}
}
return void 0;
};
ModelUtility.getFeatureIdsByLabel = function(featureIds, label) {
for (let i = 0; i < featureIds.length; i++) {
const featureIdSet = featureIds[i];
if (featureIdSet.positionalLabel === label || featureIdSet.label === label) {
return featureIdSet;
}
}
return void 0;
};
ModelUtility.hasQuantizedAttributes = function(attributes) {
if (!defined_default(attributes)) {
return false;
}
for (let i = 0; i < attributes.length; i++) {
const attribute = attributes[i];
if (defined_default(attribute.quantization)) {
return true;
}
}
return false;
};
ModelUtility.getAttributeInfo = function(attribute) {
const semantic = attribute.semantic;
const setIndex = attribute.setIndex;
let variableName;
let hasSemantic = false;
if (defined_default(semantic)) {
variableName = VertexAttributeSemantic_default.getVariableName(semantic, setIndex);
hasSemantic = true;
} else {
variableName = attribute.name;
variableName = variableName.replace(/^_/, "");
variableName = variableName.toLowerCase();
}
const isVertexColor = /^color_\d+$/.test(variableName);
const attributeType = attribute.type;
let glslType = AttributeType_default.getGlslType(attributeType);
if (isVertexColor) {
glslType = "vec4";
}
const isQuantized = defined_default(attribute.quantization);
let quantizedGlslType;
if (isQuantized) {
quantizedGlslType = isVertexColor ? "vec4" : AttributeType_default.getGlslType(attribute.quantization.type);
}
return {
attribute,
isQuantized,
variableName,
hasSemantic,
glslType,
quantizedGlslType
};
};
var cartesianMaxScratch = new Cartesian3_default();
var cartesianMinScratch = new Cartesian3_default();
ModelUtility.getPositionMinMax = function(primitive, instancingTranslationMin, instancingTranslationMax) {
const positionGltfAttribute = ModelUtility.getAttributeBySemantic(
primitive,
"POSITION"
);
let positionMax = positionGltfAttribute.max;
let positionMin = positionGltfAttribute.min;
if (defined_default(instancingTranslationMax) && defined_default(instancingTranslationMin)) {
positionMin = Cartesian3_default.add(
positionMin,
instancingTranslationMin,
cartesianMinScratch
);
positionMax = Cartesian3_default.add(
positionMax,
instancingTranslationMax,
cartesianMaxScratch
);
}
return {
min: positionMin,
max: positionMax
};
};
ModelUtility.getAxisCorrectionMatrix = function(upAxis, forwardAxis, result) {
result = Matrix4_default.clone(Matrix4_default.IDENTITY, result);
if (upAxis === Axis_default.Y) {
result = Matrix4_default.clone(Axis_default.Y_UP_TO_Z_UP, result);
} else if (upAxis === Axis_default.X) {
result = Matrix4_default.clone(Axis_default.X_UP_TO_Z_UP, result);
}
if (forwardAxis === Axis_default.Z) {
result = Matrix4_default.multiplyTransformation(result, Axis_default.Z_UP_TO_X_UP, result);
}
return result;
};
var scratchMatrix32 = new Matrix3_default();
ModelUtility.getCullFace = function(modelMatrix, primitiveType) {
if (!PrimitiveType_default.isTriangles(primitiveType)) {
return CullFace_default.BACK;
}
const matrix3 = Matrix4_default.getMatrix3(modelMatrix, scratchMatrix32);
return Matrix3_default.determinant(matrix3) < 0 ? CullFace_default.FRONT : CullFace_default.BACK;
};
ModelUtility.sanitizeGlslIdentifier = function(identifier) {
let sanitizedIdentifier = identifier.replaceAll(/[^A-Za-z0-9]+/g, "_");
sanitizedIdentifier = sanitizedIdentifier.replace(/^gl_/, "");
if (/^\d/.test(sanitizedIdentifier)) {
sanitizedIdentifier = `_${sanitizedIdentifier}`;
}
return sanitizedIdentifier;
};
ModelUtility.supportedExtensions = {
AGI_articulations: true,
CESIUM_primitive_outline: true,
CESIUM_RTC: true,
EXT_feature_metadata: true,
EXT_instance_features: true,
EXT_mesh_features: true,
EXT_mesh_gpu_instancing: true,
EXT_meshopt_compression: true,
EXT_structural_metadata: true,
EXT_texture_webp: true,
KHR_blend: true,
KHR_draco_mesh_compression: true,
KHR_techniques_webgl: true,
KHR_materials_common: true,
KHR_materials_pbrSpecularGlossiness: true,
KHR_materials_unlit: true,
KHR_mesh_quantization: true,
KHR_texture_basisu: true,
KHR_texture_transform: true,
WEB3D_quantized_attributes: true
};
ModelUtility.checkSupportedExtensions = function(extensionsRequired) {
const length3 = extensionsRequired.length;
for (let i = 0; i < length3; i++) {
const extension = extensionsRequired[i];
if (!ModelUtility.supportedExtensions[extension]) {
throw new RuntimeError_default(`Unsupported glTF Extension: ${extension}`);
}
}
};
var ModelUtility_default = ModelUtility;
// packages/engine/Source/Scene/GltfJsonLoader.js
function GltfJsonLoader(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const resourceCache = options.resourceCache;
const gltfResource = options.gltfResource;
const baseResource2 = options.baseResource;
const typedArray = options.typedArray;
const gltfJson = options.gltfJson;
const cacheKey = options.cacheKey;
Check_default.typeOf.func("options.resourceCache", resourceCache);
Check_default.typeOf.object("options.gltfResource", gltfResource);
Check_default.typeOf.object("options.baseResource", baseResource2);
this._resourceCache = resourceCache;
this._gltfResource = gltfResource;
this._baseResource = baseResource2;
this._typedArray = typedArray;
this._gltfJson = gltfJson;
this._cacheKey = cacheKey;
this._gltf = void 0;
this._bufferLoaders = [];
this._state = ResourceLoaderState_default.UNLOADED;
this._promise = void 0;
}
if (defined_default(Object.create)) {
GltfJsonLoader.prototype = Object.create(ResourceLoader_default.prototype);
GltfJsonLoader.prototype.constructor = GltfJsonLoader;
}
Object.defineProperties(GltfJsonLoader.prototype, {
/**
* The cache key of the resource.
*
* @memberof GltfJsonLoader.prototype
*
* @type {string}
* @readonly
* @private
*/
cacheKey: {
get: function() {
return this._cacheKey;
}
},
/**
* The glTF JSON.
*
* @memberof GltfJsonLoader.prototype
*
* @type {object}
* @readonly
* @private
*/
gltf: {
get: function() {
return this._gltf;
}
}
});
GltfJsonLoader.prototype.load = async function() {
if (defined_default(this._promise)) {
return this._promise;
}
this._state = ResourceLoaderState_default.LOADING;
if (defined_default(this._gltfJson)) {
this._promise = processGltfJson(this, this._gltfJson);
return this._promise;
}
if (defined_default(this._typedArray)) {
this._promise = processGltfTypedArray(this, this._typedArray);
return this._promise;
}
this._promise = loadFromUri2(this);
return this._promise;
};
async function loadFromUri2(gltfJsonLoader) {
let typedArray;
try {
const arrayBuffer = await gltfJsonLoader._fetchGltf();
if (gltfJsonLoader.isDestroyed()) {
return;
}
typedArray = new Uint8Array(arrayBuffer);
} catch (error) {
if (gltfJsonLoader.isDestroyed()) {
return;
}
handleError4(gltfJsonLoader, error);
}
return processGltfTypedArray(gltfJsonLoader, typedArray);
}
function handleError4(gltfJsonLoader, error) {
gltfJsonLoader.unload();
gltfJsonLoader._state = ResourceLoaderState_default.FAILED;
const errorMessage = `Failed to load glTF: ${gltfJsonLoader._gltfResource.url}`;
throw gltfJsonLoader.getError(errorMessage, error);
}
async function upgradeVersion(gltfJsonLoader, gltf) {
if (defined_default(gltf.asset) && gltf.asset.version === "2.0" && !usesExtension_default(gltf, "KHR_techniques_webgl") && !usesExtension_default(gltf, "KHR_materials_common")) {
return Promise.resolve();
}
const promises = [];
ForEach_default.buffer(gltf, function(buffer) {
if (!defined_default(buffer.extras._pipeline.source) && // Ignore uri if this buffer uses the glTF 1.0 KHR_binary_glTF extension
defined_default(buffer.uri)) {
const resource = gltfJsonLoader._baseResource.getDerivedResource({
url: buffer.uri
});
const resourceCache = gltfJsonLoader._resourceCache;
const bufferLoader = resourceCache.getExternalBufferLoader({
resource
});
gltfJsonLoader._bufferLoaders.push(bufferLoader);
promises.push(
bufferLoader.load().then(function() {
if (bufferLoader.isDestroyed()) {
return;
}
buffer.extras._pipeline.source = bufferLoader.typedArray;
})
);
}
});
await Promise.all(promises);
updateVersion_default(gltf);
}
function decodeDataUris(gltf) {
const promises = [];
ForEach_default.buffer(gltf, function(buffer) {
const bufferUri = buffer.uri;
if (!defined_default(buffer.extras._pipeline.source) && // Ignore uri if this buffer uses the glTF 1.0 KHR_binary_glTF extension
defined_default(bufferUri) && isDataUri_default(bufferUri)) {
delete buffer.uri;
promises.push(
Resource_default.fetchArrayBuffer(bufferUri).then(function(arrayBuffer) {
buffer.extras._pipeline.source = new Uint8Array(arrayBuffer);
})
);
}
});
return Promise.all(promises);
}
function loadEmbeddedBuffers(gltfJsonLoader, gltf) {
const promises = [];
ForEach_default.buffer(gltf, function(buffer, bufferId) {
const source = buffer.extras._pipeline.source;
if (defined_default(source) && !defined_default(buffer.uri)) {
const resourceCache = gltfJsonLoader._resourceCache;
const bufferLoader = resourceCache.getEmbeddedBufferLoader({
parentResource: gltfJsonLoader._gltfResource,
bufferId,
typedArray: source
});
gltfJsonLoader._bufferLoaders.push(bufferLoader);
promises.push(bufferLoader.load());
}
});
return Promise.all(promises);
}
async function processGltfJson(gltfJsonLoader, gltf) {
try {
addPipelineExtras_default(gltf);
await decodeDataUris(gltf);
await upgradeVersion(gltfJsonLoader, gltf);
addDefaults_default(gltf);
await loadEmbeddedBuffers(gltfJsonLoader, gltf);
removePipelineExtras_default(gltf);
const version2 = gltf.asset.version;
if (version2 !== "1.0" && version2 !== "2.0") {
throw new RuntimeError_default(`Unsupported glTF version: ${version2}`);
}
const extensionsRequired = gltf.extensionsRequired;
if (defined_default(extensionsRequired)) {
ModelUtility_default.checkSupportedExtensions(extensionsRequired);
}
gltfJsonLoader._gltf = gltf;
gltfJsonLoader._state = ResourceLoaderState_default.READY;
return gltfJsonLoader;
} catch (error) {
if (gltfJsonLoader.isDestroyed()) {
return;
}
handleError4(gltfJsonLoader, error);
}
}
async function processGltfTypedArray(gltfJsonLoader, typedArray) {
let gltf;
try {
if (getMagic_default(typedArray) === "glTF") {
gltf = parseGlb_default(typedArray);
} else {
gltf = getJsonFromTypedArray_default(typedArray);
}
} catch (error) {
if (gltfJsonLoader.isDestroyed()) {
return;
}
handleError4(gltfJsonLoader, error);
}
return processGltfJson(gltfJsonLoader, gltf);
}
GltfJsonLoader.prototype.unload = function() {
const bufferLoaders = this._bufferLoaders;
const bufferLoadersLength = bufferLoaders.length;
for (let i = 0; i < bufferLoadersLength; ++i) {
bufferLoaders[i] = !bufferLoaders[i].isDestroyed() && this._resourceCache.unload(bufferLoaders[i]);
}
this._bufferLoaders.length = 0;
this._gltf = void 0;
};
GltfJsonLoader.prototype._fetchGltf = function() {
return this._gltfResource.fetchArrayBuffer();
};
var GltfJsonLoader_default = GltfJsonLoader;
// packages/engine/Source/Scene/AlphaMode.js
var AlphaMode = {
/**
* The alpha value is ignored and the rendered output is fully opaque.
*
* @type {string}
* @constant
*/
OPAQUE: "OPAQUE",
/**
* The rendered output is either fully opaque or fully transparent depending on the alpha value and the specified alpha cutoff value.
*
* @type {string}
* @constant
*/
MASK: "MASK",
/**
* The rendered output is composited onto the destination with alpha blending.
*
* @type {string}
* @constant
*/
BLEND: "BLEND"
};
var AlphaMode_default = Object.freeze(AlphaMode);
// packages/engine/Source/Scene/ModelComponents.js
var ModelComponents = {};
function Quantization() {
this.octEncoded = false;
this.octEncodedZXY = false;
this.normalizationRange = void 0;
this.quantizedVolumeOffset = void 0;
this.quantizedVolumeDimensions = void 0;
this.quantizedVolumeStepSize = void 0;
this.componentDatatype = void 0;
this.type = void 0;
}
function Attribute() {
this.name = void 0;
this.semantic = void 0;
this.setIndex = void 0;
this.componentDatatype = void 0;
this.type = void 0;
this.normalized = false;
this.count = void 0;
this.min = void 0;
this.max = void 0;
this.constant = void 0;
this.quantization = void 0;
this.typedArray = void 0;
this.buffer = void 0;
this.byteOffset = 0;
this.byteStride = void 0;
}
function Indices() {
this.indexDatatype = void 0;
this.count = void 0;
this.buffer = void 0;
this.typedArray = void 0;
}
function FeatureIdAttribute() {
this.featureCount = void 0;
this.nullFeatureId = void 0;
this.propertyTableId = void 0;
this.setIndex = void 0;
this.label = void 0;
this.positionalLabel = void 0;
}
function FeatureIdImplicitRange() {
this.featureCount = void 0;
this.nullFeatureId = void 0;
this.propertyTableId = void 0;
this.offset = 0;
this.repeat = void 0;
this.label = void 0;
this.positionalLabel = void 0;
}
function FeatureIdTexture() {
this.featureCount = void 0;
this.nullFeatureId = void 0;
this.propertyTableId = void 0;
this.textureReader = void 0;
this.label = void 0;
this.positionalLabel = void 0;
}
function MorphTarget() {
this.attributes = [];
}
function Primitive2() {
this.attributes = [];
this.morphTargets = [];
this.indices = void 0;
this.material = void 0;
this.primitiveType = void 0;
this.featureIds = [];
this.propertyTextureIds = [];
this.propertyAttributeIds = [];
this.outlineCoordinates = void 0;
}
function Instances() {
this.attributes = [];
this.featureIds = [];
this.transformInWorldSpace = false;
}
function Skin() {
this.index = void 0;
this.joints = [];
this.inverseBindMatrices = [];
}
function Node3() {
this.name = void 0;
this.index = void 0;
this.children = [];
this.primitives = [];
this.instances = void 0;
this.skin = void 0;
this.matrix = void 0;
this.translation = void 0;
this.rotation = void 0;
this.scale = void 0;
this.morphWeights = [];
this.articulationName = void 0;
}
function Scene() {
this.nodes = [];
}
var AnimatedPropertyType = {
TRANSLATION: "translation",
ROTATION: "rotation",
SCALE: "scale",
WEIGHTS: "weights"
};
function AnimationSampler() {
this.input = [];
this.interpolation = void 0;
this.output = [];
}
function AnimationTarget() {
this.node = void 0;
this.path = void 0;
}
function AnimationChannel() {
this.sampler = void 0;
this.target = void 0;
}
function Animation() {
this.name = void 0;
this.samplers = [];
this.channels = [];
}
function ArticulationStage() {
this.name = void 0;
this.type = void 0;
this.minimumValue = void 0;
this.maximumValue = void 0;
this.initialValue = void 0;
}
function Articulation() {
this.name = void 0;
this.stages = [];
}
function Asset() {
this.credits = [];
}
function Components() {
this.asset = new Asset();
this.scene = void 0;
this.nodes = [];
this.skins = [];
this.animations = [];
this.articulations = [];
this.structuralMetadata = void 0;
this.upAxis = void 0;
this.forwardAxis = void 0;
this.transform = Matrix4_default.clone(Matrix4_default.IDENTITY);
}
function TextureReader() {
this.texture = void 0;
this.index = void 0;
this.texCoord = 0;
this.transform = Matrix3_default.clone(Matrix3_default.IDENTITY);
this.channels = void 0;
}
function MetallicRoughness() {
this.baseColorTexture = void 0;
this.metallicRoughnessTexture = void 0;
this.baseColorFactor = Cartesian4_default.clone(
MetallicRoughness.DEFAULT_BASE_COLOR_FACTOR
);
this.metallicFactor = MetallicRoughness.DEFAULT_METALLIC_FACTOR;
this.roughnessFactor = MetallicRoughness.DEFAULT_ROUGHNESS_FACTOR;
}
MetallicRoughness.DEFAULT_BASE_COLOR_FACTOR = Cartesian4_default.ONE;
MetallicRoughness.DEFAULT_METALLIC_FACTOR = 1;
MetallicRoughness.DEFAULT_ROUGHNESS_FACTOR = 1;
function SpecularGlossiness() {
this.diffuseTexture = void 0;
this.specularGlossinessTexture = void 0;
this.diffuseFactor = Cartesian4_default.clone(
SpecularGlossiness.DEFAULT_DIFFUSE_FACTOR
);
this.specularFactor = Cartesian3_default.clone(
SpecularGlossiness.DEFAULT_SPECULAR_FACTOR
);
this.glossinessFactor = SpecularGlossiness.DEFAULT_GLOSSINESS_FACTOR;
}
SpecularGlossiness.DEFAULT_DIFFUSE_FACTOR = Cartesian4_default.ONE;
SpecularGlossiness.DEFAULT_SPECULAR_FACTOR = Cartesian3_default.ONE;
SpecularGlossiness.DEFAULT_GLOSSINESS_FACTOR = 1;
function Material2() {
this.metallicRoughness = new MetallicRoughness();
this.specularGlossiness = void 0;
this.emissiveTexture = void 0;
this.normalTexture = void 0;
this.occlusionTexture = void 0;
this.emissiveFactor = Cartesian3_default.clone(Material2.DEFAULT_EMISSIVE_FACTOR);
this.alphaMode = AlphaMode_default.OPAQUE;
this.alphaCutoff = 0.5;
this.doubleSided = false;
this.unlit = false;
}
Material2.DEFAULT_EMISSIVE_FACTOR = Cartesian3_default.ZERO;
ModelComponents.Quantization = Quantization;
ModelComponents.Attribute = Attribute;
ModelComponents.Indices = Indices;
ModelComponents.FeatureIdAttribute = FeatureIdAttribute;
ModelComponents.FeatureIdTexture = FeatureIdTexture;
ModelComponents.FeatureIdImplicitRange = FeatureIdImplicitRange;
ModelComponents.MorphTarget = MorphTarget;
ModelComponents.Primitive = Primitive2;
ModelComponents.Instances = Instances;
ModelComponents.Skin = Skin;
ModelComponents.Node = Node3;
ModelComponents.Scene = Scene;
ModelComponents.AnimatedPropertyType = Object.freeze(AnimatedPropertyType);
ModelComponents.AnimationSampler = AnimationSampler;
ModelComponents.AnimationTarget = AnimationTarget;
ModelComponents.AnimationChannel = AnimationChannel;
ModelComponents.Animation = Animation;
ModelComponents.ArticulationStage = ArticulationStage;
ModelComponents.Articulation = Articulation;
ModelComponents.Asset = Asset;
ModelComponents.Components = Components;
ModelComponents.TextureReader = TextureReader;
ModelComponents.MetallicRoughness = MetallicRoughness;
ModelComponents.SpecularGlossiness = SpecularGlossiness;
ModelComponents.Material = Material2;
var ModelComponents_default = ModelComponents;
// packages/engine/Source/Scene/GltfLoaderUtil.js
var GltfLoaderUtil = {};
GltfLoaderUtil.getImageIdFromTexture = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const gltf = options.gltf;
const textureId = options.textureId;
const supportedImageFormats = options.supportedImageFormats;
Check_default.typeOf.object("options.gltf", gltf);
Check_default.typeOf.number("options.textureId", textureId);
Check_default.typeOf.object("options.supportedImageFormats", supportedImageFormats);
const texture = gltf.textures[textureId];
const extensions = texture.extensions;
if (defined_default(extensions)) {
if (supportedImageFormats.webp && defined_default(extensions.EXT_texture_webp)) {
return extensions.EXT_texture_webp.source;
} else if (supportedImageFormats.basis && defined_default(extensions.KHR_texture_basisu)) {
return extensions.KHR_texture_basisu.source;
}
}
return texture.source;
};
GltfLoaderUtil.createSampler = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const gltf = options.gltf;
const textureInfo = options.textureInfo;
const compressedTextureNoMipmap = defaultValue_default(
options.compressedTextureNoMipmap,
false
);
Check_default.typeOf.object("options.gltf", gltf);
Check_default.typeOf.object("options.textureInfo", textureInfo);
let wrapS = TextureWrap_default.REPEAT;
let wrapT = TextureWrap_default.REPEAT;
let minFilter = TextureMinificationFilter_default.LINEAR;
let magFilter = TextureMagnificationFilter_default.LINEAR;
const textureId = textureInfo.index;
const texture = gltf.textures[textureId];
const samplerId = texture.sampler;
if (defined_default(samplerId)) {
const sampler = gltf.samplers[samplerId];
wrapS = defaultValue_default(sampler.wrapS, wrapS);
wrapT = defaultValue_default(sampler.wrapT, wrapT);
minFilter = defaultValue_default(sampler.minFilter, minFilter);
magFilter = defaultValue_default(sampler.magFilter, magFilter);
}
let usesTextureTransform = false;
const extensions = textureInfo.extensions;
if (defined_default(extensions) && defined_default(extensions.KHR_texture_transform)) {
usesTextureTransform = true;
}
if ((compressedTextureNoMipmap || usesTextureTransform) && minFilter !== TextureMinificationFilter_default.LINEAR && minFilter !== TextureMinificationFilter_default.NEAREST) {
if (minFilter === TextureMinificationFilter_default.NEAREST_MIPMAP_NEAREST || minFilter === TextureMinificationFilter_default.NEAREST_MIPMAP_LINEAR) {
minFilter = TextureMinificationFilter_default.NEAREST;
} else {
minFilter = TextureMinificationFilter_default.LINEAR;
}
}
return new Sampler_default({
wrapS,
wrapT,
minificationFilter: minFilter,
magnificationFilter: magFilter
});
};
var defaultScale3 = new Cartesian2_default(1, 1);
GltfLoaderUtil.createModelTextureReader = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const textureInfo = options.textureInfo;
const channels = options.channels;
const texture = options.texture;
Check_default.typeOf.object("options.textureInfo", textureInfo);
let texCoord = defaultValue_default(textureInfo.texCoord, 0);
let transform3;
const textureTransform = defaultValue_default(
textureInfo.extensions,
defaultValue_default.EMPTY_OBJECT
).KHR_texture_transform;
if (defined_default(textureTransform)) {
texCoord = defaultValue_default(textureTransform.texCoord, texCoord);
const offset2 = defined_default(textureTransform.offset) ? Cartesian2_default.unpack(textureTransform.offset) : Cartesian2_default.ZERO;
let rotation = defaultValue_default(textureTransform.rotation, 0);
const scale = defined_default(textureTransform.scale) ? Cartesian2_default.unpack(textureTransform.scale) : defaultScale3;
rotation = -rotation;
transform3 = new Matrix3_default(
Math.cos(rotation) * scale.x,
-Math.sin(rotation) * scale.y,
offset2.x,
Math.sin(rotation) * scale.x,
Math.cos(rotation) * scale.y,
offset2.y,
0,
0,
1
);
}
const modelTextureReader = new ModelComponents_default.TextureReader();
modelTextureReader.index = textureInfo.index;
modelTextureReader.texture = texture;
modelTextureReader.texCoord = texCoord;
modelTextureReader.transform = transform3;
modelTextureReader.channels = channels;
return modelTextureReader;
};
var GltfLoaderUtil_default = GltfLoaderUtil;
// packages/engine/Source/Core/resizeImageToNextPowerOfTwo.js
function resizeImageToNextPowerOfTwo(image) {
const canvas = document.createElement("canvas");
canvas.width = Math_default.nextPowerOfTwo(image.width);
canvas.height = Math_default.nextPowerOfTwo(image.height);
const canvasContext = canvas.getContext("2d");
canvasContext.drawImage(
image,
0,
0,
image.width,
image.height,
0,
0,
canvas.width,
canvas.height
);
return canvas;
}
var resizeImageToNextPowerOfTwo_default = resizeImageToNextPowerOfTwo;
// packages/engine/Source/Scene/GltfTextureLoader.js
function GltfTextureLoader(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const resourceCache = options.resourceCache;
const gltf = options.gltf;
const textureInfo = options.textureInfo;
const gltfResource = options.gltfResource;
const baseResource2 = options.baseResource;
const supportedImageFormats = options.supportedImageFormats;
const cacheKey = options.cacheKey;
const asynchronous = defaultValue_default(options.asynchronous, true);
Check_default.typeOf.func("options.resourceCache", resourceCache);
Check_default.typeOf.object("options.gltf", gltf);
Check_default.typeOf.object("options.textureInfo", textureInfo);
Check_default.typeOf.object("options.gltfResource", gltfResource);
Check_default.typeOf.object("options.baseResource", baseResource2);
Check_default.typeOf.object("options.supportedImageFormats", supportedImageFormats);
const textureId = textureInfo.index;
const imageId = GltfLoaderUtil_default.getImageIdFromTexture({
gltf,
textureId,
supportedImageFormats
});
this._resourceCache = resourceCache;
this._gltf = gltf;
this._textureInfo = textureInfo;
this._imageId = imageId;
this._gltfResource = gltfResource;
this._baseResource = baseResource2;
this._cacheKey = cacheKey;
this._asynchronous = asynchronous;
this._imageLoader = void 0;
this._image = void 0;
this._mipLevels = void 0;
this._texture = void 0;
this._state = ResourceLoaderState_default.UNLOADED;
this._promise = void 0;
}
if (defined_default(Object.create)) {
GltfTextureLoader.prototype = Object.create(ResourceLoader_default.prototype);
GltfTextureLoader.prototype.constructor = GltfTextureLoader;
}
Object.defineProperties(GltfTextureLoader.prototype, {
/**
* The cache key of the resource.
*
* @memberof GltfTextureLoader.prototype
*
* @type {string}
* @readonly
* @private
*/
cacheKey: {
get: function() {
return this._cacheKey;
}
},
/**
* The texture.
*
* @memberof GltfTextureLoader.prototype
*
* @type {Texture}
* @readonly
* @private
*/
texture: {
get: function() {
return this._texture;
}
}
});
var scratchTextureJob = new CreateTextureJob();
async function loadResources3(loader) {
const resourceCache = loader._resourceCache;
try {
const imageLoader = resourceCache.getImageLoader({
gltf: loader._gltf,
imageId: loader._imageId,
gltfResource: loader._gltfResource,
baseResource: loader._baseResource
});
loader._imageLoader = imageLoader;
await imageLoader.load();
if (loader.isDestroyed()) {
return;
}
loader._image = imageLoader.image;
loader._mipLevels = imageLoader.mipLevels;
loader._state = ResourceLoaderState_default.LOADED;
return loader;
} catch (error) {
if (loader.isDestroyed()) {
return;
}
loader.unload();
loader._state = ResourceLoaderState_default.FAILED;
const errorMessage = "Failed to load texture";
throw loader.getError(errorMessage, error);
}
}
GltfTextureLoader.prototype.load = async function() {
if (defined_default(this._promise)) {
return this._promise;
}
this._state = ResourceLoaderState_default.LOADING;
this._promise = loadResources3(this);
return this._promise;
};
function CreateTextureJob() {
this.gltf = void 0;
this.textureInfo = void 0;
this.image = void 0;
this.context = void 0;
this.texture = void 0;
}
CreateTextureJob.prototype.set = function(gltf, textureInfo, image, mipLevels, context) {
this.gltf = gltf;
this.textureInfo = textureInfo;
this.image = image;
this.mipLevels = mipLevels;
this.context = context;
};
CreateTextureJob.prototype.execute = function() {
this.texture = createTexture3(
this.gltf,
this.textureInfo,
this.image,
this.mipLevels,
this.context
);
};
function createTexture3(gltf, textureInfo, image, mipLevels, context) {
const internalFormat = image.internalFormat;
let compressedTextureNoMipmap = false;
if (PixelFormat_default.isCompressedFormat(internalFormat) && !defined_default(mipLevels)) {
compressedTextureNoMipmap = true;
}
const sampler = GltfLoaderUtil_default.createSampler({
gltf,
textureInfo,
compressedTextureNoMipmap
});
const minFilter = sampler.minificationFilter;
const wrapS = sampler.wrapS;
const wrapT = sampler.wrapT;
const samplerRequiresMipmap2 = minFilter === TextureMinificationFilter_default.NEAREST_MIPMAP_NEAREST || minFilter === TextureMinificationFilter_default.NEAREST_MIPMAP_LINEAR || minFilter === TextureMinificationFilter_default.LINEAR_MIPMAP_NEAREST || minFilter === TextureMinificationFilter_default.LINEAR_MIPMAP_LINEAR;
const generateMipmap = !defined_default(internalFormat) && samplerRequiresMipmap2;
const requiresPowerOfTwo = generateMipmap || wrapS === TextureWrap_default.REPEAT || wrapS === TextureWrap_default.MIRRORED_REPEAT || wrapT === TextureWrap_default.REPEAT || wrapT === TextureWrap_default.MIRRORED_REPEAT;
const nonPowerOfTwo = !Math_default.isPowerOfTwo(image.width) || !Math_default.isPowerOfTwo(image.height);
const requiresResize = requiresPowerOfTwo && nonPowerOfTwo;
let texture;
if (defined_default(internalFormat)) {
if (!context.webgl2 && PixelFormat_default.isCompressedFormat(internalFormat) && nonPowerOfTwo && requiresPowerOfTwo) {
console.warn(
"Compressed texture uses REPEAT or MIRRORED_REPEAT texture wrap mode and dimensions are not powers of two. The texture may be rendered incorrectly."
);
}
texture = Texture_default.create({
context,
source: {
arrayBufferView: image.bufferView,
// Only defined for CompressedTextureBuffer
mipLevels
},
width: image.width,
height: image.height,
pixelFormat: image.internalFormat,
// Only defined for CompressedTextureBuffer
sampler
});
} else {
if (requiresResize) {
image = resizeImageToNextPowerOfTwo_default(image);
}
texture = Texture_default.create({
context,
source: image,
sampler,
flipY: false,
skipColorSpaceConversion: true
});
}
if (generateMipmap) {
texture.generateMipmap();
}
return texture;
}
GltfTextureLoader.prototype.process = function(frameState) {
Check_default.typeOf.object("frameState", frameState);
if (this._state === ResourceLoaderState_default.READY) {
return true;
}
if (this._state !== ResourceLoaderState_default.LOADED && this._state !== ResourceLoaderState_default.PROCESSING) {
return false;
}
if (defined_default(this._texture)) {
return false;
}
if (!defined_default(this._image)) {
return false;
}
this._state = ResourceLoaderState_default.PROCESSING;
let texture;
if (this._asynchronous) {
const textureJob = scratchTextureJob;
textureJob.set(
this._gltf,
this._textureInfo,
this._image,
this._mipLevels,
frameState.context
);
const jobScheduler = frameState.jobScheduler;
if (!jobScheduler.execute(textureJob, JobType_default.TEXTURE)) {
return;
}
texture = textureJob.texture;
} else {
texture = createTexture3(
this._gltf,
this._textureInfo,
this._image,
this._mipLevels,
frameState.context
);
}
this.unload();
this._texture = texture;
this._state = ResourceLoaderState_default.READY;
this._resourceCache.statistics.addTextureLoader(this);
return true;
};
GltfTextureLoader.prototype.unload = function() {
if (defined_default(this._texture)) {
this._texture.destroy();
}
if (defined_default(this._imageLoader) && !this._imageLoader.isDestroyed()) {
this._resourceCache.unload(this._imageLoader);
}
this._imageLoader = void 0;
this._image = void 0;
this._mipLevels = void 0;
this._texture = void 0;
this._gltf = void 0;
};
var GltfTextureLoader_default = GltfTextureLoader;
// packages/engine/Source/Scene/GltfVertexBufferLoader.js
function GltfVertexBufferLoader(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const resourceCache = options.resourceCache;
const gltf = options.gltf;
const gltfResource = options.gltfResource;
const baseResource2 = options.baseResource;
const bufferViewId = options.bufferViewId;
const draco = options.draco;
const attributeSemantic = options.attributeSemantic;
const accessorId = options.accessorId;
const cacheKey = options.cacheKey;
const asynchronous = defaultValue_default(options.asynchronous, true);
const loadBuffer = defaultValue_default(options.loadBuffer, false);
const loadTypedArray = defaultValue_default(options.loadTypedArray, false);
Check_default.typeOf.func("options.resourceCache", resourceCache);
Check_default.typeOf.object("options.gltf", gltf);
Check_default.typeOf.object("options.gltfResource", gltfResource);
Check_default.typeOf.object("options.baseResource", baseResource2);
if (!loadBuffer && !loadTypedArray) {
throw new DeveloperError_default(
"At least one of loadBuffer and loadTypedArray must be true."
);
}
const hasBufferViewId = defined_default(bufferViewId);
const hasDraco = hasDracoCompression(draco, attributeSemantic);
const hasAttributeSemantic = defined_default(attributeSemantic);
const hasAccessorId = defined_default(accessorId);
if (hasBufferViewId === hasDraco) {
throw new DeveloperError_default(
"One of options.bufferViewId and options.draco must be defined."
);
}
if (hasDraco && !hasAttributeSemantic) {
throw new DeveloperError_default(
"When options.draco is defined options.attributeSemantic must also be defined."
);
}
if (hasDraco && !hasAccessorId) {
throw new DeveloperError_default(
"When options.draco is defined options.accessorId must also be defined."
);
}
if (hasDraco) {
Check_default.typeOf.object("options.draco", draco);
Check_default.typeOf.string("options.attributeSemantic", attributeSemantic);
Check_default.typeOf.number("options.accessorId", accessorId);
}
this._resourceCache = resourceCache;
this._gltfResource = gltfResource;
this._baseResource = baseResource2;
this._gltf = gltf;
this._bufferViewId = bufferViewId;
this._draco = draco;
this._attributeSemantic = attributeSemantic;
this._accessorId = accessorId;
this._cacheKey = cacheKey;
this._asynchronous = asynchronous;
this._loadBuffer = loadBuffer;
this._loadTypedArray = loadTypedArray;
this._bufferViewLoader = void 0;
this._dracoLoader = void 0;
this._quantization = void 0;
this._typedArray = void 0;
this._buffer = void 0;
this._state = ResourceLoaderState_default.UNLOADED;
this._promise = void 0;
}
if (defined_default(Object.create)) {
GltfVertexBufferLoader.prototype = Object.create(ResourceLoader_default.prototype);
GltfVertexBufferLoader.prototype.constructor = GltfVertexBufferLoader;
}
Object.defineProperties(GltfVertexBufferLoader.prototype, {
/**
* The cache key of the resource.
*
* @memberof GltfVertexBufferLoader.prototype
*
* @type {string}
* @readonly
* @private
*/
cacheKey: {
get: function() {
return this._cacheKey;
}
},
/**
* The vertex buffer. This is only defined when loadAsTypedArray
is false.
*
* @memberof GltfVertexBufferLoader.prototype
*
* @type {Buffer}
* @readonly
* @private
*/
buffer: {
get: function() {
return this._buffer;
}
},
/**
* The typed array containing vertex buffer data. This is only defined when loadAsTypedArray
is true.
*
* @memberof GltfVertexBufferLoader.prototype
*
* @type {Uint8Array}
* @readonly
* @private
*/
typedArray: {
get: function() {
return this._typedArray;
}
},
/**
* Information about the quantized vertex attribute after Draco decode.
*
* @memberof GltfVertexBufferLoader.prototype
*
* @type {ModelComponents.Quantization}
* @readonly
* @private
*/
quantization: {
get: function() {
return this._quantization;
}
}
});
function hasDracoCompression(draco, semantic) {
return defined_default(draco) && defined_default(draco.attributes) && defined_default(draco.attributes[semantic]);
}
GltfVertexBufferLoader.prototype.load = async function() {
if (defined_default(this._promise)) {
return this._promise;
}
if (hasDracoCompression(this._draco, this._attributeSemantic)) {
this._promise = loadFromDraco2(this);
return this._promise;
}
this._promise = loadFromBufferView3(this);
return this._promise;
};
function getQuantizationInformation(dracoQuantization, componentDatatype, componentCount, type) {
const quantizationBits = dracoQuantization.quantizationBits;
const normalizationRange = (1 << quantizationBits) - 1;
const normalizationDivisor = 1 / normalizationRange;
const quantization = new ModelComponents_default.Quantization();
quantization.componentDatatype = componentDatatype;
quantization.octEncoded = dracoQuantization.octEncoded;
quantization.octEncodedZXY = true;
quantization.type = type;
if (quantization.octEncoded) {
quantization.type = AttributeType_default.VEC2;
quantization.normalizationRange = normalizationRange;
} else {
const MathType = AttributeType_default.getMathType(type);
if (MathType === Number) {
const dimensions = dracoQuantization.range;
quantization.quantizedVolumeOffset = dracoQuantization.minValues[0];
quantization.quantizedVolumeDimensions = dimensions;
quantization.normalizationRange = normalizationRange;
quantization.quantizedVolumeStepSize = dimensions * normalizationDivisor;
} else {
quantization.quantizedVolumeOffset = MathType.unpack(
dracoQuantization.minValues
);
quantization.normalizationRange = MathType.unpack(
new Array(componentCount).fill(normalizationRange)
);
const packedDimensions = new Array(componentCount).fill(
dracoQuantization.range
);
quantization.quantizedVolumeDimensions = MathType.unpack(
packedDimensions
);
const packedSteps = packedDimensions.map(function(dimension) {
return dimension * normalizationDivisor;
});
quantization.quantizedVolumeStepSize = MathType.unpack(packedSteps);
}
}
return quantization;
}
async function loadFromDraco2(vertexBufferLoader) {
vertexBufferLoader._state = ResourceLoaderState_default.LOADING;
const resourceCache = vertexBufferLoader._resourceCache;
try {
const dracoLoader = resourceCache.getDracoLoader({
gltf: vertexBufferLoader._gltf,
draco: vertexBufferLoader._draco,
gltfResource: vertexBufferLoader._gltfResource,
baseResource: vertexBufferLoader._baseResource
});
vertexBufferLoader._dracoLoader = dracoLoader;
await dracoLoader.load();
if (vertexBufferLoader.isDestroyed()) {
return;
}
vertexBufferLoader._state = ResourceLoaderState_default.LOADED;
return vertexBufferLoader;
} catch {
if (vertexBufferLoader.isDestroyed()) {
return;
}
handleError5(vertexBufferLoader);
}
}
function processDraco(vertexBufferLoader) {
vertexBufferLoader._state = ResourceLoaderState_default.PROCESSING;
const dracoLoader = vertexBufferLoader._dracoLoader;
const decodedVertexAttributes = dracoLoader.decodedData.vertexAttributes;
const attributeSemantic = vertexBufferLoader._attributeSemantic;
const dracoAttribute = decodedVertexAttributes[attributeSemantic];
const accessorId = vertexBufferLoader._accessorId;
const accessor = vertexBufferLoader._gltf.accessors[accessorId];
const type = accessor.type;
const typedArray = dracoAttribute.array;
const dracoQuantization = dracoAttribute.data.quantization;
if (defined_default(dracoQuantization)) {
vertexBufferLoader._quantization = getQuantizationInformation(
dracoQuantization,
dracoAttribute.data.componentDatatype,
dracoAttribute.data.componentsPerAttribute,
type
);
}
vertexBufferLoader._typedArray = new Uint8Array(
typedArray.buffer,
typedArray.byteOffset,
typedArray.byteLength
);
}
async function loadFromBufferView3(vertexBufferLoader) {
vertexBufferLoader._state = ResourceLoaderState_default.LOADING;
const resourceCache = vertexBufferLoader._resourceCache;
try {
const bufferViewLoader = resourceCache.getBufferViewLoader({
gltf: vertexBufferLoader._gltf,
bufferViewId: vertexBufferLoader._bufferViewId,
gltfResource: vertexBufferLoader._gltfResource,
baseResource: vertexBufferLoader._baseResource
});
vertexBufferLoader._bufferViewLoader = bufferViewLoader;
await bufferViewLoader.load();
if (vertexBufferLoader.isDestroyed()) {
return;
}
vertexBufferLoader._typedArray = bufferViewLoader.typedArray;
vertexBufferLoader._state = ResourceLoaderState_default.PROCESSING;
return vertexBufferLoader;
} catch (error) {
if (vertexBufferLoader.isDestroyed()) {
return;
}
handleError5(vertexBufferLoader, error);
}
}
function handleError5(vertexBufferLoader, error) {
vertexBufferLoader.unload();
vertexBufferLoader._state = ResourceLoaderState_default.FAILED;
const errorMessage = "Failed to load vertex buffer";
throw vertexBufferLoader.getError(errorMessage, error);
}
function CreateVertexBufferJob() {
this.typedArray = void 0;
this.context = void 0;
this.buffer = void 0;
}
CreateVertexBufferJob.prototype.set = function(typedArray, context) {
this.typedArray = typedArray;
this.context = context;
};
CreateVertexBufferJob.prototype.execute = function() {
this.buffer = createVertexBuffer(this.typedArray, this.context);
};
function createVertexBuffer(typedArray, context) {
const buffer = Buffer_default.createVertexBuffer({
typedArray,
context,
usage: BufferUsage_default.STATIC_DRAW
});
buffer.vertexArrayDestroyable = false;
return buffer;
}
var scratchVertexBufferJob = new CreateVertexBufferJob();
GltfVertexBufferLoader.prototype.process = function(frameState) {
Check_default.typeOf.object("frameState", frameState);
if (this._state === ResourceLoaderState_default.READY) {
return true;
}
if (this._state !== ResourceLoaderState_default.LOADED && this._state !== ResourceLoaderState_default.PROCESSING) {
return false;
}
if (defined_default(this._dracoLoader)) {
try {
const ready = this._dracoLoader.process(frameState);
if (!ready) {
return false;
}
} catch (error) {
handleError5(this, error);
}
processDraco(this);
}
let buffer;
const typedArray = this._typedArray;
if (this._loadBuffer && this._asynchronous) {
const vertexBufferJob = scratchVertexBufferJob;
vertexBufferJob.set(typedArray, frameState.context);
const jobScheduler = frameState.jobScheduler;
if (!jobScheduler.execute(vertexBufferJob, JobType_default.BUFFER)) {
return false;
}
buffer = vertexBufferJob.buffer;
} else if (this._loadBuffer) {
buffer = createVertexBuffer(typedArray, frameState.context);
}
this.unload();
this._buffer = buffer;
this._typedArray = this._loadTypedArray ? typedArray : void 0;
this._state = ResourceLoaderState_default.READY;
this._resourceCache.statistics.addGeometryLoader(this);
return true;
};
GltfVertexBufferLoader.prototype.unload = function() {
if (defined_default(this._buffer)) {
this._buffer.destroy();
}
const resourceCache = this._resourceCache;
if (defined_default(this._bufferViewLoader) && !this._bufferViewLoader.isDestroyed()) {
resourceCache.unload(this._bufferViewLoader);
}
if (defined_default(this._dracoLoader)) {
resourceCache.unload(this._dracoLoader);
}
this._bufferViewLoader = void 0;
this._dracoLoader = void 0;
this._typedArray = void 0;
this._buffer = void 0;
this._gltf = void 0;
};
var GltfVertexBufferLoader_default = GltfVertexBufferLoader;
// packages/engine/Source/Scene/MetadataClass.js
function MetadataClass(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const id = options.id;
Check_default.typeOf.string("options.id", id);
const properties = defaultValue_default(options.properties, {});
const propertiesBySemantic = {};
for (const propertyId in properties) {
if (properties.hasOwnProperty(propertyId)) {
const property = properties[propertyId];
if (defined_default(property.semantic)) {
propertiesBySemantic[property.semantic] = property;
}
}
}
this._id = id;
this._name = options.name;
this._description = options.description;
this._properties = properties;
this._propertiesBySemantic = propertiesBySemantic;
this._extras = clone_default(options.extras, true);
this._extensions = clone_default(options.extensions, true);
}
MetadataClass.fromJson = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const id = options.id;
const classDefinition = options.class;
Check_default.typeOf.string("options.id", id);
Check_default.typeOf.object("options.class", classDefinition);
const properties = {};
for (const propertyId in classDefinition.properties) {
if (classDefinition.properties.hasOwnProperty(propertyId)) {
const property = MetadataClassProperty_default.fromJson({
id: propertyId,
property: classDefinition.properties[propertyId],
enums: options.enums
});
properties[propertyId] = property;
}
}
return new MetadataClass({
id,
name: classDefinition.name,
description: classDefinition.description,
properties,
extras: classDefinition.extras,
extensions: classDefinition.extensions
});
};
Object.defineProperties(MetadataClass.prototype, {
/**
* The class properties.
*
* @memberof MetadataClass.prototype
* @type {Object3DTILES_metadata
extension is used,
* this property stores a {@link MetadataTable} instance for the tiles in the subtree.
*
* @type {MetadataTable}
* @readonly
* @private
*/
tileMetadataTable: {
get: function() {
return this._tileMetadataTable;
}
},
/**
* When tile metadata is present (3D Tiles 1.1) or the 3DTILES_metadata
extension is used,
* this property stores the JSON from the extension. This is used by {@link TileMetadata}
* to get the extras and extensions for the tiles in the subtree.
*
* @type {object}
* @readonly
* @private
*/
tilePropertyTableJson: {
get: function() {
return this._tilePropertyTableJson;
}
},
/**
* When content metadata is present (3D Tiles 1.1), this property stores
* an array of {@link MetadataTable} instances for the contents in the subtree.
*
* @type {Array}
* @readonly
* @private
*/
contentMetadataTables: {
get: function() {
return this._contentMetadataTables;
}
},
/**
* When content metadata is present (3D Tiles 1.1), this property
* an array of the JSONs from the extension. This is used to get the extras
* and extensions for the contents in the subtree.
*
* @type {Array}
* @readonly
* @private
*/
contentPropertyTableJsons: {
get: function() {
return this._contentPropertyTableJsons;
}
},
/**
* Gets the implicit tile coordinates for the root of the subtree.
*
* @type {ImplicitTileCoordinates}
* @readonly
* @private
*/
implicitCoordinates: {
get: function() {
return this._implicitCoordinates;
}
}
});
ImplicitSubtree.prototype.tileIsAvailableAtIndex = function(index) {
return this._tileAvailability.getBit(index);
};
ImplicitSubtree.prototype.tileIsAvailableAtCoordinates = function(implicitCoordinates) {
const index = this.getTileIndex(implicitCoordinates);
return this.tileIsAvailableAtIndex(index);
};
ImplicitSubtree.prototype.contentIsAvailableAtIndex = function(index, contentIndex) {
contentIndex = defaultValue_default(contentIndex, 0);
if (contentIndex < 0 || contentIndex >= this._contentAvailabilityBitstreams.length) {
throw new DeveloperError_default("contentIndex out of bounds.");
}
return this._contentAvailabilityBitstreams[contentIndex].getBit(index);
};
ImplicitSubtree.prototype.contentIsAvailableAtCoordinates = function(implicitCoordinates, contentIndex) {
const index = this.getTileIndex(implicitCoordinates);
return this.contentIsAvailableAtIndex(index, contentIndex);
};
ImplicitSubtree.prototype.childSubtreeIsAvailableAtIndex = function(index) {
return this._childSubtreeAvailability.getBit(index);
};
ImplicitSubtree.prototype.childSubtreeIsAvailableAtCoordinates = function(implicitCoordinates) {
const index = this.getChildSubtreeIndex(implicitCoordinates);
return this.childSubtreeIsAvailableAtIndex(index);
};
ImplicitSubtree.prototype.getLevelOffset = function(level) {
const branchingFactor = this._branchingFactor;
return (Math.pow(branchingFactor, level) - 1) / (branchingFactor - 1);
};
ImplicitSubtree.prototype.getParentMortonIndex = function(mortonIndex) {
let bitsPerLevel = 2;
if (this._subdivisionScheme === ImplicitSubdivisionScheme_default.OCTREE) {
bitsPerLevel = 3;
}
return mortonIndex >> bitsPerLevel;
};
ImplicitSubtree.fromSubtreeJson = async function(resource, json, subtreeView, implicitTileset, implicitCoordinates) {
Check_default.typeOf.object("resource", resource);
if (defined_default(json) === defined_default(subtreeView)) {
throw new DeveloperError_default("One of json and subtreeView must be defined.");
}
Check_default.typeOf.object("implicitTileset", implicitTileset);
Check_default.typeOf.object("implicitCoordinates", implicitCoordinates);
const subtree = new ImplicitSubtree(
resource,
implicitTileset,
implicitCoordinates
);
let chunks;
if (defined_default(json)) {
chunks = {
json,
binary: void 0
};
} else {
chunks = parseSubtreeChunks(subtreeView);
}
const subtreeJson = chunks.json;
subtree._subtreeJson = subtreeJson;
let tilePropertyTableJson;
if (hasExtension_default(subtreeJson, "3DTILES_metadata")) {
tilePropertyTableJson = subtreeJson.extensions["3DTILES_metadata"];
} else if (defined_default(subtreeJson.tileMetadata)) {
const propertyTableIndex = subtreeJson.tileMetadata;
tilePropertyTableJson = subtreeJson.propertyTables[propertyTableIndex];
}
const contentPropertyTableJsons = [];
if (defined_default(subtreeJson.contentMetadata)) {
const length3 = subtreeJson.contentMetadata.length;
for (let i = 0; i < length3; i++) {
const propertyTableIndex = subtreeJson.contentMetadata[i];
contentPropertyTableJsons.push(
subtreeJson.propertyTables[propertyTableIndex]
);
}
}
let metadata;
const schema = implicitTileset.metadataSchema;
const subtreeMetadata = subtreeJson.subtreeMetadata;
if (defined_default(subtreeMetadata)) {
const metadataClass = subtreeMetadata.class;
const subtreeMetadataClass = schema.classes[metadataClass];
metadata = new ImplicitSubtreeMetadata_default({
subtreeMetadata,
class: subtreeMetadataClass
});
}
subtree._metadata = metadata;
subtree._tilePropertyTableJson = tilePropertyTableJson;
subtree._contentPropertyTableJsons = contentPropertyTableJsons;
const defaultContentAvailability = {
constant: 0
};
subtreeJson.contentAvailabilityHeaders = [];
if (hasExtension_default(subtreeJson, "3DTILES_multiple_contents")) {
subtreeJson.contentAvailabilityHeaders = subtreeJson.extensions["3DTILES_multiple_contents"].contentAvailability;
} else if (Array.isArray(subtreeJson.contentAvailability)) {
subtreeJson.contentAvailabilityHeaders = subtreeJson.contentAvailability;
} else {
subtreeJson.contentAvailabilityHeaders.push(
defaultValue_default(subtreeJson.contentAvailability, defaultContentAvailability)
);
}
const bufferHeaders = preprocessBuffers(subtreeJson.buffers);
const bufferViewHeaders = preprocessBufferViews(
subtreeJson.bufferViews,
bufferHeaders
);
markActiveBufferViews(subtreeJson, bufferViewHeaders);
if (defined_default(tilePropertyTableJson)) {
markActiveMetadataBufferViews(tilePropertyTableJson, bufferViewHeaders);
}
for (let i = 0; i < contentPropertyTableJsons.length; i++) {
const contentPropertyTableJson = contentPropertyTableJsons[i];
markActiveMetadataBufferViews(contentPropertyTableJson, bufferViewHeaders);
}
const buffersU8 = await requestActiveBuffers(
subtree,
bufferHeaders,
chunks.binary
);
const bufferViewsU8 = parseActiveBufferViews(bufferViewHeaders, buffersU8);
parseAvailability(subtree, subtreeJson, implicitTileset, bufferViewsU8);
if (defined_default(tilePropertyTableJson)) {
parseTileMetadataTable(subtree, implicitTileset, bufferViewsU8);
makeTileJumpBuffer(subtree);
}
parseContentMetadataTables(subtree, implicitTileset, bufferViewsU8);
makeContentJumpBuffers(subtree);
subtree._ready = true;
return subtree;
};
function parseSubtreeChunks(subtreeView) {
const littleEndian2 = true;
const subtreeReader = new DataView(
subtreeView.buffer,
subtreeView.byteOffset
);
let byteOffset = 8;
const jsonByteLength = subtreeReader.getUint32(byteOffset, littleEndian2);
byteOffset += 8;
const binaryByteLength = subtreeReader.getUint32(byteOffset, littleEndian2);
byteOffset += 8;
const subtreeJson = getJsonFromTypedArray_default(
subtreeView,
byteOffset,
jsonByteLength
);
byteOffset += jsonByteLength;
const subtreeBinary = subtreeView.subarray(
byteOffset,
byteOffset + binaryByteLength
);
return {
json: subtreeJson,
binary: subtreeBinary
};
}
function preprocessBuffers(bufferHeaders) {
bufferHeaders = defined_default(bufferHeaders) ? bufferHeaders : [];
for (let i = 0; i < bufferHeaders.length; i++) {
const bufferHeader = bufferHeaders[i];
bufferHeader.isExternal = defined_default(bufferHeader.uri);
bufferHeader.isActive = false;
}
return bufferHeaders;
}
function preprocessBufferViews(bufferViewHeaders, bufferHeaders) {
bufferViewHeaders = defined_default(bufferViewHeaders) ? bufferViewHeaders : [];
for (let i = 0; i < bufferViewHeaders.length; i++) {
const bufferViewHeader = bufferViewHeaders[i];
const bufferHeader = bufferHeaders[bufferViewHeader.buffer];
bufferViewHeader.bufferHeader = bufferHeader;
bufferViewHeader.isActive = false;
}
return bufferViewHeaders;
}
function markActiveBufferViews(subtreeJson, bufferViewHeaders) {
let header;
const tileAvailabilityHeader = subtreeJson.tileAvailability;
if (defined_default(tileAvailabilityHeader.bitstream)) {
header = bufferViewHeaders[tileAvailabilityHeader.bitstream];
} else if (defined_default(tileAvailabilityHeader.bufferView)) {
header = bufferViewHeaders[tileAvailabilityHeader.bufferView];
}
if (defined_default(header)) {
header.isActive = true;
header.bufferHeader.isActive = true;
}
const contentAvailabilityHeaders = subtreeJson.contentAvailabilityHeaders;
for (let i = 0; i < contentAvailabilityHeaders.length; i++) {
header = void 0;
if (defined_default(contentAvailabilityHeaders[i].bitstream)) {
header = bufferViewHeaders[contentAvailabilityHeaders[i].bitstream];
} else if (defined_default(contentAvailabilityHeaders[i].bufferView)) {
header = bufferViewHeaders[contentAvailabilityHeaders[i].bufferView];
}
if (defined_default(header)) {
header.isActive = true;
header.bufferHeader.isActive = true;
}
}
header = void 0;
const childSubtreeAvailabilityHeader = subtreeJson.childSubtreeAvailability;
if (defined_default(childSubtreeAvailabilityHeader.bitstream)) {
header = bufferViewHeaders[childSubtreeAvailabilityHeader.bitstream];
} else if (defined_default(childSubtreeAvailabilityHeader.bufferView)) {
header = bufferViewHeaders[childSubtreeAvailabilityHeader.bufferView];
}
if (defined_default(header)) {
header.isActive = true;
header.bufferHeader.isActive = true;
}
}
function markActiveMetadataBufferViews(propertyTableJson, bufferViewHeaders) {
const properties = propertyTableJson.properties;
let header;
for (const key in properties) {
if (properties.hasOwnProperty(key)) {
const metadataHeader = properties[key];
const valuesBufferView = defaultValue_default(
metadataHeader.values,
metadataHeader.bufferView
);
header = bufferViewHeaders[valuesBufferView];
header.isActive = true;
header.bufferHeader.isActive = true;
const stringOffsetBufferView = defaultValue_default(
metadataHeader.stringOffsets,
metadataHeader.stringOffsetBufferView
);
if (defined_default(stringOffsetBufferView)) {
header = bufferViewHeaders[stringOffsetBufferView];
header.isActive = true;
header.bufferHeader.isActive = true;
}
const arrayOffsetBufferView = defaultValue_default(
metadataHeader.arrayOffsets,
metadataHeader.arrayOffsetBufferView
);
if (defined_default(arrayOffsetBufferView)) {
header = bufferViewHeaders[arrayOffsetBufferView];
header.isActive = true;
header.bufferHeader.isActive = true;
}
}
}
}
function requestActiveBuffers(subtree, bufferHeaders, internalBuffer) {
const promises = [];
for (let i = 0; i < bufferHeaders.length; i++) {
const bufferHeader = bufferHeaders[i];
if (!bufferHeader.isActive) {
promises.push(Promise.resolve(void 0));
} else if (bufferHeader.isExternal) {
const promise = requestExternalBuffer(subtree, bufferHeader);
promises.push(promise);
} else {
promises.push(Promise.resolve(internalBuffer));
}
}
return Promise.all(promises).then(function(bufferResults) {
const buffersU8 = {};
for (let i = 0; i < bufferResults.length; i++) {
const result = bufferResults[i];
if (defined_default(result)) {
buffersU8[i] = result;
}
}
return buffersU8;
});
}
async function requestExternalBuffer(subtree, bufferHeader) {
const baseResource2 = subtree._resource;
const bufferResource = baseResource2.getDerivedResource({
url: bufferHeader.uri
});
const bufferLoader = ResourceCache_default.getExternalBufferLoader({
resource: bufferResource
});
subtree._bufferLoader = bufferLoader;
try {
await bufferLoader.load();
} catch (error) {
if (bufferLoader.isDestroyed()) {
return;
}
throw error;
}
return bufferLoader.typedArray;
}
function parseActiveBufferViews(bufferViewHeaders, buffersU8) {
const bufferViewsU8 = {};
for (let i = 0; i < bufferViewHeaders.length; i++) {
const bufferViewHeader = bufferViewHeaders[i];
if (!bufferViewHeader.isActive) {
continue;
}
const start = bufferViewHeader.byteOffset;
const end = start + bufferViewHeader.byteLength;
const buffer = buffersU8[bufferViewHeader.buffer];
const bufferView = buffer.subarray(start, end);
bufferViewsU8[i] = bufferView;
}
return bufferViewsU8;
}
function parseAvailability(subtree, subtreeJson, implicitTileset, bufferViewsU8) {
const branchingFactor = implicitTileset.branchingFactor;
const subtreeLevels = implicitTileset.subtreeLevels;
const tileAvailabilityBits = (Math.pow(branchingFactor, subtreeLevels) - 1) / (branchingFactor - 1);
const childSubtreeBits = Math.pow(branchingFactor, subtreeLevels);
const hasMetadataExtension = hasExtension_default(subtreeJson, "3DTILES_metadata");
const hasTileMetadata = defined_default(subtree._tilePropertyTableJson);
let computeAvailableCountEnabled = hasMetadataExtension || hasTileMetadata;
subtree._tileAvailability = parseAvailabilityBitstream(
subtreeJson.tileAvailability,
bufferViewsU8,
tileAvailabilityBits,
computeAvailableCountEnabled
);
const hasContentMetadata = subtree._contentPropertyTableJsons.length > 0;
computeAvailableCountEnabled = computeAvailableCountEnabled || hasContentMetadata;
for (let i = 0; i < subtreeJson.contentAvailabilityHeaders.length; i++) {
const bitstream = parseAvailabilityBitstream(
subtreeJson.contentAvailabilityHeaders[i],
bufferViewsU8,
// content availability has the same length as tile availability.
tileAvailabilityBits,
computeAvailableCountEnabled
);
subtree._contentAvailabilityBitstreams.push(bitstream);
}
subtree._childSubtreeAvailability = parseAvailabilityBitstream(
subtreeJson.childSubtreeAvailability,
bufferViewsU8,
childSubtreeBits
);
}
function parseAvailabilityBitstream(availabilityJson, bufferViewsU8, lengthBits, computeAvailableCountEnabled) {
if (defined_default(availabilityJson.constant)) {
return new ImplicitAvailabilityBitstream_default({
constant: Boolean(availabilityJson.constant),
lengthBits,
availableCount: availabilityJson.availableCount
});
}
let bufferView;
if (defined_default(availabilityJson.bitstream)) {
bufferView = bufferViewsU8[availabilityJson.bitstream];
} else if (defined_default(availabilityJson.bufferView)) {
bufferView = bufferViewsU8[availabilityJson.bufferView];
}
return new ImplicitAvailabilityBitstream_default({
bitstream: bufferView,
lengthBits,
availableCount: availabilityJson.availableCount,
computeAvailableCountEnabled
});
}
function parseTileMetadataTable(subtree, implicitTileset, bufferViewsU8) {
const tilePropertyTableJson = subtree._tilePropertyTableJson;
const tileCount = subtree._tileAvailability.availableCount;
const metadataSchema = implicitTileset.metadataSchema;
const tileMetadataClassName = tilePropertyTableJson.class;
const tileMetadataClass = metadataSchema.classes[tileMetadataClassName];
subtree._tileMetadataTable = new MetadataTable_default({
class: tileMetadataClass,
count: tileCount,
properties: tilePropertyTableJson.properties,
bufferViews: bufferViewsU8
});
}
function parseContentMetadataTables(subtree, implicitTileset, bufferViewsU8) {
const contentPropertyTableJsons = subtree._contentPropertyTableJsons;
const contentAvailabilityBitstreams = subtree._contentAvailabilityBitstreams;
const metadataSchema = implicitTileset.metadataSchema;
const contentMetadataTables = subtree._contentMetadataTables;
for (let i = 0; i < contentPropertyTableJsons.length; i++) {
const contentPropertyTableJson = contentPropertyTableJsons[i];
const contentAvailabilityBitsteam = contentAvailabilityBitstreams[i];
const contentCount = contentAvailabilityBitsteam.availableCount;
const contentMetadataClassName = contentPropertyTableJson.class;
const contentMetadataClass = metadataSchema.classes[contentMetadataClassName];
const metadataTable = new MetadataTable_default({
class: contentMetadataClass,
count: contentCount,
properties: contentPropertyTableJson.properties,
bufferViews: bufferViewsU8
});
contentMetadataTables.push(metadataTable);
}
}
function makeJumpBuffer(availability) {
let entityId = 0;
const bufferLength = availability.lengthBits;
const availableCount = availability.availableCount;
let jumpBuffer;
if (availableCount < 256) {
jumpBuffer = new Uint8Array(bufferLength);
} else if (availableCount < 65536) {
jumpBuffer = new Uint16Array(bufferLength);
} else {
jumpBuffer = new Uint32Array(bufferLength);
}
for (let i = 0; i < availability.lengthBits; i++) {
if (availability.getBit(i)) {
jumpBuffer[i] = entityId;
entityId++;
}
}
return jumpBuffer;
}
function makeTileJumpBuffer(subtree) {
const tileJumpBuffer = makeJumpBuffer(subtree._tileAvailability);
subtree._tileJumpBuffer = tileJumpBuffer;
}
function makeContentJumpBuffers(subtree) {
const contentJumpBuffers = subtree._contentJumpBuffers;
const contentAvailabilityBitstreams = subtree._contentAvailabilityBitstreams;
for (let i = 0; i < contentAvailabilityBitstreams.length; i++) {
const contentAvailability = contentAvailabilityBitstreams[i];
const contentJumpBuffer = makeJumpBuffer(contentAvailability);
contentJumpBuffers.push(contentJumpBuffer);
}
}
ImplicitSubtree.prototype.getTileIndex = function(implicitCoordinates) {
const localLevel = implicitCoordinates.level - this._implicitCoordinates.level;
if (localLevel < 0 || this._subtreeLevels <= localLevel) {
throw new RuntimeError_default("level is out of bounds for this subtree");
}
const subtreeCoordinates = implicitCoordinates.getSubtreeCoordinates();
const offsetCoordinates = subtreeCoordinates.getOffsetCoordinates(
implicitCoordinates
);
const index = offsetCoordinates.tileIndex;
return index;
};
ImplicitSubtree.prototype.getChildSubtreeIndex = function(implicitCoordinates) {
const localLevel = implicitCoordinates.level - this._implicitCoordinates.level;
if (localLevel !== this._implicitCoordinates.subtreeLevels) {
throw new RuntimeError_default("level is out of bounds for this subtree");
}
const parentSubtreeCoordinates = implicitCoordinates.getParentSubtreeCoordinates();
const offsetCoordinates = parentSubtreeCoordinates.getOffsetCoordinates(
implicitCoordinates
);
const index = offsetCoordinates.mortonIndex;
return index;
};
function getTileEntityId(subtree, implicitCoordinates) {
if (!defined_default(subtree._tileMetadataTable)) {
return void 0;
}
const tileIndex = subtree.getTileIndex(implicitCoordinates);
if (subtree._tileAvailability.getBit(tileIndex)) {
return subtree._tileJumpBuffer[tileIndex];
}
return void 0;
}
function getContentEntityId(subtree, implicitCoordinates, contentIndex) {
const metadataTables = subtree._contentMetadataTables;
if (!defined_default(metadataTables)) {
return void 0;
}
const metadataTable = metadataTables[contentIndex];
if (!defined_default(metadataTable)) {
return void 0;
}
const availability = subtree._contentAvailabilityBitstreams[contentIndex];
const tileIndex = subtree.getTileIndex(implicitCoordinates);
if (availability.getBit(tileIndex)) {
const contentJumpBuffer = subtree._contentJumpBuffers[contentIndex];
return contentJumpBuffer[tileIndex];
}
return void 0;
}
ImplicitSubtree.prototype.getTileMetadataView = function(implicitCoordinates) {
const entityId = getTileEntityId(this, implicitCoordinates);
if (!defined_default(entityId)) {
return void 0;
}
const metadataTable = this._tileMetadataTable;
return new ImplicitMetadataView_default({
class: metadataTable.class,
metadataTable,
entityId,
propertyTableJson: this._tilePropertyTableJson
});
};
ImplicitSubtree.prototype.getContentMetadataView = function(implicitCoordinates, contentIndex) {
const entityId = getContentEntityId(this, implicitCoordinates, contentIndex);
if (!defined_default(entityId)) {
return void 0;
}
const metadataTable = this._contentMetadataTables[contentIndex];
const propertyTableJson = this._contentPropertyTableJsons[contentIndex];
return new ImplicitMetadataView_default({
class: metadataTable.class,
metadataTable,
entityId,
contentIndex,
propertyTableJson
});
};
ImplicitSubtree.prototype.isDestroyed = function() {
return false;
};
ImplicitSubtree.prototype.destroy = function() {
if (defined_default(this._bufferLoader)) {
ResourceCache_default.unload(this._bufferLoader);
}
return destroyObject_default(this);
};
var ImplicitSubtree_default = ImplicitSubtree;
// packages/engine/Source/Scene/MetadataSemantic.js
var MetadataSemantic = {
/**
* A unique identifier, stored as a STRING
.
*
* @type {string}
* @constant
* @private
*/
ID: "ID",
/**
* A name, stored as a STRING
. This does not have to be unique.
*
* @type {string}
* @constant
* @private
*/
NAME: "NAME",
/**
* A description, stored as a STRING
.
*
* @type {string}
* @constant
* @private
*/
DESCRIPTION: "DESCRIPTION",
/**
* The number of tiles in a tileset, stored as a UINT64
.
*
* @type {string}
* @constant
* @private
*/
TILESET_TILE_COUNT: "TILESET_TILE_COUNT",
/**
* A bounding box for a tile, stored as an array of 12 FLOAT32
or FLOAT64
components. The components are the same format as for boundingVolume.box
in 3D Tiles 1.0. This semantic is used to provide a tighter bounding volume than the one implicitly calculated in implicit tiling.
*
* @type {string}
* @constant
* @private
*/
TILE_BOUNDING_BOX: "TILE_BOUNDING_BOX",
/**
* A bounding region for a tile, stored as an array of 6 FLOAT64
components. The components are [west, south, east, north, minimumHeight, maximumHeight]
. This semantic is used to provide a tighter bounding volume than the one implicitly calculated in implicit tiling.
*
* @type {string}
* @constant
* @private
*/
TILE_BOUNDING_REGION: "TILE_BOUNDING_REGION",
/**
* A bounding sphere for a tile, stored as an array of 4 FLOAT32
or FLOAT64
components. The components are [centerX, centerY, centerZ, radius]
. This semantic is used to provide a tighter bounding volume than the one implicitly calculated in implicit tiling.
*
* @type {string}
* @constant
* @private
*/
TILE_BOUNDING_SPHERE: "TILE_BOUNDING_SPHERE",
/**
* The minimum height of a tile above (or below) the WGS84 ellipsoid, stored as a FLOAT32
or a FLOAT64
. This semantic is used to tighten bounding regions implicitly calculated in implicit tiling.
*
* @type {string}
* @constant
* @private
*/
TILE_MINIMUM_HEIGHT: "TILE_MINIMUM_HEIGHT",
/**
* The maximum height of a tile above (or below) the WGS84 ellipsoid, stored as a FLOAT32
or a FLOAT64
. This semantic is used to tighten bounding regions implicitly calculated in implicit tiling.
*
* @type {string}
* @constant
* @private
*/
TILE_MAXIMUM_HEIGHT: "TILE_MAXIMUM_HEIGHT",
/**
* The horizon occlusion point for a tile, stored as an VEC3
of FLOAT32
or FLOAT64
components.
*
* @see {@link https://cesium.com/blog/2013/04/25/horizon-culling/|Horizon Culling}
*
* @type {string}
* @constant
* @private
*/
TILE_HORIZON_OCCLUSION_POINT: "TILE_HORIZON_OCCLUSION_POINT",
/**
* The geometric error for a tile, stored as a FLOAT32
or a FLOAT64
. This semantic is used to override the geometric error implicitly calculated in implicit tiling.
*
* @type {string}
* @constant
* @private
*/
TILE_GEOMETRIC_ERROR: "TILE_GEOMETRIC_ERROR",
/**
* A bounding box for the content of a tile, stored as an array of 12 FLOAT32
or FLOAT64
components. The components are the same format as for boundingVolume.box
in 3D Tiles 1.0. This semantic is used to provide a tighter bounding volume than the one implicitly calculated in implicit tiling.
*
* @type {string}
* @constant
* @private
*/
CONTENT_BOUNDING_BOX: "CONTENT_BOUNDING_BOX",
/**
* A bounding region for the content of a tile, stored as an array of 6 FLOAT64
components. The components are [west, south, east, north, minimumHeight, maximumHeight]
. This semantic is used to provide a tighter bounding volume than the one implicitly calculated in implicit tiling.
*
* @type {string}
* @constant
* @private
*/
CONTENT_BOUNDING_REGION: "CONTENT_BOUNDING_REGION",
/**
* A bounding sphere for the content of a tile, stored as an array of 4 FLOAT32
or FLOAT64
components. The components are [centerX, centerY, centerZ, radius]
. This semantic is used to provide a tighter bounding volume than the one implicitly calculated in implicit tiling.
*
* @type {string}
* @constant
* @private
*/
CONTENT_BOUNDING_SPHERE: "CONTENT_BOUNDING_SPHERE",
/**
* The minimum height of the content of a tile above (or below) the WGS84 ellipsoid, stored as a FLOAT32
or a FLOAT64
*
* @type {string}
* @constant
* @private
*/
CONTENT_MINIMUM_HEIGHT: "CONTENT_MINIMUM_HEIGHT",
/**
* The maximum height of the content of a tile above (or below) the WGS84 ellipsoid, stored as a FLOAT32
or a FLOAT64
*
* @type {string}
* @constant
* @private
*/
CONTENT_MAXIMUM_HEIGHT: "CONTENT_MAXIMUM_HEIGHT",
/**
* The horizon occlusion point for the content of a tile, stored as an VEC3
of FLOAT32
or FLOAT64
components.
*
* @see {@link https://cesium.com/blog/2013/04/25/horizon-culling/|Horizon Culling}
*
* @type {string}
* @constant
* @private
*/
CONTENT_HORIZON_OCCLUSION_POINT: "CONTENT_HORIZON_OCCLUSION_POINT"
};
var MetadataSemantic_default = Object.freeze(MetadataSemantic);
// packages/engine/Source/Scene/parseBoundingVolumeSemantics.js
function parseBoundingVolumeSemantics(tileMetadata) {
Check_default.typeOf.object("tileMetadata", tileMetadata);
return {
tile: {
boundingVolume: parseBoundingVolume("TILE", tileMetadata),
minimumHeight: parseMinimumHeight("TILE", tileMetadata),
maximumHeight: parseMaximumHeight("TILE", tileMetadata)
},
content: {
boundingVolume: parseBoundingVolume("CONTENT", tileMetadata),
minimumHeight: parseMinimumHeight("CONTENT", tileMetadata),
maximumHeight: parseMaximumHeight("CONTENT", tileMetadata)
}
};
}
function parseBoundingVolume(prefix, tileMetadata) {
const boundingBoxSemantic = `${prefix}_BOUNDING_BOX`;
const boundingBox = tileMetadata.getPropertyBySemantic(boundingBoxSemantic);
if (defined_default(boundingBox)) {
return {
box: boundingBox
};
}
const boundingRegionSemantic = `${prefix}_BOUNDING_REGION`;
const boundingRegion = tileMetadata.getPropertyBySemantic(
boundingRegionSemantic
);
if (defined_default(boundingRegion)) {
return {
region: boundingRegion
};
}
const boundingSphereSemantic = `${prefix}_BOUNDING_SPHERE`;
const boundingSphere = tileMetadata.getPropertyBySemantic(
boundingSphereSemantic
);
if (defined_default(boundingSphere)) {
return {
sphere: boundingSphere
};
}
return void 0;
}
function parseMinimumHeight(prefix, tileMetadata) {
const minimumHeightSemantic = `${prefix}_MINIMUM_HEIGHT`;
return tileMetadata.getPropertyBySemantic(minimumHeightSemantic);
}
function parseMaximumHeight(prefix, tileMetadata) {
const maximumHeightSemantic = `${prefix}_MAXIMUM_HEIGHT`;
return tileMetadata.getPropertyBySemantic(maximumHeightSemantic);
}
var parseBoundingVolumeSemantics_default = parseBoundingVolumeSemantics;
// packages/engine/Source/Scene/Implicit3DTileContent.js
function Implicit3DTileContent(tileset, tile, resource) {
Check_default.defined("tile.implicitTileset", tile.implicitTileset);
Check_default.defined("tile.implicitCoordinates", tile.implicitCoordinates);
const implicitTileset = tile.implicitTileset;
const implicitCoordinates = tile.implicitCoordinates;
this._implicitTileset = implicitTileset;
this._implicitCoordinates = implicitCoordinates;
this._implicitSubtree = void 0;
this._tileset = tileset;
this._tile = tile;
this._resource = resource;
this._metadata = void 0;
this.featurePropertiesDirty = false;
this._group = void 0;
const templateValues = implicitCoordinates.getTemplateValues();
const subtreeResource = implicitTileset.subtreeUriTemplate.getDerivedResource(
{
templateValues
}
);
this._url = subtreeResource.getUrlComponent(true);
this._ready = false;
this._readyPromise = void 0;
}
Object.defineProperties(Implicit3DTileContent.prototype, {
featuresLength: {
get: function() {
return 0;
}
},
pointsLength: {
get: function() {
return 0;
}
},
trianglesLength: {
get: function() {
return 0;
}
},
geometryByteLength: {
get: function() {
return 0;
}
},
texturesByteLength: {
get: function() {
return 0;
}
},
batchTableByteLength: {
get: function() {
return 0;
}
},
innerContents: {
get: function() {
return void 0;
}
},
/**
* Returns true when the tile's content is ready to render; otherwise false
*
* @memberof Implicit3DTileContent.prototype
*
* @type {boolean}
* @readonly
* @private
*/
ready: {
get: function() {
return this._ready;
}
},
/**
* Gets the promise that will be resolved when the tile's content is ready to render.
*
* @memberof Implicit3DTileContent.prototype
*
* @type {PromiseImplicit3DTileContent
* always returns undefined
. Only transcoded tiles have content metadata.
* @memberof Implicit3DTileContent.prototype
* @private
*/
metadata: {
get: function() {
return void 0;
},
set: function() {
throw new DeveloperError_default("Implicit3DTileContent cannot have metadata");
}
},
batchTable: {
get: function() {
return void 0;
}
},
group: {
get: function() {
return this._group;
},
set: function(value) {
this._group = value;
}
}
});
Implicit3DTileContent.fromSubtreeJson = async function(tileset, tile, resource, json, arrayBuffer, byteOffset) {
Check_default.defined("tile.implicitTileset", tile.implicitTileset);
Check_default.defined("tile.implicitCoordinates", tile.implicitCoordinates);
if (defined_default(json) === defined_default(arrayBuffer)) {
throw new DeveloperError_default("One of json and arrayBuffer must be defined.");
}
byteOffset = defaultValue_default(byteOffset, 0);
let uint8Array;
if (defined_default(arrayBuffer)) {
uint8Array = new Uint8Array(arrayBuffer, byteOffset);
}
const implicitTileset = tile.implicitTileset;
const implicitCoordinates = tile.implicitCoordinates;
const subtree = await ImplicitSubtree_default.fromSubtreeJson(
resource,
json,
uint8Array,
implicitTileset,
implicitCoordinates
);
const content = new Implicit3DTileContent(tileset, tile, resource);
content._implicitSubtree = subtree;
expandSubtree(content, subtree);
content._ready = true;
content._readyPromise = Promise.resolve(content);
return content;
};
function expandSubtree(content, subtree) {
const placeholderTile = content._tile;
const childIndex = content._implicitCoordinates.childIndex;
const results = transcodeSubtreeTiles(
content,
subtree,
placeholderTile,
childIndex
);
const statistics2 = content._tileset.statistics;
placeholderTile.children.push(results.rootTile);
statistics2.numberOfTilesTotal++;
const childSubtrees = listChildSubtrees(content, subtree, results.bottomRow);
for (let i = 0; i < childSubtrees.length; i++) {
const subtreeLocator = childSubtrees[i];
const leafTile = subtreeLocator.tile;
const implicitChildTile = makePlaceholderChildSubtree(
content,
leafTile,
subtreeLocator.childIndex
);
leafTile.children.push(implicitChildTile);
statistics2.numberOfTilesTotal++;
}
}
function listChildSubtrees(content, subtree, bottomRow) {
const results = [];
const branchingFactor = content._implicitTileset.branchingFactor;
for (let i = 0; i < bottomRow.length; i++) {
const leafTile = bottomRow[i];
if (!defined_default(leafTile)) {
continue;
}
for (let j = 0; j < branchingFactor; j++) {
const index = i * branchingFactor + j;
if (subtree.childSubtreeIsAvailableAtIndex(index)) {
results.push({
tile: leafTile,
childIndex: j
});
}
}
}
return results;
}
function transcodeSubtreeTiles(content, subtree, placeholderTile, childIndex) {
const rootBitIndex = 0;
const rootParentIsPlaceholder = true;
const rootTile = deriveChildTile(
content,
subtree,
placeholderTile,
childIndex,
rootBitIndex,
rootParentIsPlaceholder
);
const statistics2 = content._tileset.statistics;
let parentRow = [rootTile];
let currentRow = [];
const implicitTileset = content._implicitTileset;
for (let level = 1; level < implicitTileset.subtreeLevels; level++) {
const levelOffset = subtree.getLevelOffset(level);
const numberOfChildren = implicitTileset.branchingFactor * parentRow.length;
for (let childMortonIndex = 0; childMortonIndex < numberOfChildren; childMortonIndex++) {
const childBitIndex = levelOffset + childMortonIndex;
if (!subtree.tileIsAvailableAtIndex(childBitIndex)) {
currentRow.push(void 0);
continue;
}
const parentMortonIndex = subtree.getParentMortonIndex(childMortonIndex);
const parentTile = parentRow[parentMortonIndex];
const childChildIndex = childMortonIndex % implicitTileset.branchingFactor;
const childTile = deriveChildTile(
content,
subtree,
parentTile,
childChildIndex,
childBitIndex
);
parentTile.children.push(childTile);
statistics2.numberOfTilesTotal++;
currentRow.push(childTile);
}
parentRow = currentRow;
currentRow = [];
}
return {
rootTile,
// At the end of the last loop, bottomRow was moved to parentRow
bottomRow: parentRow
};
}
function getGeometricError(tileMetadata, implicitTileset, implicitCoordinates) {
const semantic = MetadataSemantic_default.TILE_GEOMETRIC_ERROR;
if (defined_default(tileMetadata) && tileMetadata.hasPropertyBySemantic(semantic)) {
return tileMetadata.getPropertyBySemantic(semantic);
}
return implicitTileset.geometricError / Math.pow(2, implicitCoordinates.level);
}
function deriveChildTile(implicitContent, subtree, parentTile, childIndex, childBitIndex, parentIsPlaceholderTile) {
const implicitTileset = implicitContent._implicitTileset;
let implicitCoordinates;
if (defaultValue_default(parentIsPlaceholderTile, false)) {
implicitCoordinates = parentTile.implicitCoordinates;
} else {
implicitCoordinates = parentTile.implicitCoordinates.getChildCoordinates(
childIndex
);
}
let tileMetadata;
let tileBounds;
let contentBounds;
if (defined_default(subtree.tilePropertyTableJson)) {
tileMetadata = subtree.getTileMetadataView(implicitCoordinates);
const boundingVolumeSemantics = parseBoundingVolumeSemantics_default(tileMetadata);
tileBounds = boundingVolumeSemantics.tile;
contentBounds = boundingVolumeSemantics.content;
}
const contentPropertyTableJsons = subtree.contentPropertyTableJsons;
const length3 = contentPropertyTableJsons.length;
let hasImplicitContentMetadata = false;
for (let i = 0; i < length3; i++) {
if (subtree.contentIsAvailableAtCoordinates(implicitCoordinates, i)) {
hasImplicitContentMetadata = true;
break;
}
}
const boundingVolume = getTileBoundingVolume(
implicitTileset,
implicitCoordinates,
childIndex,
parentIsPlaceholderTile,
parentTile,
tileBounds
);
const contentJsons = [];
for (let i = 0; i < implicitTileset.contentCount; i++) {
if (!subtree.contentIsAvailableAtIndex(childBitIndex, i)) {
continue;
}
const childContentTemplate = implicitTileset.contentUriTemplates[i];
const childContentUri = childContentTemplate.getDerivedResource({
templateValues: implicitCoordinates.getTemplateValues()
}).url;
const contentJson = {
uri: childContentUri
};
const contentBoundingVolume = getContentBoundingVolume(
boundingVolume,
contentBounds
);
if (defined_default(contentBoundingVolume)) {
contentJson.boundingVolume = contentBoundingVolume;
}
contentJsons.push(combine_default(contentJson, implicitTileset.contentHeaders[i]));
}
const childGeometricError = getGeometricError(
tileMetadata,
implicitTileset,
implicitCoordinates
);
const tileJson = {
boundingVolume,
geometricError: childGeometricError,
refine: implicitTileset.refine,
contents: contentJsons
};
const deep = true;
const rootHeader = clone_default(implicitTileset.tileHeader, deep);
delete rootHeader.boundingVolume;
delete rootHeader.transform;
const combinedTileJson = combine_default(tileJson, rootHeader, deep);
const childTile = makeTile(
implicitContent,
implicitTileset.baseResource,
combinedTileJson,
parentTile
);
childTile.implicitCoordinates = implicitCoordinates;
childTile.implicitSubtree = subtree;
childTile.metadata = tileMetadata;
childTile.hasImplicitContentMetadata = hasImplicitContentMetadata;
return childTile;
}
function canUpdateHeights(boundingVolume, tileBounds) {
return defined_default(boundingVolume) && defined_default(tileBounds) && (defined_default(tileBounds.minimumHeight) || defined_default(tileBounds.maximumHeight)) && (hasExtension_default(boundingVolume, "3DTILES_bounding_volume_S2") || defined_default(boundingVolume.region));
}
function updateHeights(boundingVolume, tileBounds) {
if (!defined_default(tileBounds)) {
return;
}
if (hasExtension_default(boundingVolume, "3DTILES_bounding_volume_S2")) {
updateS2CellHeights(
boundingVolume.extensions["3DTILES_bounding_volume_S2"],
tileBounds.minimumHeight,
tileBounds.maximumHeight
);
} else if (defined_default(boundingVolume.region)) {
updateRegionHeights(
boundingVolume.region,
tileBounds.minimumHeight,
tileBounds.maximumHeight
);
}
}
function updateRegionHeights(region, minimumHeight, maximumHeight) {
if (defined_default(minimumHeight)) {
region[4] = minimumHeight;
}
if (defined_default(maximumHeight)) {
region[5] = maximumHeight;
}
}
function updateS2CellHeights(s2CellVolume, minimumHeight, maximumHeight) {
if (defined_default(minimumHeight)) {
s2CellVolume.minimumHeight = minimumHeight;
}
if (defined_default(maximumHeight)) {
s2CellVolume.maximumHeight = maximumHeight;
}
}
function getTileBoundingVolume(implicitTileset, implicitCoordinates, childIndex, parentIsPlaceholderTile, parentTile, tileBounds) {
let boundingVolume;
if (!defined_default(tileBounds) || !defined_default(tileBounds.boundingVolume) || !canUpdateHeights(tileBounds.boundingVolume, tileBounds) && canUpdateHeights(implicitTileset.boundingVolume, tileBounds)) {
boundingVolume = deriveBoundingVolume(
implicitTileset,
implicitCoordinates,
childIndex,
defaultValue_default(parentIsPlaceholderTile, false),
parentTile
);
} else {
boundingVolume = tileBounds.boundingVolume;
}
updateHeights(boundingVolume, tileBounds);
return boundingVolume;
}
function getContentBoundingVolume(tileBoundingVolume, contentBounds) {
let contentBoundingVolume;
if (defined_default(contentBounds)) {
contentBoundingVolume = contentBounds.boundingVolume;
}
if (canUpdateHeights(contentBoundingVolume, contentBounds)) {
updateHeights(contentBoundingVolume, contentBounds);
} else if (canUpdateHeights(tileBoundingVolume, contentBounds)) {
contentBoundingVolume = clone_default(tileBoundingVolume, true);
updateHeights(contentBoundingVolume, contentBounds);
}
return contentBoundingVolume;
}
function deriveBoundingVolume(implicitTileset, implicitCoordinates, childIndex, parentIsPlaceholderTile, parentTile) {
const rootBoundingVolume = implicitTileset.boundingVolume;
if (hasExtension_default(rootBoundingVolume, "3DTILES_bounding_volume_S2")) {
return deriveBoundingVolumeS2(
parentIsPlaceholderTile,
parentTile,
childIndex,
implicitCoordinates.level,
implicitCoordinates.x,
implicitCoordinates.y,
implicitCoordinates.z
);
}
if (defined_default(rootBoundingVolume.region)) {
const childRegion = deriveBoundingRegion(
rootBoundingVolume.region,
implicitCoordinates.level,
implicitCoordinates.x,
implicitCoordinates.y,
implicitCoordinates.z
);
return {
region: childRegion
};
}
const childBox = deriveBoundingBox(
rootBoundingVolume.box,
implicitCoordinates.level,
implicitCoordinates.x,
implicitCoordinates.y,
implicitCoordinates.z
);
return {
box: childBox
};
}
function deriveBoundingVolumeS2(parentIsPlaceholderTile, parentTile, childIndex, level, x, y, z) {
Check_default.typeOf.bool("parentIsPlaceholderTile", parentIsPlaceholderTile);
Check_default.typeOf.object("parentTile", parentTile);
Check_default.typeOf.number("childIndex", childIndex);
Check_default.typeOf.number("level", level);
Check_default.typeOf.number("x", x);
Check_default.typeOf.number("y", y);
if (defined_default(z)) {
Check_default.typeOf.number("z", z);
}
const boundingVolumeS2 = parentTile._boundingVolume;
if (parentIsPlaceholderTile) {
return {
extensions: {
"3DTILES_bounding_volume_S2": {
token: S2Cell_default.getTokenFromId(boundingVolumeS2.s2Cell._cellId),
minimumHeight: boundingVolumeS2.minimumHeight,
maximumHeight: boundingVolumeS2.maximumHeight
}
}
};
}
const face = Number(parentTile._boundingVolume.s2Cell._cellId >> BigInt(61));
const position = face % 2 === 0 ? HilbertOrder_default.encode2D(level, x, y) : HilbertOrder_default.encode2D(level, y, x);
const cell = S2Cell_default.fromFacePositionLevel(face, BigInt(position), level);
let minHeight, maxHeight;
if (defined_default(z)) {
const midpointHeight = (boundingVolumeS2.maximumHeight + boundingVolumeS2.minimumHeight) / 2;
minHeight = childIndex < 4 ? boundingVolumeS2.minimumHeight : midpointHeight;
maxHeight = childIndex < 4 ? midpointHeight : boundingVolumeS2.maximumHeight;
} else {
minHeight = boundingVolumeS2.minimumHeight;
maxHeight = boundingVolumeS2.maximumHeight;
}
return {
extensions: {
"3DTILES_bounding_volume_S2": {
token: S2Cell_default.getTokenFromId(cell._cellId),
minimumHeight: minHeight,
maximumHeight: maxHeight
}
}
};
}
var scratchScaleFactors = new Cartesian3_default();
var scratchRootCenter = new Cartesian3_default();
var scratchCenter2 = new Cartesian3_default();
var scratchHalfAxes = new Matrix3_default();
function deriveBoundingBox(rootBox, level, x, y, z) {
Check_default.typeOf.object("rootBox", rootBox);
Check_default.typeOf.number("level", level);
Check_default.typeOf.number("x", x);
Check_default.typeOf.number("y", y);
if (defined_default(z)) {
Check_default.typeOf.number("z", z);
}
if (level === 0) {
return rootBox;
}
const rootCenter = Cartesian3_default.unpack(rootBox, 0, scratchRootCenter);
const rootHalfAxes = Matrix3_default.unpack(rootBox, 3, scratchHalfAxes);
const tileScale = Math.pow(2, -level);
const modelSpaceX = -1 + (2 * x + 1) * tileScale;
const modelSpaceY = -1 + (2 * y + 1) * tileScale;
let modelSpaceZ = 0;
const scaleFactors = Cartesian3_default.fromElements(
tileScale,
tileScale,
1,
scratchScaleFactors
);
if (defined_default(z)) {
modelSpaceZ = -1 + (2 * z + 1) * tileScale;
scaleFactors.z = tileScale;
}
let center = Cartesian3_default.fromElements(
modelSpaceX,
modelSpaceY,
modelSpaceZ,
scratchCenter2
);
center = Matrix3_default.multiplyByVector(rootHalfAxes, center, scratchCenter2);
center = Cartesian3_default.add(center, rootCenter, scratchCenter2);
let halfAxes = Matrix3_default.clone(rootHalfAxes);
halfAxes = Matrix3_default.multiplyByScale(halfAxes, scaleFactors, halfAxes);
const childBox = new Array(12);
Cartesian3_default.pack(center, childBox);
Matrix3_default.pack(halfAxes, childBox, 3);
return childBox;
}
var scratchRectangle = new Rectangle_default();
function deriveBoundingRegion(rootRegion, level, x, y, z) {
Check_default.typeOf.object("rootRegion", rootRegion);
Check_default.typeOf.number("level", level);
Check_default.typeOf.number("x", x);
Check_default.typeOf.number("y", y);
if (defined_default(z)) {
Check_default.typeOf.number("z", z);
}
if (level === 0) {
return rootRegion.slice();
}
const rectangle = Rectangle_default.unpack(rootRegion, 0, scratchRectangle);
const rootMinimumHeight = rootRegion[4];
const rootMaximumHeight = rootRegion[5];
const tileScale = Math.pow(2, -level);
const childWidth = tileScale * rectangle.width;
const west = Math_default.negativePiToPi(rectangle.west + x * childWidth);
const east = Math_default.negativePiToPi(west + childWidth);
const childHeight = tileScale * rectangle.height;
const south = Math_default.negativePiToPi(rectangle.south + y * childHeight);
const north = Math_default.negativePiToPi(south + childHeight);
let minimumHeight = rootMinimumHeight;
let maximumHeight = rootMaximumHeight;
if (defined_default(z)) {
const childThickness = tileScale * (rootMaximumHeight - rootMinimumHeight);
minimumHeight += z * childThickness;
maximumHeight = minimumHeight + childThickness;
}
return [west, south, east, north, minimumHeight, maximumHeight];
}
function makePlaceholderChildSubtree(content, parentTile, childIndex) {
const implicitTileset = content._implicitTileset;
const implicitCoordinates = parentTile.implicitCoordinates.getChildCoordinates(
childIndex
);
const childBoundingVolume = deriveBoundingVolume(
implicitTileset,
implicitCoordinates,
childIndex,
false,
parentTile
);
const childGeometricError = getGeometricError(
void 0,
implicitTileset,
implicitCoordinates
);
const childContentUri = implicitTileset.subtreeUriTemplate.getDerivedResource(
{
templateValues: implicitCoordinates.getTemplateValues()
}
).url;
const tileJson = {
boundingVolume: childBoundingVolume,
geometricError: childGeometricError,
refine: implicitTileset.refine,
contents: [
{
uri: childContentUri
}
]
};
const tile = makeTile(
content,
implicitTileset.baseResource,
tileJson,
parentTile
);
tile.implicitTileset = implicitTileset;
tile.implicitCoordinates = implicitCoordinates;
return tile;
}
function makeTile(content, baseResource2, tileJson, parentTile) {
const Cesium3DTile2 = content._tile.constructor;
return new Cesium3DTile2(content._tileset, baseResource2, tileJson, parentTile);
}
Implicit3DTileContent.prototype.hasProperty = function(batchId, name) {
return false;
};
Implicit3DTileContent.prototype.getFeature = function(batchId) {
return void 0;
};
Implicit3DTileContent.prototype.applyDebugSettings = function(enabled, color) {
};
Implicit3DTileContent.prototype.applyStyle = function(style) {
};
Implicit3DTileContent.prototype.update = function(tileset, frameState) {
};
Implicit3DTileContent.prototype.isDestroyed = function() {
return false;
};
Implicit3DTileContent.prototype.destroy = function() {
this._implicitSubtree = this._implicitSubtree && this._implicitSubtree.destroy();
return destroyObject_default(this);
};
Implicit3DTileContent._deriveBoundingBox = deriveBoundingBox;
Implicit3DTileContent._deriveBoundingRegion = deriveBoundingRegion;
Implicit3DTileContent._deriveBoundingVolumeS2 = deriveBoundingVolumeS2;
var Implicit3DTileContent_default = Implicit3DTileContent;
// packages/engine/Source/Scene/ModelAnimationLoop.js
var ModelAnimationLoop = {
/**
* Play the animation once; do not loop it.
*
* @type {number}
* @constant
*/
NONE: 0,
/**
* Loop the animation playing it from the start immediately after it stops.
*
* @type {number}
* @constant
*/
REPEAT: 1,
/**
* Loop the animation. First, playing it forward, then in reverse, then forward, and so on.
*
* @type {number}
* @constant
*/
MIRRORED_REPEAT: 2
};
var ModelAnimationLoop_default = Object.freeze(ModelAnimationLoop);
// packages/engine/Source/Scene/ClippingPlane.js
function ClippingPlane(normal2, distance2) {
Check_default.typeOf.object("normal", normal2);
Check_default.typeOf.number("distance", distance2);
this._distance = distance2;
this._normal = new UpdateChangedCartesian3(normal2, this);
this.onChangeCallback = void 0;
this.index = -1;
}
Object.defineProperties(ClippingPlane.prototype, {
/**
* The shortest distance from the origin to the plane. The sign of
* distance
determines which side of the plane the origin
* is on. If distance
is positive, the origin is in the half-space
* in the direction of the normal; if negative, the origin is in the half-space
* opposite to the normal; if zero, the plane passes through the origin.
*
* @type {number}
* @memberof ClippingPlane.prototype
*/
distance: {
get: function() {
return this._distance;
},
set: function(value) {
Check_default.typeOf.number("value", value);
if (defined_default(this.onChangeCallback) && value !== this._distance) {
this.onChangeCallback(this.index);
}
this._distance = value;
}
},
/**
* The plane's normal.
*
* @type {Cartesian3}
* @memberof ClippingPlane.prototype
*/
normal: {
get: function() {
return this._normal;
},
set: function(value) {
Check_default.typeOf.object("value", value);
if (defined_default(this.onChangeCallback) && !Cartesian3_default.equals(this._normal._cartesian3, value)) {
this.onChangeCallback(this.index);
}
Cartesian3_default.clone(value, this._normal._cartesian3);
}
}
});
ClippingPlane.fromPlane = function(plane, result) {
Check_default.typeOf.object("plane", plane);
if (!defined_default(result)) {
result = new ClippingPlane(plane.normal, plane.distance);
} else {
result.normal = plane.normal;
result.distance = plane.distance;
}
return result;
};
ClippingPlane.clone = function(clippingPlane, result) {
if (!defined_default(result)) {
return new ClippingPlane(clippingPlane.normal, clippingPlane.distance);
}
result.normal = clippingPlane.normal;
result.distance = clippingPlane.distance;
return result;
};
function UpdateChangedCartesian3(normal2, clippingPlane) {
this._clippingPlane = clippingPlane;
this._cartesian3 = Cartesian3_default.clone(normal2);
}
Object.defineProperties(UpdateChangedCartesian3.prototype, {
x: {
get: function() {
return this._cartesian3.x;
},
set: function(value) {
Check_default.typeOf.number("value", value);
if (defined_default(this._clippingPlane.onChangeCallback) && value !== this._cartesian3.x) {
this._clippingPlane.onChangeCallback(this._clippingPlane.index);
}
this._cartesian3.x = value;
}
},
y: {
get: function() {
return this._cartesian3.y;
},
set: function(value) {
Check_default.typeOf.number("value", value);
if (defined_default(this._clippingPlane.onChangeCallback) && value !== this._cartesian3.y) {
this._clippingPlane.onChangeCallback(this._clippingPlane.index);
}
this._cartesian3.y = value;
}
},
z: {
get: function() {
return this._cartesian3.z;
},
set: function(value) {
Check_default.typeOf.number("value", value);
if (defined_default(this._clippingPlane.onChangeCallback) && value !== this._cartesian3.z) {
this._clippingPlane.onChangeCallback(this._clippingPlane.index);
}
this._cartesian3.z = value;
}
}
});
var ClippingPlane_default = ClippingPlane;
// packages/engine/Source/Scene/ClippingPlaneCollection.js
function ClippingPlaneCollection(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this._planes = [];
this._dirtyIndex = -1;
this._multipleDirtyPlanes = false;
this._enabled = defaultValue_default(options.enabled, true);
this.modelMatrix = Matrix4_default.clone(
defaultValue_default(options.modelMatrix, Matrix4_default.IDENTITY)
);
this.edgeColor = Color_default.clone(defaultValue_default(options.edgeColor, Color_default.WHITE));
this.edgeWidth = defaultValue_default(options.edgeWidth, 0);
this.planeAdded = new Event_default();
this.planeRemoved = new Event_default();
this._owner = void 0;
const unionClippingRegions = defaultValue_default(
options.unionClippingRegions,
false
);
this._unionClippingRegions = unionClippingRegions;
this._testIntersection = unionClippingRegions ? unionIntersectFunction : defaultIntersectFunction;
this._uint8View = void 0;
this._float32View = void 0;
this._clippingPlanesTexture = void 0;
const planes = options.planes;
if (defined_default(planes)) {
const planesLength = planes.length;
for (let i = 0; i < planesLength; ++i) {
this.add(planes[i]);
}
}
}
function unionIntersectFunction(value) {
return value === Intersect_default.OUTSIDE;
}
function defaultIntersectFunction(value) {
return value === Intersect_default.INSIDE;
}
Object.defineProperties(ClippingPlaneCollection.prototype, {
/**
* Returns the number of planes in this collection. This is commonly used with
* {@link ClippingPlaneCollection#get} to iterate over all the planes
* in the collection.
*
* @memberof ClippingPlaneCollection.prototype
* @type {number}
* @readonly
*/
length: {
get: function() {
return this._planes.length;
}
},
/**
* If true, a region will be clipped if it is on the outside of any plane in the
* collection. Otherwise, a region will only be clipped if it is on the
* outside of every plane.
*
* @memberof ClippingPlaneCollection.prototype
* @type {boolean}
* @default false
*/
unionClippingRegions: {
get: function() {
return this._unionClippingRegions;
},
set: function(value) {
if (this._unionClippingRegions === value) {
return;
}
this._unionClippingRegions = value;
this._testIntersection = value ? unionIntersectFunction : defaultIntersectFunction;
}
},
/**
* If true, clipping will be enabled.
*
* @memberof ClippingPlaneCollection.prototype
* @type {boolean}
* @default true
*/
enabled: {
get: function() {
return this._enabled;
},
set: function(value) {
if (this._enabled === value) {
return;
}
this._enabled = value;
}
},
/**
* Returns a texture containing packed, untransformed clipping planes.
*
* @memberof ClippingPlaneCollection.prototype
* @type {Texture}
* @readonly
* @private
*/
texture: {
get: function() {
return this._clippingPlanesTexture;
}
},
/**
* A reference to the ClippingPlaneCollection's owner, if any.
*
* @memberof ClippingPlaneCollection.prototype
* @readonly
* @private
*/
owner: {
get: function() {
return this._owner;
}
},
/**
* Returns a Number encapsulating the state for this ClippingPlaneCollection.
*
* Clipping mode is encoded in the sign of the number, which is just the plane count.
* If this value changes, then shader regeneration is necessary.
*
* @memberof ClippingPlaneCollection.prototype
* @returns {number} A Number that describes the ClippingPlaneCollection's state.
* @readonly
* @private
*/
clippingPlanesState: {
get: function() {
return this._unionClippingRegions ? this._planes.length : -this._planes.length;
}
}
});
function setIndexDirty(collection, index) {
collection._multipleDirtyPlanes = collection._multipleDirtyPlanes || collection._dirtyIndex !== -1 && collection._dirtyIndex !== index;
collection._dirtyIndex = index;
}
ClippingPlaneCollection.prototype.add = function(plane) {
const newPlaneIndex = this._planes.length;
const that = this;
plane.onChangeCallback = function(index) {
setIndexDirty(that, index);
};
plane.index = newPlaneIndex;
setIndexDirty(this, newPlaneIndex);
this._planes.push(plane);
this.planeAdded.raiseEvent(plane, newPlaneIndex);
};
ClippingPlaneCollection.prototype.get = function(index) {
Check_default.typeOf.number("index", index);
return this._planes[index];
};
function indexOf(planes, plane) {
const length3 = planes.length;
for (let i = 0; i < length3; ++i) {
if (Plane_default.equals(planes[i], plane)) {
return i;
}
}
return -1;
}
ClippingPlaneCollection.prototype.contains = function(clippingPlane) {
return indexOf(this._planes, clippingPlane) !== -1;
};
ClippingPlaneCollection.prototype.remove = function(clippingPlane) {
const planes = this._planes;
const index = indexOf(planes, clippingPlane);
if (index === -1) {
return false;
}
if (clippingPlane instanceof ClippingPlane_default) {
clippingPlane.onChangeCallback = void 0;
clippingPlane.index = -1;
}
const length3 = planes.length - 1;
for (let i = index; i < length3; ++i) {
const planeToKeep = planes[i + 1];
planes[i] = planeToKeep;
if (planeToKeep instanceof ClippingPlane_default) {
planeToKeep.index = i;
}
}
this._multipleDirtyPlanes = true;
planes.length = length3;
this.planeRemoved.raiseEvent(clippingPlane, index);
return true;
};
ClippingPlaneCollection.prototype.removeAll = function() {
const planes = this._planes;
const planesCount = planes.length;
for (let i = 0; i < planesCount; ++i) {
const plane = planes[i];
if (plane instanceof ClippingPlane_default) {
plane.onChangeCallback = void 0;
plane.index = -1;
}
this.planeRemoved.raiseEvent(plane, i);
}
this._multipleDirtyPlanes = true;
this._planes = [];
};
var distanceEncodeScratch = new Cartesian4_default();
var oct32EncodeScratch = new Cartesian4_default();
function packPlanesAsUint8(clippingPlaneCollection, startIndex, endIndex) {
const uint8View = clippingPlaneCollection._uint8View;
const planes = clippingPlaneCollection._planes;
let byteIndex = 0;
for (let i = startIndex; i < endIndex; ++i) {
const plane = planes[i];
const oct32Normal = AttributeCompression_default.octEncodeToCartesian4(
plane.normal,
oct32EncodeScratch
);
uint8View[byteIndex] = oct32Normal.x;
uint8View[byteIndex + 1] = oct32Normal.y;
uint8View[byteIndex + 2] = oct32Normal.z;
uint8View[byteIndex + 3] = oct32Normal.w;
const encodedDistance = Cartesian4_default.packFloat(
plane.distance,
distanceEncodeScratch
);
uint8View[byteIndex + 4] = encodedDistance.x;
uint8View[byteIndex + 5] = encodedDistance.y;
uint8View[byteIndex + 6] = encodedDistance.z;
uint8View[byteIndex + 7] = encodedDistance.w;
byteIndex += 8;
}
}
function packPlanesAsFloats(clippingPlaneCollection, startIndex, endIndex) {
const float32View = clippingPlaneCollection._float32View;
const planes = clippingPlaneCollection._planes;
let floatIndex = 0;
for (let i = startIndex; i < endIndex; ++i) {
const plane = planes[i];
const normal2 = plane.normal;
float32View[floatIndex] = normal2.x;
float32View[floatIndex + 1] = normal2.y;
float32View[floatIndex + 2] = normal2.z;
float32View[floatIndex + 3] = plane.distance;
floatIndex += 4;
}
}
function computeTextureResolution(pixelsNeeded, result) {
const maxSize = ContextLimits_default.maximumTextureSize;
result.x = Math.min(pixelsNeeded, maxSize);
result.y = Math.ceil(pixelsNeeded / result.x);
return result;
}
var textureResolutionScratch = new Cartesian2_default();
ClippingPlaneCollection.prototype.update = function(frameState) {
let clippingPlanesTexture = this._clippingPlanesTexture;
const context = frameState.context;
const useFloatTexture = ClippingPlaneCollection.useFloatTexture(context);
const pixelsNeeded = useFloatTexture ? this.length : this.length * 2;
if (defined_default(clippingPlanesTexture)) {
const currentPixelCount = clippingPlanesTexture.width * clippingPlanesTexture.height;
if (currentPixelCount < pixelsNeeded || pixelsNeeded < 0.25 * currentPixelCount) {
clippingPlanesTexture.destroy();
clippingPlanesTexture = void 0;
this._clippingPlanesTexture = void 0;
}
}
if (this.length === 0) {
return;
}
if (!defined_default(clippingPlanesTexture)) {
const requiredResolution = computeTextureResolution(
pixelsNeeded,
textureResolutionScratch
);
requiredResolution.y *= 2;
if (useFloatTexture) {
clippingPlanesTexture = new Texture_default({
context,
width: requiredResolution.x,
height: requiredResolution.y,
pixelFormat: PixelFormat_default.RGBA,
pixelDatatype: PixelDatatype_default.FLOAT,
sampler: Sampler_default.NEAREST,
flipY: false
});
this._float32View = new Float32Array(
requiredResolution.x * requiredResolution.y * 4
);
} else {
clippingPlanesTexture = new Texture_default({
context,
width: requiredResolution.x,
height: requiredResolution.y,
pixelFormat: PixelFormat_default.RGBA,
pixelDatatype: PixelDatatype_default.UNSIGNED_BYTE,
sampler: Sampler_default.NEAREST,
flipY: false
});
this._uint8View = new Uint8Array(
requiredResolution.x * requiredResolution.y * 4
);
}
this._clippingPlanesTexture = clippingPlanesTexture;
this._multipleDirtyPlanes = true;
}
const dirtyIndex = this._dirtyIndex;
if (!this._multipleDirtyPlanes && dirtyIndex === -1) {
return;
}
if (!this._multipleDirtyPlanes) {
let offsetX = 0;
let offsetY = 0;
if (useFloatTexture) {
offsetY = Math.floor(dirtyIndex / clippingPlanesTexture.width);
offsetX = Math.floor(dirtyIndex - offsetY * clippingPlanesTexture.width);
packPlanesAsFloats(this, dirtyIndex, dirtyIndex + 1);
clippingPlanesTexture.copyFrom({
source: {
width: 1,
height: 1,
arrayBufferView: this._float32View
},
xOffset: offsetX,
yOffset: offsetY
});
} else {
offsetY = Math.floor(dirtyIndex * 2 / clippingPlanesTexture.width);
offsetX = Math.floor(
dirtyIndex * 2 - offsetY * clippingPlanesTexture.width
);
packPlanesAsUint8(this, dirtyIndex, dirtyIndex + 1);
clippingPlanesTexture.copyFrom({
source: {
width: 2,
height: 1,
arrayBufferView: this._uint8View
},
xOffset: offsetX,
yOffset: offsetY
});
}
} else if (useFloatTexture) {
packPlanesAsFloats(this, 0, this._planes.length);
clippingPlanesTexture.copyFrom({
source: {
width: clippingPlanesTexture.width,
height: clippingPlanesTexture.height,
arrayBufferView: this._float32View
}
});
} else {
packPlanesAsUint8(this, 0, this._planes.length);
clippingPlanesTexture.copyFrom({
source: {
width: clippingPlanesTexture.width,
height: clippingPlanesTexture.height,
arrayBufferView: this._uint8View
}
});
}
this._multipleDirtyPlanes = false;
this._dirtyIndex = -1;
};
var scratchMatrix = new Matrix4_default();
var scratchPlane3 = new Plane_default(Cartesian3_default.UNIT_X, 0);
ClippingPlaneCollection.prototype.computeIntersectionWithBoundingVolume = function(tileBoundingVolume, transform3) {
const planes = this._planes;
const length3 = planes.length;
let modelMatrix = this.modelMatrix;
if (defined_default(transform3)) {
modelMatrix = Matrix4_default.multiply(transform3, modelMatrix, scratchMatrix);
}
let intersection = Intersect_default.INSIDE;
if (!this.unionClippingRegions && length3 > 0) {
intersection = Intersect_default.OUTSIDE;
}
for (let i = 0; i < length3; ++i) {
const plane = planes[i];
Plane_default.transform(plane, modelMatrix, scratchPlane3);
const value = tileBoundingVolume.intersectPlane(scratchPlane3);
if (value === Intersect_default.INTERSECTING) {
intersection = value;
} else if (this._testIntersection(value)) {
return value;
}
}
return intersection;
};
ClippingPlaneCollection.setOwner = function(clippingPlaneCollection, owner, key) {
if (clippingPlaneCollection === owner[key]) {
return;
}
owner[key] = owner[key] && owner[key].destroy();
if (defined_default(clippingPlaneCollection)) {
if (defined_default(clippingPlaneCollection._owner)) {
throw new DeveloperError_default(
"ClippingPlaneCollection should only be assigned to one object"
);
}
clippingPlaneCollection._owner = owner;
owner[key] = clippingPlaneCollection;
}
};
ClippingPlaneCollection.useFloatTexture = function(context) {
return context.floatingPointTexture;
};
ClippingPlaneCollection.getTextureResolution = function(clippingPlaneCollection, context, result) {
const texture = clippingPlaneCollection.texture;
if (defined_default(texture)) {
result.x = texture.width;
result.y = texture.height;
return result;
}
const pixelsNeeded = ClippingPlaneCollection.useFloatTexture(context) ? clippingPlaneCollection.length : clippingPlaneCollection.length * 2;
const requiredResolution = computeTextureResolution(pixelsNeeded, result);
requiredResolution.y *= 2;
return requiredResolution;
};
ClippingPlaneCollection.prototype.isDestroyed = function() {
return false;
};
ClippingPlaneCollection.prototype.destroy = function() {
this._clippingPlanesTexture = this._clippingPlanesTexture && this._clippingPlanesTexture.destroy();
return destroyObject_default(this);
};
var ClippingPlaneCollection_default = ClippingPlaneCollection;
// packages/engine/Source/Scene/ColorBlendMode.js
var ColorBlendMode = {
HIGHLIGHT: 0,
REPLACE: 1,
MIX: 2
};
ColorBlendMode.getColorBlend = function(colorBlendMode, colorBlendAmount) {
if (colorBlendMode === ColorBlendMode.HIGHLIGHT) {
return 0;
} else if (colorBlendMode === ColorBlendMode.REPLACE) {
return 1;
} else if (colorBlendMode === ColorBlendMode.MIX) {
return Math_default.clamp(colorBlendAmount, Math_default.EPSILON4, 1);
}
};
var ColorBlendMode_default = Object.freeze(ColorBlendMode);
// packages/engine/Source/Core/ArticulationStageType.js
var ArticulationStageType = {
XTRANSLATE: "xTranslate",
YTRANSLATE: "yTranslate",
ZTRANSLATE: "zTranslate",
XROTATE: "xRotate",
YROTATE: "yRotate",
ZROTATE: "zRotate",
XSCALE: "xScale",
YSCALE: "yScale",
ZSCALE: "zScale",
UNIFORMSCALE: "uniformScale"
};
var ArticulationStageType_default = Object.freeze(ArticulationStageType);
// packages/engine/Source/Core/InterpolationType.js
var InterpolationType = {
STEP: 0,
LINEAR: 1,
CUBICSPLINE: 2
};
var InterpolationType_default = Object.freeze(InterpolationType);
// packages/engine/Source/Scene/JsonMetadataTable.js
var emptyClass = {};
function JsonMetadataTable(options) {
Check_default.typeOf.number.greaterThan("options.count", options.count, 0);
Check_default.typeOf.object("options.properties", options.properties);
this._count = options.count;
this._properties = clone_default(options.properties, true);
}
JsonMetadataTable.prototype.hasProperty = function(propertyId) {
return MetadataEntity_default.hasProperty(propertyId, this._properties, emptyClass);
};
JsonMetadataTable.prototype.getPropertyIds = function(results) {
return MetadataEntity_default.getPropertyIds(this._properties, emptyClass, results);
};
JsonMetadataTable.prototype.getProperty = function(index, propertyId) {
Check_default.typeOf.number("index", index);
Check_default.typeOf.string("propertyId", propertyId);
if (index < 0 || index >= this._count) {
throw new DeveloperError_default(`index must be in the range [0, ${this._count})`);
}
const property = this._properties[propertyId];
if (defined_default(property)) {
return clone_default(property[index], true);
}
return void 0;
};
JsonMetadataTable.prototype.setProperty = function(index, propertyId, value) {
Check_default.typeOf.number("index", index);
Check_default.typeOf.string("propertyId", propertyId);
if (index < 0 || index >= this._count) {
throw new DeveloperError_default(`index must be in the range [0, ${this._count})`);
}
let property = this._properties[propertyId];
if (!defined_default(property)) {
property = new Array(this._count);
this._properties[propertyId] = property;
}
property[index] = clone_default(value, true);
};
var JsonMetadataTable_default = JsonMetadataTable;
// packages/engine/Source/Scene/PropertyTable.js
function PropertyTable(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
Check_default.typeOf.number("options.count", options.count);
this._name = options.name;
this._id = options.id;
this._count = options.count;
this._extras = options.extras;
this._extensions = options.extensions;
this._metadataTable = options.metadataTable;
this._jsonMetadataTable = options.jsonMetadataTable;
this._batchTableHierarchy = options.batchTableHierarchy;
}
Object.defineProperties(PropertyTable.prototype, {
/**
* A human-readable name for this table
*
* @memberof PropertyTable.prototype
* @type {string}
* @readonly
* @private
*/
name: {
get: function() {
return this._name;
}
},
/**
* An identifier for this table. Useful for debugging.
*
* @memberof PropertyTable.prototype
* @type {string|number}
* @readonly
* @private
*/
id: {
get: function() {
return this._id;
}
},
/**
* The number of features in the table.
*
* @memberof PropertyTable.prototype
* @type {number}
* @readonly
* @private
*/
count: {
get: function() {
return this._count;
}
},
/**
* The class that properties conform to.
*
* @memberof PropertyTable.prototype
* @type {MetadataClass}
* @readonly
*/
class: {
get: function() {
if (defined_default(this._metadataTable)) {
return this._metadataTable.class;
}
return void 0;
}
},
/**
* Extra user-defined properties.
*
* @memberof PropertyTable.prototype
* @type {*}
* @readonly
* @private
*/
extras: {
get: function() {
return this._extras;
}
},
/**
* An object containing extensions.
*
* @memberof PropertyTable.prototype
* @type {object}
* @readonly
* @private
*/
extensions: {
get: function() {
return this._extensions;
}
},
/**
* Get the total amount of binary metadata stored in memory. This does
* not include JSON metadata
*
* @memberof PropertyTable.prototype
* @type {number}
* @readonly
* @private
*/
byteLength: {
get: function() {
let totalByteLength = 0;
if (defined_default(this._metadataTable)) {
totalByteLength += this._metadataTable.byteLength;
}
if (defined_default(this._batchTableHierarchy)) {
totalByteLength += this._batchTableHierarchy.byteLength;
}
return totalByteLength;
}
}
});
PropertyTable.prototype.hasProperty = function(index, propertyId) {
Check_default.typeOf.number("index", index);
Check_default.typeOf.string("propertyId", propertyId);
if (defined_default(this._metadataTable) && this._metadataTable.hasProperty(propertyId)) {
return true;
}
if (defined_default(this._batchTableHierarchy) && this._batchTableHierarchy.hasProperty(index, propertyId)) {
return true;
}
if (defined_default(this._jsonMetadataTable) && this._jsonMetadataTable.hasProperty(propertyId)) {
return true;
}
return false;
};
PropertyTable.prototype.hasPropertyBySemantic = function(index, semantic) {
Check_default.typeOf.number("index", index);
Check_default.typeOf.string("semantic", semantic);
if (defined_default(this._metadataTable)) {
return this._metadataTable.hasPropertyBySemantic(semantic);
}
return false;
};
PropertyTable.prototype.propertyExists = function(propertyId) {
Check_default.typeOf.string("propertyId", propertyId);
if (defined_default(this._metadataTable) && this._metadataTable.hasProperty(propertyId)) {
return true;
}
if (defined_default(this._batchTableHierarchy) && this._batchTableHierarchy.propertyExists(propertyId)) {
return true;
}
if (defined_default(this._jsonMetadataTable) && this._jsonMetadataTable.hasProperty(propertyId)) {
return true;
}
return false;
};
PropertyTable.prototype.propertyExistsBySemantic = function(semantic) {
Check_default.typeOf.string("semantic", semantic);
if (defined_default(this._metadataTable)) {
return this._metadataTable.hasPropertyBySemantic(semantic);
}
return false;
};
var scratchResults = [];
PropertyTable.prototype.getPropertyIds = function(index, results) {
results = defined_default(results) ? results : [];
results.length = 0;
if (defined_default(this._metadataTable)) {
results.push.apply(
results,
this._metadataTable.getPropertyIds(scratchResults)
);
}
if (defined_default(this._batchTableHierarchy)) {
results.push.apply(
results,
this._batchTableHierarchy.getPropertyIds(index, scratchResults)
);
}
if (defined_default(this._jsonMetadataTable)) {
results.push.apply(
results,
this._jsonMetadataTable.getPropertyIds(scratchResults)
);
}
return results;
};
PropertyTable.prototype.getProperty = function(index, propertyId) {
let result;
if (defined_default(this._metadataTable)) {
result = this._metadataTable.getProperty(index, propertyId);
if (defined_default(result)) {
return result;
}
}
if (defined_default(this._batchTableHierarchy)) {
result = this._batchTableHierarchy.getProperty(index, propertyId);
if (defined_default(result)) {
return result;
}
}
if (defined_default(this._jsonMetadataTable)) {
result = this._jsonMetadataTable.getProperty(index, propertyId);
if (defined_default(result)) {
return result;
}
}
return void 0;
};
PropertyTable.prototype.setProperty = function(index, propertyId, value) {
if (defined_default(this._metadataTable) && this._metadataTable.setProperty(index, propertyId, value)) {
return;
}
if (defined_default(this._batchTableHierarchy) && this._batchTableHierarchy.setProperty(index, propertyId, value)) {
return;
}
if (!defined_default(this._jsonMetadataTable)) {
this._jsonMetadataTable = new JsonMetadataTable_default({
count: this._count,
properties: {}
});
}
this._jsonMetadataTable.setProperty(index, propertyId, value);
};
PropertyTable.prototype.getPropertyBySemantic = function(index, semantic) {
if (defined_default(this._metadataTable)) {
return this._metadataTable.getPropertyBySemantic(index, semantic);
}
return void 0;
};
PropertyTable.prototype.setPropertyBySemantic = function(index, semantic, value) {
if (defined_default(this._metadataTable)) {
return this._metadataTable.setPropertyBySemantic(index, semantic, value);
}
return false;
};
PropertyTable.prototype.getPropertyTypedArray = function(propertyId) {
Check_default.typeOf.string("propertyId", propertyId);
if (defined_default(this._metadataTable)) {
return this._metadataTable.getPropertyTypedArray(propertyId);
}
return void 0;
};
PropertyTable.prototype.getPropertyTypedArrayBySemantic = function(semantic) {
Check_default.typeOf.string("semantic", semantic);
if (defined_default(this._metadataTable)) {
return this._metadataTable.getPropertyTypedArrayBySemantic(semantic);
}
return void 0;
};
function checkFeatureId(featureId, featuresLength) {
if (!defined_default(featureId) || featureId < 0 || featureId >= featuresLength) {
throw new DeveloperError_default(
`featureId is required and must be between zero and featuresLength - 1 (${featuresLength}` - +")."
);
}
}
PropertyTable.prototype.isClass = function(featureId, className) {
checkFeatureId(featureId, this.count);
Check_default.typeOf.string("className", className);
const hierarchy = this._batchTableHierarchy;
if (!defined_default(hierarchy)) {
return false;
}
return hierarchy.isClass(featureId, className);
};
PropertyTable.prototype.isExactClass = function(featureId, className) {
checkFeatureId(featureId, this.count);
Check_default.typeOf.string("className", className);
return this.getExactClassName(featureId) === className;
};
PropertyTable.prototype.getExactClassName = function(featureId) {
checkFeatureId(featureId, this.count);
const hierarchy = this._batchTableHierarchy;
if (!defined_default(hierarchy)) {
return void 0;
}
return hierarchy.getClassName(featureId);
};
var PropertyTable_default = PropertyTable;
// packages/engine/Source/Scene/PropertyTextureProperty.js
function PropertyTextureProperty(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const property = options.property;
const classProperty = options.classProperty;
const textures = options.textures;
Check_default.typeOf.object("options.property", property);
Check_default.typeOf.object("options.classProperty", classProperty);
Check_default.typeOf.object("options.textures", textures);
const channels = defined_default(property.channels) ? property.channels : [0];
const textureInfo = property;
const textureReader = GltfLoaderUtil_default.createModelTextureReader({
textureInfo,
channels: reformatChannels(channels),
texture: textures[textureInfo.index]
});
this._min = property.min;
this._max = property.max;
let offset2 = property.offset;
let scale = property.scale;
const hasValueTransform = classProperty.hasValueTransform || defined_default(offset2) || defined_default(scale);
offset2 = defaultValue_default(offset2, classProperty.offset);
scale = defaultValue_default(scale, classProperty.scale);
offset2 = classProperty.unpackVectorAndMatrixTypes(offset2);
scale = classProperty.unpackVectorAndMatrixTypes(scale);
this._offset = offset2;
this._scale = scale;
this._hasValueTransform = hasValueTransform;
this._textureReader = textureReader;
this._classProperty = classProperty;
this._extras = property.extras;
this._extensions = property.extensions;
}
Object.defineProperties(PropertyTextureProperty.prototype, {
/**
* The texture reader.
*
* @memberof PropertyTextureProperty.prototype
* @type {ModelComponents.TextureReader}
* @readonly
* @private
*/
textureReader: {
get: function() {
return this._textureReader;
}
},
/**
* True if offset/scale should be applied. If both offset/scale were
* undefined, they default to identity so this property is set false
*
* @memberof PropertyTextureProperty.prototype
* @type {boolean}
* @readonly
* @private
*/
hasValueTransform: {
get: function() {
return this._hasValueTransform;
}
},
/**
* The offset to be added to property values as part of the value transform.
*
* @memberof PropertyTextureProperty.prototype
* @type {number|Cartesian2|Cartesian3|Cartesian4|Matrix2|Matrix3|Matrix4}
* @readonly
* @private
*/
offset: {
get: function() {
return this._offset;
}
},
/**
* The scale to be multiplied to property values as part of the value transform.
*
* @memberof PropertyTextureProperty.prototype
* @type {number|Cartesian2|Cartesian3|Cartesian4|Matrix2|Matrix3|Matrix4}
* @readonly
* @private
*/
scale: {
get: function() {
return this._scale;
}
},
/**
* The properties inherited from this property's class
*
* @memberof PropertyTextureProperty.prototype
* @type {MetadataClassProperty}
* @readonly
* @private
*/
classProperty: {
get: function() {
return this._classProperty;
}
},
/**
* Extra user-defined properties.
*
* @memberof PropertyTextureProperty.prototype
* @type {*}
* @readonly
* @private
*/
extras: {
get: function() {
return this._extras;
}
},
/**
* An object containing extensions.
*
* @memberof PropertyTextureProperty.prototype
* @type {*}
* @readonly
* @private
*/
extensions: {
get: function() {
return this._extensions;
}
}
});
PropertyTextureProperty.prototype.isGpuCompatible = function() {
const classProperty = this._classProperty;
const type = classProperty.type;
const componentType = classProperty.componentType;
if (classProperty.isArray) {
return !classProperty.isVariableLengthArray && classProperty.arrayLength <= 4 && type === MetadataType_default.SCALAR && componentType === MetadataComponentType_default.UINT8;
}
if (MetadataType_default.isVectorType(type) || type === MetadataType_default.SCALAR) {
return componentType === MetadataComponentType_default.UINT8;
}
return false;
};
var floatTypesByComponentCount = [void 0, "float", "vec2", "vec3", "vec4"];
var integerTypesByComponentCount = [
void 0,
"int",
"ivec2",
"ivec3",
"ivec4"
];
PropertyTextureProperty.prototype.getGlslType = function() {
const classProperty = this._classProperty;
let componentCount = MetadataType_default.getComponentCount(classProperty.type);
if (classProperty.isArray) {
componentCount = classProperty.arrayLength;
}
if (classProperty.normalized) {
return floatTypesByComponentCount[componentCount];
}
return integerTypesByComponentCount[componentCount];
};
PropertyTextureProperty.prototype.unpackInShader = function(packedValueGlsl) {
const classProperty = this._classProperty;
if (classProperty.normalized) {
return packedValueGlsl;
}
const glslType = this.getGlslType();
return `${glslType}(255.0 * ${packedValueGlsl})`;
};
function reformatChannels(channels) {
return channels.map(function(channelIndex) {
return "rgba".charAt(channelIndex);
}).join("");
}
var PropertyTextureProperty_default = PropertyTextureProperty;
// packages/engine/Source/Scene/PropertyTexture.js
function PropertyTexture(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const propertyTexture = options.propertyTexture;
const classDefinition = options.class;
const textures = options.textures;
Check_default.typeOf.object("options.propertyTexture", propertyTexture);
Check_default.typeOf.object("options.class", classDefinition);
Check_default.typeOf.object("options.textures", textures);
const extensions = propertyTexture.extensions;
const extras = propertyTexture.extras;
const properties = {};
if (defined_default(propertyTexture.properties)) {
for (const propertyId in propertyTexture.properties) {
if (propertyTexture.properties.hasOwnProperty(propertyId)) {
properties[propertyId] = new PropertyTextureProperty_default({
property: propertyTexture.properties[propertyId],
classProperty: classDefinition.properties[propertyId],
textures
});
}
}
}
this._name = options.name;
this._id = options.id;
this._class = classDefinition;
this._properties = properties;
this._extras = extras;
this._extensions = extensions;
}
Object.defineProperties(PropertyTexture.prototype, {
/**
* A human-readable name for this texture
*
* @memberof PropertyTexture.prototype
* @type {string}
* @readonly
* @private
*/
name: {
get: function() {
return this._name;
}
},
/**
* An identifier for this texture. Useful for debugging.
*
* @memberof PropertyTexture.prototype
* @type {string|number}
* @readonly
* @private
*/
id: {
get: function() {
return this._id;
}
},
/**
* The class that properties conform to.
*
* @memberof PropertyTexture.prototype
* @type {MetadataClass}
* @readonly
* @private
*/
class: {
get: function() {
return this._class;
}
},
/**
* The properties in this property texture.
*
* @memberof PropertyTexture.prototype
*
* @type {PropertyTextureProperty}
* @readonly
* @private
*/
properties: {
get: function() {
return this._properties;
}
},
/**
* Extra user-defined properties.
*
* @memberof PropertyTexture.prototype
* @type {*}
* @readonly
* @private
*/
extras: {
get: function() {
return this._extras;
}
},
/**
* An object containing extensions.
*
* @memberof PropertyTexture.prototype
* @type {object}
* @readonly
* @private
*/
extensions: {
get: function() {
return this._extensions;
}
}
});
PropertyTexture.prototype.getProperty = function(propertyId) {
Check_default.typeOf.string("propertyId", propertyId);
return this._properties[propertyId];
};
var PropertyTexture_default = PropertyTexture;
// packages/engine/Source/Scene/PropertyAttributeProperty.js
function PropertyAttributeProperty(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const property = options.property;
const classProperty = options.classProperty;
Check_default.typeOf.object("options.property", property);
Check_default.typeOf.object("options.classProperty", classProperty);
this._attribute = property.attribute;
this._classProperty = classProperty;
this._min = property.min;
this._max = property.max;
let offset2 = property.offset;
let scale = property.scale;
const hasValueTransform = classProperty.hasValueTransform || defined_default(offset2) || defined_default(scale);
offset2 = defaultValue_default(offset2, classProperty.offset);
scale = defaultValue_default(scale, classProperty.scale);
offset2 = classProperty.unpackVectorAndMatrixTypes(offset2);
scale = classProperty.unpackVectorAndMatrixTypes(scale);
this._offset = offset2;
this._scale = scale;
this._hasValueTransform = hasValueTransform;
this._extras = property.extras;
this._extensions = property.extensions;
}
Object.defineProperties(PropertyAttributeProperty.prototype, {
/**
* The attribute semantic
*
* @memberof PropertyAttributeProperty.prototype
* @type {string}
* @readonly
* @private
*/
attribute: {
get: function() {
return this._attribute;
}
},
/**
* True if offset/scale should be applied. If both offset/scale were
* undefined, they default to identity so this property is set false
*
* @memberof MetadataClassProperty.prototype
* @type {boolean}
* @readonly
* @private
*/
hasValueTransform: {
get: function() {
return this._hasValueTransform;
}
},
/**
* The offset to be added to property values as part of the value transform.
*
* @memberof MetadataClassProperty.prototype
* @type {number|Cartesian2|Cartesian3|Cartesian4|Matrix2|Matrix3|Matrix4}
* @readonly
* @private
*/
offset: {
get: function() {
return this._offset;
}
},
/**
* The scale to be multiplied to property values as part of the value transform.
*
* @memberof MetadataClassProperty.prototype
* @type {number|Cartesian2|Cartesian3|Cartesian4|Matrix2|Matrix3|Matrix4}
* @readonly
* @private
*/
scale: {
get: function() {
return this._scale;
}
},
/**
* The properties inherited from this property's class
*
* @memberof PropertyAttributeProperty.prototype
* @type {MetadataClassProperty}
* @readonly
* @private
*/
classProperty: {
get: function() {
return this._classProperty;
}
},
/**
* Extra user-defined properties.
*
* @memberof PropertyAttributeProperty.prototype
* @type {*}
* @readonly
* @private
*/
extras: {
get: function() {
return this._extras;
}
},
/**
* An object containing extensions.
*
* @memberof PropertyAttributeProperty.prototype
* @type {*}
* @readonly
* @private
*/
extensions: {
get: function() {
return this._extensions;
}
}
});
var PropertyAttributeProperty_default = PropertyAttributeProperty;
// packages/engine/Source/Scene/PropertyAttribute.js
function PropertyAttribute(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const propertyAttribute = options.propertyAttribute;
const classDefinition = options.class;
Check_default.typeOf.object("options.propertyAttribute", propertyAttribute);
Check_default.typeOf.object("options.class", classDefinition);
const properties = {};
if (defined_default(propertyAttribute.properties)) {
for (const propertyId in propertyAttribute.properties) {
if (propertyAttribute.properties.hasOwnProperty(propertyId)) {
properties[propertyId] = new PropertyAttributeProperty_default({
property: propertyAttribute.properties[propertyId],
classProperty: classDefinition.properties[propertyId]
});
}
}
}
this._name = options.name;
this._id = options.id;
this._class = classDefinition;
this._properties = properties;
this._extras = propertyAttribute.extras;
this._extensions = propertyAttribute.extensions;
}
Object.defineProperties(PropertyAttribute.prototype, {
/**
* A human-readable name for this attribute
*
* @memberof PropertyAttribute.prototype
*
* @type {string}
* @readonly
* @private
*/
name: {
get: function() {
return this._name;
}
},
/**
* An identifier for this attribute. Useful for debugging.
*
* @memberof PropertyAttribute.prototype
*
* @type {string|number}
* @readonly
* @private
*/
id: {
get: function() {
return this._id;
}
},
/**
* The class that properties conform to.
*
* @memberof PropertyAttribute.prototype
*
* @type {MetadataClass}
* @readonly
* @private
*/
class: {
get: function() {
return this._class;
}
},
/**
* The properties in this property attribute.
*
* @memberof PropertyAttribute.prototype
*
* @type {Object* See the {@link https://github.com/CesiumGS/glTF/blob/3d-tiles-next/extensions/2.0/Vendor/EXT_feature_metadata/schema/statistics.schema.json|statistics schema reference} for the full set of properties. *
* * @memberof StructuralMetadata.prototype * @type {object} * @readonly * @private */ statistics: { get: function() { return this._statistics; } }, /** * Extra user-defined properties. * * @memberof StructuralMetadata.prototype * @type {*} * @readonly * @private */ extras: { get: function() { return this._extras; } }, /** * An object containing extensions. * * @memberof StructuralMetadata.prototype * @type {object} * @readonly * @private */ extensions: { get: function() { return this._extensions; } }, /** * Number of property tables in the metadata. * * @memberof StructuralMetadata.prototype * @type {number} * @readonly * @private */ propertyTableCount: { get: function() { return this._propertyTableCount; } }, /** * The property tables in the metadata. * * @memberof StructuralMetadata.prototype * @type {PropertyTable[]} * @readonly * @private */ propertyTables: { get: function() { return this._propertyTables; } }, /** * The property textures in the metadata. * * @memberof StructuralMetadata.prototype * @type {PropertyTexture[]} * @readonly * @private */ propertyTextures: { get: function() { return this._propertyTextures; } }, /** * The property attributes from the structural metadata extension * * @memberof StructuralMetadata.prototype * @type {PropertyAttribute[]} * @readonly * @private */ propertyAttributes: { get: function() { return this._propertyAttributes; } }, /** * Total size in bytes across all property tables * * @memberof StructuralMetadata.prototype * @type {number} * @readonly * @private */ propertyTablesByteLength: { get: function() { if (!defined_default(this._propertyTables)) { return 0; } let totalByteLength = 0; const length3 = this._propertyTables.length; for (let i = 0; i < length3; i++) { totalByteLength += this._propertyTables[i].byteLength; } return totalByteLength; } } }); StructuralMetadata.prototype.getPropertyTable = function(propertyTableId) { Check_default.typeOf.number("propertyTableId", propertyTableId); return this._propertyTables[propertyTableId]; }; StructuralMetadata.prototype.getPropertyTexture = function(propertyTextureId) { Check_default.typeOf.number("propertyTextureId", propertyTextureId); return this._propertyTextures[propertyTextureId]; }; StructuralMetadata.prototype.getPropertyAttribute = function(propertyAttributeId) { Check_default.typeOf.number("propertyAttributeId", propertyAttributeId); return this._propertyAttributes[propertyAttributeId]; }; var StructuralMetadata_default = StructuralMetadata; // packages/engine/Source/Scene/parseStructuralMetadata.js function parseStructuralMetadata(options) { options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT); const extension = options.extension; const schema = options.schema; Check_default.typeOf.object("options.extension", extension); Check_default.typeOf.object("options.schema", schema); const propertyTables = []; if (defined_default(extension.propertyTables)) { for (let i = 0; i < extension.propertyTables.length; i++) { const propertyTable = extension.propertyTables[i]; const classDefinition = schema.classes[propertyTable.class]; const metadataTable = new MetadataTable_default({ count: propertyTable.count, properties: propertyTable.properties, class: classDefinition, bufferViews: options.bufferViews }); propertyTables.push( new PropertyTable_default({ id: i, name: propertyTable.name, count: propertyTable.count, metadataTable, extras: propertyTable.extras, extensions: propertyTable.extensions }) ); } } const propertyTextures = []; if (defined_default(extension.propertyTextures)) { for (let i = 0; i < extension.propertyTextures.length; i++) { const propertyTexture = extension.propertyTextures[i]; propertyTextures.push( new PropertyTexture_default({ id: i, name: propertyTexture.name, propertyTexture, class: schema.classes[propertyTexture.class], textures: options.textures }) ); } } const propertyAttributes = []; if (defined_default(extension.propertyAttributes)) { for (let i = 0; i < extension.propertyAttributes.length; i++) { const propertyAttribute = extension.propertyAttributes[i]; propertyAttributes.push( new PropertyAttribute_default({ id: i, name: propertyAttribute.name, class: schema.classes[propertyAttribute.class], propertyAttribute }) ); } } return new StructuralMetadata_default({ schema, propertyTables, propertyTextures, propertyAttributes, statistics: extension.statistics, extras: extension.extras, extensions: extension.extensions }); } var parseStructuralMetadata_default = parseStructuralMetadata; // packages/engine/Source/Scene/parseFeatureMetadataLegacy.js function parseFeatureMetadataLegacy(options) { options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT); const extension = options.extension; const schema = options.schema; Check_default.typeOf.object("options.extension", extension); Check_default.typeOf.object("options.schema", schema); let i; const propertyTables = []; let sortedIds; if (defined_default(extension.featureTables)) { sortedIds = Object.keys(extension.featureTables).sort(); for (i = 0; i < sortedIds.length; i++) { const featureTableId = sortedIds[i]; const featureTable = extension.featureTables[featureTableId]; const classDefinition = schema.classes[featureTable.class]; const metadataTable = new MetadataTable_default({ count: featureTable.count, properties: featureTable.properties, class: classDefinition, bufferViews: options.bufferViews }); propertyTables.push( new PropertyTable_default({ id: featureTableId, count: featureTable.count, metadataTable, extras: featureTable.extras, extensions: featureTable.extensions }) ); } } const propertyTextures = []; if (defined_default(extension.featureTextures)) { sortedIds = Object.keys(extension.featureTextures).sort(); for (i = 0; i < sortedIds.length; i++) { const featureTextureId = sortedIds[i]; const featureTexture = extension.featureTextures[featureTextureId]; propertyTextures.push( new PropertyTexture_default({ id: featureTextureId, propertyTexture: transcodeToPropertyTexture(featureTexture), class: schema.classes[featureTexture.class], textures: options.textures }) ); } } return new StructuralMetadata_default({ schema, propertyTables, propertyTextures, statistics: extension.statistics, extras: extension.extras, extensions: extension.extensions }); } function transcodeToPropertyTexture(featureTexture) { const propertyTexture = { class: featureTexture.class, properties: {} }; const properties = featureTexture.properties; for (const propertyId in properties) { if (properties.hasOwnProperty(propertyId)) { const oldProperty = properties[propertyId]; const property = { // EXT_structural_metadata uses numeric channel indices instead of // a string of channel letters like "rgba". channels: reformatChannels2(oldProperty.channels), extras: oldProperty.extras, extensions: oldProperty.extensions }; propertyTexture.properties[propertyId] = combine_default( oldProperty.texture, property, true ); } } return propertyTexture; } function reformatChannels2(channelsString) { const length3 = channelsString.length; const result = new Array(length3); for (let i = 0; i < length3; i++) { result[i] = "rgba".indexOf(channelsString[i]); } return result; } var parseFeatureMetadataLegacy_default = parseFeatureMetadataLegacy; // packages/engine/Source/Scene/GltfStructuralMetadataLoader.js function GltfStructuralMetadataLoader(options) { options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT); const gltf = options.gltf; const extension = options.extension; const extensionLegacy = options.extensionLegacy; const gltfResource = options.gltfResource; const baseResource2 = options.baseResource; const supportedImageFormats = options.supportedImageFormats; const frameState = options.frameState; const cacheKey = options.cacheKey; const asynchronous = defaultValue_default(options.asynchronous, true); Check_default.typeOf.object("options.gltf", gltf); Check_default.typeOf.object("options.gltfResource", gltfResource); Check_default.typeOf.object("options.baseResource", baseResource2); Check_default.typeOf.object("options.supportedImageFormats", supportedImageFormats); Check_default.typeOf.object("options.frameState", frameState); if (!defined_default(options.extension) && !defined_default(options.extensionLegacy)) { throw new DeveloperError_default( "One of options.extension or options.extensionLegacy must be specified" ); } this._gltfResource = gltfResource; this._baseResource = baseResource2; this._gltf = gltf; this._extension = extension; this._extensionLegacy = extensionLegacy; this._supportedImageFormats = supportedImageFormats; this._frameState = frameState; this._cacheKey = cacheKey; this._asynchronous = asynchronous; this._bufferViewLoaders = []; this._bufferViewIds = []; this._textureLoaders = []; this._textureIds = []; this._schemaLoader = void 0; this._structuralMetadata = void 0; this._state = ResourceLoaderState_default.UNLOADED; this._promise = void 0; } if (defined_default(Object.create)) { GltfStructuralMetadataLoader.prototype = Object.create( ResourceLoader_default.prototype ); GltfStructuralMetadataLoader.prototype.constructor = GltfStructuralMetadataLoader; } Object.defineProperties(GltfStructuralMetadataLoader.prototype, { /** * The cache key of the resource. * * @memberof GltfStructuralMetadataLoader.prototype * * @type {string} * @readonly * @private */ cacheKey: { get: function() { return this._cacheKey; } }, /** * The parsed structural metadata * * @memberof GltfStructuralMetadataLoader.prototype * * @type {StructuralMetadata} * @readonly * @private */ structuralMetadata: { get: function() { return this._structuralMetadata; } } }); async function loadResources4(loader) { try { const bufferViewsPromise = loadBufferViews(loader); const texturesPromise = loadTextures(loader); const schemaPromise = loadSchema(loader); await Promise.all([bufferViewsPromise, texturesPromise, schemaPromise]); if (loader.isDestroyed()) { return; } loader._gltf = void 0; loader._state = ResourceLoaderState_default.LOADED; return loader; } catch (error) { if (loader.isDestroyed()) { return; } loader.unload(); loader._state = ResourceLoaderState_default.FAILED; const errorMessage = "Failed to load structural metadata"; throw loader.getError(errorMessage, error); } } GltfStructuralMetadataLoader.prototype.load = function() { if (defined_default(this._promise)) { return this._promise; } this._state = ResourceLoaderState_default.LOADING; this._promise = loadResources4(this); return this._promise; }; function gatherBufferViewIdsFromProperties(properties, bufferViewIdSet) { for (const propertyId in properties) { if (properties.hasOwnProperty(propertyId)) { const property = properties[propertyId]; const values = property.values; const arrayOffsets = property.arrayOffsets; const stringOffsets = property.stringOffsets; if (defined_default(values)) { bufferViewIdSet[values] = true; } if (defined_default(arrayOffsets)) { bufferViewIdSet[arrayOffsets] = true; } if (defined_default(stringOffsets)) { bufferViewIdSet[stringOffsets] = true; } } } } function gatherBufferViewIdsFromPropertiesLegacy(properties, bufferViewIdSet) { for (const propertyId in properties) { if (properties.hasOwnProperty(propertyId)) { const property = properties[propertyId]; const bufferView = property.bufferView; const arrayOffsetBufferView = property.arrayOffsetBufferView; const stringOffsetBufferView = property.stringOffsetBufferView; if (defined_default(bufferView)) { bufferViewIdSet[bufferView] = true; } if (defined_default(arrayOffsetBufferView)) { bufferViewIdSet[arrayOffsetBufferView] = true; } if (defined_default(stringOffsetBufferView)) { bufferViewIdSet[stringOffsetBufferView] = true; } } } } function gatherUsedBufferViewIds(extension) { const propertyTables = extension.propertyTables; const bufferViewIdSet = {}; if (defined_default(propertyTables)) { for (let i = 0; i < propertyTables.length; i++) { const propertyTable = propertyTables[i]; gatherBufferViewIdsFromProperties( propertyTable.properties, bufferViewIdSet ); } } return bufferViewIdSet; } function gatherUsedBufferViewIdsLegacy(extensionLegacy) { const featureTables = extensionLegacy.featureTables; const bufferViewIdSet = {}; if (defined_default(featureTables)) { for (const featureTableId in featureTables) { if (featureTables.hasOwnProperty(featureTableId)) { const featureTable = featureTables[featureTableId]; const properties = featureTable.properties; if (defined_default(properties)) { gatherBufferViewIdsFromPropertiesLegacy(properties, bufferViewIdSet); } } } } return bufferViewIdSet; } async function loadBufferViews(structuralMetadataLoader) { let bufferViewIds; if (defined_default(structuralMetadataLoader._extension)) { bufferViewIds = gatherUsedBufferViewIds( structuralMetadataLoader._extension ); } else { bufferViewIds = gatherUsedBufferViewIdsLegacy( structuralMetadataLoader._extensionLegacy ); } const bufferViewPromises = []; for (const bufferViewId in bufferViewIds) { if (bufferViewIds.hasOwnProperty(bufferViewId)) { const bufferViewLoader = ResourceCache_default.getBufferViewLoader({ gltf: structuralMetadataLoader._gltf, bufferViewId: parseInt(bufferViewId), gltfResource: structuralMetadataLoader._gltfResource, baseResource: structuralMetadataLoader._baseResource }); structuralMetadataLoader._bufferViewLoaders.push(bufferViewLoader); structuralMetadataLoader._bufferViewIds.push(bufferViewId); bufferViewPromises.push(bufferViewLoader.load()); } } return Promise.all(bufferViewPromises); } function gatherUsedTextureIds(structuralMetadataExtension) { const textureIds = {}; const propertyTextures = structuralMetadataExtension.propertyTextures; if (defined_default(propertyTextures)) { for (let i = 0; i < propertyTextures.length; i++) { const propertyTexture = propertyTextures[i]; const properties = propertyTexture.properties; if (defined_default(properties)) { gatherTextureIdsFromProperties(properties, textureIds); } } } return textureIds; } function gatherTextureIdsFromProperties(properties, textureIds) { for (const propertyId in properties) { if (properties.hasOwnProperty(propertyId)) { const textureInfo = properties[propertyId]; textureIds[textureInfo.index] = textureInfo; } } } function gatherUsedTextureIdsLegacy(extensionLegacy) { const textureIds = {}; const featureTextures = extensionLegacy.featureTextures; if (defined_default(featureTextures)) { for (const featureTextureId in featureTextures) { if (featureTextures.hasOwnProperty(featureTextureId)) { const featureTexture = featureTextures[featureTextureId]; const properties = featureTexture.properties; if (defined_default(properties)) { gatherTextureIdsFromPropertiesLegacy(properties, textureIds); } } } } return textureIds; } function gatherTextureIdsFromPropertiesLegacy(properties, textureIds) { for (const propertyId in properties) { if (properties.hasOwnProperty(propertyId)) { const property = properties[propertyId]; const textureInfo = property.texture; textureIds[textureInfo.index] = textureInfo; } } } function loadTextures(structuralMetadataLoader) { let textureIds; if (defined_default(structuralMetadataLoader._extension)) { textureIds = gatherUsedTextureIds(structuralMetadataLoader._extension); } else { textureIds = gatherUsedTextureIdsLegacy( structuralMetadataLoader._extensionLegacy ); } const gltf = structuralMetadataLoader._gltf; const gltfResource = structuralMetadataLoader._gltfResource; const baseResource2 = structuralMetadataLoader._baseResource; const supportedImageFormats = structuralMetadataLoader._supportedImageFormats; const frameState = structuralMetadataLoader._frameState; const asynchronous = structuralMetadataLoader._asynchronous; const texturePromises = []; for (const textureId in textureIds) { if (textureIds.hasOwnProperty(textureId)) { const textureLoader = ResourceCache_default.getTextureLoader({ gltf, textureInfo: textureIds[textureId], gltfResource, baseResource: baseResource2, supportedImageFormats, frameState, asynchronous }); structuralMetadataLoader._textureLoaders.push(textureLoader); structuralMetadataLoader._textureIds.push(textureId); texturePromises.push(textureLoader.load()); } } return Promise.all(texturePromises); } async function loadSchema(structuralMetadataLoader) { const extension = defaultValue_default( structuralMetadataLoader._extension, structuralMetadataLoader._extensionLegacy ); let schemaLoader; if (defined_default(extension.schemaUri)) { const resource = structuralMetadataLoader._baseResource.getDerivedResource({ url: extension.schemaUri }); schemaLoader = ResourceCache_default.getSchemaLoader({ resource }); } else { schemaLoader = ResourceCache_default.getSchemaLoader({ schema: extension.schema }); } structuralMetadataLoader._schemaLoader = schemaLoader; await schemaLoader.load(); if (!schemaLoader.isDestroyed()) { return schemaLoader.schema; } } GltfStructuralMetadataLoader.prototype.process = function(frameState) { Check_default.typeOf.object("frameState", frameState); if (this._state === ResourceLoaderState_default.READY) { return true; } if (this._state !== ResourceLoaderState_default.LOADED) { return false; } const textureLoaders = this._textureLoaders; const textureLoadersLength = textureLoaders.length; let ready = true; for (let i = 0; i < textureLoadersLength; ++i) { const textureLoader = textureLoaders[i]; const textureReady = textureLoader.process(frameState); ready = ready && textureReady; } if (!ready) { return false; } const schema = this._schemaLoader.schema; const bufferViews = {}; for (let i = 0; i < this._bufferViewIds.length; ++i) { const bufferViewId = this._bufferViewIds[i]; const bufferViewLoader = this._bufferViewLoaders[i]; if (!bufferViewLoader.isDestroyed()) { const bufferViewTypedArray = new Uint8Array(bufferViewLoader.typedArray); bufferViews[bufferViewId] = bufferViewTypedArray; } } const textures = {}; for (let i = 0; i < this._textureIds.length; ++i) { const textureId = this._textureIds[i]; const textureLoader = textureLoaders[i]; if (!textureLoader.isDestroyed()) { textures[textureId] = textureLoader.texture; } } if (defined_default(this._extension)) { this._structuralMetadata = parseStructuralMetadata_default({ extension: this._extension, schema, bufferViews, textures }); } else { this._structuralMetadata = parseFeatureMetadataLegacy_default({ extension: this._extensionLegacy, schema, bufferViews, textures }); } unloadBufferViews(this); this._state = ResourceLoaderState_default.READY; return true; }; function unloadBufferViews(structuralMetadataLoader) { const bufferViewLoaders = structuralMetadataLoader._bufferViewLoaders; const bufferViewLoadersLength = bufferViewLoaders.length; for (let i = 0; i < bufferViewLoadersLength; ++i) { ResourceCache_default.unload(bufferViewLoaders[i]); } structuralMetadataLoader._bufferViewLoaders.length = 0; structuralMetadataLoader._bufferViewIds.length = 0; } function unloadTextures(structuralMetadataLoader) { const textureLoaders = structuralMetadataLoader._textureLoaders; const textureLoadersLength = textureLoaders.length; for (let i = 0; i < textureLoadersLength; ++i) { ResourceCache_default.unload(textureLoaders[i]); } structuralMetadataLoader._textureLoaders.length = 0; structuralMetadataLoader._textureIds.length = 0; } GltfStructuralMetadataLoader.prototype.unload = function() { unloadBufferViews(this); unloadTextures(this); if (defined_default(this._schemaLoader)) { ResourceCache_default.unload(this._schemaLoader); } this._schemaLoader = void 0; this._structuralMetadata = void 0; }; var GltfStructuralMetadataLoader_default = GltfStructuralMetadataLoader; // packages/engine/Source/Scene/InstanceAttributeSemantic.js var InstanceAttributeSemantic = { /** * Per-instance translation. * * @type {string} * @constant */ TRANSLATION: "TRANSLATION", /** * Per-instance rotation. * * @type {string} * @constant */ ROTATION: "ROTATION", /** * Per-instance scale. * * @type {string} * @constant */ SCALE: "SCALE", /** * Per-instance feature ID. * * @type {string} * @constant */ FEATURE_ID: "_FEATURE_ID" }; InstanceAttributeSemantic.fromGltfSemantic = function(gltfSemantic) { Check_default.typeOf.string("gltfSemantic", gltfSemantic); let semantic = gltfSemantic; const setIndexRegex = /^(\w+)_\d+$/; const setIndexMatch = setIndexRegex.exec(gltfSemantic); if (setIndexMatch !== null) { semantic = setIndexMatch[1]; } switch (semantic) { case "TRANSLATION": return InstanceAttributeSemantic.TRANSLATION; case "ROTATION": return InstanceAttributeSemantic.ROTATION; case "SCALE": return InstanceAttributeSemantic.SCALE; case "_FEATURE_ID": return InstanceAttributeSemantic.FEATURE_ID; } return void 0; }; var InstanceAttributeSemantic_default = Object.freeze(InstanceAttributeSemantic); // packages/engine/Source/Scene/Model/PrimitiveOutlineGenerator.js var MAX_GLTF_UINT16_INDEX = 65534; var MAX_GLTF_UINT8_INDEX = 255; function PrimitiveOutlineGenerator(options) { options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT); const triangleIndices = options.triangleIndices; const outlineIndices = options.outlineIndices; const originalVertexCount = options.originalVertexCount; Check_default.typeOf.object("options.triangleIndices", triangleIndices); Check_default.typeOf.object("options.outlineIndices", outlineIndices); Check_default.typeOf.number("options.originalVertexCount", originalVertexCount); this._triangleIndices = triangleIndices; this._originalVertexCount = originalVertexCount; this._edges = new EdgeSet(outlineIndices, originalVertexCount); this._outlineCoordinatesTypedArray = void 0; this._extraVertices = []; initialize5(this); } Object.defineProperties(PrimitiveOutlineGenerator.prototype, { /** * The updated triangle indices after generating outlines. The caller is for * responsible for updating the primitive's indices to use this array. * * @memberof PrimitiveOutlineGenerator.prototype * * @type {Uint8Array|Uint16Array|Uint32Array} * @readonly * * @private */ updatedTriangleIndices: { get: function() { return this._triangleIndices; } }, /** * The computed outline coordinates. The caller is responsible for * turning this into a vec3 attribute for rendering. * * @memberof PrimitiveOutlineGenerator.prototype * * @type {Float32Array} * @readonly * * @private */ outlineCoordinates: { get: function() { return this._outlineCoordinatesTypedArray; } } }); function initialize5(outlineGenerator) { let triangleIndices = outlineGenerator._triangleIndices; const edges = outlineGenerator._edges; const outlineCoordinates = []; const extraVertices = outlineGenerator._extraVertices; const vertexCount = outlineGenerator._originalVertexCount; const vertexCopies = {}; for (let i = 0; i < triangleIndices.length; i += 3) { let i0 = triangleIndices[i]; let i1 = triangleIndices[i + 1]; let i2 = triangleIndices[i + 2]; const all = false; const hasEdge01 = all || edges.hasEdge(i0, i1); const hasEdge12 = all || edges.hasEdge(i1, i2); const hasEdge20 = all || edges.hasEdge(i2, i0); let unmatchableVertexIndex = matchAndStoreCoordinates( outlineCoordinates, i0, i1, i2, hasEdge01, hasEdge12, hasEdge20 ); while (defined_default(unmatchableVertexIndex)) { let copy = vertexCopies[unmatchableVertexIndex]; if (!defined_default(copy)) { copy = vertexCount + extraVertices.length; let original2 = unmatchableVertexIndex; while (original2 >= vertexCount) { original2 = extraVertices[original2 - vertexCount]; } extraVertices.push(original2); vertexCopies[unmatchableVertexIndex] = copy; } if (copy > MAX_GLTF_UINT16_INDEX && (triangleIndices instanceof Uint16Array || triangleIndices instanceof Uint8Array)) { triangleIndices = new Uint32Array(triangleIndices); } else if (copy > MAX_GLTF_UINT8_INDEX && triangleIndices instanceof Uint8Array) { triangleIndices = new Uint16Array(triangleIndices); } if (unmatchableVertexIndex === i0) { i0 = copy; triangleIndices[i] = copy; } else if (unmatchableVertexIndex === i1) { i1 = copy; triangleIndices[i + 1] = copy; } else { i2 = copy; triangleIndices[i + 2] = copy; } unmatchableVertexIndex = matchAndStoreCoordinates( outlineCoordinates, i0, i1, i2, hasEdge01, hasEdge12, hasEdge20 ); } } outlineGenerator._triangleIndices = triangleIndices; outlineGenerator._outlineCoordinatesTypedArray = new Float32Array( outlineCoordinates ); } function matchAndStoreCoordinates(outlineCoordinates, i0, i1, i2, hasEdge01, hasEdge12, hasEdge20) { const a0 = hasEdge20 ? 1 : 0; const b0 = hasEdge01 ? 1 : 0; const c0 = 0; const i0Mask = computeOrderMask(outlineCoordinates, i0, a0, b0, c0); if (i0Mask === 0) { return i0; } const a1 = 0; const b1 = hasEdge01 ? 1 : 0; const c14 = hasEdge12 ? 1 : 0; const i1Mask = computeOrderMask(outlineCoordinates, i1, a1, b1, c14); if (i1Mask === 0) { return i1; } const a22 = hasEdge20 ? 1 : 0; const b2 = 0; const c22 = hasEdge12 ? 1 : 0; const i2Mask = computeOrderMask(outlineCoordinates, i2, a22, b2, c22); if (i2Mask === 0) { return i2; } const workingOrders = i0Mask & i1Mask & i2Mask; let a3, b, c; if (workingOrders & 1 << 0) { a3 = 0; b = 1; c = 2; } else if (workingOrders & 1 << 1) { a3 = 0; c = 1; b = 2; } else if (workingOrders & 1 << 2) { b = 0; a3 = 1; c = 2; } else if (workingOrders & 1 << 3) { b = 0; c = 1; a3 = 2; } else if (workingOrders & 1 << 4) { c = 0; a3 = 1; b = 2; } else if (workingOrders & 1 << 5) { c = 0; b = 1; a3 = 2; } else { const i0ValidOrderCount = popcount6Bit(i0Mask); const i1ValidOrderCount = popcount6Bit(i1Mask); const i2ValidOrderCount = popcount6Bit(i2Mask); if (i0ValidOrderCount < i1ValidOrderCount && i0ValidOrderCount < i2ValidOrderCount) { return i0; } else if (i1ValidOrderCount < i2ValidOrderCount) { return i1; } return i2; } const i0Start = i0 * 3; outlineCoordinates[i0Start + a3] = a0; outlineCoordinates[i0Start + b] = b0; outlineCoordinates[i0Start + c] = c0; const i1Start = i1 * 3; outlineCoordinates[i1Start + a3] = a1; outlineCoordinates[i1Start + b] = b1; outlineCoordinates[i1Start + c] = c14; const i2Start = i2 * 3; outlineCoordinates[i2Start + a3] = a22; outlineCoordinates[i2Start + b] = b2; outlineCoordinates[i2Start + c] = c22; return void 0; } function computeOrderMask(outlineCoordinates, vertexIndex, a3, b, c) { const startIndex = vertexIndex * 3; const first = outlineCoordinates[startIndex]; const second = outlineCoordinates[startIndex + 1]; const third = outlineCoordinates[startIndex + 2]; if (!defined_default(first)) { return 63; } return (first === a3 && second === b && third === c) << 0 | (first === a3 && second === c && third === b) << 1 | (first === b && second === a3 && third === c) << 2 | (first === b && second === c && third === a3) << 3 | (first === c && second === a3 && third === b) << 4 | (first === c && second === b && third === a3) << 5; } function popcount6Bit(value) { return (value & 1) + (value >> 1 & 1) + (value >> 2 & 1) + (value >> 3 & 1) + (value >> 4 & 1) + (value >> 5 & 1); } PrimitiveOutlineGenerator.prototype.updateAttribute = function(attributeTypedArray) { const extraVertices = this._extraVertices; const originalLength = attributeTypedArray.length; const stride = originalLength / this._originalVertexCount; const extraVerticesLength = extraVertices.length; const ArrayType = attributeTypedArray.constructor; const result = new ArrayType( attributeTypedArray.length + extraVerticesLength * stride ); result.set(attributeTypedArray); for (let i = 0; i < extraVerticesLength; i++) { const sourceIndex = extraVertices[i] * stride; const resultIndex = originalLength + i * stride; for (let j = 0; j < stride; j++) { result[resultIndex + j] = result[sourceIndex + j]; } } return result; }; PrimitiveOutlineGenerator.createTexture = function(context) { let cache = context.cache.modelOutliningCache; if (!defined_default(cache)) { cache = context.cache.modelOutliningCache = {}; } if (defined_default(cache.outlineTexture)) { return cache.outlineTexture; } const maxSize = Math.min(4096, ContextLimits_default.maximumTextureSize); let size = maxSize; const levelZero = createMipLevel(size); const mipLevels = []; while (size > 1) { size >>= 1; mipLevels.push(createMipLevel(size)); } const texture = new Texture_default({ context, source: { arrayBufferView: levelZero, mipLevels }, width: maxSize, height: 1, pixelFormat: PixelFormat_default.LUMINANCE, sampler: new Sampler_default({ wrapS: TextureWrap_default.CLAMP_TO_EDGE, wrapT: TextureWrap_default.CLAMP_TO_EDGE, minificationFilter: TextureMinificationFilter_default.LINEAR_MIPMAP_LINEAR, magnificationFilter: TextureMagnificationFilter_default.LINEAR }) }); cache.outlineTexture = texture; return texture; }; function createMipLevel(size) { const texture = new Uint8Array(size); texture[size - 1] = 192; if (size === 8) { texture[size - 1] = 96; } else if (size === 4) { texture[size - 1] = 48; } else if (size === 2) { texture[size - 1] = 24; } else if (size === 1) { texture[size - 1] = 12; } return texture; } function EdgeSet(edgeIndices, originalVertexCount) { this._originalVertexCount = originalVertexCount; this._edges = /* @__PURE__ */ new Set(); for (let i = 0; i < edgeIndices.length; i += 2) { const a3 = edgeIndices[i]; const b = edgeIndices[i + 1]; const small = Math.min(a3, b); const big = Math.max(a3, b); const hash2 = small * this._originalVertexCount + big; this._edges.add(hash2); } } EdgeSet.prototype.hasEdge = function(a3, b) { const small = Math.min(a3, b); const big = Math.max(a3, b); const hash2 = small * this._originalVertexCount + big; return this._edges.has(hash2); }; var PrimitiveOutlineGenerator_default = PrimitiveOutlineGenerator; // packages/engine/Source/Scene/PrimitiveLoadPlan.js function AttributeLoadPlan(attribute) { Check_default.typeOf.object("attribute", attribute); this.attribute = attribute; this.loadBuffer = false; this.loadTypedArray = false; } function IndicesLoadPlan(indices2) { Check_default.typeOf.object("indices", indices2); this.indices = indices2; this.loadBuffer = false; this.loadTypedArray = false; } function PrimitiveLoadPlan(primitive) { Check_default.typeOf.object("primitive", primitive); this.primitive = primitive; this.attributePlans = []; this.indicesPlan = void 0; this.needsOutlines = false; this.outlineIndices = void 0; } PrimitiveLoadPlan.prototype.postProcess = function(context) { if (this.needsOutlines) { generateOutlines(this); generateBuffers(this, context); } }; function generateOutlines(loadPlan) { const primitive = loadPlan.primitive; const indices2 = primitive.indices; const vertexCount = primitive.attributes[0].count; const generator = new PrimitiveOutlineGenerator_default({ triangleIndices: indices2.typedArray, outlineIndices: loadPlan.outlineIndices, originalVertexCount: vertexCount }); indices2.typedArray = generator.updatedTriangleIndices; indices2.indexDatatype = IndexDatatype_default.fromTypedArray(indices2.typedArray); const outlineCoordinates = makeOutlineCoordinatesAttribute( generator.outlineCoordinates ); const outlineCoordinatesPlan = new AttributeLoadPlan(outlineCoordinates); outlineCoordinatesPlan.loadBuffer = true; outlineCoordinatesPlan.loadTypedArray = false; loadPlan.attributePlans.push(outlineCoordinatesPlan); primitive.outlineCoordinates = outlineCoordinatesPlan.attribute; const attributePlans = loadPlan.attributePlans; const attributesLength = loadPlan.attributePlans.length; for (let i = 0; i < attributesLength; i++) { const attribute = attributePlans[i].attribute; attribute.typedArray = generator.updateAttribute(attribute.typedArray); } } function makeOutlineCoordinatesAttribute(outlineCoordinatesTypedArray) { const attribute = new ModelComponents_default.Attribute(); attribute.name = "_OUTLINE_COORDINATES"; attribute.typedArray = outlineCoordinatesTypedArray; attribute.componentDatatype = ComponentDatatype_default.FLOAT; attribute.type = AttributeType_default.VEC3; attribute.normalized = false; attribute.count = outlineCoordinatesTypedArray.length / 3; return attribute; } function generateBuffers(loadPlan, context) { generateAttributeBuffers(loadPlan.attributePlans, context); if (defined_default(loadPlan.indicesPlan)) { generateIndexBuffers(loadPlan.indicesPlan, context); } } function generateAttributeBuffers(attributePlans, context) { const attributesLength = attributePlans.length; for (let i = 0; i < attributesLength; i++) { const attributePlan = attributePlans[i]; const attribute = attributePlan.attribute; const typedArray = attribute.typedArray; if (attributePlan.loadBuffer) { const buffer = Buffer_default.createVertexBuffer({ typedArray, context, usage: BufferUsage_default.STATIC_DRAW }); buffer.vertexArrayDestroyable = false; attribute.buffer = buffer; } if (!attributePlan.loadTypedArray) { attribute.typedArray = void 0; } } } function generateIndexBuffers(indicesPlan, context) { const indices2 = indicesPlan.indices; if (indicesPlan.loadBuffer) { const buffer = Buffer_default.createIndexBuffer({ typedArray: indices2.typedArray, context, usage: BufferUsage_default.STATIC_DRAW, indexDatatype: indices2.indexDatatype }); indices2.buffer = buffer; buffer.vertexArrayDestroyable = false; } if (!indicesPlan.loadTypedArray) { indices2.typedArray = void 0; } } PrimitiveLoadPlan.AttributeLoadPlan = AttributeLoadPlan; PrimitiveLoadPlan.IndicesLoadPlan = IndicesLoadPlan; var PrimitiveLoadPlan_default = PrimitiveLoadPlan; // packages/engine/Source/Scene/SupportedImageFormats.js function SupportedImageFormats(options) { options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT); this.webp = defaultValue_default(options.webp, false); this.basis = defaultValue_default(options.basis, false); } var SupportedImageFormats_default = SupportedImageFormats; // packages/engine/Source/Scene/GltfLoader.js var Attribute2 = ModelComponents_default.Attribute; var Indices2 = ModelComponents_default.Indices; var FeatureIdAttribute2 = ModelComponents_default.FeatureIdAttribute; var FeatureIdTexture2 = ModelComponents_default.FeatureIdTexture; var FeatureIdImplicitRange2 = ModelComponents_default.FeatureIdImplicitRange; var MorphTarget2 = ModelComponents_default.MorphTarget; var Primitive3 = ModelComponents_default.Primitive; var Instances2 = ModelComponents_default.Instances; var Skin2 = ModelComponents_default.Skin; var Node4 = ModelComponents_default.Node; var AnimatedPropertyType2 = ModelComponents_default.AnimatedPropertyType; var AnimationSampler2 = ModelComponents_default.AnimationSampler; var AnimationTarget2 = ModelComponents_default.AnimationTarget; var AnimationChannel2 = ModelComponents_default.AnimationChannel; var Animation2 = ModelComponents_default.Animation; var ArticulationStage2 = ModelComponents_default.ArticulationStage; var Articulation2 = ModelComponents_default.Articulation; var Asset2 = ModelComponents_default.Asset; var Scene2 = ModelComponents_default.Scene; var Components2 = ModelComponents_default.Components; var MetallicRoughness2 = ModelComponents_default.MetallicRoughness; var SpecularGlossiness2 = ModelComponents_default.SpecularGlossiness; var Material3 = ModelComponents_default.Material; var GltfLoaderState = { /** * The initial state of the glTF loader before load() is called. * * @type {number} * @constant * * @private */ NOT_LOADED: 0, /** * The state of the loader while waiting for the glTF JSON loader promise * to resolve. * * @type {number} * @constant * * @private */ LOADING: 1, /** * The state of the loader once the glTF JSON is loaded but before * process() is called. * * @type {number} * @constant * * @private */ LOADED: 2, /** * The state of the loader while parsing the glTF and creating GPU resources * as needed. * * @type {number} * @constant * * @private */ PROCESSING: 3, /** * For some features like handling CESIUM_primitive_outlines, the geometry * must be modified after it is loaded. The post-processing state handles * any geometry modification (if needed). ** This state is not used for asynchronous texture loading. *
* * @type {number} * @constant * * @private */ POST_PROCESSING: 4, /** * Once the processing/post-processing states are finished, the loader * enters the processed state (sometimes from a promise chain). The next * call to process() will advance to the ready state. * * @type {number} * @constant * * @private */ PROCESSED: 5, /** * When the loader reaches the ready state, the loaders' promise will be * resolved. * * @type {number} * @constant * * @private */ READY: 6, /** * If an error occurs at any point, the loader switches to the failed state. * * @type {number} * @constant * * @private */ FAILED: 7, /** * If unload() is called, the loader switches to the unloaded state. * * @type {number} * @constant * * @private */ UNLOADED: 8 }; function GltfLoader(options) { options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT); const gltfResource = options.gltfResource; let baseResource2 = options.baseResource; const typedArray = options.typedArray; const releaseGltfJson = defaultValue_default(options.releaseGltfJson, false); const asynchronous = defaultValue_default(options.asynchronous, true); const incrementallyLoadTextures = defaultValue_default( options.incrementallyLoadTextures, true ); const upAxis = defaultValue_default(options.upAxis, Axis_default.Y); const forwardAxis = defaultValue_default(options.forwardAxis, Axis_default.Z); const loadAttributesAsTypedArray = defaultValue_default( options.loadAttributesAsTypedArray, false ); const loadAttributesFor2D = defaultValue_default(options.loadAttributesFor2D, false); const loadIndicesForWireframe = defaultValue_default( options.loadIndicesForWireframe, false ); const loadPrimitiveOutline2 = defaultValue_default(options.loadPrimitiveOutline, true); const loadForClassification = defaultValue_default( options.loadForClassification, false ); const renameBatchIdSemantic = defaultValue_default( options.renameBatchIdSemantic, false ); Check_default.typeOf.object("options.gltfResource", gltfResource); baseResource2 = defined_default(baseResource2) ? baseResource2 : gltfResource.clone(); this._gltfJson = options.gltfJson; this._gltfResource = gltfResource; this._baseResource = baseResource2; this._typedArray = typedArray; this._releaseGltfJson = releaseGltfJson; this._asynchronous = asynchronous; this._incrementallyLoadTextures = incrementallyLoadTextures; this._upAxis = upAxis; this._forwardAxis = forwardAxis; this._loadAttributesAsTypedArray = loadAttributesAsTypedArray; this._loadAttributesFor2D = loadAttributesFor2D; this._loadIndicesForWireframe = loadIndicesForWireframe; this._loadPrimitiveOutline = loadPrimitiveOutline2; this._loadForClassification = loadForClassification; this._renameBatchIdSemantic = renameBatchIdSemantic; this._sortedPropertyTableIds = void 0; this._sortedFeatureTextureIds = void 0; this._gltfJsonLoader = void 0; this._state = GltfLoaderState.NOT_LOADED; this._textureState = GltfLoaderState.NOT_LOADED; this._promise = void 0; this._processError = void 0; this._textureErrors = []; this._primitiveLoadPlans = []; this._loaderPromises = []; this._textureLoaders = []; this._texturesPromises = []; this._textureCallbacks = []; this._bufferViewLoaders = []; this._geometryLoaders = []; this._geometryCallbacks = []; this._structuralMetadataLoader = void 0; this._loadResourcesPromise = void 0; this._resourcesLoaded = false; this._texturesLoaded = false; this._postProcessBuffers = []; this._components = void 0; } if (defined_default(Object.create)) { GltfLoader.prototype = Object.create(ResourceLoader_default.prototype); GltfLoader.prototype.constructor = GltfLoader; } Object.defineProperties(GltfLoader.prototype, { /** * The cache key of the resource. * * @memberof GltfLoader.prototype * * @type {string} * @readonly * @private */ cacheKey: { get: function() { return void 0; } }, /** * The loaded components. * * @memberof GltfLoader.prototype * * @type {ModelComponents.Components} * @readonly * @private */ components: { get: function() { return this._components; } }, /** * The loaded glTF json. * * @memberof GltfLoader.prototype * * @type {object} * @readonly * @private */ gltfJson: { get: function() { if (defined_default(this._gltfJsonLoader)) { return this._gltfJsonLoader.gltf; } return this._gltfJson; } }, /** * Returns true if textures are loaded separately from the other glTF resources. * * @memberof GltfLoader.prototype * * @type {boolean} * @readonly * @private */ incrementallyLoadTextures: { get: function() { return this._incrementallyLoadTextures; } }, /** * true if textures are loaded, useful when incrementallyLoadTextures is true * * @memberof GltfLoader.prototype * * @type {boolean} * @readonly * @private */ texturesLoaded: { get: function() { return this._texturesLoaded; } } }); async function loadGltfJson(loader) { loader._state = GltfLoaderState.LOADING; loader._textureState = GltfLoaderState.LOADING; try { const gltfJsonLoader = ResourceCache_default.getGltfJsonLoader({ gltfResource: loader._gltfResource, baseResource: loader._baseResource, typedArray: loader._typedArray, gltfJson: loader._gltfJson }); loader._gltfJsonLoader = gltfJsonLoader; await gltfJsonLoader.load(); if (loader.isDestroyed() || loader.isUnloaded() || gltfJsonLoader.isDestroyed()) { return; } loader._state = GltfLoaderState.LOADED; loader._textureState = GltfLoaderState.LOADED; return loader; } catch (error) { if (loader.isDestroyed()) { return; } loader._state = GltfLoaderState.FAILED; loader._textureState = GltfLoaderState.FAILED; handleError6(loader, error); } } async function loadResources5(loader, frameState) { if (!FeatureDetection_default.supportsWebP.initialized) { await FeatureDetection_default.supportsWebP.initialize(); } const supportedImageFormats = new SupportedImageFormats_default({ webp: FeatureDetection_default.supportsWebP(), basis: frameState.context.supportsBasis }); const gltf = loader.gltfJson; const promise = parse(loader, gltf, supportedImageFormats, frameState); loader._state = GltfLoaderState.PROCESSING; loader._textureState = GltfLoaderState.PROCESSING; if (defined_default(loader._gltfJsonLoader) && loader._releaseGltfJson) { ResourceCache_default.unload(loader._gltfJsonLoader); loader._gltfJsonLoader = void 0; } return promise; } GltfLoader.prototype.load = async function() { if (defined_default(this._promise)) { return this._promise; } this._promise = loadGltfJson(this); return this._promise; }; function handleError6(gltfLoader, error) { gltfLoader.unload(); const errorMessage = "Failed to load glTF"; throw gltfLoader.getError(errorMessage, error); } function processLoaders(loader, frameState) { let i; let ready = true; const geometryLoaders = loader._geometryLoaders; const geometryLoadersLength = geometryLoaders.length; for (i = 0; i < geometryLoadersLength; ++i) { const geometryReady = geometryLoaders[i].process(frameState); if (geometryReady && defined_default(loader._geometryCallbacks[i])) { loader._geometryCallbacks[i](); loader._geometryCallbacks[i] = void 0; } ready = ready && geometryReady; } const structuralMetadataLoader = loader._structuralMetadataLoader; if (defined_default(structuralMetadataLoader)) { const metadataReady = structuralMetadataLoader.process(frameState); if (metadataReady) { loader._components.structuralMetadata = structuralMetadataLoader.structuralMetadata; } ready = ready && metadataReady; } if (ready) { loader._state = GltfLoaderState.POST_PROCESSING; } } function postProcessGeometry(loader, context) { const loadPlans = loader._primitiveLoadPlans; const length3 = loadPlans.length; for (let i = 0; i < length3; i++) { const loadPlan = loadPlans[i]; loadPlan.postProcess(context); if (loadPlan.needsOutlines) { gatherPostProcessBuffers(loader, loadPlan); } } } function gatherPostProcessBuffers(loader, primitiveLoadPlan) { const buffers = loader._postProcessBuffers; const primitive = primitiveLoadPlan.primitive; const outlineCoordinates = primitive.outlineCoordinates; if (defined_default(outlineCoordinates)) { buffers.push(outlineCoordinates.buffer); } const attributes = primitive.attributes; const length3 = attributes.length; for (let i = 0; i < length3; i++) { const attribute = attributes[i]; if (defined_default(attribute.buffer)) { buffers.push(attribute.buffer); } } const indices2 = primitive.indices; if (defined_default(indices2) && defined_default(indices2.buffer)) { buffers.push(indices2.buffer); } } GltfLoader.prototype._process = function(frameState) { if (this._state === GltfLoaderState.READY) { return true; } if (this._state === GltfLoaderState.PROCESSING) { processLoaders(this, frameState); } if (this._resourcesLoaded && this._state === GltfLoaderState.POST_PROCESSING) { postProcessGeometry(this, frameState.context); this._state = GltfLoaderState.PROCESSED; } if (this._resourcesLoaded && this._state === GltfLoaderState.PROCESSED) { unloadBufferViewLoaders(this); this._typedArray = void 0; this._state = GltfLoaderState.READY; return true; } return false; }; GltfLoader.prototype._processTextures = function(frameState) { if (this._textureState === GltfLoaderState.READY) { return true; } if (this._textureState !== GltfLoaderState.PROCESSING) { return false; } let i; let ready = true; const textureLoaders = this._textureLoaders; const textureLoadersLength = textureLoaders.length; for (i = 0; i < textureLoadersLength; ++i) { const textureReady = textureLoaders[i].process(frameState); if (textureReady && defined_default(this._textureCallbacks[i])) { this._textureCallbacks[i](); this._textureCallbacks[i] = void 0; } ready = ready && textureReady; } if (!ready) { return false; } this._textureState = GltfLoaderState.READY; this._texturesLoaded = true; return true; }; GltfLoader.prototype.process = function(frameState) { Check_default.typeOf.object("frameState", frameState); if (this._state === GltfLoaderState.LOADED && !defined_default(this._loadResourcesPromise)) { this._loadResourcesPromise = loadResources5(this, frameState).then(() => { this._resourcesLoaded = true; }).catch((error) => { this._processError = error; }); } if (defined_default(this._processError)) { this._state = GltfLoaderState.FAILED; const error = this._processError; this._processError = void 0; handleError6(this, error); } const textureError = this._textureErrors.pop(); if (defined_default(textureError)) { const error = this.getError("Failed to load glTF texture", textureError); error.name = "TextureError"; throw error; } if (this._state === GltfLoaderState.FAILED) { return false; } let ready = false; try { ready = this._process(frameState); } catch (error) { this._state = GltfLoaderState.FAILED; handleError6(this, error); } let texturesReady = false; try { texturesReady = this._processTextures(frameState); } catch (error) { this._textureState = GltfLoaderState.FAILED; handleError6(this, error); } if (this._incrementallyLoadTextures) { return ready; } return ready && texturesReady; }; function getVertexBufferLoader(loader, gltf, accessorId, semantic, draco, loadBuffer, loadTypedArray, frameState) { const accessor = gltf.accessors[accessorId]; const bufferViewId = accessor.bufferView; const vertexBufferLoader = ResourceCache_default.getVertexBufferLoader({ gltf, gltfResource: loader._gltfResource, baseResource: loader._baseResource, frameState, bufferViewId, draco, attributeSemantic: semantic, accessorId, asynchronous: loader._asynchronous, loadBuffer, loadTypedArray }); return vertexBufferLoader; } function getIndexBufferLoader(loader, gltf, accessorId, draco, loadBuffer, loadTypedArray, frameState) { const indexBufferLoader = ResourceCache_default.getIndexBufferLoader({ gltf, accessorId, gltfResource: loader._gltfResource, baseResource: loader._baseResource, frameState, draco, asynchronous: loader._asynchronous, loadBuffer, loadTypedArray }); return indexBufferLoader; } function getBufferViewLoader(loader, gltf, bufferViewId) { const bufferViewLoader = ResourceCache_default.getBufferViewLoader({ gltf, bufferViewId, gltfResource: loader._gltfResource, baseResource: loader._baseResource }); loader._bufferViewLoaders.push(bufferViewLoader); return bufferViewLoader; } function getPackedTypedArray(gltf, accessor, bufferViewTypedArray) { let byteOffset = accessor.byteOffset; const byteStride = getAccessorByteStride_default(gltf, accessor); const count = accessor.count; const componentCount = numberOfComponentsForType_default(accessor.type); const componentType = accessor.componentType; const componentByteLength = ComponentDatatype_default.getSizeInBytes(componentType); const defaultByteStride = componentByteLength * componentCount; const componentsLength = count * componentCount; if (byteStride === defaultByteStride) { bufferViewTypedArray = new Uint8Array(bufferViewTypedArray); return ComponentDatatype_default.createArrayBufferView( componentType, bufferViewTypedArray.buffer, bufferViewTypedArray.byteOffset + byteOffset, componentsLength ); } const accessorTypedArray = ComponentDatatype_default.createTypedArray( componentType, componentsLength ); const dataView = new DataView(bufferViewTypedArray.buffer); const components = new Array(componentCount); const componentReader = getComponentReader_default(accessor.componentType); byteOffset = bufferViewTypedArray.byteOffset + byteOffset; for (let i = 0; i < count; ++i) { componentReader( dataView, byteOffset, componentCount, componentByteLength, components ); for (let j = 0; j < componentCount; ++j) { accessorTypedArray[i * componentCount + j] = components[j]; } byteOffset += byteStride; } return accessorTypedArray; } function loadDefaultAccessorValues(accessor, values) { const accessorType = accessor.type; if (accessorType === AttributeType_default.SCALAR) { return values.fill(0); } const MathType = AttributeType_default.getMathType(accessorType); return values.fill(MathType.clone(MathType.ZERO)); } function loadAccessorValues(accessor, typedArray, values, useQuaternion) { const accessorType = accessor.type; const accessorCount = accessor.count; if (accessorType === AttributeType_default.SCALAR) { for (let i = 0; i < accessorCount; i++) { values[i] = typedArray[i]; } } else if (accessorType === AttributeType_default.VEC4 && useQuaternion) { for (let i = 0; i < accessorCount; i++) { values[i] = Quaternion_default.unpack(typedArray, i * 4); } } else { const MathType = AttributeType_default.getMathType(accessorType); const numberOfComponents = AttributeType_default.getNumberOfComponents( accessorType ); for (let i = 0; i < accessorCount; i++) { values[i] = MathType.unpack(typedArray, i * numberOfComponents); } } return values; } async function loadAccessorBufferView(loader, bufferViewLoader, gltf, accessor, useQuaternion, values) { await bufferViewLoader.load(); if (loader.isDestroyed()) { return; } const bufferViewTypedArray = bufferViewLoader.typedArray; const typedArray = getPackedTypedArray(gltf, accessor, bufferViewTypedArray); useQuaternion = defaultValue_default(useQuaternion, false); loadAccessorValues(accessor, typedArray, values, useQuaternion); } function loadAccessor(loader, gltf, accessorId, useQuaternion) { const accessor = gltf.accessors[accessorId]; const accessorCount = accessor.count; const values = new Array(accessorCount); const bufferViewId = accessor.bufferView; if (defined_default(bufferViewId)) { const bufferViewLoader = getBufferViewLoader(loader, gltf, bufferViewId); const promise = loadAccessorBufferView( loader, bufferViewLoader, gltf, accessor, useQuaternion, values ); loader._loaderPromises.push(promise); return values; } return loadDefaultAccessorValues(accessor, values); } function fromArray(MathType, values) { if (!defined_default(values)) { return void 0; } if (MathType === Number) { return values[0]; } return MathType.unpack(values); } function getDefault2(MathType) { if (MathType === Number) { return 0; } return new MathType(); } function getQuantizationDivisor(componentDatatype) { switch (componentDatatype) { case ComponentDatatype_default.BYTE: return 127; case ComponentDatatype_default.UNSIGNED_BYTE: return 255; case ComponentDatatype_default.SHORT: return 32767; case ComponentDatatype_default.UNSIGNED_SHORT: return 65535; default: return 1; } } var minimumBoundsByType = { VEC2: new Cartesian2_default(-1, -1), VEC3: new Cartesian3_default(-1, -1, -1), VEC4: new Cartesian4_default(-1, -1, -1, -1) }; function dequantizeMinMax(attribute, VectorType) { const divisor = getQuantizationDivisor(attribute.componentDatatype); const minimumBound = minimumBoundsByType[attribute.type]; let min3 = attribute.min; if (defined_default(min3)) { min3 = VectorType.divideByScalar(min3, divisor, min3); min3 = VectorType.maximumByComponent(min3, minimumBound, min3); } let max3 = attribute.max; if (defined_default(max3)) { max3 = VectorType.divideByScalar(max3, divisor, max3); max3 = VectorType.maximumByComponent(max3, minimumBound, max3); } attribute.min = min3; attribute.max = max3; } function setQuantizationFromWeb3dQuantizedAttributes(extension, attribute, MathType) { const decodeMatrix = extension.decodeMatrix; const decodedMin = fromArray(MathType, extension.decodedMin); const decodedMax = fromArray(MathType, extension.decodedMax); if (defined_default(decodedMin) && defined_default(decodedMax)) { attribute.min = decodedMin; attribute.max = decodedMax; } const quantization = new ModelComponents_default.Quantization(); quantization.componentDatatype = attribute.componentDatatype; quantization.type = attribute.type; if (decodeMatrix.length === 4) { quantization.quantizedVolumeOffset = decodeMatrix[2]; quantization.quantizedVolumeStepSize = decodeMatrix[0]; } else if (decodeMatrix.length === 9) { quantization.quantizedVolumeOffset = new Cartesian2_default( decodeMatrix[6], decodeMatrix[7] ); quantization.quantizedVolumeStepSize = new Cartesian2_default( decodeMatrix[0], decodeMatrix[4] ); } else if (decodeMatrix.length === 16) { quantization.quantizedVolumeOffset = new Cartesian3_default( decodeMatrix[12], decodeMatrix[13], decodeMatrix[14] ); quantization.quantizedVolumeStepSize = new Cartesian3_default( decodeMatrix[0], decodeMatrix[5], decodeMatrix[10] ); } else if (decodeMatrix.length === 25) { quantization.quantizedVolumeOffset = new Cartesian4_default( decodeMatrix[20], decodeMatrix[21], decodeMatrix[22], decodeMatrix[23] ); quantization.quantizedVolumeStepSize = new Cartesian4_default( decodeMatrix[0], decodeMatrix[6], decodeMatrix[12], decodeMatrix[18] ); } attribute.quantization = quantization; } function createAttribute(gltf, accessorId, name, semantic, setIndex) { const accessor = gltf.accessors[accessorId]; const MathType = AttributeType_default.getMathType(accessor.type); const normalized = defaultValue_default(accessor.normalized, false); const attribute = new Attribute2(); attribute.name = name; attribute.semantic = semantic; attribute.setIndex = setIndex; attribute.constant = getDefault2(MathType); attribute.componentDatatype = accessor.componentType; attribute.normalized = normalized; attribute.count = accessor.count; attribute.type = accessor.type; attribute.min = fromArray(MathType, accessor.min); attribute.max = fromArray(MathType, accessor.max); attribute.byteOffset = accessor.byteOffset; attribute.byteStride = getAccessorByteStride_default(gltf, accessor); if (hasExtension_default(accessor, "WEB3D_quantized_attributes")) { setQuantizationFromWeb3dQuantizedAttributes( accessor.extensions.WEB3D_quantized_attributes, attribute, MathType ); } const isQuantizable = attribute.semantic === VertexAttributeSemantic_default.POSITION || attribute.semantic === VertexAttributeSemantic_default.NORMAL || attribute.semantic === VertexAttributeSemantic_default.TANGENT || attribute.semantic === VertexAttributeSemantic_default.TEXCOORD; const hasKhrMeshQuantization = gltf.extensionsRequired?.includes( "KHR_mesh_quantization" ); if (hasKhrMeshQuantization && normalized && isQuantizable) { dequantizeMinMax(attribute, MathType); } return attribute; } function getSetIndex(gltfSemantic) { const setIndexRegex = /^\w+_(\d+)$/; const setIndexMatch = setIndexRegex.exec(gltfSemantic); if (setIndexMatch !== null) { return parseInt(setIndexMatch[1]); } return void 0; } var scratchSemanticInfo = { gltfSemantic: void 0, renamedSemantic: void 0, modelSemantic: void 0 }; function getSemanticInfo(loader, semanticType, gltfSemantic) { let renamedSemantic = gltfSemantic; if (loader._renameBatchIdSemantic && (gltfSemantic === "_BATCHID" || gltfSemantic === "BATCHID")) { renamedSemantic = "_FEATURE_ID_0"; } const modelSemantic = semanticType.fromGltfSemantic(renamedSemantic); const semanticInfo = scratchSemanticInfo; semanticInfo.gltfSemantic = gltfSemantic; semanticInfo.renamedSemantic = renamedSemantic; semanticInfo.modelSemantic = modelSemantic; return semanticInfo; } function isClassificationAttribute(attributeSemantic) { const isPositionAttribute = attributeSemantic === VertexAttributeSemantic_default.POSITION; const isFeatureIdAttribute = attributeSemantic === VertexAttributeSemantic_default.FEATURE_ID; const isTexcoordAttribute = attributeSemantic === VertexAttributeSemantic_default.TEXCOORD; return isPositionAttribute || isFeatureIdAttribute || isTexcoordAttribute; } function finalizeDracoAttribute(attribute, vertexBufferLoader, loadBuffer, loadTypedArray) { attribute.byteOffset = 0; attribute.byteStride = void 0; attribute.quantization = vertexBufferLoader.quantization; if (loadBuffer) { attribute.buffer = vertexBufferLoader.buffer; } if (loadTypedArray) { const componentDatatype = defined_default(vertexBufferLoader.quantization) ? vertexBufferLoader.quantization.componentDatatype : attribute.componentDatatype; attribute.typedArray = ComponentDatatype_default.createArrayBufferView( componentDatatype, vertexBufferLoader.typedArray.buffer ); } } function finalizeAttribute(gltf, accessor, attribute, vertexBufferLoader, loadBuffer, loadTypedArray) { if (loadBuffer) { attribute.buffer = vertexBufferLoader.buffer; } if (loadTypedArray) { const bufferViewTypedArray = vertexBufferLoader.typedArray; attribute.typedArray = getPackedTypedArray( gltf, accessor, bufferViewTypedArray ); if (!loadBuffer) { attribute.byteOffset = 0; attribute.byteStride = void 0; } } } function loadAttribute(loader, gltf, accessorId, semanticInfo, draco, loadBuffer, loadTypedArray, frameState) { const accessor = gltf.accessors[accessorId]; const bufferViewId = accessor.bufferView; const gltfSemantic = semanticInfo.gltfSemantic; const renamedSemantic = semanticInfo.renamedSemantic; const modelSemantic = semanticInfo.modelSemantic; const setIndex = defined_default(modelSemantic) ? getSetIndex(renamedSemantic) : void 0; const name = gltfSemantic; const attribute = createAttribute( gltf, accessorId, name, modelSemantic, setIndex ); if (!defined_default(draco) && !defined_default(bufferViewId)) { return attribute; } const vertexBufferLoader = getVertexBufferLoader( loader, gltf, accessorId, gltfSemantic, draco, loadBuffer, loadTypedArray, frameState ); const index = loader._geometryLoaders.length; loader._geometryLoaders.push(vertexBufferLoader); const promise = vertexBufferLoader.load(); loader._loaderPromises.push(promise); loader._geometryCallbacks[index] = () => { if (defined_default(draco) && defined_default(draco.attributes) && defined_default(draco.attributes[gltfSemantic])) { finalizeDracoAttribute( attribute, vertexBufferLoader, loadBuffer, loadTypedArray ); } else { finalizeAttribute( gltf, accessor, attribute, vertexBufferLoader, loadBuffer, loadTypedArray ); } }; return attribute; } function loadVertexAttribute(loader, gltf, accessorId, semanticInfo, draco, hasInstances, needsPostProcessing, frameState) { const modelSemantic = semanticInfo.modelSemantic; const isPositionAttribute = modelSemantic === VertexAttributeSemantic_default.POSITION; const isFeatureIdAttribute = modelSemantic === VertexAttributeSemantic_default.FEATURE_ID; const loadTypedArrayFor2D = isPositionAttribute && !hasInstances && loader._loadAttributesFor2D && !frameState.scene3DOnly; const loadTypedArrayForClassification = loader._loadForClassification && isFeatureIdAttribute; const outputTypedArrayOnly = loader._loadAttributesAsTypedArray; const outputBuffer = !outputTypedArrayOnly; const outputTypedArray = outputTypedArrayOnly || loadTypedArrayFor2D || loadTypedArrayForClassification; const loadBuffer = needsPostProcessing ? false : outputBuffer; const loadTypedArray = needsPostProcessing ? true : outputTypedArray; const attribute = loadAttribute( loader, gltf, accessorId, semanticInfo, draco, loadBuffer, loadTypedArray, frameState ); const attributePlan = new PrimitiveLoadPlan_default.AttributeLoadPlan(attribute); attributePlan.loadBuffer = outputBuffer; attributePlan.loadTypedArray = outputTypedArray; return attributePlan; } function loadInstancedAttribute(loader, gltf, accessorId, attributes, gltfSemantic, frameState) { const hasRotation = defined_default(attributes.ROTATION); const hasTranslationMinMax = defined_default(attributes.TRANSLATION) && defined_default(gltf.accessors[attributes.TRANSLATION].min) && defined_default(gltf.accessors[attributes.TRANSLATION].max); const semanticInfo = getSemanticInfo( loader, InstanceAttributeSemantic_default, gltfSemantic ); const modelSemantic = semanticInfo.modelSemantic; const isTransformAttribute = modelSemantic === InstanceAttributeSemantic_default.TRANSLATION || modelSemantic === InstanceAttributeSemantic_default.ROTATION || modelSemantic === InstanceAttributeSemantic_default.SCALE; const isTranslationAttribute = modelSemantic === InstanceAttributeSemantic_default.TRANSLATION; const loadAsTypedArrayOnly = loader._loadAttributesAsTypedArray || hasRotation && isTransformAttribute || !frameState.context.instancedArrays; const loadBuffer = !loadAsTypedArrayOnly; const loadFor2D = loader._loadAttributesFor2D && !frameState.scene3DOnly; const loadTranslationAsTypedArray = isTranslationAttribute && (!hasTranslationMinMax || loadFor2D); const loadTypedArray = loadAsTypedArrayOnly || loadTranslationAsTypedArray; return loadAttribute( loader, gltf, accessorId, semanticInfo, void 0, loadBuffer, loadTypedArray, frameState ); } function loadIndices(loader, gltf, accessorId, draco, hasFeatureIds, needsPostProcessing, frameState) { const accessor = gltf.accessors[accessorId]; const bufferViewId = accessor.bufferView; if (!defined_default(draco) && !defined_default(bufferViewId)) { return void 0; } const indices2 = new Indices2(); indices2.count = accessor.count; const loadAttributesAsTypedArray = loader._loadAttributesAsTypedArray; const loadForWireframe = loader._loadIndicesForWireframe && !frameState.context.webgl2; const loadForClassification = loader._loadForClassification && hasFeatureIds; const outputTypedArrayOnly = loadAttributesAsTypedArray; const outputBuffer = !outputTypedArrayOnly; const outputTypedArray = loadAttributesAsTypedArray || loadForWireframe || loadForClassification; const loadBuffer = needsPostProcessing ? false : outputBuffer; const loadTypedArray = needsPostProcessing ? true : outputTypedArray; const indexBufferLoader = getIndexBufferLoader( loader, gltf, accessorId, draco, loadBuffer, loadTypedArray, frameState ); const index = loader._geometryLoaders.length; loader._geometryLoaders.push(indexBufferLoader); const promise = indexBufferLoader.load(); loader._loaderPromises.push(promise); loader._geometryCallbacks[index] = () => { indices2.indexDatatype = indexBufferLoader.indexDatatype; indices2.buffer = indexBufferLoader.buffer; indices2.typedArray = indexBufferLoader.typedArray; }; const indicesPlan = new PrimitiveLoadPlan_default.IndicesLoadPlan(indices2); indicesPlan.loadBuffer = outputBuffer; indicesPlan.loadTypedArray = outputTypedArray; return indicesPlan; } function loadTexture(loader, gltf, textureInfo, supportedImageFormats, frameState, samplerOverride) { const imageId = GltfLoaderUtil_default.getImageIdFromTexture({ gltf, textureId: textureInfo.index, supportedImageFormats }); if (!defined_default(imageId)) { return void 0; } const textureLoader = ResourceCache_default.getTextureLoader({ gltf, textureInfo, gltfResource: loader._gltfResource, baseResource: loader._baseResource, supportedImageFormats, frameState, asynchronous: loader._asynchronous }); const textureReader = GltfLoaderUtil_default.createModelTextureReader({ textureInfo }); const index = loader._textureLoaders.length; loader._textureLoaders.push(textureLoader); const promise = textureLoader.load().catch((error) => { if (loader.isDestroyed()) { return; } if (!loader._incrementallyLoadTextures) { throw error; } loader._textureState = GltfLoaderState.FAILED; loader._textureErrors.push(error); }); loader._texturesPromises.push(promise); loader._textureCallbacks[index] = () => { textureReader.texture = textureLoader.texture; if (defined_default(samplerOverride)) { textureReader.texture.sampler = samplerOverride; } }; return textureReader; } function loadMaterial(loader, gltf, gltfMaterial, supportedImageFormats, frameState) { const material = new Material3(); const extensions = defaultValue_default( gltfMaterial.extensions, defaultValue_default.EMPTY_OBJECT ); const pbrSpecularGlossiness = extensions.KHR_materials_pbrSpecularGlossiness; const pbrMetallicRoughness = gltfMaterial.pbrMetallicRoughness; material.unlit = defined_default(extensions.KHR_materials_unlit); if (defined_default(pbrSpecularGlossiness)) { const specularGlossiness = new SpecularGlossiness2(); material.specularGlossiness = specularGlossiness; if (defined_default(pbrSpecularGlossiness.diffuseTexture)) { specularGlossiness.diffuseTexture = loadTexture( loader, gltf, pbrSpecularGlossiness.diffuseTexture, supportedImageFormats, frameState ); } if (defined_default(pbrSpecularGlossiness.specularGlossinessTexture)) { if (defined_default(pbrSpecularGlossiness.specularGlossinessTexture)) { specularGlossiness.specularGlossinessTexture = loadTexture( loader, gltf, pbrSpecularGlossiness.specularGlossinessTexture, supportedImageFormats, frameState ); } } specularGlossiness.diffuseFactor = fromArray( Cartesian4_default, pbrSpecularGlossiness.diffuseFactor ); specularGlossiness.specularFactor = fromArray( Cartesian3_default, pbrSpecularGlossiness.specularFactor ); specularGlossiness.glossinessFactor = pbrSpecularGlossiness.glossinessFactor; material.pbrSpecularGlossiness = pbrSpecularGlossiness; } else if (defined_default(pbrMetallicRoughness)) { const metallicRoughness = new MetallicRoughness2(); if (defined_default(pbrMetallicRoughness.baseColorTexture)) { metallicRoughness.baseColorTexture = loadTexture( loader, gltf, pbrMetallicRoughness.baseColorTexture, supportedImageFormats, frameState ); } if (defined_default(pbrMetallicRoughness.metallicRoughnessTexture)) { metallicRoughness.metallicRoughnessTexture = loadTexture( loader, gltf, pbrMetallicRoughness.metallicRoughnessTexture, supportedImageFormats, frameState ); } metallicRoughness.baseColorFactor = fromArray( Cartesian4_default, pbrMetallicRoughness.baseColorFactor ); metallicRoughness.metallicFactor = pbrMetallicRoughness.metallicFactor; metallicRoughness.roughnessFactor = pbrMetallicRoughness.roughnessFactor; material.metallicRoughness = metallicRoughness; } if (defined_default(gltfMaterial.emissiveTexture)) { material.emissiveTexture = loadTexture( loader, gltf, gltfMaterial.emissiveTexture, supportedImageFormats, frameState ); } if (defined_default(gltfMaterial.normalTexture) && !loader._loadForClassification) { material.normalTexture = loadTexture( loader, gltf, gltfMaterial.normalTexture, supportedImageFormats, frameState ); } if (defined_default(gltfMaterial.occlusionTexture)) { material.occlusionTexture = loadTexture( loader, gltf, gltfMaterial.occlusionTexture, supportedImageFormats, frameState ); } material.emissiveFactor = fromArray(Cartesian3_default, gltfMaterial.emissiveFactor); material.alphaMode = gltfMaterial.alphaMode; material.alphaCutoff = gltfMaterial.alphaCutoff; material.doubleSided = gltfMaterial.doubleSided; return material; } function loadFeatureIdAttribute(featureIds, positionalLabel) { const featureIdAttribute = new FeatureIdAttribute2(); featureIdAttribute.featureCount = featureIds.featureCount; featureIdAttribute.nullFeatureId = featureIds.nullFeatureId; featureIdAttribute.propertyTableId = featureIds.propertyTable; featureIdAttribute.setIndex = featureIds.attribute; featureIdAttribute.label = featureIds.label; featureIdAttribute.positionalLabel = positionalLabel; return featureIdAttribute; } function loadFeatureIdAttributeLegacy(gltfFeatureIdAttribute, featureTableId, featureCount, positionalLabel) { const featureIdAttribute = new FeatureIdAttribute2(); const featureIds = gltfFeatureIdAttribute.featureIds; featureIdAttribute.featureCount = featureCount; featureIdAttribute.propertyTableId = featureTableId; featureIdAttribute.setIndex = getSetIndex(featureIds.attribute); featureIdAttribute.positionalLabel = positionalLabel; return featureIdAttribute; } function loadDefaultFeatureIds(featureIds, positionalLabel) { const featureIdRange = new FeatureIdImplicitRange2(); featureIdRange.propertyTableId = featureIds.propertyTable; featureIdRange.featureCount = featureIds.featureCount; featureIdRange.nullFeatureId = featureIds.nullFeatureId; featureIdRange.label = featureIds.label; featureIdRange.positionalLabel = positionalLabel; featureIdRange.offset = 0; featureIdRange.repeat = 1; return featureIdRange; } function loadFeatureIdImplicitRangeLegacy(gltfFeatureIdAttribute, featureTableId, featureCount, positionalLabel) { const featureIdRange = new FeatureIdImplicitRange2(); const featureIds = gltfFeatureIdAttribute.featureIds; featureIdRange.propertyTableId = featureTableId; featureIdRange.featureCount = featureCount; featureIdRange.offset = defaultValue_default(featureIds.constant, 0); const divisor = defaultValue_default(featureIds.divisor, 0); featureIdRange.repeat = divisor === 0 ? void 0 : divisor; featureIdRange.positionalLabel = positionalLabel; return featureIdRange; } function loadFeatureIdTexture(loader, gltf, gltfFeatureIdTexture, supportedImageFormats, frameState, positionalLabel) { const featureIdTexture = new FeatureIdTexture2(); featureIdTexture.featureCount = gltfFeatureIdTexture.featureCount; featureIdTexture.nullFeatureId = gltfFeatureIdTexture.nullFeatureId; featureIdTexture.propertyTableId = gltfFeatureIdTexture.propertyTable; featureIdTexture.label = gltfFeatureIdTexture.label; featureIdTexture.positionalLabel = positionalLabel; const textureInfo = gltfFeatureIdTexture.texture; featureIdTexture.textureReader = loadTexture( loader, gltf, textureInfo, supportedImageFormats, frameState, Sampler_default.NEAREST // Feature ID textures require nearest sampling ); const channels = defined_default(textureInfo.channels) ? textureInfo.channels : [0]; const channelString = channels.map(function(channelIndex) { return "rgba".charAt(channelIndex); }).join(""); featureIdTexture.textureReader.channels = channelString; return featureIdTexture; } function loadFeatureIdTextureLegacy(loader, gltf, gltfFeatureIdTexture, featureTableId, supportedImageFormats, frameState, featureCount, positionalLabel) { const featureIdTexture = new FeatureIdTexture2(); const featureIds = gltfFeatureIdTexture.featureIds; const textureInfo = featureIds.texture; featureIdTexture.featureCount = featureCount; featureIdTexture.propertyTableId = featureTableId; featureIdTexture.textureReader = loadTexture( loader, gltf, textureInfo, supportedImageFormats, frameState, Sampler_default.NEAREST // Feature ID textures require nearest sampling ); featureIdTexture.textureReader.channels = featureIds.channels; featureIdTexture.positionalLabel = positionalLabel; return featureIdTexture; } function loadMorphTarget(loader, gltf, target, needsPostProcessing, primitiveLoadPlan, frameState) { const morphTarget = new MorphTarget2(); const draco = void 0; const hasInstances = false; for (const semantic in target) { if (target.hasOwnProperty(semantic)) { const accessorId = target[semantic]; const semanticInfo = getSemanticInfo( loader, VertexAttributeSemantic_default, semantic ); const attributePlan = loadVertexAttribute( loader, gltf, accessorId, semanticInfo, draco, hasInstances, needsPostProcessing, frameState ); morphTarget.attributes.push(attributePlan.attribute); primitiveLoadPlan.attributePlans.push(attributePlan); } } return morphTarget; } function loadPrimitive(loader, gltf, gltfPrimitive, hasInstances, supportedImageFormats, frameState) { const primitive = new Primitive3(); const primitivePlan = new PrimitiveLoadPlan_default(primitive); loader._primitiveLoadPlans.push(primitivePlan); const materialId = gltfPrimitive.material; if (defined_default(materialId)) { primitive.material = loadMaterial( loader, gltf, gltf.materials[materialId], supportedImageFormats, frameState ); } const extensions = defaultValue_default( gltfPrimitive.extensions, defaultValue_default.EMPTY_OBJECT ); let needsPostProcessing = false; const outlineExtension = extensions.CESIUM_primitive_outline; if (loader._loadPrimitiveOutline && defined_default(outlineExtension)) { needsPostProcessing = true; primitivePlan.needsOutlines = true; primitivePlan.outlineIndices = loadPrimitiveOutline( loader, gltf, outlineExtension, primitivePlan ); } const loadForClassification = loader._loadForClassification; const draco = extensions.KHR_draco_mesh_compression; let hasFeatureIds = false; const attributes = gltfPrimitive.attributes; if (defined_default(attributes)) { for (const semantic in attributes) { if (attributes.hasOwnProperty(semantic)) { const accessorId = attributes[semantic]; const semanticInfo = getSemanticInfo( loader, VertexAttributeSemantic_default, semantic ); const modelSemantic = semanticInfo.modelSemantic; if (loadForClassification && !isClassificationAttribute(modelSemantic)) { continue; } if (modelSemantic === VertexAttributeSemantic_default.FEATURE_ID) { hasFeatureIds = true; } const attributePlan = loadVertexAttribute( loader, gltf, accessorId, semanticInfo, draco, hasInstances, needsPostProcessing, frameState ); primitivePlan.attributePlans.push(attributePlan); primitive.attributes.push(attributePlan.attribute); } } } const targets = gltfPrimitive.targets; if (defined_default(targets) && !loadForClassification) { const targetsLength = targets.length; for (let i = 0; i < targetsLength; ++i) { primitive.morphTargets.push( loadMorphTarget( loader, gltf, targets[i], needsPostProcessing, primitivePlan, frameState ) ); } } const indices2 = gltfPrimitive.indices; if (defined_default(indices2)) { const indicesPlan = loadIndices( loader, gltf, indices2, draco, hasFeatureIds, needsPostProcessing, frameState ); if (defined_default(indicesPlan)) { primitivePlan.indicesPlan = indicesPlan; primitive.indices = indicesPlan.indices; } } const structuralMetadata = extensions.EXT_structural_metadata; const meshFeatures = extensions.EXT_mesh_features; const featureMetadataLegacy = extensions.EXT_feature_metadata; const hasFeatureMetadataLegacy = defined_default(featureMetadataLegacy); if (defined_default(meshFeatures)) { loadPrimitiveFeatures( loader, gltf, primitive, meshFeatures, supportedImageFormats, frameState ); } else if (hasFeatureMetadataLegacy) { loadPrimitiveFeaturesLegacy( loader, gltf, primitive, featureMetadataLegacy, supportedImageFormats, frameState ); } if (defined_default(structuralMetadata)) { loadPrimitiveMetadata(primitive, structuralMetadata); } else if (hasFeatureMetadataLegacy) { loadPrimitiveMetadataLegacy(loader, primitive, featureMetadataLegacy); } const primitiveType = gltfPrimitive.mode; if (loadForClassification && primitiveType !== PrimitiveType_default.TRIANGLES) { throw new RuntimeError_default( "Only triangle meshes can be used for classification." ); } primitive.primitiveType = primitiveType; return primitive; } function loadPrimitiveOutline(loader, gltf, outlineExtension) { const accessorId = outlineExtension.indices; const useQuaternion = false; return loadAccessor(loader, gltf, accessorId, useQuaternion); } function loadPrimitiveFeatures(loader, gltf, primitive, meshFeaturesExtension, supportedImageFormats, frameState) { let featureIdsArray; if (defined_default(meshFeaturesExtension) && defined_default(meshFeaturesExtension.featureIds)) { featureIdsArray = meshFeaturesExtension.featureIds; } else { featureIdsArray = []; } for (let i = 0; i < featureIdsArray.length; i++) { const featureIds = featureIdsArray[i]; const label = `featureId_${i}`; let featureIdComponent; if (defined_default(featureIds.texture)) { featureIdComponent = loadFeatureIdTexture( loader, gltf, featureIds, supportedImageFormats, frameState, label ); } else if (defined_default(featureIds.attribute)) { featureIdComponent = loadFeatureIdAttribute(featureIds, label); } else { featureIdComponent = loadDefaultFeatureIds(featureIds, label); } primitive.featureIds.push(featureIdComponent); } } function loadPrimitiveFeaturesLegacy(loader, gltf, primitive, metadataExtension, supportedImageFormats, frameState) { const featureTables = gltf.extensions.EXT_feature_metadata.featureTables; let nextFeatureIdIndex = 0; const featureIdAttributes = metadataExtension.featureIdAttributes; if (defined_default(featureIdAttributes)) { const featureIdAttributesLength = featureIdAttributes.length; for (let i = 0; i < featureIdAttributesLength; ++i) { const featureIdAttribute = featureIdAttributes[i]; const featureTableId = featureIdAttribute.featureTable; const propertyTableId = loader._sortedPropertyTableIds.indexOf( featureTableId ); const featureCount = featureTables[featureTableId].count; const label = `featureId_${nextFeatureIdIndex}`; nextFeatureIdIndex++; let featureIdComponent; if (defined_default(featureIdAttribute.featureIds.attribute)) { featureIdComponent = loadFeatureIdAttributeLegacy( featureIdAttribute, propertyTableId, featureCount, label ); } else { featureIdComponent = loadFeatureIdImplicitRangeLegacy( featureIdAttribute, propertyTableId, featureCount, label ); } primitive.featureIds.push(featureIdComponent); } } const featureIdTextures = metadataExtension.featureIdTextures; if (defined_default(featureIdTextures)) { const featureIdTexturesLength = featureIdTextures.length; for (let i = 0; i < featureIdTexturesLength; ++i) { const featureIdTexture = featureIdTextures[i]; const featureTableId = featureIdTexture.featureTable; const propertyTableId = loader._sortedPropertyTableIds.indexOf( featureTableId ); const featureCount = featureTables[featureTableId].count; const featureIdLabel = `featureId_${nextFeatureIdIndex}`; nextFeatureIdIndex++; const featureIdComponent = loadFeatureIdTextureLegacy( loader, gltf, featureIdTexture, propertyTableId, supportedImageFormats, frameState, featureCount, featureIdLabel ); primitive.featureIds.push(featureIdComponent); } } } function loadPrimitiveMetadata(primitive, structuralMetadataExtension) { if (!defined_default(structuralMetadataExtension)) { return; } if (defined_default(structuralMetadataExtension.propertyTextures)) { primitive.propertyTextureIds = structuralMetadataExtension.propertyTextures; } if (defined_default(structuralMetadataExtension.propertyAttributes)) { primitive.propertyAttributeIds = structuralMetadataExtension.propertyAttributes; } } function loadPrimitiveMetadataLegacy(loader, primitive, metadataExtension) { if (defined_default(metadataExtension.featureTextures)) { primitive.propertyTextureIds = metadataExtension.featureTextures.map( function(id) { return loader._sortedFeatureTextureIds.indexOf(id); } ); } } function loadInstances(loader, gltf, nodeExtensions, frameState) { const instancingExtension = nodeExtensions.EXT_mesh_gpu_instancing; const instances = new Instances2(); const attributes = instancingExtension.attributes; if (defined_default(attributes)) { for (const semantic in attributes) { if (attributes.hasOwnProperty(semantic)) { const accessorId = attributes[semantic]; instances.attributes.push( loadInstancedAttribute( loader, gltf, accessorId, attributes, semantic, frameState ) ); } } } const instancingExtExtensions = defaultValue_default( instancingExtension.extensions, defaultValue_default.EMPTY_OBJECT ); const instanceFeatures = nodeExtensions.EXT_instance_features; const featureMetadataLegacy = instancingExtExtensions.EXT_feature_metadata; if (defined_default(instanceFeatures)) { loadInstanceFeatures(instances, instanceFeatures); } else if (defined_default(featureMetadataLegacy)) { loadInstanceFeaturesLegacy( gltf, instances, featureMetadataLegacy, loader._sortedPropertyTableIds ); } return instances; } function loadInstanceFeatures(instances, instanceFeaturesExtension) { const featureIdsArray = instanceFeaturesExtension.featureIds; for (let i = 0; i < featureIdsArray.length; i++) { const featureIds = featureIdsArray[i]; const label = `instanceFeatureId_${i}`; let featureIdComponent; if (defined_default(featureIds.attribute)) { featureIdComponent = loadFeatureIdAttribute(featureIds, label); } else { featureIdComponent = loadDefaultFeatureIds(featureIds, label); } instances.featureIds.push(featureIdComponent); } } function loadInstanceFeaturesLegacy(gltf, instances, metadataExtension, sortedPropertyTableIds) { const featureTables = gltf.extensions.EXT_feature_metadata.featureTables; const featureIdAttributes = metadataExtension.featureIdAttributes; if (defined_default(featureIdAttributes)) { const featureIdAttributesLength = featureIdAttributes.length; for (let i = 0; i < featureIdAttributesLength; ++i) { const featureIdAttribute = featureIdAttributes[i]; const featureTableId = featureIdAttribute.featureTable; const propertyTableId = sortedPropertyTableIds.indexOf(featureTableId); const featureCount = featureTables[featureTableId].count; const label = `instanceFeatureId_${i}`; let featureIdComponent; if (defined_default(featureIdAttribute.featureIds.attribute)) { featureIdComponent = loadFeatureIdAttributeLegacy( featureIdAttribute, propertyTableId, featureCount, label ); } else { featureIdComponent = loadFeatureIdImplicitRangeLegacy( featureIdAttribute, propertyTableId, featureCount, label ); } instances.featureIds.push(featureIdComponent); } } } function loadNode(loader, gltf, gltfNode, supportedImageFormats, frameState) { const node = new Node4(); node.name = gltfNode.name; node.matrix = fromArray(Matrix4_default, gltfNode.matrix); node.translation = fromArray(Cartesian3_default, gltfNode.translation); node.rotation = fromArray(Quaternion_default, gltfNode.rotation); node.scale = fromArray(Cartesian3_default, gltfNode.scale); const nodeExtensions = defaultValue_default( gltfNode.extensions, defaultValue_default.EMPTY_OBJECT ); const instancingExtension = nodeExtensions.EXT_mesh_gpu_instancing; const articulationsExtension = nodeExtensions.AGI_articulations; if (defined_default(instancingExtension)) { if (loader._loadForClassification) { throw new RuntimeError_default( "Models with the EXT_mesh_gpu_instancing extension cannot be used for classification." ); } node.instances = loadInstances(loader, gltf, nodeExtensions, frameState); } if (defined_default(articulationsExtension)) { node.articulationName = articulationsExtension.articulationName; } const meshId = gltfNode.mesh; if (defined_default(meshId)) { const mesh = gltf.meshes[meshId]; const primitives = mesh.primitives; const primitivesLength = primitives.length; for (let i = 0; i < primitivesLength; ++i) { node.primitives.push( loadPrimitive( loader, gltf, primitives[i], defined_default(node.instances), supportedImageFormats, frameState ) ); } const morphWeights = defaultValue_default(gltfNode.weights, mesh.weights); const targets = node.primitives[0].morphTargets; const targetsLength = targets.length; node.morphWeights = defined_default(morphWeights) ? morphWeights.slice() : new Array(targetsLength).fill(0); } return node; } function loadNodes(loader, gltf, supportedImageFormats, frameState) { if (!defined_default(gltf.nodes)) { return []; } let i; let j; const nodesLength = gltf.nodes.length; const nodes = new Array(nodesLength); for (i = 0; i < nodesLength; ++i) { const node = loadNode( loader, gltf, gltf.nodes[i], supportedImageFormats, frameState ); node.index = i; nodes[i] = node; } for (i = 0; i < nodesLength; ++i) { const childrenNodeIds = gltf.nodes[i].children; if (defined_default(childrenNodeIds)) { const childrenLength = childrenNodeIds.length; for (j = 0; j < childrenLength; ++j) { nodes[i].children.push(nodes[childrenNodeIds[j]]); } } } return nodes; } function loadSkin(loader, gltf, gltfSkin, nodes) { const skin = new Skin2(); const jointIds = gltfSkin.joints; const jointsLength = jointIds.length; const joints = new Array(jointsLength); for (let i = 0; i < jointsLength; ++i) { joints[i] = nodes[jointIds[i]]; } skin.joints = joints; const inverseBindMatricesAccessorId = gltfSkin.inverseBindMatrices; if (defined_default(inverseBindMatricesAccessorId)) { skin.inverseBindMatrices = loadAccessor( loader, gltf, inverseBindMatricesAccessorId ); } else { skin.inverseBindMatrices = new Array(jointsLength).fill(Matrix4_default.IDENTITY); } return skin; } function loadSkins(loader, gltf, nodes) { const gltfSkins = gltf.skins; if (loader._loadForClassification || !defined_default(gltfSkins)) { return []; } const skinsLength = gltf.skins.length; const skins = new Array(skinsLength); for (let i = 0; i < skinsLength; ++i) { const skin = loadSkin(loader, gltf, gltf.skins[i], nodes); skin.index = i; skins[i] = skin; } const nodesLength = nodes.length; for (let i = 0; i < nodesLength; ++i) { const skinId = gltf.nodes[i].skin; if (defined_default(skinId)) { nodes[i].skin = skins[skinId]; } } return skins; } async function loadStructuralMetadata(loader, gltf, extension, extensionLegacy, supportedImageFormats, frameState) { const structuralMetadataLoader = new GltfStructuralMetadataLoader_default({ gltf, extension, extensionLegacy, gltfResource: loader._gltfResource, baseResource: loader._baseResource, supportedImageFormats, frameState, asynchronous: loader._asynchronous }); loader._structuralMetadataLoader = structuralMetadataLoader; return structuralMetadataLoader.load(); } function loadAnimationSampler(loader, gltf, gltfSampler) { const animationSampler = new AnimationSampler2(); const inputAccessorId = gltfSampler.input; animationSampler.input = loadAccessor(loader, gltf, inputAccessorId); const gltfInterpolation = gltfSampler.interpolation; animationSampler.interpolation = defaultValue_default( InterpolationType_default[gltfInterpolation], InterpolationType_default.LINEAR ); const outputAccessorId = gltfSampler.output; animationSampler.output = loadAccessor(loader, gltf, outputAccessorId, true); return animationSampler; } function loadAnimationTarget(gltfTarget, nodes) { const animationTarget = new AnimationTarget2(); const nodeIndex = gltfTarget.node; if (!defined_default(nodeIndex)) { return void 0; } animationTarget.node = nodes[nodeIndex]; const path = gltfTarget.path.toUpperCase(); animationTarget.path = AnimatedPropertyType2[path]; return animationTarget; } function loadAnimationChannel(gltfChannel, samplers, nodes) { const animationChannel = new AnimationChannel2(); const samplerIndex = gltfChannel.sampler; animationChannel.sampler = samplers[samplerIndex]; animationChannel.target = loadAnimationTarget(gltfChannel.target, nodes); return animationChannel; } function loadAnimation(loader, gltf, gltfAnimation, nodes) { let i; const animation = new Animation2(); animation.name = gltfAnimation.name; const gltfSamplers = gltfAnimation.samplers; const samplersLength = gltfSamplers.length; const samplers = new Array(samplersLength); for (i = 0; i < samplersLength; i++) { const sampler = loadAnimationSampler(loader, gltf, gltfSamplers[i]); sampler.index = i; samplers[i] = sampler; } const gltfChannels = gltfAnimation.channels; const channelsLength = gltfChannels.length; const channels = new Array(channelsLength); for (i = 0; i < channelsLength; i++) { channels[i] = loadAnimationChannel(gltfChannels[i], samplers, nodes); } animation.samplers = samplers; animation.channels = channels; return animation; } function loadAnimations(loader, gltf, nodes) { const gltfAnimations = gltf.animations; if (loader._loadForClassification || !defined_default(gltfAnimations)) { return []; } const animationsLength = gltf.animations.length; const animations = new Array(animationsLength); for (let i = 0; i < animationsLength; ++i) { const animation = loadAnimation(loader, gltf, gltf.animations[i], nodes); animation.index = i; animations[i] = animation; } return animations; } function loadArticulationStage(gltfStage) { const stage = new ArticulationStage2(); stage.name = gltfStage.name; const type = gltfStage.type.toUpperCase(); stage.type = ArticulationStageType_default[type]; stage.minimumValue = gltfStage.minimumValue; stage.maximumValue = gltfStage.maximumValue; stage.initialValue = gltfStage.initialValue; return stage; } function loadArticulation(gltfArticulation) { const articulation = new Articulation2(); articulation.name = gltfArticulation.name; const gltfStages = gltfArticulation.stages; const gltfStagesLength = gltfStages.length; const stages = new Array(gltfStagesLength); for (let i = 0; i < gltfStagesLength; i++) { const stage = loadArticulationStage(gltfStages[i]); stages[i] = stage; } articulation.stages = stages; return articulation; } function loadArticulations(gltf) { const extensions = defaultValue_default(gltf.extensions, defaultValue_default.EMPTY_OBJECT); const articulationsExtension = extensions.AGI_articulations; if (!defined_default(articulationsExtension)) { return []; } const gltfArticulations = articulationsExtension.articulations; if (!defined_default(gltfArticulations)) { return []; } const gltfArticulationsLength = gltfArticulations.length; const articulations = new Array(gltfArticulationsLength); for (let i = 0; i < gltfArticulationsLength; i++) { const articulation = loadArticulation(gltfArticulations[i]); articulations[i] = articulation; } return articulations; } function getSceneNodeIds(gltf) { let nodesIds; if (defined_default(gltf.scenes) && defined_default(gltf.scene)) { nodesIds = gltf.scenes[gltf.scene].nodes; } nodesIds = defaultValue_default(nodesIds, gltf.nodes); nodesIds = defined_default(nodesIds) ? nodesIds : []; return nodesIds; } function loadScene(gltf, nodes) { const scene = new Scene2(); const sceneNodeIds = getSceneNodeIds(gltf); scene.nodes = sceneNodeIds.map(function(sceneNodeId) { return nodes[sceneNodeId]; }); return scene; } var scratchCenter3 = new Cartesian3_default(); function parse(loader, gltf, supportedImageFormats, frameState) { const extensions = defaultValue_default(gltf.extensions, defaultValue_default.EMPTY_OBJECT); const structuralMetadataExtension = extensions.EXT_structural_metadata; const featureMetadataExtensionLegacy = extensions.EXT_feature_metadata; const cesiumRtcExtension = extensions.CESIUM_RTC; if (defined_default(featureMetadataExtensionLegacy)) { const featureTables = featureMetadataExtensionLegacy.featureTables; const featureTextures = featureMetadataExtensionLegacy.featureTextures; const allPropertyTableIds = defined_default(featureTables) ? featureTables : []; const allFeatureTextureIds = defined_default(featureTextures) ? featureTextures : []; loader._sortedPropertyTableIds = Object.keys(allPropertyTableIds).sort(); loader._sortedFeatureTextureIds = Object.keys(allFeatureTextureIds).sort(); } const nodes = loadNodes(loader, gltf, supportedImageFormats, frameState); const skins = loadSkins(loader, gltf, nodes); const animations = loadAnimations(loader, gltf, nodes); const articulations = loadArticulations(gltf); const scene = loadScene(gltf, nodes); const components = new Components2(); const asset = new Asset2(); const copyright = gltf.asset.copyright; if (defined_default(copyright)) { const credits = copyright.split(";").map(function(string) { return new Credit_default(string.trim()); }); asset.credits = credits; } components.asset = asset; components.scene = scene; components.nodes = nodes; components.skins = skins; components.animations = animations; components.articulations = articulations; components.upAxis = loader._upAxis; components.forwardAxis = loader._forwardAxis; if (defined_default(cesiumRtcExtension)) { const center = Cartesian3_default.fromArray( cesiumRtcExtension.center, 0, scratchCenter3 ); components.transform = Matrix4_default.fromTranslation( center, components.transform ); } loader._components = components; if (defined_default(structuralMetadataExtension) || defined_default(featureMetadataExtensionLegacy)) { const promise = loadStructuralMetadata( loader, gltf, structuralMetadataExtension, featureMetadataExtensionLegacy, supportedImageFormats, frameState ); loader._loaderPromises.push(promise); } const readyPromises = []; readyPromises.push.apply(readyPromises, loader._loaderPromises); if (!loader._incrementallyLoadTextures) { readyPromises.push.apply(readyPromises, loader._texturesPromises); } return Promise.all(readyPromises); } function unloadTextures2(loader) { const textureLoaders = loader._textureLoaders; const textureLoadersLength = textureLoaders.length; for (let i = 0; i < textureLoadersLength; ++i) { textureLoaders[i] = !textureLoaders[i].isDestroyed() && ResourceCache_default.unload(textureLoaders[i]); } loader._textureLoaders.length = 0; } function unloadBufferViewLoaders(loader) { const bufferViewLoaders = loader._bufferViewLoaders; const bufferViewLoadersLength = bufferViewLoaders.length; for (let i = 0; i < bufferViewLoadersLength; ++i) { bufferViewLoaders[i] = !bufferViewLoaders[i].isDestroyed() && ResourceCache_default.unload(bufferViewLoaders[i]); } loader._bufferViewLoaders.length = 0; } function unloadGeometry(loader) { const geometryLoaders = loader._geometryLoaders; const geometryLoadersLength = geometryLoaders.length; for (let i = 0; i < geometryLoadersLength; ++i) { geometryLoaders[i] = !geometryLoaders[i].isDestroyed() && ResourceCache_default.unload(geometryLoaders[i]); } loader._geometryLoaders.length = 0; } function unloadGeneratedAttributes(loader) { const buffers = loader._postProcessBuffers; const length3 = buffers.length; for (let i = 0; i < length3; i++) { const buffer = buffers[i]; if (!buffer.isDestroyed()) { buffer.destroy(); } } buffers.length = 0; } function unloadStructuralMetadata(loader) { if (defined_default(loader._structuralMetadataLoader) && !loader._structuralMetadataLoader.isDestroyed()) { loader._structuralMetadataLoader.destroy(); loader._structuralMetadataLoader = void 0; } } GltfLoader.prototype.isUnloaded = function() { return this._state === GltfLoaderState.UNLOADED; }; GltfLoader.prototype.unload = function() { if (defined_default(this._gltfJsonLoader) && !this._gltfJsonLoader.isDestroyed()) { ResourceCache_default.unload(this._gltfJsonLoader); } this._gltfJsonLoader = void 0; unloadTextures2(this); unloadBufferViewLoaders(this); unloadGeometry(this); unloadGeneratedAttributes(this); unloadStructuralMetadata(this); this._components = void 0; this._typedArray = void 0; this._state = GltfLoaderState.UNLOADED; }; var GltfLoader_default = GltfLoader; // packages/engine/Source/Shaders/PostProcessStages/PointCloudEyeDomeLighting.js var PointCloudEyeDomeLighting_default = "uniform sampler2D u_pointCloud_colorGBuffer;\nuniform sampler2D u_pointCloud_depthGBuffer;\nuniform vec2 u_distanceAndEdlStrength;\nin vec2 v_textureCoordinates;\n\nvec2 neighborContribution(float log2Depth, vec2 offset)\n{\n float dist = u_distanceAndEdlStrength.x;\n vec2 texCoordOrig = v_textureCoordinates + offset * dist;\n vec2 texCoord0 = v_textureCoordinates + offset * floor(dist);\n vec2 texCoord1 = v_textureCoordinates + offset * ceil(dist);\n\n float depthOrLogDepth0 = czm_unpackDepth(texture(u_pointCloud_depthGBuffer, texCoord0));\n float depthOrLogDepth1 = czm_unpackDepth(texture(u_pointCloud_depthGBuffer, texCoord1));\n\n // ignore depth values that are the clear depth\n if (depthOrLogDepth0 == 0.0 || depthOrLogDepth1 == 0.0) {\n return vec2(0.0);\n }\n\n // interpolate the two adjacent depth values\n float depthMix = mix(depthOrLogDepth0, depthOrLogDepth1, fract(dist));\n vec4 eyeCoordinate = czm_windowToEyeCoordinates(texCoordOrig, depthMix);\n return vec2(max(0.0, log2Depth - log2(-eyeCoordinate.z / eyeCoordinate.w)), 1.0);\n}\n\nvoid main()\n{\n float depthOrLogDepth = czm_unpackDepth(texture(u_pointCloud_depthGBuffer, v_textureCoordinates));\n\n vec4 eyeCoordinate = czm_windowToEyeCoordinates(gl_FragCoord.xy, depthOrLogDepth);\n eyeCoordinate /= eyeCoordinate.w;\n\n float log2Depth = log2(-eyeCoordinate.z);\n\n if (depthOrLogDepth == 0.0) // 0.0 is the clear value for the gbuffer\n {\n discard;\n }\n\n vec4 color = texture(u_pointCloud_colorGBuffer, v_textureCoordinates);\n\n // sample from neighbors left, right, down, up\n vec2 texelSize = 1.0 / czm_viewport.zw;\n\n vec2 responseAndCount = vec2(0.0);\n\n responseAndCount += neighborContribution(log2Depth, vec2(-texelSize.x, 0.0));\n responseAndCount += neighborContribution(log2Depth, vec2(+texelSize.x, 0.0));\n responseAndCount += neighborContribution(log2Depth, vec2(0.0, -texelSize.y));\n responseAndCount += neighborContribution(log2Depth, vec2(0.0, +texelSize.y));\n\n float response = responseAndCount.x / responseAndCount.y;\n float strength = u_distanceAndEdlStrength.y;\n float shade = exp(-response * 300.0 * strength);\n color.rgb *= shade;\n out_FragColor = vec4(color);\n\n // Input and output depth are the same.\n gl_FragDepth = depthOrLogDepth;\n}\n"; // packages/engine/Source/Scene/PointCloudEyeDomeLighting.js function PointCloudEyeDomeLighting() { this._framebuffer = new FramebufferManager_default({ colorAttachmentsLength: 2, depth: true, supportsDepthTexture: true }); this._drawCommand = void 0; this._clearCommand = void 0; this._strength = 1; this._radius = 1; } Object.defineProperties(PointCloudEyeDomeLighting.prototype, { framebuffer: { get: function() { return this._framebuffer.framebuffer; } }, colorGBuffer: { get: function() { return this._framebuffer.getColorTexture(0); } }, depthGBuffer: { get: function() { return this._framebuffer.getColorTexture(1); } } }); function destroyFramebuffer(processor) { processor._framebuffer.destroy(); processor._drawCommand = void 0; processor._clearCommand = void 0; } var distanceAndEdlStrengthScratch = new Cartesian2_default(); function createCommands4(processor, context) { const blendFS = new ShaderSource_default({ defines: ["LOG_DEPTH_WRITE"], sources: [PointCloudEyeDomeLighting_default] }); const blendUniformMap = { u_pointCloud_colorGBuffer: function() { return processor.colorGBuffer; }, u_pointCloud_depthGBuffer: function() { return processor.depthGBuffer; }, u_distanceAndEdlStrength: function() { distanceAndEdlStrengthScratch.x = processor._radius; distanceAndEdlStrengthScratch.y = processor._strength; return distanceAndEdlStrengthScratch; } }; const blendRenderState = RenderState_default.fromCache({ blending: BlendingState_default.ALPHA_BLEND, depthMask: true, depthTest: { enabled: true }, stencilTest: StencilConstants_default.setCesium3DTileBit(), stencilMask: StencilConstants_default.CESIUM_3D_TILE_MASK }); processor._drawCommand = context.createViewportQuadCommand(blendFS, { uniformMap: blendUniformMap, renderState: blendRenderState, pass: Pass_default.CESIUM_3D_TILE, owner: processor }); processor._clearCommand = new ClearCommand_default({ framebuffer: processor.framebuffer, color: new Color_default(0, 0, 0, 0), depth: 1, renderState: RenderState_default.fromCache(), pass: Pass_default.CESIUM_3D_TILE, owner: processor }); } function createResources(processor, context) { const width = context.drawingBufferWidth; const height = context.drawingBufferHeight; processor._framebuffer.update(context, width, height); createCommands4(processor, context); } function isSupported(context) { return context.drawBuffers && context.fragmentDepth; } PointCloudEyeDomeLighting.isSupported = isSupported; function getECShaderProgram(context, shaderProgram) { let shader = context.shaderCache.getDerivedShaderProgram(shaderProgram, "EC"); if (!defined_default(shader)) { const attributeLocations8 = shaderProgram._attributeLocations; const fs = shaderProgram.fragmentShaderSource.clone(); fs.sources.splice( 0, 0, `layout (location = 0) out vec4 out_FragData_0; layout (location = 1) out vec4 out_FragData_1;` ); fs.sources = fs.sources.map(function(source) { source = ShaderSource_default.replaceMain( source, "czm_point_cloud_post_process_main" ); source = source.replaceAll(/out_FragColor/g, "out_FragData_0"); return source; }); fs.sources.push( "void main() \n{ \n czm_point_cloud_post_process_main(); \n#ifdef LOG_DEPTH\n czm_writeLogDepth();\n out_FragData_1 = czm_packDepth(gl_FragDepth); \n#else\n out_FragData_1 = czm_packDepth(gl_FragCoord.z);\n#endif\n}" ); shader = context.shaderCache.createDerivedShaderProgram( shaderProgram, "EC", { vertexShaderSource: shaderProgram.vertexShaderSource, fragmentShaderSource: fs, attributeLocations: attributeLocations8 } ); } return shader; } PointCloudEyeDomeLighting.prototype.update = function(frameState, commandStart, pointCloudShading, boundingVolume) { if (!isSupported(frameState.context)) { return; } this._strength = pointCloudShading.eyeDomeLightingStrength; this._radius = pointCloudShading.eyeDomeLightingRadius * frameState.pixelRatio; createResources(this, frameState.context); let i; const commandList = frameState.commandList; const commandEnd = commandList.length; for (i = commandStart; i < commandEnd; ++i) { const command = commandList[i]; if (command.primitiveType !== PrimitiveType_default.POINTS || command.pass === Pass_default.TRANSLUCENT) { continue; } let derivedCommand; let originalShaderProgram; let derivedCommandObject = command.derivedCommands.pointCloudProcessor; if (defined_default(derivedCommandObject)) { derivedCommand = derivedCommandObject.command; originalShaderProgram = derivedCommandObject.originalShaderProgram; } if (!defined_default(derivedCommand) || command.dirty || originalShaderProgram !== command.shaderProgram || derivedCommand.framebuffer !== this.framebuffer) { derivedCommand = DrawCommand_default.shallowClone(command, derivedCommand); derivedCommand.framebuffer = this.framebuffer; derivedCommand.shaderProgram = getECShaderProgram( frameState.context, command.shaderProgram ); derivedCommand.castShadows = false; derivedCommand.receiveShadows = false; if (!defined_default(derivedCommandObject)) { derivedCommandObject = { command: derivedCommand, originalShaderProgram: command.shaderProgram }; command.derivedCommands.pointCloudProcessor = derivedCommandObject; } derivedCommandObject.originalShaderProgram = command.shaderProgram; } commandList[i] = derivedCommand; } const clearCommand = this._clearCommand; const blendCommand = this._drawCommand; blendCommand.boundingVolume = boundingVolume; commandList.push(blendCommand); commandList.push(clearCommand); }; PointCloudEyeDomeLighting.prototype.isDestroyed = function() { return false; }; PointCloudEyeDomeLighting.prototype.destroy = function() { destroyFramebuffer(this); return destroyObject_default(this); }; var PointCloudEyeDomeLighting_default2 = PointCloudEyeDomeLighting; // packages/engine/Source/Scene/PointCloudShading.js function PointCloudShading(options) { const pointCloudShading = defaultValue_default(options, {}); this.attenuation = defaultValue_default(pointCloudShading.attenuation, false); this.geometricErrorScale = defaultValue_default( pointCloudShading.geometricErrorScale, 1 ); this.maximumAttenuation = pointCloudShading.maximumAttenuation; this.baseResolution = pointCloudShading.baseResolution; this.eyeDomeLighting = defaultValue_default(pointCloudShading.eyeDomeLighting, true); this.eyeDomeLightingStrength = defaultValue_default( pointCloudShading.eyeDomeLightingStrength, 1 ); this.eyeDomeLightingRadius = defaultValue_default( pointCloudShading.eyeDomeLightingRadius, 1 ); this.backFaceCulling = defaultValue_default(pointCloudShading.backFaceCulling, false); this.normalShading = defaultValue_default(pointCloudShading.normalShading, true); } PointCloudShading.isSupported = function(scene) { return PointCloudEyeDomeLighting_default2.isSupported(scene.context); }; var PointCloudShading_default = PointCloudShading; // packages/engine/Source/Scene/SceneTransforms.js var SceneTransforms = {}; var actualPositionScratch = new Cartesian4_default(0, 0, 0, 1); var positionCC = new Cartesian4_default(); var scratchViewport2 = new BoundingRectangle_default(); var scratchWindowCoord0 = new Cartesian2_default(); var scratchWindowCoord1 = new Cartesian2_default(); SceneTransforms.wgs84ToWindowCoordinates = function(scene, position, result) { return SceneTransforms.wgs84WithEyeOffsetToWindowCoordinates( scene, position, Cartesian3_default.ZERO, result ); }; var scratchCartesian42 = new Cartesian4_default(); var scratchEyeOffset = new Cartesian3_default(); function worldToClip(position, eyeOffset, camera, result) { const viewMatrix = camera.viewMatrix; const positionEC = Matrix4_default.multiplyByVector( viewMatrix, Cartesian4_default.fromElements( position.x, position.y, position.z, 1, scratchCartesian42 ), scratchCartesian42 ); const zEyeOffset = Cartesian3_default.multiplyComponents( eyeOffset, Cartesian3_default.normalize(positionEC, scratchEyeOffset), scratchEyeOffset ); positionEC.x += eyeOffset.x + zEyeOffset.x; positionEC.y += eyeOffset.y + zEyeOffset.y; positionEC.z += zEyeOffset.z; return Matrix4_default.multiplyByVector( camera.frustum.projectionMatrix, positionEC, result ); } var scratchMaxCartographic = new Cartographic_default( Math.PI, Math_default.PI_OVER_TWO ); var scratchProjectedCartesian = new Cartesian3_default(); var scratchCameraPosition = new Cartesian3_default(); SceneTransforms.wgs84WithEyeOffsetToWindowCoordinates = function(scene, position, eyeOffset, result) { if (!defined_default(scene)) { throw new DeveloperError_default("scene is required."); } if (!defined_default(position)) { throw new DeveloperError_default("position is required."); } const frameState = scene.frameState; const actualPosition = SceneTransforms.computeActualWgs84Position( frameState, position, actualPositionScratch ); if (!defined_default(actualPosition)) { return void 0; } const canvas = scene.canvas; const viewport = scratchViewport2; viewport.x = 0; viewport.y = 0; viewport.width = canvas.clientWidth; viewport.height = canvas.clientHeight; const camera = scene.camera; let cameraCentered = false; if (frameState.mode === SceneMode_default.SCENE2D) { const projection = scene.mapProjection; const maxCartographic = scratchMaxCartographic; const maxCoord = projection.project( maxCartographic, scratchProjectedCartesian ); const cameraPosition = Cartesian3_default.clone( camera.position, scratchCameraPosition ); const frustum = camera.frustum.clone(); const viewportTransformation = Matrix4_default.computeViewportTransformation( viewport, 0, 1, new Matrix4_default() ); const projectionMatrix = camera.frustum.projectionMatrix; const x = camera.positionWC.y; const eyePoint = Cartesian3_default.fromElements( Math_default.sign(x) * maxCoord.x - x, 0, -camera.positionWC.x ); const windowCoordinates = Transforms_default.pointToGLWindowCoordinates( projectionMatrix, viewportTransformation, eyePoint ); if (x === 0 || windowCoordinates.x <= 0 || windowCoordinates.x >= canvas.clientWidth) { cameraCentered = true; } else { if (windowCoordinates.x > canvas.clientWidth * 0.5) { viewport.width = windowCoordinates.x; camera.frustum.right = maxCoord.x - x; positionCC = worldToClip(actualPosition, eyeOffset, camera, positionCC); SceneTransforms.clipToGLWindowCoordinates( viewport, positionCC, scratchWindowCoord0 ); viewport.x += windowCoordinates.x; camera.position.x = -camera.position.x; const right = camera.frustum.right; camera.frustum.right = -camera.frustum.left; camera.frustum.left = -right; positionCC = worldToClip(actualPosition, eyeOffset, camera, positionCC); SceneTransforms.clipToGLWindowCoordinates( viewport, positionCC, scratchWindowCoord1 ); } else { viewport.x += windowCoordinates.x; viewport.width -= windowCoordinates.x; camera.frustum.left = -maxCoord.x - x; positionCC = worldToClip(actualPosition, eyeOffset, camera, positionCC); SceneTransforms.clipToGLWindowCoordinates( viewport, positionCC, scratchWindowCoord0 ); viewport.x = viewport.x - viewport.width; camera.position.x = -camera.position.x; const left = camera.frustum.left; camera.frustum.left = -camera.frustum.right; camera.frustum.right = -left; positionCC = worldToClip(actualPosition, eyeOffset, camera, positionCC); SceneTransforms.clipToGLWindowCoordinates( viewport, positionCC, scratchWindowCoord1 ); } Cartesian3_default.clone(cameraPosition, camera.position); camera.frustum = frustum.clone(); result = Cartesian2_default.clone(scratchWindowCoord0, result); if (result.x < 0 || result.x > canvas.clientWidth) { result.x = scratchWindowCoord1.x; } } } if (frameState.mode !== SceneMode_default.SCENE2D || cameraCentered) { positionCC = worldToClip(actualPosition, eyeOffset, camera, positionCC); if (positionCC.z < 0 && !(camera.frustum instanceof OrthographicFrustum_default) && !(camera.frustum instanceof OrthographicOffCenterFrustum_default)) { return void 0; } result = SceneTransforms.clipToGLWindowCoordinates( viewport, positionCC, result ); } result.y = canvas.clientHeight - result.y; return result; }; SceneTransforms.wgs84ToDrawingBufferCoordinates = function(scene, position, result) { result = SceneTransforms.wgs84ToWindowCoordinates(scene, position, result); if (!defined_default(result)) { return void 0; } return SceneTransforms.transformWindowToDrawingBuffer(scene, result, result); }; var projectedPosition = new Cartesian3_default(); var positionInCartographic = new Cartographic_default(); SceneTransforms.computeActualWgs84Position = function(frameState, position, result) { const mode2 = frameState.mode; if (mode2 === SceneMode_default.SCENE3D) { return Cartesian3_default.clone(position, result); } const projection = frameState.mapProjection; const cartographic2 = projection.ellipsoid.cartesianToCartographic( position, positionInCartographic ); if (!defined_default(cartographic2)) { return void 0; } projection.project(cartographic2, projectedPosition); if (mode2 === SceneMode_default.COLUMBUS_VIEW) { return Cartesian3_default.fromElements( projectedPosition.z, projectedPosition.x, projectedPosition.y, result ); } if (mode2 === SceneMode_default.SCENE2D) { return Cartesian3_default.fromElements( 0, projectedPosition.x, projectedPosition.y, result ); } const morphTime = frameState.morphTime; return Cartesian3_default.fromElements( Math_default.lerp(projectedPosition.z, position.x, morphTime), Math_default.lerp(projectedPosition.x, position.y, morphTime), Math_default.lerp(projectedPosition.y, position.z, morphTime), result ); }; var positionNDC = new Cartesian3_default(); var positionWC = new Cartesian3_default(); var viewportTransform = new Matrix4_default(); SceneTransforms.clipToGLWindowCoordinates = function(viewport, position, result) { Cartesian3_default.divideByScalar(position, position.w, positionNDC); Matrix4_default.computeViewportTransformation(viewport, 0, 1, viewportTransform); Matrix4_default.multiplyByPoint(viewportTransform, positionNDC, positionWC); return Cartesian2_default.fromCartesian3(positionWC, result); }; SceneTransforms.transformWindowToDrawingBuffer = function(scene, windowPosition, result) { const canvas = scene.canvas; const xScale = scene.drawingBufferWidth / canvas.clientWidth; const yScale = scene.drawingBufferHeight / canvas.clientHeight; return Cartesian2_default.fromElements( windowPosition.x * xScale, windowPosition.y * yScale, result ); }; var scratchNDC = new Cartesian4_default(); var scratchWorldCoords = new Cartesian4_default(); SceneTransforms.drawingBufferToWgs84Coordinates = function(scene, drawingBufferPosition, depth, result) { const context = scene.context; const uniformState = context.uniformState; const currentFrustum = uniformState.currentFrustum; const near = currentFrustum.x; const far = currentFrustum.y; if (scene.frameState.useLogDepth) { const log2Depth = depth * uniformState.log2FarDepthFromNearPlusOne; const depthFromNear = Math.pow(2, log2Depth) - 1; depth = far * (1 - near / (depthFromNear + near)) / (far - near); } const viewport = scene.view.passState.viewport; const ndc = Cartesian4_default.clone(Cartesian4_default.UNIT_W, scratchNDC); ndc.x = (drawingBufferPosition.x - viewport.x) / viewport.width * 2 - 1; ndc.y = (drawingBufferPosition.y - viewport.y) / viewport.height * 2 - 1; ndc.z = depth * 2 - 1; ndc.w = 1; let worldCoords; let frustum = scene.camera.frustum; if (!defined_default(frustum.fovy)) { const offCenterFrustum = frustum.offCenterFrustum; if (defined_default(offCenterFrustum)) { frustum = offCenterFrustum; } worldCoords = scratchWorldCoords; worldCoords.x = (ndc.x * (frustum.right - frustum.left) + frustum.left + frustum.right) * 0.5; worldCoords.y = (ndc.y * (frustum.top - frustum.bottom) + frustum.bottom + frustum.top) * 0.5; worldCoords.z = (ndc.z * (near - far) - near - far) * 0.5; worldCoords.w = 1; worldCoords = Matrix4_default.multiplyByVector( uniformState.inverseView, worldCoords, worldCoords ); } else { worldCoords = Matrix4_default.multiplyByVector( uniformState.inverseViewProjection, ndc, scratchWorldCoords ); const w = 1 / worldCoords.w; Cartesian3_default.multiplyByScalar(worldCoords, w, worldCoords); } return Cartesian3_default.fromCartesian4(worldCoords, result); }; var SceneTransforms_default = SceneTransforms; // packages/engine/Source/Scene/SplitDirection.js var SplitDirection = { /** * Display the primitive or ImageryLayer to the left of the {@link Scene#splitPosition}. * * @type {number} * @constant */ LEFT: -1, /** * Always display the primitive or ImageryLayer. * * @type {number} * @constant */ NONE: 0, /** * Display the primitive or ImageryLayer to the right of the {@link Scene#splitPosition}. * * @type {number} * @constant */ RIGHT: 1 }; var SplitDirection_default = Object.freeze(SplitDirection); // packages/engine/Source/Scene/B3dmParser.js var B3dmParser = {}; B3dmParser._deprecationWarning = deprecationWarning_default; var sizeOfUint324 = Uint32Array.BYTES_PER_ELEMENT; B3dmParser.parse = function(arrayBuffer, byteOffset) { const byteStart = defaultValue_default(byteOffset, 0); Check_default.defined("arrayBuffer", arrayBuffer); byteOffset = byteStart; const uint8Array = new Uint8Array(arrayBuffer); const view = new DataView(arrayBuffer); byteOffset += sizeOfUint324; const version2 = view.getUint32(byteOffset, true); if (version2 !== 1) { throw new RuntimeError_default( `Only Batched 3D Model version 1 is supported. Version ${version2} is not.` ); } byteOffset += sizeOfUint324; const byteLength = view.getUint32(byteOffset, true); byteOffset += sizeOfUint324; let featureTableJsonByteLength = view.getUint32(byteOffset, true); byteOffset += sizeOfUint324; let featureTableBinaryByteLength = view.getUint32(byteOffset, true); byteOffset += sizeOfUint324; let batchTableJsonByteLength = view.getUint32(byteOffset, true); byteOffset += sizeOfUint324; let batchTableBinaryByteLength = view.getUint32(byteOffset, true); byteOffset += sizeOfUint324; let batchLength; if (batchTableJsonByteLength >= 570425344) { byteOffset -= sizeOfUint324 * 2; batchLength = featureTableJsonByteLength; batchTableJsonByteLength = featureTableBinaryByteLength; batchTableBinaryByteLength = 0; featureTableJsonByteLength = 0; featureTableBinaryByteLength = 0; B3dmParser._deprecationWarning( "b3dm-legacy-header", "This b3dm header is using the legacy format [batchLength] [batchTableByteLength]. The new format is [featureTableJsonByteLength] [featureTableBinaryByteLength] [batchTableJsonByteLength] [batchTableBinaryByteLength] from https://github.com/CesiumGS/3d-tiles/tree/main/specification/TileFormats/Batched3DModel." ); } else if (batchTableBinaryByteLength >= 570425344) { byteOffset -= sizeOfUint324; batchLength = batchTableJsonByteLength; batchTableJsonByteLength = featureTableJsonByteLength; batchTableBinaryByteLength = featureTableBinaryByteLength; featureTableJsonByteLength = 0; featureTableBinaryByteLength = 0; B3dmParser._deprecationWarning( "b3dm-legacy-header", "This b3dm header is using the legacy format [batchTableJsonByteLength] [batchTableBinaryByteLength] [batchLength]. The new format is [featureTableJsonByteLength] [featureTableBinaryByteLength] [batchTableJsonByteLength] [batchTableBinaryByteLength] from https://github.com/CesiumGS/3d-tiles/tree/main/specification/TileFormats/Batched3DModel." ); } let featureTableJson; if (featureTableJsonByteLength === 0) { featureTableJson = { BATCH_LENGTH: defaultValue_default(batchLength, 0) }; } else { featureTableJson = getJsonFromTypedArray_default( uint8Array, byteOffset, featureTableJsonByteLength ); byteOffset += featureTableJsonByteLength; } const featureTableBinary = new Uint8Array( arrayBuffer, byteOffset, featureTableBinaryByteLength ); byteOffset += featureTableBinaryByteLength; let batchTableJson; let batchTableBinary; if (batchTableJsonByteLength > 0) { batchTableJson = getJsonFromTypedArray_default( uint8Array, byteOffset, batchTableJsonByteLength ); byteOffset += batchTableJsonByteLength; if (batchTableBinaryByteLength > 0) { batchTableBinary = new Uint8Array( arrayBuffer, byteOffset, batchTableBinaryByteLength ); batchTableBinary = new Uint8Array(batchTableBinary); byteOffset += batchTableBinaryByteLength; } } const gltfByteLength = byteStart + byteLength - byteOffset; if (gltfByteLength === 0) { throw new RuntimeError_default("glTF byte length must be greater than 0."); } let gltfView; if (byteOffset % 4 === 0) { gltfView = new Uint8Array(arrayBuffer, byteOffset, gltfByteLength); } else { B3dmParser._deprecationWarning( "b3dm-glb-unaligned", "The embedded glb is not aligned to a 4-byte boundary." ); gltfView = new Uint8Array( uint8Array.subarray(byteOffset, byteOffset + gltfByteLength) ); } return { batchLength, featureTableJson, featureTableBinary, batchTableJson, batchTableBinary, gltf: gltfView }; }; var B3dmParser_default = B3dmParser; // packages/engine/Source/Scene/Cesium3DTileFeatureTable.js function Cesium3DTileFeatureTable(featureTableJson, featureTableBinary) { this.json = featureTableJson; this.buffer = featureTableBinary; this._cachedTypedArrays = {}; this.featuresLength = 0; } function getTypedArrayFromBinary(featureTable, semantic, componentType, componentLength, count, byteOffset) { const cachedTypedArrays = featureTable._cachedTypedArrays; let typedArray = cachedTypedArrays[semantic]; if (!defined_default(typedArray)) { typedArray = ComponentDatatype_default.createArrayBufferView( componentType, featureTable.buffer.buffer, featureTable.buffer.byteOffset + byteOffset, count * componentLength ); cachedTypedArrays[semantic] = typedArray; } return typedArray; } function getTypedArrayFromArray(featureTable, semantic, componentType, array) { const cachedTypedArrays = featureTable._cachedTypedArrays; let typedArray = cachedTypedArrays[semantic]; if (!defined_default(typedArray)) { typedArray = ComponentDatatype_default.createTypedArray(componentType, array); cachedTypedArrays[semantic] = typedArray; } return typedArray; } Cesium3DTileFeatureTable.prototype.getGlobalProperty = function(semantic, componentType, componentLength) { const jsonValue = this.json[semantic]; if (!defined_default(jsonValue)) { return void 0; } if (defined_default(jsonValue.byteOffset)) { componentType = defaultValue_default(componentType, ComponentDatatype_default.UNSIGNED_INT); componentLength = defaultValue_default(componentLength, 1); return getTypedArrayFromBinary( this, semantic, componentType, componentLength, 1, jsonValue.byteOffset ); } return jsonValue; }; Cesium3DTileFeatureTable.prototype.hasProperty = function(semantic) { return defined_default(this.json[semantic]); }; Cesium3DTileFeatureTable.prototype.getPropertyArray = function(semantic, componentType, componentLength) { const jsonValue = this.json[semantic]; if (!defined_default(jsonValue)) { return void 0; } if (defined_default(jsonValue.byteOffset)) { if (defined_default(jsonValue.componentType)) { componentType = ComponentDatatype_default.fromName(jsonValue.componentType); } return getTypedArrayFromBinary( this, semantic, componentType, componentLength, this.featuresLength, jsonValue.byteOffset ); } return getTypedArrayFromArray(this, semantic, componentType, jsonValue); }; Cesium3DTileFeatureTable.prototype.getProperty = function(semantic, componentType, componentLength, featureId, result) { const jsonValue = this.json[semantic]; if (!defined_default(jsonValue)) { return void 0; } const typedArray = this.getPropertyArray( semantic, componentType, componentLength ); if (componentLength === 1) { return typedArray[featureId]; } for (let i = 0; i < componentLength; ++i) { result[i] = typedArray[componentLength * featureId + i]; } return result; }; var Cesium3DTileFeatureTable_default = Cesium3DTileFeatureTable; // packages/engine/Source/Scene/parseBatchTable.js function parseBatchTable(options) { Check_default.typeOf.number("options.count", options.count); Check_default.typeOf.object("options.batchTable", options.batchTable); const featureCount = options.count; const batchTable = options.batchTable; const binaryBody = options.binaryBody; const parseAsPropertyAttributes = defaultValue_default( options.parseAsPropertyAttributes, false ); const customAttributeOutput = options.customAttributeOutput; if (parseAsPropertyAttributes && !defined_default(customAttributeOutput)) { throw new DeveloperError_default( "customAttributeOutput is required when parsing batch table as property attributes" ); } const partitionResults = partitionProperties(batchTable); let jsonMetadataTable; if (defined_default(partitionResults.jsonProperties)) { jsonMetadataTable = new JsonMetadataTable_default({ count: featureCount, properties: partitionResults.jsonProperties }); } let hierarchy; if (defined_default(partitionResults.hierarchy)) { hierarchy = new BatchTableHierarchy_default({ extension: partitionResults.hierarchy, binaryBody }); } const className = MetadataClass_default.BATCH_TABLE_CLASS_NAME; const binaryProperties = partitionResults.binaryProperties; let metadataTable; let propertyAttributes; let transcodedSchema; if (parseAsPropertyAttributes) { const attributeResults = transcodeBinaryPropertiesAsPropertyAttributes( featureCount, className, binaryProperties, binaryBody, customAttributeOutput ); transcodedSchema = attributeResults.transcodedSchema; const propertyAttribute = new PropertyAttribute_default({ propertyAttribute: attributeResults.propertyAttributeJson, class: attributeResults.transcodedClass }); propertyAttributes = [propertyAttribute]; } else { const binaryResults = transcodeBinaryProperties( featureCount, className, binaryProperties, binaryBody ); transcodedSchema = binaryResults.transcodedSchema; const featureTableJson = binaryResults.featureTableJson; metadataTable = new MetadataTable_default({ count: featureTableJson.count, properties: featureTableJson.properties, class: binaryResults.transcodedClass, bufferViews: binaryResults.bufferViewsTypedArrays }); propertyAttributes = []; } const propertyTables = []; if (defined_default(metadataTable) || defined_default(jsonMetadataTable) || defined_default(hierarchy)) { const propertyTable = new PropertyTable_default({ id: 0, name: "Batch Table", count: featureCount, metadataTable, jsonMetadataTable, batchTableHierarchy: hierarchy }); propertyTables.push(propertyTable); } const metadataOptions = { schema: transcodedSchema, propertyTables, propertyAttributes, extensions: partitionResults.extensions, extras: partitionResults.extras }; return new StructuralMetadata_default(metadataOptions); } function partitionProperties(batchTable) { const legacyHierarchy = batchTable.HIERARCHY; const extras = batchTable.extras; const extensions = batchTable.extensions; let hierarchyExtension; if (defined_default(legacyHierarchy)) { parseBatchTable._deprecationWarning( "batchTableHierarchyExtension", "The batch table HIERARCHY property has been moved to an extension. Use extensions.3DTILES_batch_table_hierarchy instead." ); hierarchyExtension = legacyHierarchy; } else if (defined_default(extensions)) { hierarchyExtension = extensions["3DTILES_batch_table_hierarchy"]; } let jsonProperties; const binaryProperties = {}; for (const propertyId in batchTable) { if (!batchTable.hasOwnProperty(propertyId) || // these cases were handled above; propertyId === "HIERARCHY" || propertyId === "extensions" || propertyId === "extras") { continue; } const property = batchTable[propertyId]; if (Array.isArray(property)) { jsonProperties = defined_default(jsonProperties) ? jsonProperties : {}; jsonProperties[propertyId] = property; } else { binaryProperties[propertyId] = property; } } return { binaryProperties, jsonProperties, hierarchy: hierarchyExtension, extras, extensions }; } function transcodeBinaryProperties(featureCount, className, binaryProperties, binaryBody) { const classProperties = {}; const featureTableProperties = {}; const bufferViewsTypedArrays = {}; let bufferViewCount = 0; for (const propertyId in binaryProperties) { if (!binaryProperties.hasOwnProperty(propertyId)) { continue; } if (!defined_default(binaryBody)) { throw new RuntimeError_default( `Property ${propertyId} requires a batch table binary.` ); } const property = binaryProperties[propertyId]; const binaryAccessor = getBinaryAccessor_default(property); featureTableProperties[propertyId] = { bufferView: bufferViewCount }; classProperties[propertyId] = transcodePropertyType(property); bufferViewsTypedArrays[bufferViewCount] = binaryAccessor.createArrayBufferView( binaryBody.buffer, binaryBody.byteOffset + property.byteOffset, featureCount ); bufferViewCount++; } const schemaJson = { classes: {} }; schemaJson.classes[className] = { properties: classProperties }; const transcodedSchema = MetadataSchema_default.fromJson(schemaJson); const featureTableJson = { class: className, count: featureCount, properties: featureTableProperties }; return { featureTableJson, bufferViewsTypedArrays, transcodedSchema, transcodedClass: transcodedSchema.classes[className] }; } function transcodeBinaryPropertiesAsPropertyAttributes(featureCount, className, binaryProperties, binaryBody, customAttributeOutput) { const classProperties = {}; const propertyAttributeProperties = {}; let nextPlaceholderId = 0; for (const propertyId in binaryProperties) { if (!binaryProperties.hasOwnProperty(propertyId)) { continue; } const property = binaryProperties[propertyId]; if (!defined_default(binaryBody) && !defined_default(property.typedArray)) { throw new RuntimeError_default( `Property ${propertyId} requires a batch table binary.` ); } let sanitizedPropertyId = ModelUtility_default.sanitizeGlslIdentifier(propertyId); if (sanitizedPropertyId === "" || classProperties.hasOwnProperty(sanitizedPropertyId)) { sanitizedPropertyId = `property_${nextPlaceholderId}`; nextPlaceholderId++; } const classProperty = transcodePropertyType(property); classProperty.name = propertyId; classProperties[sanitizedPropertyId] = classProperty; let customAttributeName = sanitizedPropertyId.toUpperCase(); if (!customAttributeName.startsWith("_")) { customAttributeName = `_${customAttributeName}`; } let attributeTypedArray = property.typedArray; if (!defined_default(attributeTypedArray)) { const binaryAccessor = getBinaryAccessor_default(property); attributeTypedArray = binaryAccessor.createArrayBufferView( binaryBody.buffer, binaryBody.byteOffset + property.byteOffset, featureCount ); } const attribute = new ModelComponents_default.Attribute(); attribute.name = customAttributeName; attribute.count = featureCount; attribute.type = property.type; const componentDatatype = ComponentDatatype_default.fromTypedArray( attributeTypedArray ); if (componentDatatype === ComponentDatatype_default.INT || componentDatatype === ComponentDatatype_default.UNSIGNED_INT || componentDatatype === ComponentDatatype_default.DOUBLE) { parseBatchTable._oneTimeWarning( "Cast pnts property to floats", `Point cloud property "${customAttributeName}" will be cast to a float array because INT, UNSIGNED_INT, and DOUBLE are not valid WebGL vertex attribute types. Some precision may be lost.` ); attributeTypedArray = new Float32Array(attributeTypedArray); } attribute.componentDatatype = ComponentDatatype_default.fromTypedArray( attributeTypedArray ); attribute.typedArray = attributeTypedArray; customAttributeOutput.push(attribute); propertyAttributeProperties[sanitizedPropertyId] = { attribute: customAttributeName }; } const schemaJson = { classes: {} }; schemaJson.classes[className] = { properties: classProperties }; const transcodedSchema = MetadataSchema_default.fromJson(schemaJson); const propertyAttributeJson = { properties: propertyAttributeProperties }; return { class: className, propertyAttributeJson, transcodedSchema, transcodedClass: transcodedSchema.classes[className] }; } function transcodePropertyType(property) { const componentType = transcodeComponentType(property.componentType); return { type: property.type, componentType }; } function transcodeComponentType(componentType) { switch (componentType) { case "BYTE": return "INT8"; case "UNSIGNED_BYTE": return "UINT8"; case "SHORT": return "INT16"; case "UNSIGNED_SHORT": return "UINT16"; case "INT": return "INT32"; case "UNSIGNED_INT": return "UINT32"; case "FLOAT": return "FLOAT32"; case "DOUBLE": return "FLOAT64"; } } parseBatchTable._deprecationWarning = deprecationWarning_default; parseBatchTable._oneTimeWarning = oneTimeWarning_default; var parseBatchTable_default = parseBatchTable; // packages/engine/Source/Scene/Model/B3dmLoader.js var B3dmLoaderState = { UNLOADED: 0, LOADING: 1, PROCESSING: 2, READY: 3, FAILED: 4 }; var FeatureIdAttribute3 = ModelComponents_default.FeatureIdAttribute; function B3dmLoader(options) { options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT); const b3dmResource = options.b3dmResource; let baseResource2 = options.baseResource; const arrayBuffer = options.arrayBuffer; const byteOffset = defaultValue_default(options.byteOffset, 0); const releaseGltfJson = defaultValue_default(options.releaseGltfJson, false); const asynchronous = defaultValue_default(options.asynchronous, true); const incrementallyLoadTextures = defaultValue_default( options.incrementallyLoadTextures, true ); const upAxis = defaultValue_default(options.upAxis, Axis_default.Y); const forwardAxis = defaultValue_default(options.forwardAxis, Axis_default.X); const loadAttributesAsTypedArray = defaultValue_default( options.loadAttributesAsTypedArray, false ); const loadAttributesFor2D = defaultValue_default(options.loadAttributesFor2D, false); const loadIndicesForWireframe = defaultValue_default( options.loadIndicesForWireframe, false ); const loadPrimitiveOutline2 = defaultValue_default(options.loadPrimitiveOutline, true); const loadForClassification = defaultValue_default( options.loadForClassification, false ); Check_default.typeOf.object("options.b3dmResource", b3dmResource); Check_default.typeOf.object("options.arrayBuffer", arrayBuffer); baseResource2 = defined_default(baseResource2) ? baseResource2 : b3dmResource.clone(); this._b3dmResource = b3dmResource; this._baseResource = baseResource2; 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._loadIndicesForWireframe = loadIndicesForWireframe; this._loadPrimitiveOutline = loadPrimitiveOutline2; this._loadForClassification = loadForClassification; this._state = B3dmLoaderState.UNLOADED; this._promise = void 0; this._gltfLoader = void 0; this._batchLength = 0; this._propertyTable = void 0; this._batchTable = void 0; this._components = void 0; this._transform = Matrix4_default.IDENTITY; } if (defined_default(Object.create)) { B3dmLoader.prototype = Object.create(ResourceLoader_default.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 void 0; } }, /** * The loaded components. * * @memberof B3dmLoader.prototype * * @type {ModelComponents.Components} * @readonly * @private */ components: { get: function() { return this._components; } } }); B3dmLoader.prototype.load = function() { if (defined_default(this._promise)) { return this._promise; } const b3dm = B3dmParser_default.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_default( featureTableJson, featureTableBinary ); batchLength = featureTable.getGlobalProperty("BATCH_LENGTH"); this._batchLength = batchLength; const rtcCenter = featureTable.getGlobalProperty( "RTC_CENTER", ComponentDatatype_default.FLOAT, 3 ); if (defined_default(rtcCenter)) { this._transform = Matrix4_default.fromTranslation(Cartesian3_default.fromArray(rtcCenter)); } this._batchTable = { json: batchTableJson, binary: batchTableBinary }; const gltfLoader = new GltfLoader_default({ 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, 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() { if (that.isDestroyed()) { return; } that._state = B3dmLoaderState.PROCESSING; return that; }).catch(function(error) { if (that.isDestroyed()) { return; } return handleError7(that, error); }); return this._promise; }; function handleError7(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) { Check_default.typeOf.object("frameState", frameState); if (this._state === B3dmLoaderState.READY) { return true; } if (this._state !== B3dmLoaderState.PROCESSING) { return false; } const ready = this._gltfLoader.process(frameState); if (!ready) { return false; } const components = this._gltfLoader.components; components.transform = Matrix4_default.multiplyTransformation( this._transform, components.transform, components.transform ); createStructuralMetadata(this, components); this._components = components; this._arrayBuffer = void 0; 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_default(batchTable.json)) { structuralMetadata = parseBatchTable_default({ count: batchLength, batchTable: batchTable.json, binaryBody: batchTable.binary }); } else { const emptyPropertyTable = new PropertyTable_default({ name: MetadataClass_default.BATCH_TABLE_CLASS_NAME, count: batchLength }); structuralMetadata = new StructuralMetadata_default({ schema: {}, propertyTables: [emptyPropertyTable] }); } const nodes = components.scene.nodes; const length3 = nodes.length; for (let i = 0; i < length3; i++) { processNode(nodes[i]); } components.structuralMetadata = structuralMetadata; } 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_default.getAttributeBySemantic( primitive, VertexAttributeSemantic_default.FEATURE_ID ); if (defined_default(featureIdVertexAttribute)) { featureIdVertexAttribute.setIndex = 0; const featureIdAttribute = new FeatureIdAttribute3(); featureIdAttribute.propertyTableId = 0; featureIdAttribute.setIndex = 0; featureIdAttribute.positionalLabel = "featureId_0"; primitive.featureIds.push(featureIdAttribute); } } } B3dmLoader.prototype.unload = function() { if (defined_default(this._gltfLoader) && !this._gltfLoader.isDestroyed()) { this._gltfLoader.unload(); } this._components = void 0; this._arrayBuffer = void 0; }; var B3dmLoader_default = B3dmLoader; // packages/engine/Source/Scene/Model/GeoJsonLoader.js function GeoJsonLoader(options) { options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT); Check_default.typeOf.object("options.geoJson", options.geoJson); this._geoJson = options.geoJson; this._components = void 0; } if (defined_default(Object.create)) { GeoJsonLoader.prototype = Object.create(ResourceLoader_default.prototype); GeoJsonLoader.prototype.constructor = GeoJsonLoader; } Object.defineProperties(GeoJsonLoader.prototype, { /** * The cache key of the resource. * * @memberof GeoJsonLoader.prototype * * @type {string} * @readonly * @private */ cacheKey: { get: function() { return void 0; } }, /** * The loaded components. * * @memberof GeoJsonLoader.prototype * * @type {ModelComponents.Components} * @readonly * @private */ components: { get: function() { return this._components; } } }); GeoJsonLoader.prototype.load = function() { return Promise.resolve(this); }; GeoJsonLoader.prototype.process = function(frameState) { Check_default.typeOf.object("frameState", frameState); if (defined_default(this._components)) { return true; } this._components = parse2(this._geoJson, frameState); this._geoJson = void 0; return true; }; function ParsedFeature() { this.lines = void 0; this.points = void 0; this.properties = void 0; } function ParseResult() { this.features = []; } function parsePosition(position) { const x = position[0]; const y = position[1]; const z = defaultValue_default(position[2], 0); return new Cartesian3_default(x, y, z); } function parseLineString(coordinates) { const positionsLength = coordinates.length; const line = new Array(positionsLength); for (let i = 0; i < positionsLength; i++) { line[i] = parsePosition(coordinates[i]); } const lines = [line]; return lines; } function parseMultiLineString(coordinates) { const linesLength = coordinates.length; const lines = new Array(linesLength); for (let i = 0; i < linesLength; i++) { lines[i] = parseLineString(coordinates[i])[0]; } return lines; } function parsePolygon(coordinates) { const linesLength = coordinates.length; const lines = new Array(linesLength); for (let i = 0; i < linesLength; i++) { lines[i] = parseLineString(coordinates[i])[0]; } return lines; } function parseMultiPolygon(coordinates) { const polygonsLength = coordinates.length; const lines = []; for (let i = 0; i < polygonsLength; i++) { Array.prototype.push.apply(lines, parsePolygon(coordinates[i])); } return lines; } function parsePoint(coordinates) { return [parsePosition(coordinates)]; } function parseMultiPoint(coordinates) { const pointsLength = coordinates.length; const points = new Array(pointsLength); for (let i = 0; i < pointsLength; i++) { points[i] = parsePosition(coordinates[i]); } return points; } var geometryTypes = { LineString: parseLineString, MultiLineString: parseMultiLineString, MultiPolygon: parseMultiPolygon, Polygon: parsePolygon, MultiPoint: parseMultiPoint, Point: parsePoint }; var primitiveTypes = { LineString: PrimitiveType_default.LINES, MultiLineString: PrimitiveType_default.LINES, MultiPolygon: PrimitiveType_default.LINES, Polygon: PrimitiveType_default.LINES, MultiPoint: PrimitiveType_default.POINTS, Point: PrimitiveType_default.POINTS }; function parseFeature(feature2, result) { if (!defined_default(feature2.geometry)) { return; } const geometryType = feature2.geometry.type; const geometryFunction = geometryTypes[geometryType]; const primitiveType = primitiveTypes[geometryType]; const coordinates = feature2.geometry.coordinates; if (!defined_default(geometryFunction)) { return; } if (!defined_default(coordinates)) { return; } const parsedFeature = new ParsedFeature(); if (primitiveType === PrimitiveType_default.LINES) { parsedFeature.lines = geometryFunction(coordinates); } else if (primitiveType === PrimitiveType_default.POINTS) { parsedFeature.points = geometryFunction(coordinates); } parsedFeature.properties = feature2.properties; result.features.push(parsedFeature); } function parseFeatureCollection(featureCollection, result) { const features = featureCollection.features; const featuresLength = features.length; for (let i = 0; i < featuresLength; i++) { parseFeature(features[i], result); } } var geoJsonObjectTypes = { FeatureCollection: parseFeatureCollection, Feature: parseFeature }; var scratchCartesian7 = new Cartesian3_default(); function createLinesPrimitive(features, toLocal, frameState) { let vertexCount = 0; let indexCount = 0; const featureCount = features.length; for (let i = 0; i < featureCount; i++) { const feature2 = features[i]; if (defined_default(feature2.lines)) { const linesLength = feature2.lines.length; for (let j = 0; j < linesLength; j++) { const line = feature2.lines[j]; vertexCount += line.length; indexCount += (line.length - 1) * 2; } } } const positionsTypedArray = new Float32Array(vertexCount * 3); const featureIdsTypedArray = new Float32Array(vertexCount); const indicesTypedArray = IndexDatatype_default.createTypedArray( vertexCount, indexCount ); const indexDatatype = IndexDatatype_default.fromTypedArray(indicesTypedArray); const localMin = new Cartesian3_default( Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY ); const localMax = new Cartesian3_default( Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY ); let vertexCounter = 0; let segmentCounter = 0; for (let i = 0; i < featureCount; i++) { const feature2 = features[i]; if (!defined_default(feature2.lines)) { continue; } const linesLength = feature2.lines.length; for (let j = 0; j < linesLength; j++) { const line = feature2.lines[j]; const positionsLength = line.length; for (let k = 0; k < positionsLength; k++) { const cartographic2 = line[k]; const globalCartesian = Cartesian3_default.fromDegrees( cartographic2.x, cartographic2.y, cartographic2.z, Ellipsoid_default.WGS84, scratchCartesian7 ); const localCartesian = Matrix4_default.multiplyByPoint( toLocal, globalCartesian, scratchCartesian7 ); Cartesian3_default.minimumByComponent(localMin, localCartesian, localMin); Cartesian3_default.maximumByComponent(localMax, localCartesian, localMax); Cartesian3_default.pack(localCartesian, positionsTypedArray, vertexCounter * 3); featureIdsTypedArray[vertexCounter] = i; if (k < positionsLength - 1) { indicesTypedArray[segmentCounter * 2] = vertexCounter; indicesTypedArray[segmentCounter * 2 + 1] = vertexCounter + 1; segmentCounter++; } vertexCounter++; } } } const positionBuffer = Buffer_default.createVertexBuffer({ typedArray: positionsTypedArray, context: frameState.context, usage: BufferUsage_default.STATIC_DRAW }); positionBuffer.vertexArrayDestroyable = false; const featureIdBuffer = Buffer_default.createVertexBuffer({ typedArray: featureIdsTypedArray, context: frameState.context, usage: BufferUsage_default.STATIC_DRAW }); featureIdBuffer.vertexArrayDestroyable = false; const indexBuffer = Buffer_default.createIndexBuffer({ typedArray: indicesTypedArray, context: frameState.context, usage: BufferUsage_default.STATIC_DRAW, indexDatatype }); indexBuffer.vertexArrayDestroyable = false; const positionAttribute = new ModelComponents_default.Attribute(); positionAttribute.semantic = VertexAttributeSemantic_default.POSITION; positionAttribute.componentDatatype = ComponentDatatype_default.FLOAT; positionAttribute.type = AttributeType_default.VEC3; positionAttribute.count = vertexCount; positionAttribute.min = localMin; positionAttribute.max = localMax; positionAttribute.buffer = positionBuffer; const featureIdAttribute = new ModelComponents_default.Attribute(); featureIdAttribute.semantic = VertexAttributeSemantic_default.FEATURE_ID; featureIdAttribute.setIndex = 0; featureIdAttribute.componentDatatype = ComponentDatatype_default.FLOAT; featureIdAttribute.type = AttributeType_default.SCALAR; featureIdAttribute.count = vertexCount; featureIdAttribute.buffer = featureIdBuffer; const attributes = [positionAttribute, featureIdAttribute]; const material = new ModelComponents_default.Material(); material.unlit = true; const indices2 = new ModelComponents_default.Indices(); indices2.indexDatatype = indexDatatype; indices2.count = indicesTypedArray.length; indices2.buffer = indexBuffer; const featureId = new ModelComponents_default.FeatureIdAttribute(); featureId.featureCount = featureCount; featureId.propertyTableId = 0; featureId.setIndex = 0; featureId.positionalLabel = "featureId_0"; const featureIds = [featureId]; const primitive = new ModelComponents_default.Primitive(); primitive.attributes = attributes; primitive.indices = indices2; primitive.featureIds = featureIds; primitive.primitiveType = PrimitiveType_default.LINES; primitive.material = material; return primitive; } function createPointsPrimitive(features, toLocal, frameState) { let vertexCount = 0; const featureCount = features.length; for (let i = 0; i < featureCount; i++) { const feature2 = features[i]; if (defined_default(feature2.points)) { vertexCount += feature2.points.length; } } const positionsTypedArray = new Float32Array(vertexCount * 3); const featureIdsTypedArray = new Float32Array(vertexCount); const localMin = new Cartesian3_default( Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY ); const localMax = new Cartesian3_default( Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY ); let vertexCounter = 0; for (let i = 0; i < featureCount; i++) { const feature2 = features[i]; if (!defined_default(feature2.points)) { continue; } const pointsLength = feature2.points.length; for (let j = 0; j < pointsLength; j++) { const cartographic2 = feature2.points[j]; const globalCartesian = Cartesian3_default.fromDegrees( cartographic2.x, cartographic2.y, cartographic2.z, Ellipsoid_default.WGS84, scratchCartesian7 ); const localCartesian = Matrix4_default.multiplyByPoint( toLocal, globalCartesian, scratchCartesian7 ); Cartesian3_default.minimumByComponent(localMin, localCartesian, localMin); Cartesian3_default.maximumByComponent(localMax, localCartesian, localMax); Cartesian3_default.pack(localCartesian, positionsTypedArray, vertexCounter * 3); featureIdsTypedArray[vertexCounter] = i; vertexCounter++; } } const positionBuffer = Buffer_default.createVertexBuffer({ typedArray: positionsTypedArray, context: frameState.context, usage: BufferUsage_default.STATIC_DRAW }); positionBuffer.vertexArrayDestroyable = false; const featureIdBuffer = Buffer_default.createVertexBuffer({ typedArray: featureIdsTypedArray, context: frameState.context, usage: BufferUsage_default.STATIC_DRAW }); featureIdBuffer.vertexArrayDestroyable = false; const positionAttribute = new ModelComponents_default.Attribute(); positionAttribute.semantic = VertexAttributeSemantic_default.POSITION; positionAttribute.componentDatatype = ComponentDatatype_default.FLOAT; positionAttribute.type = AttributeType_default.VEC3; positionAttribute.count = vertexCount; positionAttribute.min = localMin; positionAttribute.max = localMax; positionAttribute.buffer = positionBuffer; const featureIdAttribute = new ModelComponents_default.Attribute(); featureIdAttribute.semantic = VertexAttributeSemantic_default.FEATURE_ID; featureIdAttribute.setIndex = 0; featureIdAttribute.componentDatatype = ComponentDatatype_default.FLOAT; featureIdAttribute.type = AttributeType_default.SCALAR; featureIdAttribute.count = vertexCount; featureIdAttribute.buffer = featureIdBuffer; const attributes = [positionAttribute, featureIdAttribute]; const material = new ModelComponents_default.Material(); material.unlit = true; const featureId = new ModelComponents_default.FeatureIdAttribute(); featureId.featureCount = featureCount; featureId.propertyTableId = 0; featureId.setIndex = 0; featureId.positionalLabel = "featureId_0"; const featureIds = [featureId]; const primitive = new ModelComponents_default.Primitive(); primitive.attributes = attributes; primitive.featureIds = featureIds; primitive.primitiveType = PrimitiveType_default.POINTS; primitive.material = material; return primitive; } function parse2(geoJson, frameState) { const result = new ParseResult(); const parseFunction = geoJsonObjectTypes[geoJson.type]; if (defined_default(parseFunction)) { parseFunction(geoJson, result); } const features = result.features; const featureCount = features.length; if (featureCount === 0) { throw new RuntimeError_default("GeoJSON must have at least one feature"); } const properties = {}; for (let i = 0; i < featureCount; i++) { const feature2 = features[i]; const featureProperties = defaultValue_default( feature2.properties, defaultValue_default.EMPTY_OBJECT ); for (const propertyId in featureProperties) { if (featureProperties.hasOwnProperty(propertyId)) { if (!defined_default(properties[propertyId])) { properties[propertyId] = new Array(featureCount); } } } } for (let i = 0; i < featureCount; i++) { const feature2 = features[i]; for (const propertyId in properties) { if (properties.hasOwnProperty(propertyId)) { const value = defaultValue_default(feature2.properties[propertyId], ""); properties[propertyId][i] = value; } } } const jsonMetadataTable = new JsonMetadataTable_default({ count: featureCount, properties }); const propertyTable = new PropertyTable_default({ id: 0, count: featureCount, jsonMetadataTable }); const propertyTables = [propertyTable]; const schema = MetadataSchema_default.fromJson({}); const structuralMetadata = new StructuralMetadata_default({ schema, propertyTables }); const cartographicMin = new Cartesian3_default( Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY ); const cartographicMax = new Cartesian3_default( Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY ); let hasLines = false; let hasPoints = false; for (let i = 0; i < featureCount; i++) { const feature2 = features[i]; if (defined_default(feature2.lines)) { hasLines = true; const linesLength = feature2.lines.length; for (let j = 0; j < linesLength; j++) { const line = feature2.lines[j]; const positionsLength = line.length; for (let k = 0; k < positionsLength; k++) { Cartesian3_default.minimumByComponent( cartographicMin, line[k], cartographicMin ); Cartesian3_default.maximumByComponent( cartographicMax, line[k], cartographicMax ); } } } if (defined_default(feature2.points)) { hasPoints = true; const pointsLength = feature2.points.length; for (let j = 0; j < pointsLength; j++) { const point = feature2.points[j]; Cartesian3_default.minimumByComponent(cartographicMin, point, cartographicMin); Cartesian3_default.maximumByComponent(cartographicMax, point, cartographicMax); } } } const cartographicCenter = Cartesian3_default.midpoint( cartographicMin, cartographicMax, new Cartesian3_default() ); const ecefCenter = Cartesian3_default.fromDegrees( cartographicCenter.x, cartographicCenter.y, cartographicCenter.z, Ellipsoid_default.WGS84, new Cartesian3_default() ); const toGlobal = Transforms_default.eastNorthUpToFixedFrame( ecefCenter, Ellipsoid_default.WGS84, new Matrix4_default() ); const toLocal = Matrix4_default.inverseTransformation(toGlobal, new Matrix4_default()); const primitives = []; if (hasLines) { primitives.push(createLinesPrimitive(features, toLocal, frameState)); } if (hasPoints) { primitives.push(createPointsPrimitive(features, toLocal, frameState)); } const node = new ModelComponents_default.Node(); node.index = 0; node.primitives = primitives; const nodes = [node]; const scene = new ModelComponents_default.Scene(); scene.nodes = nodes; const components = new ModelComponents_default.Components(); components.scene = scene; components.nodes = nodes; components.transform = toGlobal; components.structuralMetadata = structuralMetadata; return components; } GeoJsonLoader.prototype.unload = function() { this._components = void 0; }; var GeoJsonLoader_default = GeoJsonLoader; // packages/engine/Source/Scene/I3dmParser.js var I3dmParser = {}; I3dmParser._deprecationWarning = deprecationWarning_default; var sizeOfUint325 = Uint32Array.BYTES_PER_ELEMENT; I3dmParser.parse = function(arrayBuffer, byteOffset) { Check_default.defined("arrayBuffer", arrayBuffer); const byteStart = defaultValue_default(byteOffset, 0); byteOffset = byteStart; const uint8Array = new Uint8Array(arrayBuffer); const view = new DataView(arrayBuffer); byteOffset += sizeOfUint325; const version2 = view.getUint32(byteOffset, true); if (version2 !== 1) { throw new RuntimeError_default( `Only Instanced 3D Model version 1 is supported. Version ${version2} is not.` ); } byteOffset += sizeOfUint325; const byteLength = view.getUint32(byteOffset, true); byteOffset += sizeOfUint325; const featureTableJsonByteLength = view.getUint32(byteOffset, true); if (featureTableJsonByteLength === 0) { throw new RuntimeError_default( "featureTableJsonByteLength is zero, the feature table must be defined." ); } byteOffset += sizeOfUint325; const featureTableBinaryByteLength = view.getUint32(byteOffset, true); byteOffset += sizeOfUint325; const batchTableJsonByteLength = view.getUint32(byteOffset, true); byteOffset += sizeOfUint325; const batchTableBinaryByteLength = view.getUint32(byteOffset, true); byteOffset += sizeOfUint325; const gltfFormat = view.getUint32(byteOffset, true); if (gltfFormat !== 1 && gltfFormat !== 0) { throw new RuntimeError_default( `Only glTF format 0 (uri) or 1 (embedded) are supported. Format ${gltfFormat} is not.` ); } byteOffset += sizeOfUint325; const featureTableJson = getJsonFromTypedArray_default( uint8Array, byteOffset, featureTableJsonByteLength ); byteOffset += featureTableJsonByteLength; const featureTableBinary = new Uint8Array( arrayBuffer, byteOffset, featureTableBinaryByteLength ); byteOffset += featureTableBinaryByteLength; let batchTableJson; let batchTableBinary; if (batchTableJsonByteLength > 0) { batchTableJson = getJsonFromTypedArray_default( uint8Array, byteOffset, batchTableJsonByteLength ); byteOffset += batchTableJsonByteLength; if (batchTableBinaryByteLength > 0) { batchTableBinary = new Uint8Array( arrayBuffer, byteOffset, batchTableBinaryByteLength ); batchTableBinary = new Uint8Array(batchTableBinary); byteOffset += batchTableBinaryByteLength; } } const gltfByteLength = byteStart + byteLength - byteOffset; if (gltfByteLength === 0) { throw new RuntimeError_default("glTF byte length must be greater than 0."); } let gltfView; if (byteOffset % 4 === 0) { gltfView = new Uint8Array(arrayBuffer, byteOffset, gltfByteLength); } else { I3dmParser._deprecationWarning( "i3dm-glb-unaligned", "The embedded glb is not aligned to a 4-byte boundary." ); gltfView = new Uint8Array( uint8Array.subarray(byteOffset, byteOffset + gltfByteLength) ); } return { gltfFormat, featureTableJson, featureTableBinary, batchTableJson, batchTableBinary, gltf: gltfView }; }; var I3dmParser_default = I3dmParser; // packages/engine/Source/Scene/Model/I3dmLoader.js var I3dmLoaderState = { NOT_LOADED: 0, LOADING: 1, PROCESSING: 2, POST_PROCESSING: 3, READY: 4, FAILED: 5, UNLOADED: 6 }; var Attribute3 = ModelComponents_default.Attribute; var FeatureIdAttribute4 = ModelComponents_default.FeatureIdAttribute; var Instances3 = ModelComponents_default.Instances; function I3dmLoader(options) { options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT); const i3dmResource = options.i3dmResource; const arrayBuffer = options.arrayBuffer; let baseResource2 = options.baseResource; const byteOffset = defaultValue_default(options.byteOffset, 0); const releaseGltfJson = defaultValue_default(options.releaseGltfJson, false); const asynchronous = defaultValue_default(options.asynchronous, true); const incrementallyLoadTextures = defaultValue_default( options.incrementallyLoadTextures, true ); const upAxis = defaultValue_default(options.upAxis, Axis_default.Y); const forwardAxis = defaultValue_default(options.forwardAxis, Axis_default.X); const loadAttributesAsTypedArray = defaultValue_default( options.loadAttributesAsTypedArray, false ); const loadIndicesForWireframe = defaultValue_default( options.loadIndicesForWireframe, false ); const loadPrimitiveOutline2 = defaultValue_default(options.loadPrimitiveOutline, true); Check_default.typeOf.object("options.i3dmResource", i3dmResource); Check_default.typeOf.object("options.arrayBuffer", arrayBuffer); baseResource2 = defined_default(baseResource2) ? baseResource2 : i3dmResource.clone(); this._i3dmResource = i3dmResource; this._baseResource = baseResource2; 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._loadIndicesForWireframe = loadIndicesForWireframe; this._loadPrimitiveOutline = loadPrimitiveOutline2; this._state = I3dmLoaderState.NOT_LOADED; this._promise = void 0; this._gltfLoader = void 0; this._buffers = []; this._components = void 0; this._transform = Matrix4_default.IDENTITY; this._batchTable = void 0; this._featureTable = void 0; this._instancesLength = 0; } if (defined_default(Object.create)) { I3dmLoader.prototype = Object.create(ResourceLoader_default.prototype); I3dmLoader.prototype.constructor = I3dmLoader; } Object.defineProperties(I3dmLoader.prototype, { /** * true if textures are loaded, useful when incrementallyLoadTextures is true * * @memberof I3dmLoader.prototype * * @type {boolean} * @readonly * @private */ texturesLoaded: { get: function() { return this._gltfLoader?.texturesLoaded; } }, /** * The cache key of the resource * * @memberof I3dmLoader.prototype * * @type {string} * @readonly * @private */ cacheKey: { get: function() { return void 0; } }, /** * The loaded components. * * @memberof I3dmLoader.prototype * * @type {ModelComponents.Components} * @default {@link Matrix4.IDENTITY} * @readonly * @private */ components: { get: function() { return this._components; } } }); I3dmLoader.prototype.load = function() { if (defined_default(this._promise)) { return this._promise; } const i3dm = I3dmParser_default.parse(this._arrayBuffer, this._byteOffset); const featureTableJson = i3dm.featureTableJson; const featureTableBinary = i3dm.featureTableBinary; const batchTableJson = i3dm.batchTableJson; const batchTableBinary = i3dm.batchTableBinary; const gltfFormat = i3dm.gltfFormat; const featureTable = new Cesium3DTileFeatureTable_default( featureTableJson, featureTableBinary ); this._featureTable = featureTable; const instancesLength = featureTable.getGlobalProperty("INSTANCES_LENGTH"); featureTable.featuresLength = instancesLength; if (!defined_default(instancesLength)) { throw new RuntimeError_default( "Feature table global property: INSTANCES_LENGTH must be defined" ); } this._instancesLength = instancesLength; const rtcCenter = featureTable.getGlobalProperty( "RTC_CENTER", ComponentDatatype_default.FLOAT, 3 ); if (defined_default(rtcCenter)) { this._transform = Matrix4_default.fromTranslation(Cartesian3_default.fromArray(rtcCenter)); } this._batchTable = { json: batchTableJson, binary: batchTableBinary }; const loaderOptions = { upAxis: this._upAxis, forwardAxis: this._forwardAxis, releaseGltfJson: this._releaseGltfJson, incrementallyLoadTextures: this._incrementallyLoadTextures, loadAttributesAsTypedArray: this._loadAttributesAsTypedArray, loadIndicesForWireframe: this._loadIndicesForWireframe, loadPrimitiveOutline: this._loadPrimitiveOutline }; if (gltfFormat === 0) { let gltfUrl = getStringFromTypedArray_default(i3dm.gltf); gltfUrl = gltfUrl.replace(/[\s\0]+$/, ""); const gltfResource = this._baseResource.getDerivedResource({ url: gltfUrl }); loaderOptions.gltfResource = gltfResource; loaderOptions.baseResource = gltfResource; } else { loaderOptions.gltfResource = this._i3dmResource; loaderOptions.typedArray = i3dm.gltf; } const gltfLoader = new GltfLoader_default(loaderOptions); this._gltfLoader = gltfLoader; this._state = I3dmLoaderState.LOADING; this._promise = gltfLoader.load().then(() => { if (this.isDestroyed()) { return; } this._state = I3dmLoaderState.PROCESSING; return this; }).catch((error) => { if (this.isDestroyed()) { return; } throw handleError8(this, error); }); return this._promise; }; function handleError8(i3dmLoader, error) { i3dmLoader.unload(); i3dmLoader._state = I3dmLoaderState.FAILED; const errorMessage = "Failed to load i3dm"; return i3dmLoader.getError(errorMessage, error); } I3dmLoader.prototype.process = function(frameState) { Check_default.typeOf.object("frameState", frameState); if (this._state === I3dmLoaderState.READY) { return true; } const gltfLoader = this._gltfLoader; let ready = false; if (this._state === I3dmLoaderState.PROCESSING) { ready = gltfLoader.process(frameState); } if (!ready) { return false; } const components = gltfLoader.components; components.transform = Matrix4_default.multiplyTransformation( this._transform, components.transform, components.transform ); createInstances(this, components, frameState); createStructuralMetadata2(this, components); this._components = components; this._arrayBuffer = void 0; this._state = I3dmLoaderState.READY; return true; }; function createStructuralMetadata2(loader, components) { const batchTable = loader._batchTable; const instancesLength = loader._instancesLength; if (instancesLength === 0) { return; } let structuralMetadata; if (defined_default(batchTable.json)) { structuralMetadata = parseBatchTable_default({ count: instancesLength, batchTable: batchTable.json, binaryBody: batchTable.binary }); } else { const emptyPropertyTable = new PropertyTable_default({ name: MetadataClass_default.BATCH_TABLE_CLASS_NAME, count: instancesLength }); structuralMetadata = new StructuralMetadata_default({ schema: {}, propertyTables: [emptyPropertyTable] }); } components.structuralMetadata = structuralMetadata; } var positionScratch4 = new Cartesian3_default(); var propertyScratch1 = new Array(4); var transformScratch = new Matrix4_default(); function createInstances(loader, components, frameState) { let i; const featureTable = loader._featureTable; const instancesLength = loader._instancesLength; if (instancesLength === 0) { return; } const rtcCenter = featureTable.getGlobalProperty( "RTC_CENTER", ComponentDatatype_default.FLOAT, 3 ); const eastNorthUp = featureTable.getGlobalProperty("EAST_NORTH_UP"); const hasRotation = featureTable.hasProperty("NORMAL_UP") || featureTable.hasProperty("NORMAL_UP_OCT32P") || eastNorthUp; const hasScale = featureTable.hasProperty("SCALE") || featureTable.hasProperty("SCALE_NON_UNIFORM"); const translationTypedArray = getPositions(featureTable, instancesLength); let rotationTypedArray; if (hasRotation) { rotationTypedArray = new Float32Array(4 * instancesLength); } let scaleTypedArray; if (hasScale) { scaleTypedArray = new Float32Array(3 * instancesLength); } const featureIdArray = new Float32Array(instancesLength); const instancePositions = Cartesian3_default.unpackArray(translationTypedArray); let instancePosition = new Cartesian3_default(); const instanceNormalRight = new Cartesian3_default(); const instanceNormalUp = new Cartesian3_default(); const instanceNormalForward = new Cartesian3_default(); const instanceRotation = new Matrix3_default(); const instanceQuaternion = new Quaternion_default(); const instanceQuaternionArray = new Array(4); const instanceScale = new Cartesian3_default(); const instanceScaleArray = new Array(3); const instanceTransform = new Matrix4_default(); if (!defined_default(rtcCenter)) { const positionBoundingSphere = BoundingSphere_default.fromPoints(instancePositions); for (i = 0; i < instancePositions.length; i++) { Cartesian3_default.subtract( instancePositions[i], positionBoundingSphere.center, positionScratch4 ); translationTypedArray[3 * i + 0] = positionScratch4.x; translationTypedArray[3 * i + 1] = positionScratch4.y; translationTypedArray[3 * i + 2] = positionScratch4.z; } const centerTransform = Matrix4_default.fromTranslation( positionBoundingSphere.center, transformScratch ); components.transform = Matrix4_default.multiplyTransformation( centerTransform, components.transform, components.transform ); } for (i = 0; i < instancesLength; i++) { instancePosition = Cartesian3_default.clone(instancePositions[i]); if (defined_default(rtcCenter)) { Cartesian3_default.add( instancePosition, Cartesian3_default.unpack(rtcCenter), instancePosition ); } if (hasRotation) { processRotation( featureTable, eastNorthUp, i, instanceQuaternion, instancePosition, instanceNormalUp, instanceNormalRight, instanceNormalForward, instanceRotation, instanceTransform ); Quaternion_default.pack(instanceQuaternion, instanceQuaternionArray, 0); rotationTypedArray[4 * i + 0] = instanceQuaternionArray[0]; rotationTypedArray[4 * i + 1] = instanceQuaternionArray[1]; rotationTypedArray[4 * i + 2] = instanceQuaternionArray[2]; rotationTypedArray[4 * i + 3] = instanceQuaternionArray[3]; } if (hasScale) { processScale(featureTable, i, instanceScale); Cartesian3_default.pack(instanceScale, instanceScaleArray, 0); scaleTypedArray[3 * i + 0] = instanceScaleArray[0]; scaleTypedArray[3 * i + 1] = instanceScaleArray[1]; scaleTypedArray[3 * i + 2] = instanceScaleArray[2]; } let batchId = featureTable.getProperty( "BATCH_ID", ComponentDatatype_default.UNSIGNED_SHORT, 1, i ); if (!defined_default(batchId)) { batchId = i; } featureIdArray[i] = batchId; } const instances = new Instances3(); instances.transformInWorldSpace = true; const buffers = loader._buffers; const translationAttribute = new Attribute3(); translationAttribute.name = "Instance Translation"; translationAttribute.semantic = InstanceAttributeSemantic_default.TRANSLATION; translationAttribute.componentDatatype = ComponentDatatype_default.FLOAT; translationAttribute.type = AttributeType_default.VEC3; translationAttribute.count = instancesLength; translationAttribute.typedArray = translationTypedArray; if (!hasRotation) { const buffer2 = Buffer_default.createVertexBuffer({ context: frameState.context, typedArray: translationTypedArray, usage: BufferUsage_default.STATIC_DRAW }); buffer2.vertexArrayDestroyable = false; buffers.push(buffer2); translationAttribute.buffer = buffer2; } instances.attributes.push(translationAttribute); if (hasRotation) { const rotationAttribute = new Attribute3(); rotationAttribute.name = "Instance Rotation"; rotationAttribute.semantic = InstanceAttributeSemantic_default.ROTATION; rotationAttribute.componentDatatype = ComponentDatatype_default.FLOAT; rotationAttribute.type = AttributeType_default.VEC4; rotationAttribute.count = instancesLength; rotationAttribute.typedArray = rotationTypedArray; instances.attributes.push(rotationAttribute); } if (hasScale) { const scaleAttribute = new Attribute3(); scaleAttribute.name = "Instance Scale"; scaleAttribute.semantic = InstanceAttributeSemantic_default.SCALE; scaleAttribute.componentDatatype = ComponentDatatype_default.FLOAT; scaleAttribute.type = AttributeType_default.VEC3; scaleAttribute.count = instancesLength; if (hasRotation) { scaleAttribute.typedArray = scaleTypedArray; } else { const buffer2 = Buffer_default.createVertexBuffer({ context: frameState.context, typedArray: scaleTypedArray, usage: BufferUsage_default.STATIC_DRAW }); buffer2.vertexArrayDestroyable = false; buffers.push(buffer2); scaleAttribute.buffer = buffer2; } instances.attributes.push(scaleAttribute); } const featureIdAttribute = new Attribute3(); featureIdAttribute.name = "Instance Feature ID"; featureIdAttribute.setIndex = 0; featureIdAttribute.semantic = InstanceAttributeSemantic_default.FEATURE_ID; featureIdAttribute.componentDatatype = ComponentDatatype_default.FLOAT; featureIdAttribute.type = AttributeType_default.SCALAR; featureIdAttribute.count = instancesLength; const buffer = Buffer_default.createVertexBuffer({ context: frameState.context, typedArray: featureIdArray, usage: BufferUsage_default.STATIC_DRAW }); buffer.vertexArrayDestroyable = false; buffers.push(buffer); featureIdAttribute.buffer = buffer; instances.attributes.push(featureIdAttribute); const featureIdInstanceAttribute = new FeatureIdAttribute4(); featureIdInstanceAttribute.propertyTableId = 0; featureIdInstanceAttribute.setIndex = 0; featureIdInstanceAttribute.positionalLabel = "instanceFeatureId_0"; instances.featureIds.push(featureIdInstanceAttribute); const nodes = components.nodes; const nodesLength = nodes.length; let makeInstancesCopy = false; for (i = 0; i < nodesLength; i++) { const node = nodes[i]; if (node.primitives.length > 0) { node.instances = makeInstancesCopy ? createInstancesCopy(instances) : instances; makeInstancesCopy = true; } } } function createInstancesCopy(instances) { const instancesCopy = new Instances3(); instancesCopy.transformInWorldSpace = instances.transformInWorldSpace; const attributes = instances.attributes; const attributesLength = attributes.length; for (let i = 0; i < attributesLength; i++) { const attributeCopy = clone_default(attributes[i], false); instancesCopy.attributes.push(attributeCopy); } instancesCopy.featureIds = instances.featureIds; return instancesCopy; } function getPositions(featureTable, instancesLength) { if (featureTable.hasProperty("POSITION")) { return featureTable.getPropertyArray( "POSITION", ComponentDatatype_default.FLOAT, 3 ); } else if (featureTable.hasProperty("POSITION_QUANTIZED")) { const quantizedPositions = featureTable.getPropertyArray( "POSITION_QUANTIZED", ComponentDatatype_default.UNSIGNED_SHORT, 3 ); const quantizedVolumeOffset = featureTable.getGlobalProperty( "QUANTIZED_VOLUME_OFFSET", ComponentDatatype_default.FLOAT, 3 ); if (!defined_default(quantizedVolumeOffset)) { throw new RuntimeError_default( "Global property: QUANTIZED_VOLUME_OFFSET must be defined for quantized positions." ); } const quantizedVolumeScale = featureTable.getGlobalProperty( "QUANTIZED_VOLUME_SCALE", ComponentDatatype_default.FLOAT, 3 ); if (!defined_default(quantizedVolumeScale)) { throw new RuntimeError_default( "Global property: QUANTIZED_VOLUME_SCALE must be defined for quantized positions." ); } const decodedPositions = new Float32Array(quantizedPositions.length); for (let i = 0; i < quantizedPositions.length / 3; i++) { for (let j = 0; j < 3; j++) { const index = 3 * i + j; decodedPositions[index] = quantizedPositions[index] / 65535 * quantizedVolumeScale[j] + quantizedVolumeOffset[j]; } } return decodedPositions; } else { throw new RuntimeError_default( "Either POSITION or POSITION_QUANTIZED must be defined for each instance." ); } } var propertyScratch2 = new Array(4); function processRotation(featureTable, eastNorthUp, i, instanceQuaternion, instancePosition, instanceNormalUp, instanceNormalRight, instanceNormalForward, instanceRotation, instanceTransform) { const normalUp = featureTable.getProperty( "NORMAL_UP", ComponentDatatype_default.FLOAT, 3, i, propertyScratch1 ); const normalRight = featureTable.getProperty( "NORMAL_RIGHT", ComponentDatatype_default.FLOAT, 3, i, propertyScratch2 ); let hasCustomOrientation = false; if (defined_default(normalUp)) { if (!defined_default(normalRight)) { throw new RuntimeError_default( "To define a custom orientation, both NORMAL_UP and NORMAL_RIGHT must be defined." ); } Cartesian3_default.unpack(normalUp, 0, instanceNormalUp); Cartesian3_default.unpack(normalRight, 0, instanceNormalRight); hasCustomOrientation = true; } else { const octNormalUp = featureTable.getProperty( "NORMAL_UP_OCT32P", ComponentDatatype_default.UNSIGNED_SHORT, 2, i, propertyScratch1 ); const octNormalRight = featureTable.getProperty( "NORMAL_RIGHT_OCT32P", ComponentDatatype_default.UNSIGNED_SHORT, 2, i, propertyScratch2 ); if (defined_default(octNormalUp)) { if (!defined_default(octNormalRight)) { throw new RuntimeError_default( "To define a custom orientation with oct-encoded vectors, both NORMAL_UP_OCT32P and NORMAL_RIGHT_OCT32P must be defined." ); } AttributeCompression_default.octDecodeInRange( octNormalUp[0], octNormalUp[1], 65535, instanceNormalUp ); AttributeCompression_default.octDecodeInRange( octNormalRight[0], octNormalRight[1], 65535, instanceNormalRight ); hasCustomOrientation = true; } else if (eastNorthUp) { Transforms_default.eastNorthUpToFixedFrame( instancePosition, Ellipsoid_default.WGS84, instanceTransform ); Matrix4_default.getMatrix3(instanceTransform, instanceRotation); } else { Matrix3_default.clone(Matrix3_default.IDENTITY, instanceRotation); } } if (hasCustomOrientation) { Cartesian3_default.cross( instanceNormalRight, instanceNormalUp, instanceNormalForward ); Cartesian3_default.normalize(instanceNormalForward, instanceNormalForward); Matrix3_default.setColumn( instanceRotation, 0, instanceNormalRight, instanceRotation ); Matrix3_default.setColumn(instanceRotation, 1, instanceNormalUp, instanceRotation); Matrix3_default.setColumn( instanceRotation, 2, instanceNormalForward, instanceRotation ); } Quaternion_default.fromRotationMatrix(instanceRotation, instanceQuaternion); } function processScale(featureTable, i, instanceScale) { instanceScale = Cartesian3_default.fromElements(1, 1, 1, instanceScale); const scale = featureTable.getProperty( "SCALE", ComponentDatatype_default.FLOAT, 1, i ); if (defined_default(scale)) { Cartesian3_default.multiplyByScalar(instanceScale, scale, instanceScale); } const nonUniformScale = featureTable.getProperty( "SCALE_NON_UNIFORM", ComponentDatatype_default.FLOAT, 3, i, propertyScratch1 ); if (defined_default(nonUniformScale)) { instanceScale.x *= nonUniformScale[0]; instanceScale.y *= nonUniformScale[1]; instanceScale.z *= nonUniformScale[2]; } } function unloadBuffers(loader) { const buffers = loader._buffers; const length3 = buffers.length; for (let i = 0; i < length3; i++) { const buffer = buffers[i]; if (!buffer.isDestroyed()) { buffer.destroy(); } } buffers.length = 0; } I3dmLoader.prototype.isUnloaded = function() { return this._state === I3dmLoaderState.UNLOADED; }; I3dmLoader.prototype.unload = function() { if (defined_default(this._gltfLoader) && !this._gltfLoader.isDestroyed()) { this._gltfLoader.unload(); } unloadBuffers(this); this._components = void 0; this._arrayBuffer = void 0; this._state = I3dmLoaderState.UNLOADED; }; var I3dmLoader_default = I3dmLoader; // packages/engine/Source/Scene/ModelAnimationState.js var ModelAnimationState = { STOPPED: 0, ANIMATING: 1 }; var ModelAnimationState_default = Object.freeze(ModelAnimationState); // packages/engine/Source/Core/Spline.js function Spline() { this.times = void 0; this.points = void 0; DeveloperError_default.throwInstantiationError(); } Spline.getPointType = function(point) { if (typeof point === "number") { return Number; } if (point instanceof Cartesian3_default) { return Cartesian3_default; } if (point instanceof Quaternion_default) { return Quaternion_default; } throw new DeveloperError_default( "point must be a Cartesian3, Quaternion, or number." ); }; Spline.prototype.evaluate = DeveloperError_default.throwInstantiationError; Spline.prototype.findTimeInterval = function(time, startIndex) { const times = this.times; const length3 = times.length; Check_default.typeOf.number("time", time); if (time < times[0] || time > times[length3 - 1]) { throw new DeveloperError_default("time is out of range."); } startIndex = defaultValue_default(startIndex, 0); if (time >= times[startIndex]) { if (startIndex + 1 < length3 && time < times[startIndex + 1]) { return startIndex; } else if (startIndex + 2 < length3 && time < times[startIndex + 2]) { return startIndex + 1; } } else if (startIndex - 1 >= 0 && time >= times[startIndex - 1]) { return startIndex - 1; } let i; if (time > times[startIndex]) { for (i = startIndex; i < length3 - 1; ++i) { if (time >= times[i] && time < times[i + 1]) { break; } } } else { for (i = startIndex - 1; i >= 0; --i) { if (time >= times[i] && time < times[i + 1]) { break; } } } if (i === length3 - 1) { i = length3 - 2; } return i; }; Spline.prototype.wrapTime = function(time) { Check_default.typeOf.number("time", time); const times = this.times; const timeEnd = times[times.length - 1]; const timeStart = times[0]; const timeStretch = timeEnd - timeStart; let divs; if (time < timeStart) { divs = Math.floor((timeStart - time) / timeStretch) + 1; time += divs * timeStretch; } if (time > timeEnd) { divs = Math.floor((time - timeEnd) / timeStretch) + 1; time -= divs * timeStretch; } return time; }; Spline.prototype.clampTime = function(time) { Check_default.typeOf.number("time", time); const times = this.times; return Math_default.clamp(time, times[0], times[times.length - 1]); }; var Spline_default = Spline; // packages/engine/Source/Core/ConstantSpline.js function ConstantSpline(value) { this._value = value; this._valueType = Spline_default.getPointType(value); } Object.defineProperties(ConstantSpline.prototype, { /** * The constant value that the spline evaluates to. * * @memberof ConstantSpline.prototype * * @type {number|Cartesian3|Quaternion} * @readonly */ value: { get: function() { return this._value; } } }); ConstantSpline.prototype.findTimeInterval = function(time) { throw new DeveloperError_default( "findTimeInterval cannot be called on a ConstantSpline." ); }; ConstantSpline.prototype.wrapTime = function(time) { Check_default.typeOf.number("time", time); return 0; }; ConstantSpline.prototype.clampTime = function(time) { Check_default.typeOf.number("time", time); return 0; }; ConstantSpline.prototype.evaluate = function(time, result) { Check_default.typeOf.number("time", time); const value = this._value; const ValueType = this._valueType; if (ValueType === Number) { return value; } return ValueType.clone(value, result); }; var ConstantSpline_default = ConstantSpline; // packages/engine/Source/Core/LinearSpline.js function LinearSpline(options) { options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT); const points = options.points; const times = options.times; if (!defined_default(points) || !defined_default(times)) { throw new DeveloperError_default("points and times are required."); } if (points.length < 2) { throw new DeveloperError_default( "points.length must be greater than or equal to 2." ); } if (times.length !== points.length) { throw new DeveloperError_default("times.length must be equal to points.length."); } this._times = times; this._points = points; this._pointType = Spline_default.getPointType(points[0]); this._lastTimeIndex = 0; } Object.defineProperties(LinearSpline.prototype, { /** * An array of times for the control points. * * @memberof LinearSpline.prototype * * @type {number[]} * @readonly */ times: { get: function() { return this._times; } }, /** * An array of {@link Cartesian3} control points. * * @memberof LinearSpline.prototype * * @type {number[]|Cartesian3[]} * @readonly */ points: { get: function() { return this._points; } } }); LinearSpline.prototype.findTimeInterval = Spline_default.prototype.findTimeInterval; LinearSpline.prototype.wrapTime = Spline_default.prototype.wrapTime; LinearSpline.prototype.clampTime = Spline_default.prototype.clampTime; LinearSpline.prototype.evaluate = function(time, result) { const points = this.points; const times = this.times; const i = this._lastTimeIndex = this.findTimeInterval( time, this._lastTimeIndex ); const u3 = (time - times[i]) / (times[i + 1] - times[i]); const PointType = this._pointType; if (PointType === Number) { return (1 - u3) * points[i] + u3 * points[i + 1]; } if (!defined_default(result)) { result = new Cartesian3_default(); } return Cartesian3_default.lerp(points[i], points[i + 1], u3, result); }; var LinearSpline_default = LinearSpline; // packages/engine/Source/Core/TridiagonalSystemSolver.js var TridiagonalSystemSolver = {}; TridiagonalSystemSolver.solve = function(lower, diagonal, upper, right) { if (!defined_default(lower) || !(lower instanceof Array)) { throw new DeveloperError_default("The array lower is required."); } if (!defined_default(diagonal) || !(diagonal instanceof Array)) { throw new DeveloperError_default("The array diagonal is required."); } if (!defined_default(upper) || !(upper instanceof Array)) { throw new DeveloperError_default("The array upper is required."); } if (!defined_default(right) || !(right instanceof Array)) { throw new DeveloperError_default("The array right is required."); } if (diagonal.length !== right.length) { throw new DeveloperError_default("diagonal and right must have the same lengths."); } if (lower.length !== upper.length) { throw new DeveloperError_default("lower and upper must have the same lengths."); } else if (lower.length !== diagonal.length - 1) { throw new DeveloperError_default( "lower and upper must be one less than the length of diagonal." ); } const c = new Array(upper.length); const d = new Array(right.length); const x = new Array(right.length); let i; for (i = 0; i < d.length; i++) { d[i] = new Cartesian3_default(); x[i] = new Cartesian3_default(); } c[0] = upper[0] / diagonal[0]; d[0] = Cartesian3_default.multiplyByScalar(right[0], 1 / diagonal[0], d[0]); let scalar; for (i = 1; i < c.length; ++i) { scalar = 1 / (diagonal[i] - c[i - 1] * lower[i - 1]); c[i] = upper[i] * scalar; d[i] = Cartesian3_default.subtract( right[i], Cartesian3_default.multiplyByScalar(d[i - 1], lower[i - 1], d[i]), d[i] ); d[i] = Cartesian3_default.multiplyByScalar(d[i], scalar, d[i]); } scalar = 1 / (diagonal[i] - c[i - 1] * lower[i - 1]); d[i] = Cartesian3_default.subtract( right[i], Cartesian3_default.multiplyByScalar(d[i - 1], lower[i - 1], d[i]), d[i] ); d[i] = Cartesian3_default.multiplyByScalar(d[i], scalar, d[i]); x[x.length - 1] = d[d.length - 1]; for (i = x.length - 2; i >= 0; --i) { x[i] = Cartesian3_default.subtract( d[i], Cartesian3_default.multiplyByScalar(x[i + 1], c[i], x[i]), x[i] ); } return x; }; var TridiagonalSystemSolver_default = TridiagonalSystemSolver; // packages/engine/Source/Core/HermiteSpline.js var scratchLower = []; var scratchDiagonal = []; var scratchUpper = []; var scratchRight = []; function generateClamped(points, firstTangent, lastTangent) { const l = scratchLower; const u3 = scratchUpper; const d = scratchDiagonal; const r = scratchRight; l.length = u3.length = points.length - 1; d.length = r.length = points.length; let i; l[0] = d[0] = 1; u3[0] = 0; let right = r[0]; if (!defined_default(right)) { right = r[0] = new Cartesian3_default(); } Cartesian3_default.clone(firstTangent, right); for (i = 1; i < l.length - 1; ++i) { l[i] = u3[i] = 1; d[i] = 4; right = r[i]; if (!defined_default(right)) { right = r[i] = new Cartesian3_default(); } Cartesian3_default.subtract(points[i + 1], points[i - 1], right); Cartesian3_default.multiplyByScalar(right, 3, right); } l[i] = 0; u3[i] = 1; d[i] = 4; right = r[i]; if (!defined_default(right)) { right = r[i] = new Cartesian3_default(); } Cartesian3_default.subtract(points[i + 1], points[i - 1], right); Cartesian3_default.multiplyByScalar(right, 3, right); d[i + 1] = 1; right = r[i + 1]; if (!defined_default(right)) { right = r[i + 1] = new Cartesian3_default(); } Cartesian3_default.clone(lastTangent, right); return TridiagonalSystemSolver_default.solve(l, d, u3, r); } function generateNatural(points) { const l = scratchLower; const u3 = scratchUpper; const d = scratchDiagonal; const r = scratchRight; l.length = u3.length = points.length - 1; d.length = r.length = points.length; let i; l[0] = u3[0] = 1; d[0] = 2; let right = r[0]; if (!defined_default(right)) { right = r[0] = new Cartesian3_default(); } Cartesian3_default.subtract(points[1], points[0], right); Cartesian3_default.multiplyByScalar(right, 3, right); for (i = 1; i < l.length; ++i) { l[i] = u3[i] = 1; d[i] = 4; right = r[i]; if (!defined_default(right)) { right = r[i] = new Cartesian3_default(); } Cartesian3_default.subtract(points[i + 1], points[i - 1], right); Cartesian3_default.multiplyByScalar(right, 3, right); } d[i] = 2; right = r[i]; if (!defined_default(right)) { right = r[i] = new Cartesian3_default(); } Cartesian3_default.subtract(points[i], points[i - 1], right); Cartesian3_default.multiplyByScalar(right, 3, right); return TridiagonalSystemSolver_default.solve(l, d, u3, r); } function HermiteSpline(options) { options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT); const points = options.points; const times = options.times; const inTangents = options.inTangents; const outTangents = options.outTangents; if (!defined_default(points) || !defined_default(times) || !defined_default(inTangents) || !defined_default(outTangents)) { throw new DeveloperError_default( "times, points, inTangents, and outTangents are required." ); } if (points.length < 2) { throw new DeveloperError_default( "points.length must be greater than or equal to 2." ); } if (times.length !== points.length) { throw new DeveloperError_default("times.length must be equal to points.length."); } if (inTangents.length !== outTangents.length || inTangents.length !== points.length - 1) { throw new DeveloperError_default( "inTangents and outTangents must have a length equal to points.length - 1." ); } this._times = times; this._points = points; this._pointType = Spline_default.getPointType(points[0]); if (this._pointType !== Spline_default.getPointType(inTangents[0]) || this._pointType !== Spline_default.getPointType(outTangents[0])) { throw new DeveloperError_default( "inTangents and outTangents must be of the same type as points." ); } this._inTangents = inTangents; this._outTangents = outTangents; this._lastTimeIndex = 0; } Object.defineProperties(HermiteSpline.prototype, { /** * An array of times for the control points. * * @memberof HermiteSpline.prototype * * @type {number[]} * @readonly */ times: { get: function() { return this._times; } }, /** * An array of control points. * * @memberof HermiteSpline.prototype * * @type {Cartesian3[]} * @readonly */ points: { get: function() { return this._points; } }, /** * An array of incoming tangents at each control point. * * @memberof HermiteSpline.prototype * * @type {Cartesian3[]} * @readonly */ inTangents: { get: function() { return this._inTangents; } }, /** * An array of outgoing tangents at each control point. * * @memberof HermiteSpline.prototype * * @type {Cartesian3[]} * @readonly */ outTangents: { get: function() { return this._outTangents; } } }); HermiteSpline.createC1 = function(options) { options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT); const times = options.times; const points = options.points; const tangents = options.tangents; if (!defined_default(points) || !defined_default(times) || !defined_default(tangents)) { throw new DeveloperError_default("points, times and tangents are required."); } if (points.length < 2) { throw new DeveloperError_default( "points.length must be greater than or equal to 2." ); } if (times.length !== points.length || times.length !== tangents.length) { throw new DeveloperError_default( "times, points and tangents must have the same length." ); } const outTangents = tangents.slice(0, tangents.length - 1); const inTangents = tangents.slice(1, tangents.length); return new HermiteSpline({ times, points, inTangents, outTangents }); }; HermiteSpline.createNaturalCubic = function(options) { options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT); const times = options.times; const points = options.points; if (!defined_default(points) || !defined_default(times)) { throw new DeveloperError_default("points and times are required."); } if (points.length < 2) { throw new DeveloperError_default( "points.length must be greater than or equal to 2." ); } if (times.length !== points.length) { throw new DeveloperError_default("times.length must be equal to points.length."); } if (points.length < 3) { return new LinearSpline_default({ points, times }); } const tangents = generateNatural(points); const outTangents = tangents.slice(0, tangents.length - 1); const inTangents = tangents.slice(1, tangents.length); return new HermiteSpline({ times, points, inTangents, outTangents }); }; HermiteSpline.createClampedCubic = function(options) { options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT); const times = options.times; const points = options.points; const firstTangent = options.firstTangent; const lastTangent = options.lastTangent; if (!defined_default(points) || !defined_default(times) || !defined_default(firstTangent) || !defined_default(lastTangent)) { throw new DeveloperError_default( "points, times, firstTangent and lastTangent are required." ); } if (points.length < 2) { throw new DeveloperError_default( "points.length must be greater than or equal to 2." ); } if (times.length !== points.length) { throw new DeveloperError_default("times.length must be equal to points.length."); } const PointType = Spline_default.getPointType(points[0]); if (PointType !== Spline_default.getPointType(firstTangent) || PointType !== Spline_default.getPointType(lastTangent)) { throw new DeveloperError_default( "firstTangent and lastTangent must be of the same type as points." ); } if (points.length < 3) { return new LinearSpline_default({ points, times }); } const tangents = generateClamped(points, firstTangent, lastTangent); const outTangents = tangents.slice(0, tangents.length - 1); const inTangents = tangents.slice(1, tangents.length); return new HermiteSpline({ times, points, inTangents, outTangents }); }; HermiteSpline.hermiteCoefficientMatrix = new Matrix4_default( 2, -3, 0, 1, -2, 3, 0, 0, 1, -2, 1, 0, 1, -1, 0, 0 ); HermiteSpline.prototype.findTimeInterval = Spline_default.prototype.findTimeInterval; var scratchTimeVec = new Cartesian4_default(); var scratchTemp = new Cartesian3_default(); HermiteSpline.prototype.wrapTime = Spline_default.prototype.wrapTime; HermiteSpline.prototype.clampTime = Spline_default.prototype.clampTime; HermiteSpline.prototype.evaluate = function(time, result) { const points = this.points; const times = this.times; const inTangents = this.inTangents; const outTangents = this.outTangents; this._lastTimeIndex = this.findTimeInterval(time, this._lastTimeIndex); const i = this._lastTimeIndex; const timesDelta = times[i + 1] - times[i]; const u3 = (time - times[i]) / timesDelta; const timeVec = scratchTimeVec; timeVec.z = u3; timeVec.y = u3 * u3; timeVec.x = timeVec.y * u3; timeVec.w = 1; const coefs = Matrix4_default.multiplyByVector( HermiteSpline.hermiteCoefficientMatrix, timeVec, timeVec ); coefs.z *= timesDelta; coefs.w *= timesDelta; const PointType = this._pointType; if (PointType === Number) { return points[i] * coefs.x + points[i + 1] * coefs.y + outTangents[i] * coefs.z + inTangents[i] * coefs.w; } if (!defined_default(result)) { result = new PointType(); } result = PointType.multiplyByScalar(points[i], coefs.x, result); PointType.multiplyByScalar(points[i + 1], coefs.y, scratchTemp); PointType.add(result, scratchTemp, result); PointType.multiplyByScalar(outTangents[i], coefs.z, scratchTemp); PointType.add(result, scratchTemp, result); PointType.multiplyByScalar(inTangents[i], coefs.w, scratchTemp); return PointType.add(result, scratchTemp, result); }; var HermiteSpline_default = HermiteSpline; // packages/engine/Source/Core/SteppedSpline.js function SteppedSpline(options) { options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT); const points = options.points; const times = options.times; if (!defined_default(points) || !defined_default(times)) { throw new DeveloperError_default("points and times are required."); } if (points.length < 2) { throw new DeveloperError_default( "points.length must be greater than or equal to 2." ); } if (times.length !== points.length) { throw new DeveloperError_default("times.length must be equal to points.length."); } this._times = times; this._points = points; this._pointType = Spline_default.getPointType(points[0]); this._lastTimeIndex = 0; } Object.defineProperties(SteppedSpline.prototype, { /** * An array of times for the control points. * * @memberof SteppedSpline.prototype * * @type {number[]} * @readonly */ times: { get: function() { return this._times; } }, /** * An array of control points. * * @memberof SteppedSpline.prototype * * @type {number[]|Cartesian3[]|Quaternion[]} * @readonly */ points: { get: function() { return this._points; } } }); SteppedSpline.prototype.findTimeInterval = Spline_default.prototype.findTimeInterval; SteppedSpline.prototype.wrapTime = Spline_default.prototype.wrapTime; SteppedSpline.prototype.clampTime = Spline_default.prototype.clampTime; SteppedSpline.prototype.evaluate = function(time, result) { const points = this.points; this._lastTimeIndex = this.findTimeInterval(time, this._lastTimeIndex); const i = this._lastTimeIndex; const PointType = this._pointType; if (PointType === Number) { return points[i]; } if (!defined_default(result)) { result = new PointType(); } return PointType.clone(points[i], result); }; var SteppedSpline_default = SteppedSpline; // packages/engine/Source/Core/QuaternionSpline.js function createEvaluateFunction(spline) { const points = spline.points; const times = spline.times; return function(time, result) { if (!defined_default(result)) { result = new Quaternion_default(); } const i = spline._lastTimeIndex = spline.findTimeInterval( time, spline._lastTimeIndex ); const u3 = (time - times[i]) / (times[i + 1] - times[i]); const q0 = points[i]; const q12 = points[i + 1]; return Quaternion_default.fastSlerp(q0, q12, u3, result); }; } function QuaternionSpline(options) { options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT); const points = options.points; const times = options.times; if (!defined_default(points) || !defined_default(times)) { throw new DeveloperError_default("points and times are required."); } if (points.length < 2) { throw new DeveloperError_default( "points.length must be greater than or equal to 2." ); } if (times.length !== points.length) { throw new DeveloperError_default("times.length must be equal to points.length."); } this._times = times; this._points = points; this._evaluateFunction = createEvaluateFunction(this); this._lastTimeIndex = 0; } Object.defineProperties(QuaternionSpline.prototype, { /** * An array of times for the control points. * * @memberof QuaternionSpline.prototype * * @type {number[]} * @readonly */ times: { get: function() { return this._times; } }, /** * An array of {@link Quaternion} control points. * * @memberof QuaternionSpline.prototype * * @type {Quaternion[]} * @readonly */ points: { get: function() { return this._points; } } }); QuaternionSpline.prototype.findTimeInterval = Spline_default.prototype.findTimeInterval; QuaternionSpline.prototype.wrapTime = Spline_default.prototype.wrapTime; QuaternionSpline.prototype.clampTime = Spline_default.prototype.clampTime; QuaternionSpline.prototype.evaluate = function(time, result) { return this._evaluateFunction(time, result); }; var QuaternionSpline_default = QuaternionSpline; // packages/engine/Source/Scene/Model/ModelAnimationChannel.js var AnimatedPropertyType3 = ModelComponents_default.AnimatedPropertyType; function ModelAnimationChannel(options) { options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT); const channel = options.channel; const runtimeAnimation = options.runtimeAnimation; const runtimeNode = options.runtimeNode; Check_default.typeOf.object("options.channel", channel); Check_default.typeOf.object("options.runtimeAnimation", runtimeAnimation); Check_default.typeOf.object("options.runtimeNode", runtimeNode); this._channel = channel; this._runtimeAnimation = runtimeAnimation; this._runtimeNode = runtimeNode; this._splines = []; this._path = void 0; initialize6(this); } Object.defineProperties(ModelAnimationChannel.prototype, { /** * The glTF animation channel. * * @memberof ModelAnimationChannel.prototype * * @type {ModelComponents.AnimationChannel} * @readonly * * @private */ channel: { get: function() { return this._channel; } }, /** * The runtime animation that owns this channel. * * @memberof ModelAnimationChannel.prototype * * @type {ModelAnimation} * @readonly * * @private */ runtimeAnimation: { get: function() { return this._runtimeAnimation; } }, /** * The runtime node that this channel animates. * * @memberof ModelAnimationChannel.prototype * * @type {ModelRuntimeNode} * @readonly * * @private */ runtimeNode: { get: function() { return this._runtimeNode; } }, /** * The splines used to evaluate this animation channel. * * @memberof ModelAnimationChannel.prototype * * @type {Spline[]} * @readonly * * @private */ splines: { get: function() { return this._splines; } } }); function createCubicSpline(times, points) { const cubicPoints = []; const inTangents = []; const outTangents = []; const length3 = points.length; for (let i = 0; i < length3; i += 3) { inTangents.push(points[i]); cubicPoints.push(points[i + 1]); outTangents.push(points[i + 2]); } inTangents.splice(0, 1); outTangents.length = outTangents.length - 1; return new HermiteSpline_default({ times, points: cubicPoints, inTangents, outTangents }); } function createSpline(times, points, interpolation, path) { if (times.length === 1 && points.length === 1) { return new ConstantSpline_default(points[0]); } switch (interpolation) { case InterpolationType_default.STEP: return new SteppedSpline_default({ times, points }); case InterpolationType_default.CUBICSPLINE: return createCubicSpline(times, points); case InterpolationType_default.LINEAR: if (path === AnimatedPropertyType3.ROTATION) { return new QuaternionSpline_default({ times, points }); } return new LinearSpline_default({ times, points }); } } function createSplines(times, points, interpolation, path, count) { const splines = []; if (path === AnimatedPropertyType3.WEIGHTS) { const pointsLength = points.length; const outputLength = pointsLength / count; let targetIndex, i; for (targetIndex = 0; targetIndex < count; targetIndex++) { const output = new Array(outputLength); let pointsIndex = targetIndex; if (interpolation === InterpolationType_default.CUBICSPLINE) { for (i = 0; i < outputLength; i += 3) { output[i] = points[pointsIndex]; output[i + 1] = points[pointsIndex + count]; output[i + 2] = points[pointsIndex + 2 * count]; pointsIndex += count * 3; } } else { for (i = 0; i < outputLength; i++) { output[i] = points[pointsIndex]; pointsIndex += count; } } splines.push(createSpline(times, output, interpolation, path)); } } else { splines.push(createSpline(times, points, interpolation, path)); } return splines; } var scratchVariable; function initialize6(runtimeChannel) { const channel = runtimeChannel._channel; const sampler = channel.sampler; const times = sampler.input; const points = sampler.output; const interpolation = sampler.interpolation; const target = channel.target; const path = target.path; const runtimeNode = runtimeChannel._runtimeNode; const count = defined_default(runtimeNode.morphWeights) ? runtimeNode.morphWeights.length : 1; const splines = createSplines(times, points, interpolation, path, count); runtimeChannel._splines = splines; runtimeChannel._path = path; switch (path) { case AnimatedPropertyType3.TRANSLATION: case AnimatedPropertyType3.SCALE: scratchVariable = new Cartesian3_default(); break; case AnimatedPropertyType3.ROTATION: scratchVariable = new Quaternion_default(); break; case AnimatedPropertyType3.WEIGHTS: break; } } ModelAnimationChannel.prototype.animate = function(time) { const splines = this._splines; const path = this._path; const model = this._runtimeAnimation.model; const runtimeNode = this._runtimeNode; if (path === AnimatedPropertyType3.WEIGHTS) { const morphWeights = runtimeNode.morphWeights; const length3 = morphWeights.length; for (let i = 0; i < length3; i++) { const spline = splines[i]; const localAnimationTime = model.clampAnimations ? spline.clampTime(time) : spline.wrapTime(time); morphWeights[i] = spline.evaluate(localAnimationTime); } } else if (runtimeNode.userAnimated) { return; } else { const spline = splines[0]; const localAnimationTime = model.clampAnimations ? spline.clampTime(time) : spline.wrapTime(time); runtimeNode[path] = spline.evaluate(localAnimationTime, scratchVariable); } }; var ModelAnimationChannel_default = ModelAnimationChannel; // packages/engine/Source/Scene/Model/ModelAnimation.js function ModelAnimation(model, animation, options) { this._animation = animation; this._name = animation.name; this._runtimeChannels = void 0; this._startTime = JulianDate_default.clone(options.startTime); this._delay = defaultValue_default(options.delay, 0); this._stopTime = JulianDate_default.clone(options.stopTime); this.removeOnStop = defaultValue_default(options.removeOnStop, false); this._multiplier = defaultValue_default(options.multiplier, 1); this._reverse = defaultValue_default(options.reverse, false); this._loop = defaultValue_default(options.loop, ModelAnimationLoop_default.NONE); this._animationTime = options.animationTime; this._prevAnimationDelta = void 0; this.start = new Event_default(); this.update = new Event_default(); this.stop = new Event_default(); this._state = ModelAnimationState_default.STOPPED; this._computedStartTime = void 0; this._duration = void 0; const that = this; this._raiseStartEvent = function() { that.start.raiseEvent(model, that); }; this._updateEventTime = 0; this._raiseUpdateEvent = function() { that.update.raiseEvent(model, that, that._updateEventTime); }; this._raiseStopEvent = function() { that.stop.raiseEvent(model, that); }; this._model = model; this._localStartTime = void 0; this._localStopTime = void 0; initialize7(this); } Object.defineProperties(ModelAnimation.prototype, { /** * The glTF animation. * * @memberof ModelAnimation.prototype * * @type {ModelComponents.Animation} * @readonly * * @private */ animation: { get: function() { return this._animation; } }, /** * The name that identifies this animation in the model, if it exists. * * @memberof ModelAnimation.prototype * * @type {string} * @readonly */ name: { get: function() { return this._name; } }, /** * The runtime animation channels for this animation. * * @memberof ModelAnimation.prototype * * @type {ModelAnimationChannel[]} * @readonly * * @private */ runtimeChannels: { get: function() { return this._runtimeChannels; } }, /** * The {@link Model} that owns this animation. * * @memberof ModelAnimation.prototype * * @type {Model} * @readonly * * @private */ model: { get: function() { return this._model; } }, /** * The starting point of the animation in local animation time. This is the minimum * time value across all of the keyframes belonging to this animation. * * @memberof ModelAnimation.prototype * * @type {number} * @readonly * * @private */ localStartTime: { get: function() { return this._localStartTime; } }, /** * The stopping point of the animation in local animation time. This is the maximum * time value across all of the keyframes belonging to this animation. * * @memberof ModelAnimation.prototype * * @type {number} * @readonly * * @private */ localStopTime: { get: function() { return this._localStopTime; } }, /** * The scene time to start playing this animation. When this isundefined
,
* the animation starts at the next frame.
*
* @memberof ModelAnimation.prototype
*
* @type {JulianDate}
* @readonly
*
* @default undefined
*/
startTime: {
get: function() {
return this._startTime;
}
},
/**
* The delay, in seconds, from {@link ModelAnimation#startTime} to start playing.
*
* @memberof ModelAnimation.prototype
*
* @type {number}
* @readonly
*
* @default undefined
*/
delay: {
get: function() {
return this._delay;
}
},
/**
* The scene time to stop playing this animation. When this is undefined
,
* the animation is played for its full duration and perhaps repeated depending on
* {@link ModelAnimation#loop}.
*
* @memberof ModelAnimation.prototype
*
* @type {JulianDate}
* @readonly
*
* @default undefined
*/
stopTime: {
get: function() {
return this._stopTime;
}
},
/**
* Values greater than 1.0
increase the speed that the animation is played relative
* to the scene clock speed; values less than 1.0
decrease the speed. A value of
* 1.0
plays the animation at the speed in the glTF animation mapped to the scene
* clock speed. For example, if the scene is played at 2x real-time, a two-second glTF animation
* will play in one second even if multiplier
is 1.0
.
*
* @memberof ModelAnimation.prototype
*
* @type {number}
* @readonly
*
* @default 1.0
*/
multiplier: {
get: function() {
return this._multiplier;
}
},
/**
* When true
, the animation is played in reverse.
*
* @memberof ModelAnimation.prototype
*
* @type {boolean}
* @readonly
*
* @default false
*/
reverse: {
get: function() {
return this._reverse;
}
},
/**
* Determines if and how the animation is looped.
*
* @memberof ModelAnimation.prototype
*
* @type {ModelAnimationLoop}
* @readonly
*
* @default {@link ModelAnimationLoop.NONE}
*/
loop: {
get: function() {
return this._loop;
}
},
/**
* If this is defined, it will be used to compute the local animation time
* instead of the scene's time.
*
* @memberof ModelAnimation.prototype
*
* @type {ModelAnimation.AnimationTimeCallback}
* @default undefined
*/
animationTime: {
get: function() {
return this._animationTime;
}
}
});
function initialize7(runtimeAnimation) {
let localStartTime = Number.MAX_VALUE;
let localStopTime = -Number.MAX_VALUE;
const sceneGraph = runtimeAnimation._model.sceneGraph;
const animation = runtimeAnimation._animation;
const channels = animation.channels;
const length3 = channels.length;
const runtimeChannels = [];
for (let i = 0; i < length3; i++) {
const channel = channels[i];
const target = channel.target;
if (!defined_default(target)) {
continue;
}
const nodeIndex = target.node.index;
const runtimeNode = sceneGraph._runtimeNodes[nodeIndex];
const runtimeChannel = new ModelAnimationChannel_default({
channel,
runtimeAnimation,
runtimeNode
});
const times = channel.sampler.input;
localStartTime = Math.min(localStartTime, times[0]);
localStopTime = Math.max(localStopTime, times[times.length - 1]);
runtimeChannels.push(runtimeChannel);
}
runtimeAnimation._runtimeChannels = runtimeChannels;
runtimeAnimation._localStartTime = localStartTime;
runtimeAnimation._localStopTime = localStopTime;
}
ModelAnimation.prototype.animate = function(time) {
const runtimeChannels = this._runtimeChannels;
const length3 = runtimeChannels.length;
for (let i = 0; i < length3; i++) {
runtimeChannels[i].animate(time);
}
};
var ModelAnimation_default = ModelAnimation;
// packages/engine/Source/Scene/Model/ModelAnimationCollection.js
function ModelAnimationCollection(model) {
this.animationAdded = new Event_default();
this.animationRemoved = new Event_default();
this.animateWhilePaused = false;
this._model = model;
this._runtimeAnimations = [];
this._previousTime = void 0;
}
Object.defineProperties(ModelAnimationCollection.prototype, {
/**
* The number of animations in the collection.
*
* @memberof ModelAnimationCollection.prototype
*
* @type {number}
* @readonly
*/
length: {
get: function() {
return this._runtimeAnimations.length;
}
},
/**
* The model that owns this animation collection.
*
* @memberof ModelAnimationCollection.prototype
*
* @type {Model}
* @readonly
*/
model: {
get: function() {
return this._model;
}
}
});
function addAnimation(collection, animation, options) {
const model = collection._model;
const runtimeAnimation = new ModelAnimation_default(model, animation, options);
collection._runtimeAnimations.push(runtimeAnimation);
collection.animationAdded.raiseEvent(model, runtimeAnimation);
return runtimeAnimation;
}
ModelAnimationCollection.prototype.add = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const model = this._model;
if (!model.ready) {
throw new DeveloperError_default(
"Animations are not loaded. Wait for Model.ready to be true."
);
}
const animations = model.sceneGraph.components.animations;
if (!defined_default(options.name) && !defined_default(options.index)) {
throw new DeveloperError_default(
"Either options.name or options.index must be defined."
);
}
if (defined_default(options.multiplier) && options.multiplier <= 0) {
throw new DeveloperError_default("options.multiplier must be greater than zero.");
}
if (defined_default(options.index) && (options.index >= animations.length || options.index < 0)) {
throw new DeveloperError_default("options.index must be a valid animation index.");
}
let index = options.index;
if (defined_default(index)) {
return addAnimation(this, animations[index], options);
}
const length3 = animations.length;
for (let i = 0; i < length3; ++i) {
if (animations[i].name === options.name) {
index = i;
break;
}
}
if (!defined_default(index)) {
throw new DeveloperError_default("options.name must be a valid animation name.");
}
return addAnimation(this, animations[index], options);
};
ModelAnimationCollection.prototype.addAll = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const model = this._model;
if (!model.ready) {
throw new DeveloperError_default(
"Animations are not loaded. Wait for Model.ready to be true."
);
}
if (defined_default(options.multiplier) && options.multiplier <= 0) {
throw new DeveloperError_default("options.multiplier must be greater than zero.");
}
const animations = model.sceneGraph.components.animations;
const addedAnimations = [];
const length3 = animations.length;
for (let i = 0; i < length3; ++i) {
const animation = addAnimation(this, animations[i], options);
addedAnimations.push(animation);
}
return addedAnimations;
};
ModelAnimationCollection.prototype.remove = function(runtimeAnimation) {
if (!defined_default(runtimeAnimation)) {
return false;
}
const animations = this._runtimeAnimations;
const i = animations.indexOf(runtimeAnimation);
if (i !== -1) {
animations.splice(i, 1);
this.animationRemoved.raiseEvent(this._model, runtimeAnimation);
return true;
}
return false;
};
ModelAnimationCollection.prototype.removeAll = function() {
const model = this._model;
const animations = this._runtimeAnimations;
const length3 = animations.length;
this._runtimeAnimations.length = 0;
for (let i = 0; i < length3; ++i) {
this.animationRemoved.raiseEvent(model, animations[i]);
}
};
ModelAnimationCollection.prototype.contains = function(runtimeAnimation) {
if (defined_default(runtimeAnimation)) {
return this._runtimeAnimations.indexOf(runtimeAnimation) !== -1;
}
return false;
};
ModelAnimationCollection.prototype.get = function(index) {
if (!defined_default(index)) {
throw new DeveloperError_default("index is required.");
}
if (index >= this._runtimeAnimations.length || index < 0) {
throw new DeveloperError_default(
"index must be valid within the range of the collection"
);
}
return this._runtimeAnimations[index];
};
var animationsToRemove = [];
function createAnimationRemovedFunction(modelAnimationCollection, model, animation) {
return function() {
modelAnimationCollection.animationRemoved.raiseEvent(model, animation);
};
}
ModelAnimationCollection.prototype.update = function(frameState) {
const runtimeAnimations = this._runtimeAnimations;
let length3 = runtimeAnimations.length;
if (length3 === 0) {
this._previousTime = void 0;
return false;
}
if (!this.animateWhilePaused && JulianDate_default.equals(frameState.time, this._previousTime)) {
return false;
}
this._previousTime = JulianDate_default.clone(frameState.time, this._previousTime);
let animationOccurred = false;
const sceneTime = frameState.time;
const model = this._model;
for (let i = 0; i < length3; ++i) {
const runtimeAnimation = runtimeAnimations[i];
if (!defined_default(runtimeAnimation._computedStartTime)) {
runtimeAnimation._computedStartTime = JulianDate_default.addSeconds(
defaultValue_default(runtimeAnimation.startTime, sceneTime),
runtimeAnimation.delay,
new JulianDate_default()
);
}
if (!defined_default(runtimeAnimation._duration)) {
runtimeAnimation._duration = runtimeAnimation.localStopTime * (1 / runtimeAnimation.multiplier);
}
const startTime = runtimeAnimation._computedStartTime;
const duration = runtimeAnimation._duration;
const stopTime = runtimeAnimation.stopTime;
const pastStartTime = JulianDate_default.lessThanOrEquals(startTime, sceneTime);
const reachedStopTime = defined_default(stopTime) && JulianDate_default.greaterThan(sceneTime, stopTime);
let delta = 0;
if (duration !== 0) {
const seconds = JulianDate_default.secondsDifference(
reachedStopTime ? stopTime : sceneTime,
startTime
);
delta = defined_default(runtimeAnimation._animationTime) ? runtimeAnimation._animationTime(duration, seconds) : seconds / duration;
}
const repeat = runtimeAnimation.loop === ModelAnimationLoop_default.REPEAT || runtimeAnimation.loop === ModelAnimationLoop_default.MIRRORED_REPEAT;
const play = (pastStartTime || repeat && !defined_default(runtimeAnimation.startTime)) && (delta <= 1 || repeat) && !reachedStopTime;
if (delta === runtimeAnimation._prevAnimationDelta) {
const animationStopped = runtimeAnimation._state === ModelAnimationState_default.STOPPED;
if (play !== animationStopped) {
continue;
}
}
runtimeAnimation._prevAnimationDelta = delta;
if (play || runtimeAnimation._state === ModelAnimationState_default.ANIMATING) {
if (play && runtimeAnimation._state === ModelAnimationState_default.STOPPED) {
runtimeAnimation._state = ModelAnimationState_default.ANIMATING;
if (runtimeAnimation.start.numberOfListeners > 0) {
frameState.afterRender.push(runtimeAnimation._raiseStartEvent);
}
}
if (runtimeAnimation.loop === ModelAnimationLoop_default.REPEAT) {
delta = delta - Math.floor(delta);
} else if (runtimeAnimation.loop === ModelAnimationLoop_default.MIRRORED_REPEAT) {
const floor = Math.floor(delta);
const fract2 = delta - floor;
delta = floor % 2 === 1 ? 1 - fract2 : fract2;
}
if (runtimeAnimation.reverse) {
delta = 1 - delta;
}
let localAnimationTime = delta * duration * runtimeAnimation.multiplier;
localAnimationTime = Math_default.clamp(
localAnimationTime,
runtimeAnimation.localStartTime,
runtimeAnimation.localStopTime
);
runtimeAnimation.animate(localAnimationTime);
if (runtimeAnimation.update.numberOfListeners > 0) {
runtimeAnimation._updateEventTime = localAnimationTime;
frameState.afterRender.push(runtimeAnimation._raiseUpdateEvent);
}
animationOccurred = true;
if (!play) {
runtimeAnimation._state = ModelAnimationState_default.STOPPED;
if (runtimeAnimation.stop.numberOfListeners > 0) {
frameState.afterRender.push(runtimeAnimation._raiseStopEvent);
}
if (runtimeAnimation.removeOnStop) {
animationsToRemove.push(runtimeAnimation);
}
}
}
}
length3 = animationsToRemove.length;
for (let j = 0; j < length3; ++j) {
const animationToRemove = animationsToRemove[j];
runtimeAnimations.splice(runtimeAnimations.indexOf(animationToRemove), 1);
frameState.afterRender.push(
createAnimationRemovedFunction(this, model, animationToRemove)
);
}
animationsToRemove.length = 0;
return animationOccurred;
};
var ModelAnimationCollection_default = ModelAnimationCollection;
// packages/engine/Source/Scene/Model/ModelFeature.js
function ModelFeature(options) {
this._model = options.model;
this._featureTable = options.featureTable;
this._featureId = options.featureId;
this._color = void 0;
}
Object.defineProperties(ModelFeature.prototype, {
/**
* Gets or sets if the feature will be shown. This is set for all features
* when a style's show is evaluated.
*
* @memberof ModelFeature.prototype
*
* @type {boolean}
*
* @default true
*/
show: {
get: function() {
return this._featureTable.getShow(this._featureId);
},
set: function(value) {
this._featureTable.setShow(this._featureId, value);
}
},
/**
* Gets or sets the highlight color multiplied with the feature's color. When
* this is white, the feature's color is not changed. This is set for all features
* when a style's color is evaluated.
*
* @memberof ModelFeature.prototype
*
* @type {Color}
*
* @default {@link Color.WHITE}
*/
color: {
get: function() {
if (!defined_default(this._color)) {
this._color = new Color_default();
}
return this._featureTable.getColor(this._featureId, this._color);
},
set: function(value) {
this._featureTable.setColor(this._featureId, value);
}
},
/**
* All objects returned by {@link Scene#pick} have a primitive
property. This returns
* the model containing the feature.
*
* @memberof ModelFeature.prototype
*
* @type {Model}
*
* @readonly
* @private
*/
primitive: {
get: function() {
return this._model;
}
},
/**
* The {@link ModelFeatureTable} that this feature belongs to.
*
* @memberof ModelFeature.prototype
*
* @type {ModelFeatureTable}
*
* @readonly
* @private
*/
featureTable: {
get: function() {
return this._featureTable;
}
},
/**
* Get the feature ID associated with this feature. For 3D Tiles 1.0, the
* batch ID is returned. For EXT_mesh_features, this is the feature ID from
* the selected feature ID set.
*
* @memberof ModelFeature.prototype
*
* @type {number}
*
* @readonly
* @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.
*/
featureId: {
get: function() {
return this._featureId;
}
}
});
ModelFeature.prototype.hasProperty = function(name) {
return this._featureTable.hasProperty(this._featureId, name);
};
ModelFeature.prototype.getProperty = function(name) {
return this._featureTable.getProperty(this._featureId, name);
};
ModelFeature.prototype.getPropertyInherited = function(name) {
if (this._featureTable.hasPropertyBySemantic(this._featureId, name)) {
return this._featureTable.getPropertyBySemantic(this._featureId, name);
}
return this._featureTable.getProperty(this._featureId, name);
};
ModelFeature.prototype.getPropertyIds = function(results) {
return this._featureTable.getPropertyIds(results);
};
ModelFeature.prototype.setProperty = function(name, value) {
return this._featureTable.setProperty(this._featureId, name, value);
};
var ModelFeature_default = ModelFeature;
// packages/engine/Source/Scene/Model/StyleCommandsNeeded.js
var StyleCommandsNeeded2 = {
ALL_OPAQUE: 0,
ALL_TRANSLUCENT: 1,
OPAQUE_AND_TRANSLUCENT: 2
};
StyleCommandsNeeded2.getStyleCommandsNeeded = function(featuresLength, translucentFeaturesLength) {
if (translucentFeaturesLength === 0) {
return StyleCommandsNeeded2.ALL_OPAQUE;
} else if (translucentFeaturesLength === featuresLength) {
return StyleCommandsNeeded2.ALL_TRANSLUCENT;
}
return StyleCommandsNeeded2.OPAQUE_AND_TRANSLUCENT;
};
var StyleCommandsNeeded_default = Object.freeze(StyleCommandsNeeded2);
// packages/engine/Source/Scene/Model/ModelType.js
var ModelType = {
/**
* An individual glTF model.
* * Not to be confused with {@link ModelType.TILE_GLTF} * which is for 3D Tiles *
* * @type {string} * @constant */ GLTF: "GLTF", /** * A glTF model used as tile content in a 3D Tileset via *3DTILES_content_gltf
.
* * Not to be confused with {@link ModelType.GLTF} * which is for individual models *
* * @type {string} * @constant */ TILE_GLTF: "TILE_GLTF", /** * A 3D Tiles 1.0 Batched 3D Model * * @type {string} * @constant */ TILE_B3DM: "B3DM", /** * A 3D Tiles 1.0 Instanced 3D Model * * @type {string} * @constant */ TILE_I3DM: "I3DM", /** * A 3D Tiles 1.0 Point Cloud * * @type {string} * @constant */ TILE_PNTS: "PNTS", /** * GeoJSON content forMAXAR_content_geojson
extension
*
* @type {string}
* @constant
*/
TILE_GEOJSON: "TILE_GEOJSON"
};
ModelType.is3DTiles = function(modelType) {
Check_default.typeOf.string("modelType", modelType);
switch (modelType) {
case ModelType.TILE_GLTF:
case ModelType.TILE_B3DM:
case ModelType.TILE_I3DM:
case ModelType.TILE_PNTS:
case ModelType.TILE_GEOJSON:
return true;
case ModelType.GLTF:
return false;
default:
throw new DeveloperError_default("modelType is not a valid value.");
}
};
var ModelType_default = Object.freeze(ModelType);
// packages/engine/Source/Scene/Model/ModelFeatureTable.js
function ModelFeatureTable(options) {
const model = options.model;
const propertyTable = options.propertyTable;
Check_default.typeOf.object("propertyTable", propertyTable);
Check_default.typeOf.object("model", model);
this._propertyTable = propertyTable;
this._model = model;
this._features = void 0;
this._featuresLength = 0;
this._batchTexture = void 0;
this._styleCommandsNeededDirty = false;
this._styleCommandsNeeded = StyleCommandsNeeded_default.ALL_OPAQUE;
initialize8(this);
}
Object.defineProperties(ModelFeatureTable.prototype, {
/**
* The batch texture created for the features in this table.
*
* @memberof ModelFeatureTable.prototype
*
* @type {BatchTexture}
* @readonly
*
* @private
*/
batchTexture: {
get: function() {
return this._batchTexture;
}
},
/**
* The number of features in this table.
*
* @memberof ModelFeatureTable.prototype
*
* @type {number}
* @readonly
*
* @private
*/
featuresLength: {
get: function() {
return this._featuresLength;
}
},
/**
* Size of the batch texture. This does not count the property table size
* as that is counted separately through StructuralMetadata.
*
* @memberof ModelFeatureTable.prototype
*
* @type {number}
* @readonly
*
* @private
*/
batchTextureByteLength: {
get: function() {
if (defined_default(this._batchTexture)) {
return this._batchTexture.byteLength;
}
return 0;
}
},
/**
* A flag to indicate whether or not the types of style commands needed by this feature table have changed.
*
* @memberof ModelFeatureTable.prototype
*
* @type {boolean}
* @readonly
*
* @private
*/
styleCommandsNeededDirty: {
get: function() {
return this._styleCommandsNeededDirty;
}
}
});
function initialize8(modelFeatureTable) {
const model = modelFeatureTable._model;
const is3DTiles = ModelType_default.is3DTiles(model.type);
const featuresLength = modelFeatureTable._propertyTable.count;
if (featuresLength === 0) {
return;
}
let i;
const features = new Array(featuresLength);
if (is3DTiles) {
const content = model.content;
for (i = 0; i < featuresLength; i++) {
features[i] = new Cesium3DTileFeature_default(content, i);
}
} else {
for (i = 0; i < featuresLength; i++) {
features[i] = new ModelFeature_default({
model,
featureId: i,
featureTable: modelFeatureTable
});
}
}
modelFeatureTable._features = features;
modelFeatureTable._featuresLength = featuresLength;
modelFeatureTable._batchTexture = new BatchTexture_default({
featuresLength,
owner: modelFeatureTable,
statistics: is3DTiles ? model.content.tileset.statistics : void 0
});
}
ModelFeatureTable.prototype.update = function(frameState) {
this._styleCommandsNeededDirty = false;
this._batchTexture.update(void 0, frameState);
const currentStyleCommandsNeeded = StyleCommandsNeeded_default.getStyleCommandsNeeded(
this._featuresLength,
this._batchTexture.translucentFeaturesLength
);
if (this._styleCommandsNeeded !== currentStyleCommandsNeeded) {
this._styleCommandsNeededDirty = true;
this._styleCommandsNeeded = currentStyleCommandsNeeded;
}
};
ModelFeatureTable.prototype.setShow = function(featureId, show) {
this._batchTexture.setShow(featureId, show);
};
ModelFeatureTable.prototype.setAllShow = function(show) {
this._batchTexture.setAllShow(show);
};
ModelFeatureTable.prototype.getShow = function(featureId) {
return this._batchTexture.getShow(featureId);
};
ModelFeatureTable.prototype.setColor = function(featureId, color) {
this._batchTexture.setColor(featureId, color);
};
ModelFeatureTable.prototype.setAllColor = function(color) {
this._batchTexture.setAllColor(color);
};
ModelFeatureTable.prototype.getColor = function(featureId, result) {
return this._batchTexture.getColor(featureId, result);
};
ModelFeatureTable.prototype.getPickColor = function(featureId) {
return this._batchTexture.getPickColor(featureId);
};
ModelFeatureTable.prototype.getFeature = function(featureId) {
return this._features[featureId];
};
ModelFeatureTable.prototype.hasProperty = function(featureId, propertyName) {
return this._propertyTable.hasProperty(featureId, propertyName);
};
ModelFeatureTable.prototype.hasPropertyBySemantic = function(featureId, propertyName) {
return this._propertyTable.hasPropertyBySemantic(featureId, propertyName);
};
ModelFeatureTable.prototype.getProperty = function(featureId, name) {
return this._propertyTable.getProperty(featureId, name);
};
ModelFeatureTable.prototype.getPropertyBySemantic = function(featureId, semantic) {
return this._propertyTable.getPropertyBySemantic(featureId, semantic);
};
ModelFeatureTable.prototype.getPropertyIds = function(results) {
return this._propertyTable.getPropertyIds(results);
};
ModelFeatureTable.prototype.setProperty = function(featureId, name, value) {
return this._propertyTable.setProperty(featureId, name, value);
};
ModelFeatureTable.prototype.isClass = function(featureId, className) {
return this._propertyTable.isClass(featureId, className);
};
ModelFeatureTable.prototype.isExactClass = function(featureId, className) {
return this._propertyTable.isExactClass(featureId, className);
};
ModelFeatureTable.prototype.getExactClassName = function(featureId) {
return this._propertyTable.getExactClassName(featureId);
};
var scratchColor6 = new Color_default();
ModelFeatureTable.prototype.applyStyle = function(style) {
if (!defined_default(style)) {
this.setAllColor(BatchTexture_default.DEFAULT_COLOR_VALUE);
this.setAllShow(BatchTexture_default.DEFAULT_SHOW_VALUE);
return;
}
for (let i = 0; i < this._featuresLength; i++) {
const feature2 = this.getFeature(i);
const color = defined_default(style.color) ? defaultValue_default(
style.color.evaluateColor(feature2, scratchColor6),
BatchTexture_default.DEFAULT_COLOR_VALUE
) : BatchTexture_default.DEFAULT_COLOR_VALUE;
const show = defined_default(style.show) ? defaultValue_default(
style.show.evaluate(feature2),
BatchTexture_default.DEFAULT_SHOW_VALUE
) : BatchTexture_default.DEFAULT_SHOW_VALUE;
this.setColor(i, color);
this.setShow(i, show);
}
};
ModelFeatureTable.prototype.isDestroyed = function() {
return false;
};
ModelFeatureTable.prototype.destroy = function(frameState) {
this._batchTexture = this._batchTexture && this._batchTexture.destroy();
destroyObject_default(this);
};
var ModelFeatureTable_default = ModelFeatureTable;
// packages/engine/Source/Shaders/Model/ModelFS.js
var ModelFS_default = "#if defined(HAS_NORMALS) && !defined(HAS_TANGENTS) && !defined(LIGHTING_UNLIT)\n #ifdef GL_OES_standard_derivatives\n #extension GL_OES_standard_derivatives : enable\n #endif\n#endif\n\nczm_modelMaterial defaultModelMaterial()\n{\n czm_modelMaterial material;\n material.diffuse = vec3(0.0);\n material.specular = vec3(1.0);\n material.roughness = 1.0;\n material.occlusion = 1.0;\n material.normalEC = vec3(0.0, 0.0, 1.0);\n material.emissive = vec3(0.0);\n material.alpha = 1.0;\n return material;\n}\n\nvec4 handleAlpha(vec3 color, float alpha)\n{\n #ifdef ALPHA_MODE_MASK\n if (alpha < u_alphaCutoff) {\n discard;\n }\n #endif\n\n return vec4(color, alpha);\n}\n\nSelectedFeature selectedFeature;\n\nvoid main()\n{\n #ifdef HAS_MODEL_SPLITTER\n modelSplitterStage();\n #endif\n\n czm_modelMaterial material = defaultModelMaterial();\n\n ProcessedAttributes attributes;\n geometryStage(attributes);\n\n FeatureIds featureIds;\n featureIdStage(featureIds, attributes);\n\n Metadata metadata;\n MetadataClass metadataClass;\n MetadataStatistics metadataStatistics;\n metadataStage(metadata, metadataClass, metadataStatistics, attributes);\n\n #ifdef HAS_SELECTED_FEATURE_ID\n selectedFeatureIdStage(selectedFeature, featureIds);\n #endif\n\n #ifndef CUSTOM_SHADER_REPLACE_MATERIAL\n materialStage(material, attributes, selectedFeature);\n #endif\n\n #ifdef HAS_CUSTOM_FRAGMENT_SHADER\n customShaderStage(material, attributes, featureIds, metadata, metadataClass, metadataStatistics);\n #endif\n\n lightingStage(material, attributes);\n\n #ifdef HAS_SELECTED_FEATURE_ID\n cpuStylingStage(material, selectedFeature);\n #endif\n\n #ifdef HAS_MODEL_COLOR\n modelColorStage(material);\n #endif\n\n #ifdef HAS_PRIMITIVE_OUTLINE\n primitiveOutlineStage(material);\n #endif\n\n vec4 color = handleAlpha(material.diffuse, material.alpha);\n\n #ifdef HAS_CLIPPING_PLANES\n modelClippingPlanesStage(color);\n #endif\n\n #if defined(HAS_SILHOUETTE) && defined(HAS_NORMALS)\n silhouetteStage(color);\n #endif\n\n out_FragColor = color;\n}\n";
// packages/engine/Source/Shaders/Model/ModelVS.js
var ModelVS_default = "precision highp float;\n\nczm_modelVertexOutput defaultVertexOutput(vec3 positionMC) {\n czm_modelVertexOutput vsOutput;\n vsOutput.positionMC = positionMC;\n vsOutput.pointSize = 1.0;\n return vsOutput;\n}\n\nvoid main() \n{\n // Initialize the attributes struct with all\n // attributes except quantized ones.\n ProcessedAttributes attributes;\n initializeAttributes(attributes);\n\n // Dequantize the quantized ones and add them to the\n // attributes struct.\n #ifdef USE_DEQUANTIZATION\n dequantizationStage(attributes);\n #endif\n\n #ifdef HAS_MORPH_TARGETS\n morphTargetsStage(attributes);\n #endif\n\n #ifdef HAS_SKINNING\n skinningStage(attributes);\n #endif\n\n #ifdef HAS_PRIMITIVE_OUTLINE\n primitiveOutlineStage();\n #endif\n\n // Compute the bitangent according to the formula in the glTF spec.\n // Normal and tangents can be affected by morphing and skinning, so\n // the bitangent should not be computed until their values are finalized.\n #ifdef HAS_BITANGENTS\n attributes.bitangentMC = normalize(cross(attributes.normalMC, attributes.tangentMC) * attributes.tangentSignMC);\n #endif\n\n FeatureIds featureIds;\n featureIdStage(featureIds, attributes);\n\n #ifdef HAS_SELECTED_FEATURE_ID\n SelectedFeature feature;\n selectedFeatureIdStage(feature, featureIds);\n // Handle any show properties that come from the style.\n cpuStylingStage(attributes.positionMC, feature);\n #endif\n\n #if defined(USE_2D_POSITIONS) || defined(USE_2D_INSTANCING)\n // The scene mode 2D pipeline stage and instancing stage add a different\n // model view matrix to accurately project the model to 2D. However, the\n // output positions and normals should be transformed by the 3D matrices\n // to keep the data the same for the fragment shader.\n mat4 modelView = czm_modelView3D;\n mat3 normal = czm_normal3D;\n #else\n // These are used for individual model projection because they will\n // automatically change based on the scene mode.\n mat4 modelView = czm_modelView;\n mat3 normal = czm_normal;\n #endif\n\n // Update the position for this instance in place\n #ifdef HAS_INSTANCING\n\n // The legacy instance stage is used when rendering i3dm models that \n // encode instances transforms in world space, as opposed to glTF models\n // that use EXT_mesh_gpu_instancing, where instance transforms are encoded\n // in object space.\n #ifdef USE_LEGACY_INSTANCING\n mat4 instanceModelView;\n mat3 instanceModelViewInverseTranspose;\n \n legacyInstancingStage(attributes, instanceModelView, instanceModelViewInverseTranspose);\n\n modelView = instanceModelView;\n normal = instanceModelViewInverseTranspose;\n #else\n instancingStage(attributes);\n #endif\n\n #ifdef USE_PICKING\n v_pickColor = a_pickColor;\n #endif\n\n #endif\n\n Metadata metadata;\n MetadataClass metadataClass;\n MetadataStatistics metadataStatistics;\n metadataStage(metadata, metadataClass, metadataStatistics, attributes);\n\n #ifdef HAS_CUSTOM_VERTEX_SHADER\n czm_modelVertexOutput vsOutput = defaultVertexOutput(attributes.positionMC);\n customShaderStage(vsOutput, attributes, featureIds, metadata, metadataClass, metadataStatistics);\n #endif\n\n // Compute the final position in each coordinate system needed.\n // This returns the value that will be assigned to gl_Position.\n vec4 positionClip = geometryStage(attributes, modelView, normal); \n\n #ifdef HAS_SILHOUETTE\n silhouetteStage(attributes, positionClip);\n #endif\n\n #ifdef HAS_POINT_CLOUD_SHOW_STYLE\n float show = pointCloudShowStylingStage(attributes, metadata);\n #else\n float show = 1.0;\n #endif\n\n #ifdef HAS_POINT_CLOUD_BACK_FACE_CULLING\n show *= pointCloudBackFaceCullingStage();\n #endif\n\n #ifdef HAS_POINT_CLOUD_COLOR_STYLE\n v_pointCloudColor = pointCloudColorStylingStage(attributes, metadata);\n #endif\n\n #ifdef PRIMITIVE_TYPE_POINTS\n #ifdef HAS_CUSTOM_VERTEX_SHADER\n gl_PointSize = vsOutput.pointSize;\n #elif defined(HAS_POINT_CLOUD_POINT_SIZE_STYLE) || defined(HAS_POINT_CLOUD_ATTENUATION)\n gl_PointSize = pointCloudPointSizeStylingStage(attributes, metadata);\n #else\n gl_PointSize = 1.0;\n #endif\n\n gl_PointSize *= show;\n #endif\n\n gl_Position = show * positionClip;\n}\n";
// packages/engine/Source/Scene/Model/ClassificationModelDrawCommand.js
function ClassificationModelDrawCommand(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const command = options.command;
const renderResources = options.primitiveRenderResources;
Check_default.typeOf.object("options.command", command);
Check_default.typeOf.object("options.primitiveRenderResources", renderResources);
const model = renderResources.model;
this._command = command;
this._model = model;
this._runtimePrimitive = renderResources.runtimePrimitive;
this._modelMatrix = command.modelMatrix;
this._boundingVolume = command.boundingVolume;
this._cullFace = command.renderState.cull.face;
const type = model.classificationType;
this._classificationType = type;
this._classifiesTerrain = type !== ClassificationType_default.CESIUM_3D_TILE;
this._classifies3DTiles = type !== ClassificationType_default.TERRAIN;
this._useDebugWireframe = model._enableDebugWireframe && model.debugWireframe;
this._pickId = renderResources.pickId;
this._commandListTerrain = [];
this._commandList3DTiles = [];
this._commandListIgnoreShow = [];
this._commandListDebugWireframe = [];
this._commandListTerrainPicking = [];
this._commandList3DTilesPicking = [];
initialize9(this);
}
function getStencilDepthRenderState3(stencilFunction) {
return {
colorMask: {
red: false,
green: false,
blue: false,
alpha: false
},
stencilTest: {
enabled: true,
frontFunction: stencilFunction,
frontOperation: {
fail: StencilOperation_default.KEEP,
zFail: StencilOperation_default.DECREMENT_WRAP,
zPass: StencilOperation_default.KEEP
},
backFunction: stencilFunction,
backOperation: {
fail: StencilOperation_default.KEEP,
zFail: StencilOperation_default.INCREMENT_WRAP,
zPass: StencilOperation_default.KEEP
},
reference: StencilConstants_default.CESIUM_3D_TILE_MASK,
mask: StencilConstants_default.CESIUM_3D_TILE_MASK
},
stencilMask: StencilConstants_default.CLASSIFICATION_MASK,
depthTest: {
enabled: true,
func: DepthFunction_default.LESS_OR_EQUAL
},
depthMask: false
};
}
var colorRenderState2 = {
stencilTest: {
enabled: true,
frontFunction: StencilFunction_default.NOT_EQUAL,
frontOperation: {
fail: StencilOperation_default.ZERO,
zFail: StencilOperation_default.ZERO,
zPass: StencilOperation_default.ZERO
},
backFunction: StencilFunction_default.NOT_EQUAL,
backOperation: {
fail: StencilOperation_default.ZERO,
zFail: StencilOperation_default.ZERO,
zPass: StencilOperation_default.ZERO
},
reference: 0,
mask: StencilConstants_default.CLASSIFICATION_MASK
},
stencilMask: StencilConstants_default.CLASSIFICATION_MASK,
depthTest: {
enabled: false
},
depthMask: false,
blending: BlendingState_default.PRE_MULTIPLIED_ALPHA_BLEND
};
var pickRenderState3 = {
stencilTest: {
enabled: true,
frontFunction: StencilFunction_default.NOT_EQUAL,
frontOperation: {
fail: StencilOperation_default.ZERO,
zFail: StencilOperation_default.ZERO,
zPass: StencilOperation_default.ZERO
},
backFunction: StencilFunction_default.NOT_EQUAL,
backOperation: {
fail: StencilOperation_default.ZERO,
zFail: StencilOperation_default.ZERO,
zPass: StencilOperation_default.ZERO
},
reference: 0,
mask: StencilConstants_default.CLASSIFICATION_MASK
},
stencilMask: StencilConstants_default.CLASSIFICATION_MASK,
depthTest: {
enabled: false
},
depthMask: false
};
var scratchDerivedCommands = [];
function initialize9(drawCommand) {
const command = drawCommand._command;
const derivedCommands = scratchDerivedCommands;
if (drawCommand._useDebugWireframe) {
command.pass = Pass_default.OPAQUE;
derivedCommands.length = 0;
derivedCommands.push(command);
drawCommand._commandListDebugWireframe = createBatchCommands(
drawCommand,
derivedCommands,
drawCommand._commandListDebugWireframe
);
const commandList = drawCommand._commandListDebugWireframe;
const length3 = commandList.length;
for (let i = 0; i < length3; i++) {
const command2 = commandList[i];
command2.count *= 2;
command2.offset *= 2;
}
return;
}
const model = drawCommand.model;
const allowPicking = model.allowPicking;
if (drawCommand._classifiesTerrain) {
const pass = Pass_default.TERRAIN_CLASSIFICATION;
const stencilDepthCommand = deriveStencilDepthCommand(command, pass);
const colorCommand = deriveColorCommand(command, pass);
derivedCommands.length = 0;
derivedCommands.push(stencilDepthCommand, colorCommand);
drawCommand._commandListTerrain = createBatchCommands(
drawCommand,
derivedCommands,
drawCommand._commandListTerrain
);
if (allowPicking) {
drawCommand._commandListTerrainPicking = createPickCommands3(
drawCommand,
derivedCommands,
drawCommand._commandListTerrainPicking
);
}
}
if (drawCommand._classifies3DTiles) {
const pass = Pass_default.CESIUM_3D_TILE_CLASSIFICATION;
const stencilDepthCommand = deriveStencilDepthCommand(command, pass);
const colorCommand = deriveColorCommand(command, pass);
derivedCommands.length = 0;
derivedCommands.push(stencilDepthCommand, colorCommand);
drawCommand._commandList3DTiles = createBatchCommands(
drawCommand,
derivedCommands,
drawCommand._commandList3DTiles
);
if (allowPicking) {
drawCommand._commandList3DTilesPicking = createPickCommands3(
drawCommand,
derivedCommands,
drawCommand._commandList3DTilesPicking
);
}
}
}
function createBatchCommands(drawCommand, derivedCommands, result) {
const runtimePrimitive = drawCommand._runtimePrimitive;
const batchLengths = runtimePrimitive.batchLengths;
const batchOffsets = runtimePrimitive.batchOffsets;
const numBatches = batchLengths.length;
const numDerivedCommands = derivedCommands.length;
for (let i = 0; i < numBatches; i++) {
const batchLength = batchLengths[i];
const batchOffset = batchOffsets[i];
for (let j = 0; j < numDerivedCommands; j++) {
const derivedCommand = derivedCommands[j];
const batchCommand = DrawCommand_default.shallowClone(derivedCommand);
batchCommand.count = batchLength;
batchCommand.offset = batchOffset;
result.push(batchCommand);
}
}
return result;
}
function deriveStencilDepthCommand(command, pass) {
const stencilDepthCommand = DrawCommand_default.shallowClone(command);
stencilDepthCommand.cull = false;
stencilDepthCommand.pass = pass;
const stencilFunction = pass === Pass_default.TERRAIN_CLASSIFICATION ? StencilFunction_default.ALWAYS : StencilFunction_default.EQUAL;
const renderState = getStencilDepthRenderState3(stencilFunction);
stencilDepthCommand.renderState = RenderState_default.fromCache(renderState);
return stencilDepthCommand;
}
function deriveColorCommand(command, pass) {
const colorCommand = DrawCommand_default.shallowClone(command);
colorCommand.cull = false;
colorCommand.pass = pass;
colorCommand.renderState = RenderState_default.fromCache(colorRenderState2);
return colorCommand;
}
var scratchPickCommands = [];
function createPickCommands3(drawCommand, derivedCommands, commandList) {
const renderState = RenderState_default.fromCache(pickRenderState3);
const stencilDepthCommand = derivedCommands[0];
const colorCommand = derivedCommands[1];
const pickStencilDepthCommand = DrawCommand_default.shallowClone(stencilDepthCommand);
pickStencilDepthCommand.cull = true;
pickStencilDepthCommand.pickOnly = true;
const pickColorCommand = DrawCommand_default.shallowClone(colorCommand);
pickColorCommand.cull = true;
pickColorCommand.pickOnly = true;
pickColorCommand.renderState = renderState;
pickColorCommand.pickId = drawCommand._pickId;
const pickCommands = scratchPickCommands;
pickCommands.length = 0;
pickCommands.push(pickStencilDepthCommand, pickColorCommand);
return createBatchCommands(drawCommand, pickCommands, commandList);
}
Object.defineProperties(ClassificationModelDrawCommand.prototype, {
/**
* The main draw command that the other commands are derived from.
*
* @memberof ClassificationModelDrawCommand.prototype
* @type {DrawCommand}
*
* @readonly
* @private
*/
command: {
get: function() {
return this._command;
}
},
/**
* The runtime primitive that the draw command belongs to.
*
* @memberof ClassificationModelDrawCommand.prototype
* @type {ModelRuntimePrimitive}
*
* @readonly
* @private
*/
runtimePrimitive: {
get: function() {
return this._runtimePrimitive;
}
},
/**
* The batch lengths used to generate multiple draw commands.
*
* @memberof ClassificationModelDrawCommand.prototype
* @type {number[]}
*
* @readonly
* @private
*/
batchLengths: {
get: function() {
return this._runtimePrimitive.batchLengths;
}
},
/**
* The batch offsets used to generate multiple draw commands.
*
* @memberof ClassificationModelDrawCommand.prototype
* @type {number[]}
*
* @readonly
* @private
*/
batchOffsets: {
get: function() {
return this._runtimePrimitive.batchOffsets;
}
},
/**
* The model that the draw command belongs to.
*
* @memberof ClassificationModelDrawCommand.prototype
* @type {Model}
*
* @readonly
* @private
*/
model: {
get: function() {
return this._model;
}
},
/**
* The classification type of the model that this draw command belongs to.
*
* @memberof ClassificationModelDrawCommand.prototype
* @type {ClassificationType}
*
* @readonly
* @private
*/
classificationType: {
get: function() {
return this._classificationType;
}
},
/**
* The current model matrix applied to the draw commands.
*
* @memberof ClassificationModelDrawCommand.prototype
* @type {Matrix4}
*
* @readonly
* @private
*/
modelMatrix: {
get: function() {
return this._modelMatrix;
},
set: function(value) {
this._modelMatrix = Matrix4_default.clone(value, this._modelMatrix);
const boundingSphere = this._runtimePrimitive.boundingSphere;
this._boundingVolume = BoundingSphere_default.transform(
boundingSphere,
this._modelMatrix,
this._boundingVolume
);
}
},
/**
* The bounding volume of the main draw command. This is equivalent
* to the primitive's bounding sphere transformed by the draw
* command's model matrix.
*
* @memberof ClassificationModelDrawCommand.prototype
* @type {BoundingSphere}
*
* @readonly
* @private
*/
boundingVolume: {
get: function() {
return this._boundingVolume;
}
},
/**
* Culling is disabled for classification models, so this has no effect on
* how the model renders. This only exists to match the interface of
* {@link ModelDrawCommand}.
*
* @memberof ClassificationModelDrawCommand.prototype
* @type {CullFace}
*
* @private
*/
cullFace: {
get: function() {
return this._cullFace;
},
set: function(value) {
this._cullFace = value;
}
}
});
ClassificationModelDrawCommand.prototype.pushCommands = function(frameState, result) {
const passes = frameState.passes;
if (passes.render) {
if (this._useDebugWireframe) {
result.push.apply(result, this._commandListDebugWireframe);
return;
}
if (this._classifiesTerrain) {
result.push.apply(result, this._commandListTerrain);
}
if (this._classifies3DTiles) {
result.push.apply(result, this._commandList3DTiles);
}
const useIgnoreShowCommands = frameState.invertClassification && this._classifies3DTiles;
if (useIgnoreShowCommands) {
if (this._commandListIgnoreShow.length === 0) {
const pass = Pass_default.CESIUM_3D_TILE_CLASSIFICATION_IGNORE_SHOW;
const command = deriveStencilDepthCommand(this._command, pass);
const derivedCommands = scratchDerivedCommands;
derivedCommands.length = 0;
derivedCommands.push(command);
this._commandListIgnoreShow = createBatchCommands(
this,
derivedCommands,
this._commandListIgnoreShow
);
}
result.push.apply(result, this._commandListIgnoreShow);
}
}
if (passes.pick) {
if (this._classifiesTerrain) {
result.push.apply(result, this._commandListTerrainPicking);
}
if (this._classifies3DTiles) {
result.push.apply(result, this._commandList3DTilesPicking);
}
}
return result;
};
var ClassificationModelDrawCommand_default = ClassificationModelDrawCommand;
// packages/engine/Source/Scene/Model/ModelDrawCommand.js
function ModelDrawCommand(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const command = options.command;
const renderResources = options.primitiveRenderResources;
Check_default.typeOf.object("options.command", command);
Check_default.typeOf.object("options.primitiveRenderResources", renderResources);
const model = renderResources.model;
this._model = model;
const runtimePrimitive = renderResources.runtimePrimitive;
this._runtimePrimitive = runtimePrimitive;
const isTranslucent = command.pass === Pass_default.TRANSLUCENT;
const isDoubleSided = runtimePrimitive.primitive.material.doubleSided;
const usesBackFaceCulling = !isDoubleSided && !isTranslucent;
const hasSilhouette = renderResources.hasSilhouette;
const needsTranslucentCommand = !isTranslucent && !hasSilhouette;
const needsSkipLevelOfDetailCommands = renderResources.hasSkipLevelOfDetail && !isTranslucent;
const needsSilhouetteCommands = hasSilhouette;
this._command = command;
this._modelMatrix = Matrix4_default.clone(command.modelMatrix);
this._boundingVolume = BoundingSphere_default.clone(command.boundingVolume);
this._modelMatrix2D = new Matrix4_default();
this._boundingVolume2D = new BoundingSphere_default();
this._modelMatrix2DDirty = false;
this._backFaceCulling = command.renderState.cull.enabled;
this._cullFace = command.renderState.cull.face;
this._shadows = model.shadows;
this._debugShowBoundingVolume = command.debugShowBoundingVolume;
this._usesBackFaceCulling = usesBackFaceCulling;
this._needsTranslucentCommand = needsTranslucentCommand;
this._needsSkipLevelOfDetailCommands = needsSkipLevelOfDetailCommands;
this._needsSilhouetteCommands = needsSilhouetteCommands;
this._originalCommand = void 0;
this._translucentCommand = void 0;
this._skipLodBackfaceCommand = void 0;
this._skipLodStencilCommand = void 0;
this._silhouetteModelCommand = void 0;
this._silhouetteColorCommand = void 0;
this._derivedCommands = [];
this._has2DCommands = false;
initialize10(this);
}
function ModelDerivedCommand(options) {
this.command = options.command;
this.updateShadows = options.updateShadows;
this.updateBackFaceCulling = options.updateBackFaceCulling;
this.updateCullFace = options.updateCullFace;
this.updateDebugShowBoundingVolume = options.updateDebugShowBoundingVolume;
this.is2D = defaultValue_default(options.is2D, false);
this.derivedCommand2D = void 0;
}
ModelDerivedCommand.clone = function(derivedCommand) {
return new ModelDerivedCommand({
command: derivedCommand.command,
updateShadows: derivedCommand.updateShadows,
updateBackFaceCulling: derivedCommand.updateBackFaceCulling,
updateCullFace: derivedCommand.updateCullFace,
updateDebugShowBoundingVolume: derivedCommand.updateDebugShowBoundingVolume,
is2D: derivedCommand.is2D,
derivedCommand2D: derivedCommand.derivedCommand2D
});
};
function initialize10(drawCommand) {
const command = drawCommand._command;
command.modelMatrix = drawCommand._modelMatrix;
command.boundingVolume = drawCommand._boundingVolume;
const model = drawCommand._model;
const usesBackFaceCulling = drawCommand._usesBackFaceCulling;
const derivedCommands = drawCommand._derivedCommands;
drawCommand._originalCommand = new ModelDerivedCommand({
command,
updateShadows: true,
updateBackFaceCulling: usesBackFaceCulling,
updateCullFace: usesBackFaceCulling,
updateDebugShowBoundingVolume: true,
is2D: false
});
derivedCommands.push(drawCommand._originalCommand);
if (drawCommand._needsTranslucentCommand) {
drawCommand._translucentCommand = new ModelDerivedCommand({
command: deriveTranslucentCommand2(command),
updateShadows: true,
updateBackFaceCulling: false,
updateCullFace: false,
updateDebugShowBoundingVolume: true
});
derivedCommands.push(drawCommand._translucentCommand);
}
if (drawCommand._needsSkipLevelOfDetailCommands) {
drawCommand._skipLodBackfaceCommand = new ModelDerivedCommand({
command: deriveSkipLodBackfaceCommand(command),
updateShadows: false,
updateBackFaceCulling: false,
updateCullFace: usesBackFaceCulling,
updateDebugShowBoundingVolume: false
});
drawCommand._skipLodStencilCommand = new ModelDerivedCommand({
command: deriveSkipLodStencilCommand(command, model),
updateShadows: true,
updateBackFaceCulling: usesBackFaceCulling,
updateCullFace: usesBackFaceCulling,
updateDebugShowBoundingVolume: true
});
derivedCommands.push(drawCommand._skipLodBackfaceCommand);
derivedCommands.push(drawCommand._skipLodStencilCommand);
}
if (drawCommand._needsSilhouetteCommands) {
drawCommand._silhouetteModelCommand = new ModelDerivedCommand({
command: deriveSilhouetteModelCommand(command, model),
updateShadows: true,
updateBackFaceCulling: usesBackFaceCulling,
updateCullFace: usesBackFaceCulling,
updateDebugShowBoundingVolume: true
});
drawCommand._silhouetteColorCommand = new ModelDerivedCommand({
command: deriveSilhouetteColorCommand(command, model),
updateShadows: false,
updateBackFaceCulling: false,
updateCullFace: false,
updateDebugShowBoundingVolume: false
});
derivedCommands.push(drawCommand._silhouetteModelCommand);
derivedCommands.push(drawCommand._silhouetteColorCommand);
}
}
Object.defineProperties(ModelDrawCommand.prototype, {
/**
* The main draw command that the other commands are derived from.
*
* @memberof ModelDrawCommand.prototype
* @type {DrawCommand}
*
* @readonly
* @private
*/
command: {
get: function() {
return this._command;
}
},
/**
* The runtime primitive that the draw command belongs to.
*
* @memberof ModelDrawCommand.prototype
* @type {ModelRuntimePrimitive}
*
* @readonly
* @private
*/
runtimePrimitive: {
get: function() {
return this._runtimePrimitive;
}
},
/**
* The model that the draw command belongs to.
*
* @memberof ModelDrawCommand.prototype
* @type {Model}
*
* @readonly
* @private
*/
model: {
get: function() {
return this._model;
}
},
/**
* The primitive type of the draw command.
*
* @memberof ModelDrawCommand.prototype
* @type {PrimitiveType}
*
* @readonly
* @private
*/
primitiveType: {
get: function() {
return this._command.primitiveType;
}
},
/**
* The current model matrix applied to the draw commands. If there are
* 2D draw commands, their model matrix will be derived from the 3D one.
*
* @memberof ModelDrawCommand.prototype
* @type {Matrix4}
*
* @readonly
* @private
*/
modelMatrix: {
get: function() {
return this._modelMatrix;
},
set: function(value) {
this._modelMatrix = Matrix4_default.clone(value, this._modelMatrix);
this._modelMatrix2DDirty = true;
this._boundingVolume = BoundingSphere_default.transform(
this.runtimePrimitive.boundingSphere,
this._modelMatrix,
this._boundingVolume
);
}
},
/**
* The bounding volume of the main draw command. This is equivalent
* to the primitive's bounding sphere transformed by the draw
* command's model matrix.
*
* @memberof ModelDrawCommand.prototype
* @type {BoundingSphere}
*
* @readonly
* @private
*/
boundingVolume: {
get: function() {
return this._boundingVolume;
}
},
/**
* Whether the geometry casts or receives shadows from light sources.
*
* @memberof ModelDrawCommand.prototype
* @type {ShadowMode}
*
* @private
*/
shadows: {
get: function() {
return this._shadows;
},
set: function(value) {
this._shadows = value;
updateShadows(this);
}
},
/**
* Whether to cull back-facing geometry. When true, back face culling is
* determined by the material's doubleSided property; when false, back face
* culling is disabled. Back faces are not culled if the command is
* translucent.
*
* @memberof ModelDrawCommand.prototype
* @type {boolean}
*
* @private
*/
backFaceCulling: {
get: function() {
return this._backFaceCulling;
},
set: function(value) {
if (this._backFaceCulling === value) {
return;
}
this._backFaceCulling = value;
updateBackFaceCulling(this);
}
},
/**
* Determines which faces to cull, if culling is enabled.
*
* @memberof ModelDrawCommand.prototype
* @type {CullFace}
*
* @private
*/
cullFace: {
get: function() {
return this._cullFace;
},
set: function(value) {
if (this._cullFace === value) {
return;
}
this._cullFace = value;
updateCullFace(this);
}
},
/**
* Whether to draw the bounding sphere associated with this draw command.
*
* @memberof ModelDrawCommand.prototype
* @type {boolean}
*
* @private
*/
debugShowBoundingVolume: {
get: function() {
return this._debugShowBoundingVolume;
},
set: function(value) {
if (this._debugShowBoundingVolume === value) {
return;
}
this._debugShowBoundingVolume = value;
updateDebugShowBoundingVolume(this);
}
}
});
function updateModelMatrix2D(drawCommand, frameState) {
const modelMatrix = drawCommand._modelMatrix;
drawCommand._modelMatrix2D = Matrix4_default.clone(
modelMatrix,
drawCommand._modelMatrix2D
);
drawCommand._modelMatrix2D[13] -= Math_default.sign(modelMatrix[13]) * 2 * Math_default.PI * frameState.mapProjection.ellipsoid.maximumRadius;
drawCommand._boundingVolume2D = BoundingSphere_default.transform(
drawCommand.runtimePrimitive.boundingSphere,
drawCommand._modelMatrix2D,
drawCommand._boundingVolume2D
);
}
function updateShadows(drawCommand) {
const shadows = drawCommand.shadows;
const castShadows = ShadowMode_default.castShadows(shadows);
const receiveShadows = ShadowMode_default.receiveShadows(shadows);
const derivedCommands = drawCommand._derivedCommands;
for (let i = 0; i < derivedCommands.length; ++i) {
const derivedCommand = derivedCommands[i];
if (derivedCommand.updateShadows) {
const command = derivedCommand.command;
command.castShadows = castShadows;
command.receiveShadows = receiveShadows;
}
}
}
function updateBackFaceCulling(drawCommand) {
const backFaceCulling = drawCommand.backFaceCulling;
const derivedCommands = drawCommand._derivedCommands;
for (let i = 0; i < derivedCommands.length; ++i) {
const derivedCommand = derivedCommands[i];
if (derivedCommand.updateBackFaceCulling) {
const command = derivedCommand.command;
const renderState = clone_default(command.renderState, true);
renderState.cull.enabled = backFaceCulling;
command.renderState = RenderState_default.fromCache(renderState);
}
}
}
function updateCullFace(drawCommand) {
const cullFace = drawCommand.cullFace;
const derivedCommands = drawCommand._derivedCommands;
for (let i = 0; i < derivedCommands.length; ++i) {
const derivedCommand = derivedCommands[i];
if (derivedCommand.updateCullFace) {
const command = derivedCommand.command;
const renderState = clone_default(command.renderState, true);
renderState.cull.face = cullFace;
command.renderState = RenderState_default.fromCache(renderState);
}
}
}
function updateDebugShowBoundingVolume(drawCommand) {
const debugShowBoundingVolume2 = drawCommand.debugShowBoundingVolume;
const derivedCommands = drawCommand._derivedCommands;
for (let i = 0; i < derivedCommands.length; ++i) {
const derivedCommand = derivedCommands[i];
if (derivedCommand.updateDebugShowBoundingVolume) {
const command = derivedCommand.command;
command.debugShowBoundingVolume = debugShowBoundingVolume2;
}
}
}
ModelDrawCommand.prototype.pushCommands = function(frameState, result) {
const use2D = shouldUse2DCommands(this, frameState);
if (use2D && !this._has2DCommands) {
derive2DCommands(this);
this._has2DCommands = true;
this._modelMatrix2DDirty = true;
}
if (this._modelMatrix2DDirty) {
updateModelMatrix2D(this, frameState);
this._modelMatrix2DDirty = false;
}
const styleCommandsNeeded = this.model.styleCommandsNeeded;
if (this._needsTranslucentCommand && defined_default(styleCommandsNeeded)) {
if (styleCommandsNeeded !== StyleCommandsNeeded_default.ALL_OPAQUE) {
pushCommand(result, this._translucentCommand, use2D);
}
if (styleCommandsNeeded === StyleCommandsNeeded_default.ALL_TRANSLUCENT) {
return;
}
}
if (this._needsSkipLevelOfDetailCommands) {
const { tileset, tile } = this._model.content;
if (tileset.hasMixedContent) {
if (!tile._finalResolution) {
pushCommand(
tileset._backfaceCommands,
this._skipLodBackfaceCommand,
use2D
);
}
updateSkipLodStencilCommand(this, tile, use2D);
pushCommand(result, this._skipLodStencilCommand, use2D);
return;
}
}
if (this._needsSilhouetteCommands) {
pushCommand(result, this._silhouetteModelCommand, use2D);
return;
}
pushCommand(result, this._originalCommand, use2D);
return result;
};
ModelDrawCommand.prototype.pushSilhouetteCommands = function(frameState, result) {
const use2D = shouldUse2DCommands(this, frameState);
pushCommand(result, this._silhouetteColorCommand, use2D);
return result;
};
function pushCommand(commandList, derivedCommand, use2D) {
commandList.push(derivedCommand.command);
if (use2D) {
commandList.push(derivedCommand.derivedCommand2D.command);
}
}
function shouldUse2DCommands(drawCommand, frameState) {
if (frameState.mode !== SceneMode_default.SCENE2D || drawCommand.model._projectTo2D) {
return false;
}
const model = drawCommand.model;
const boundingSphere = model.sceneGraph._boundingSphere2D;
const left = boundingSphere.center.y - boundingSphere.radius;
const right = boundingSphere.center.y + boundingSphere.radius;
const idl2D = frameState.mapProjection.ellipsoid.maximumRadius * Math_default.PI;
return left < idl2D && right > idl2D || left < -idl2D && right > -idl2D;
}
function derive2DCommand(drawCommand, derivedCommand) {
if (!defined_default(derivedCommand)) {
return;
}
const derivedCommand2D = ModelDerivedCommand.clone(derivedCommand);
const command2D = DrawCommand_default.shallowClone(derivedCommand.command);
command2D.modelMatrix = drawCommand._modelMatrix2D;
command2D.boundingVolume = drawCommand._boundingVolume2D;
derivedCommand2D.command = command2D;
derivedCommand2D.updateShadows = false;
derivedCommand2D.is2D = true;
derivedCommand.derivedCommand2D = derivedCommand2D;
drawCommand._derivedCommands.push(derivedCommand2D);
return derivedCommand2D;
}
function derive2DCommands(drawCommand) {
derive2DCommand(drawCommand, drawCommand._originalCommand);
derive2DCommand(drawCommand, drawCommand._translucentCommand);
derive2DCommand(drawCommand, drawCommand._skipLodBackfaceCommand);
derive2DCommand(drawCommand, drawCommand._skipLodStencilCommand);
derive2DCommand(drawCommand, drawCommand._silhouetteModelCommand);
derive2DCommand(drawCommand, drawCommand._silhouetteColorCommand);
}
function deriveTranslucentCommand2(command) {
const derivedCommand = DrawCommand_default.shallowClone(command);
derivedCommand.pass = Pass_default.TRANSLUCENT;
const rs = clone_default(command.renderState, true);
rs.cull.enabled = false;
rs.depthMask = false;
rs.blending = BlendingState_default.ALPHA_BLEND;
derivedCommand.renderState = RenderState_default.fromCache(rs);
return derivedCommand;
}
function deriveSilhouetteModelCommand(command, model) {
const stencilReference = model._silhouetteId % 255;
const silhouetteModelCommand = DrawCommand_default.shallowClone(command);
const renderState = clone_default(command.renderState, true);
renderState.stencilTest = {
enabled: true,
frontFunction: WebGLConstants_default.ALWAYS,
backFunction: WebGLConstants_default.ALWAYS,
reference: stencilReference,
mask: ~0,
frontOperation: {
fail: WebGLConstants_default.KEEP,
zFail: WebGLConstants_default.KEEP,
zPass: WebGLConstants_default.REPLACE
},
backOperation: {
fail: WebGLConstants_default.KEEP,
zFail: WebGLConstants_default.KEEP,
zPass: WebGLConstants_default.REPLACE
}
};
if (model.isInvisible()) {
renderState.colorMask = {
red: false,
green: false,
blue: false,
alpha: false
};
}
silhouetteModelCommand.renderState = RenderState_default.fromCache(renderState);
return silhouetteModelCommand;
}
function deriveSilhouetteColorCommand(command, model) {
const stencilReference = model._silhouetteId % 255;
const silhouetteColorCommand = DrawCommand_default.shallowClone(command);
const renderState = clone_default(command.renderState, true);
renderState.cull.enabled = false;
const silhouetteTranslucent = command.pass === Pass_default.TRANSLUCENT || model.silhouetteColor.alpha < 1;
if (silhouetteTranslucent) {
silhouetteColorCommand.pass = Pass_default.TRANSLUCENT;
renderState.depthMask = false;
renderState.blending = BlendingState_default.ALPHA_BLEND;
}
renderState.stencilTest = {
enabled: true,
frontFunction: WebGLConstants_default.NOTEQUAL,
backFunction: WebGLConstants_default.NOTEQUAL,
reference: stencilReference,
mask: ~0,
frontOperation: {
fail: WebGLConstants_default.KEEP,
zFail: WebGLConstants_default.KEEP,
zPass: WebGLConstants_default.KEEP
},
backOperation: {
fail: WebGLConstants_default.KEEP,
zFail: WebGLConstants_default.KEEP,
zPass: WebGLConstants_default.KEEP
}
};
const uniformMap2 = clone_default(command.uniformMap);
uniformMap2.model_silhouettePass = function() {
return true;
};
silhouetteColorCommand.renderState = RenderState_default.fromCache(renderState);
silhouetteColorCommand.uniformMap = uniformMap2;
silhouetteColorCommand.castShadows = false;
silhouetteColorCommand.receiveShadows = false;
return silhouetteColorCommand;
}
function updateSkipLodStencilCommand(drawCommand, tile, use2D) {
const stencilDerivedComand = drawCommand._skipLodStencilCommand;
const stencilCommand = stencilDerivedComand.command;
const selectionDepth = tile._selectionDepth;
const lastSelectionDepth = getLastSelectionDepth2(stencilCommand);
if (selectionDepth !== lastSelectionDepth) {
const skipLodStencilReference = getStencilReference(selectionDepth);
const renderState = clone_default(stencilCommand.renderState, true);
renderState.stencilTest.reference = skipLodStencilReference;
stencilCommand.renderState = RenderState_default.fromCache(renderState);
if (use2D) {
stencilDerivedComand.derivedCommand2D.renderState = renderState;
}
}
}
function getLastSelectionDepth2(stencilCommand) {
const reference = stencilCommand.renderState.stencilTest.reference;
return (reference & StencilConstants_default.SKIP_LOD_MASK) >>> StencilConstants_default.SKIP_LOD_BIT_SHIFT;
}
function getStencilReference(selectionDepth) {
return StencilConstants_default.CESIUM_3D_TILE_MASK | selectionDepth << StencilConstants_default.SKIP_LOD_BIT_SHIFT;
}
function deriveSkipLodBackfaceCommand(command) {
const backfaceCommand = DrawCommand_default.shallowClone(command);
const renderState = clone_default(command.renderState, true);
renderState.cull.enabled = true;
renderState.cull.face = CullFace_default.FRONT;
renderState.colorMask = {
red: false,
green: false,
blue: false,
alpha: false
};
renderState.polygonOffset = {
enabled: true,
factor: 5,
units: 5
};
const uniformMap2 = clone_default(backfaceCommand.uniformMap);
const polygonOffset = new Cartesian2_default(5, 5);
uniformMap2.u_polygonOffset = function() {
return polygonOffset;
};
backfaceCommand.renderState = RenderState_default.fromCache(renderState);
backfaceCommand.uniformMap = uniformMap2;
backfaceCommand.castShadows = false;
backfaceCommand.receiveShadows = false;
return backfaceCommand;
}
function deriveSkipLodStencilCommand(command) {
const stencilCommand = DrawCommand_default.shallowClone(command);
const renderState = clone_default(command.renderState, true);
const { stencilTest } = renderState;
stencilTest.enabled = true;
stencilTest.mask = StencilConstants_default.SKIP_LOD_MASK;
stencilTest.reference = StencilConstants_default.CESIUM_3D_TILE_MASK;
stencilTest.frontFunction = StencilFunction_default.GREATER_OR_EQUAL;
stencilTest.frontOperation.zPass = StencilOperation_default.REPLACE;
stencilTest.backFunction = StencilFunction_default.GREATER_OR_EQUAL;
stencilTest.backOperation.zPass = StencilOperation_default.REPLACE;
renderState.stencilMask = StencilConstants_default.CESIUM_3D_TILE_MASK | StencilConstants_default.SKIP_LOD_MASK;
stencilCommand.renderState = RenderState_default.fromCache(renderState);
return stencilCommand;
}
var ModelDrawCommand_default = ModelDrawCommand;
// packages/engine/Source/Scene/Model/buildDrawCommand.js
function buildDrawCommand(primitiveRenderResources, frameState) {
const shaderBuilder = primitiveRenderResources.shaderBuilder;
shaderBuilder.addVertexLines(ModelVS_default);
shaderBuilder.addFragmentLines(ModelFS_default);
const indexBuffer = getIndexBuffer(primitiveRenderResources);
const vertexArray = new VertexArray_default({
context: frameState.context,
indexBuffer,
attributes: primitiveRenderResources.attributes
});
const model = primitiveRenderResources.model;
model._pipelineResources.push(vertexArray);
const shaderProgram = shaderBuilder.buildShaderProgram(frameState.context);
model._pipelineResources.push(shaderProgram);
const pass = primitiveRenderResources.alphaOptions.pass;
const sceneGraph = model.sceneGraph;
const is3D = frameState.mode === SceneMode_default.SCENE3D;
let modelMatrix, boundingSphere;
if (!is3D && !frameState.scene3DOnly && model._projectTo2D) {
modelMatrix = Matrix4_default.multiplyTransformation(
sceneGraph._computedModelMatrix,
primitiveRenderResources.runtimeNode.computedTransform,
new Matrix4_default()
);
const runtimePrimitive = primitiveRenderResources.runtimePrimitive;
boundingSphere = runtimePrimitive.boundingSphere2D;
} else {
const computedModelMatrix = is3D ? sceneGraph._computedModelMatrix : sceneGraph._computedModelMatrix2D;
modelMatrix = Matrix4_default.multiplyTransformation(
computedModelMatrix,
primitiveRenderResources.runtimeNode.computedTransform,
new Matrix4_default()
);
boundingSphere = BoundingSphere_default.transform(
primitiveRenderResources.boundingSphere,
modelMatrix,
primitiveRenderResources.boundingSphere
);
}
let renderState = clone_default(
RenderState_default.fromCache(primitiveRenderResources.renderStateOptions),
true
);
renderState.cull.face = ModelUtility_default.getCullFace(
modelMatrix,
primitiveRenderResources.primitiveType
);
renderState = RenderState_default.fromCache(renderState);
const hasClassification = defined_default(model.classificationType);
const castShadows = hasClassification ? false : ShadowMode_default.castShadows(model.shadows);
const receiveShadows = hasClassification ? false : ShadowMode_default.receiveShadows(model.shadows);
const pickId = hasClassification ? void 0 : primitiveRenderResources.pickId;
const command = new DrawCommand_default({
boundingVolume: boundingSphere,
modelMatrix,
uniformMap: primitiveRenderResources.uniformMap,
renderState,
vertexArray,
shaderProgram,
cull: model.cull,
pass,
count: primitiveRenderResources.count,
owner: model,
pickId,
instanceCount: primitiveRenderResources.instanceCount,
primitiveType: primitiveRenderResources.primitiveType,
debugShowBoundingVolume: model.debugShowBoundingVolume,
castShadows,
receiveShadows
});
if (hasClassification) {
return new ClassificationModelDrawCommand_default({
primitiveRenderResources,
command
});
}
return new ModelDrawCommand_default({
primitiveRenderResources,
command
});
}
function getIndexBuffer(primitiveRenderResources) {
const wireframeIndexBuffer = primitiveRenderResources.wireframeIndexBuffer;
if (defined_default(wireframeIndexBuffer)) {
return wireframeIndexBuffer;
}
const indices2 = primitiveRenderResources.indices;
if (!defined_default(indices2)) {
return void 0;
}
if (!defined_default(indices2.buffer)) {
throw new DeveloperError_default("Indices must be provided as a Buffer");
}
return indices2.buffer;
}
var buildDrawCommand_default = buildDrawCommand;
// packages/engine/Source/Scene/Model/TilesetPipelineStage.js
var TilesetPipelineStage = {
name: "TilesetPipelineStage"
// Helps with debugging
};
TilesetPipelineStage.process = function(renderResources, model, frameState) {
if (model.hasSkipLevelOfDetail(frameState)) {
const shaderBuilder = renderResources.shaderBuilder;
shaderBuilder.addDefine(
"POLYGON_OFFSET",
void 0,
ShaderDestination_default.FRAGMENT
);
const uniformMap2 = {
u_polygonOffset: function() {
return Cartesian2_default.ZERO;
}
};
renderResources.uniformMap = combine_default(
uniformMap2,
renderResources.uniformMap
);
renderResources.hasSkipLevelOfDetail = true;
}
const renderStateOptions = renderResources.renderStateOptions;
renderStateOptions.stencilTest = StencilConstants_default.setCesium3DTileBit();
renderStateOptions.stencilMask = StencilConstants_default.CESIUM_3D_TILE_MASK;
};
var TilesetPipelineStage_default = TilesetPipelineStage;
// packages/engine/Source/Shaders/Model/ImageBasedLightingStageFS.js
var ImageBasedLightingStageFS_default = "vec3 proceduralIBL(\n vec3 positionEC,\n vec3 normalEC,\n vec3 lightDirectionEC,\n vec3 lightColorHdr,\n czm_pbrParameters pbrParameters\n) {\n vec3 v = -positionEC;\n vec3 positionWC = vec3(czm_inverseView * vec4(positionEC, 1.0));\n vec3 vWC = -normalize(positionWC);\n vec3 l = normalize(lightDirectionEC);\n vec3 n = normalEC;\n vec3 r = normalize(czm_inverseViewRotation * normalize(reflect(v, n)));\n\n float NdotL = clamp(dot(n, l), 0.001, 1.0);\n float NdotV = abs(dot(n, v)) + 0.001;\n\n // Figure out if the reflection vector hits the ellipsoid\n float vertexRadius = length(positionWC);\n float horizonDotNadir = 1.0 - min(1.0, czm_ellipsoidRadii.x / vertexRadius);\n float reflectionDotNadir = dot(r, normalize(positionWC));\n // Flipping the X vector is a cheap way to get the inverse of czm_temeToPseudoFixed, since that's a rotation about Z.\n r.x = -r.x;\n r = -normalize(czm_temeToPseudoFixed * r);\n r.x = -r.x;\n\n vec3 diffuseColor = pbrParameters.diffuseColor;\n float roughness = pbrParameters.roughness;\n vec3 specularColor = pbrParameters.f0;\n\n float inverseRoughness = 1.04 - roughness;\n inverseRoughness *= inverseRoughness;\n vec3 sceneSkyBox = czm_textureCube(czm_environmentMap, r).rgb * inverseRoughness;\n\n float atmosphereHeight = 0.05;\n float blendRegionSize = 0.1 * ((1.0 - inverseRoughness) * 8.0 + 1.1 - horizonDotNadir);\n float blendRegionOffset = roughness * -1.0;\n float farAboveHorizon = clamp(horizonDotNadir - blendRegionSize * 0.5 + blendRegionOffset, 1.0e-10 - blendRegionSize, 0.99999);\n float aroundHorizon = clamp(horizonDotNadir + blendRegionSize * 0.5, 1.0e-10 - blendRegionSize, 0.99999);\n float farBelowHorizon = clamp(horizonDotNadir + blendRegionSize * 1.5, 1.0e-10 - blendRegionSize, 0.99999);\n float smoothstepHeight = smoothstep(0.0, atmosphereHeight, horizonDotNadir);\n vec3 belowHorizonColor = mix(vec3(0.1, 0.15, 0.25), vec3(0.4, 0.7, 0.9), smoothstepHeight);\n vec3 nadirColor = belowHorizonColor * 0.5;\n vec3 aboveHorizonColor = mix(vec3(0.9, 1.0, 1.2), belowHorizonColor, roughness * 0.5);\n vec3 blueSkyColor = mix(vec3(0.18, 0.26, 0.48), aboveHorizonColor, reflectionDotNadir * inverseRoughness * 0.5 + 0.75);\n vec3 zenithColor = mix(blueSkyColor, sceneSkyBox, smoothstepHeight);\n vec3 blueSkyDiffuseColor = vec3(0.7, 0.85, 0.9); \n float diffuseIrradianceFromEarth = (1.0 - horizonDotNadir) * (reflectionDotNadir * 0.25 + 0.75) * smoothstepHeight; \n float diffuseIrradianceFromSky = (1.0 - smoothstepHeight) * (1.0 - (reflectionDotNadir * 0.25 + 0.25));\n vec3 diffuseIrradiance = blueSkyDiffuseColor * clamp(diffuseIrradianceFromEarth + diffuseIrradianceFromSky, 0.0, 1.0);\n float notDistantRough = (1.0 - horizonDotNadir * roughness * 0.8);\n vec3 specularIrradiance = mix(zenithColor, aboveHorizonColor, smoothstep(farAboveHorizon, aroundHorizon, reflectionDotNadir) * notDistantRough);\n specularIrradiance = mix(specularIrradiance, belowHorizonColor, smoothstep(aroundHorizon, farBelowHorizon, reflectionDotNadir) * inverseRoughness);\n specularIrradiance = mix(specularIrradiance, nadirColor, smoothstep(farBelowHorizon, 1.0, reflectionDotNadir) * inverseRoughness);\n\n // Luminance model from page 40 of http://silviojemma.com/public/papers/lighting/spherical-harmonic-lighting.pdf\n #ifdef USE_SUN_LUMINANCE \n // Angle between sun and zenith\n float LdotZenith = clamp(dot(normalize(czm_inverseViewRotation * l), vWC), 0.001, 1.0);\n float S = acos(LdotZenith);\n // Angle between zenith and current pixel\n float NdotZenith = clamp(dot(normalize(czm_inverseViewRotation * n), vWC), 0.001, 1.0);\n // Angle between sun and current pixel\n float gamma = acos(NdotL);\n float numerator = ((0.91 + 10.0 * exp(-3.0 * gamma) + 0.45 * pow(NdotL, 2.0)) * (1.0 - exp(-0.32 / NdotZenith)));\n float denominator = (0.91 + 10.0 * exp(-3.0 * S) + 0.45 * pow(LdotZenith,2.0)) * (1.0 - exp(-0.32));\n float luminance = model_luminanceAtZenith * (numerator / denominator);\n #endif \n\n vec2 brdfLut = texture(czm_brdfLut, vec2(NdotV, roughness)).rg;\n vec3 iblColor = (diffuseIrradiance * diffuseColor * model_iblFactor.x) + (specularIrradiance * czm_srgbToLinear(specularColor * brdfLut.x + brdfLut.y) * model_iblFactor.y);\n float maximumComponent = max(max(lightColorHdr.x, lightColorHdr.y), lightColorHdr.z);\n vec3 lightColor = lightColorHdr / max(maximumComponent, 1.0);\n iblColor *= lightColor;\n\n #ifdef USE_SUN_LUMINANCE \n iblColor *= luminance;\n #endif\n\n return iblColor;\n}\n\n#if defined(DIFFUSE_IBL) || defined(SPECULAR_IBL)\nvec3 textureIBL(\n vec3 positionEC,\n vec3 normalEC,\n vec3 lightDirectionEC,\n czm_pbrParameters pbrParameters\n) {\n vec3 diffuseColor = pbrParameters.diffuseColor;\n float roughness = pbrParameters.roughness;\n vec3 specularColor = pbrParameters.f0;\n\n vec3 v = -positionEC;\n vec3 n = normalEC;\n vec3 l = normalize(lightDirectionEC);\n vec3 h = normalize(v + l);\n\n float NdotV = abs(dot(n, v)) + 0.001;\n float VdotH = clamp(dot(v, h), 0.0, 1.0);\n\n const mat3 yUpToZUp = mat3(\n -1.0, 0.0, 0.0,\n 0.0, 0.0, -1.0, \n 0.0, 1.0, 0.0\n ); \n vec3 cubeDir = normalize(yUpToZUp * model_iblReferenceFrameMatrix * normalize(reflect(-v, n))); \n\n #ifdef DIFFUSE_IBL \n #ifdef CUSTOM_SPHERICAL_HARMONICS\n vec3 diffuseIrradiance = czm_sphericalHarmonics(cubeDir, model_sphericalHarmonicCoefficients); \n #else\n vec3 diffuseIrradiance = czm_sphericalHarmonics(cubeDir, czm_sphericalHarmonicCoefficients); \n #endif \n #else \n vec3 diffuseIrradiance = vec3(0.0); \n #endif \n\n #ifdef SPECULAR_IBL\n vec3 r0 = specularColor.rgb;\n float reflectance = max(max(r0.r, r0.g), r0.b);\n vec3 r90 = vec3(clamp(reflectance * 25.0, 0.0, 1.0));\n vec3 F = fresnelSchlick2(r0, r90, VdotH);\n \n vec2 brdfLut = texture(czm_brdfLut, vec2(NdotV, roughness)).rg;\n #ifdef CUSTOM_SPECULAR_IBL \n vec3 specularIBL = czm_sampleOctahedralProjection(model_specularEnvironmentMaps, model_specularEnvironmentMapsSize, cubeDir, roughness * model_specularEnvironmentMapsMaximumLOD, model_specularEnvironmentMapsMaximumLOD);\n #else \n vec3 specularIBL = czm_sampleOctahedralProjection(czm_specularEnvironmentMaps, czm_specularEnvironmentMapSize, cubeDir, roughness * czm_specularEnvironmentMapsMaximumLOD, czm_specularEnvironmentMapsMaximumLOD);\n #endif \n specularIBL *= F * brdfLut.x + brdfLut.y;\n #else \n vec3 specularIBL = vec3(0.0); \n #endif\n\n return diffuseColor * diffuseIrradiance + specularColor * specularIBL;\n}\n#endif\n\nvec3 imageBasedLightingStage(\n vec3 positionEC,\n vec3 normalEC,\n vec3 lightDirectionEC,\n vec3 lightColorHdr,\n czm_pbrParameters pbrParameters\n) {\n #if defined(DIFFUSE_IBL) || defined(SPECULAR_IBL)\n // Environment maps were provided, use them for IBL\n return textureIBL(\n positionEC,\n normalEC,\n lightDirectionEC,\n pbrParameters\n );\n #else\n // Use the procedural IBL if there are no environment maps\n return proceduralIBL(\n positionEC,\n normalEC,\n lightDirectionEC,\n lightColorHdr,\n pbrParameters\n );\n #endif\n}";
// packages/engine/Source/Scene/Model/ImageBasedLightingPipelineStage.js
var ImageBasedLightingPipelineStage = {
name: "ImageBasedLightingPipelineStage"
// Helps with debugging
};
ImageBasedLightingPipelineStage.process = function(renderResources, model, frameState) {
const imageBasedLighting = model.imageBasedLighting;
const shaderBuilder = renderResources.shaderBuilder;
shaderBuilder.addDefine(
"USE_IBL_LIGHTING",
void 0,
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addUniform(
"vec2",
"model_iblFactor",
ShaderDestination_default.FRAGMENT
);
if (OctahedralProjectedCubeMap_default.isSupported(frameState.context)) {
const addMatrix = imageBasedLighting.useSphericalHarmonics || imageBasedLighting.useSpecularEnvironmentMaps || imageBasedLighting.enabled;
if (addMatrix) {
shaderBuilder.addUniform(
"mat3",
"model_iblReferenceFrameMatrix",
ShaderDestination_default.FRAGMENT
);
}
if (defined_default(imageBasedLighting.sphericalHarmonicCoefficients)) {
shaderBuilder.addDefine(
"DIFFUSE_IBL",
void 0,
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addDefine(
"CUSTOM_SPHERICAL_HARMONICS",
void 0,
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addUniform(
"vec3",
"model_sphericalHarmonicCoefficients[9]",
ShaderDestination_default.FRAGMENT
);
} else if (imageBasedLighting.useDefaultSphericalHarmonics) {
shaderBuilder.addDefine(
"DIFFUSE_IBL",
void 0,
ShaderDestination_default.FRAGMENT
);
}
if (defined_default(imageBasedLighting.specularEnvironmentMapAtlas) && imageBasedLighting.specularEnvironmentMapAtlas.ready) {
shaderBuilder.addDefine(
"SPECULAR_IBL",
void 0,
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addDefine(
"CUSTOM_SPECULAR_IBL",
void 0,
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addUniform(
"sampler2D",
"model_specularEnvironmentMaps",
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addUniform(
"vec2",
"model_specularEnvironmentMapsSize",
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addUniform(
"float",
"model_specularEnvironmentMapsMaximumLOD",
ShaderDestination_default.FRAGMENT
);
} else if (model.useDefaultSpecularMaps) {
shaderBuilder.addDefine(
"SPECULAR_IBL",
void 0,
ShaderDestination_default.FRAGMENT
);
}
}
if (defined_default(imageBasedLighting.luminanceAtZenith)) {
shaderBuilder.addDefine(
"USE_SUN_LUMINANCE",
void 0,
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addUniform(
"float",
"model_luminanceAtZenith",
ShaderDestination_default.FRAGMENT
);
}
shaderBuilder.addFragmentLines(ImageBasedLightingStageFS_default);
const uniformMap2 = {
model_iblFactor: function() {
return imageBasedLighting.imageBasedLightingFactor;
},
model_iblReferenceFrameMatrix: function() {
return model._iblReferenceFrameMatrix;
},
model_luminanceAtZenith: function() {
return imageBasedLighting.luminanceAtZenith;
},
model_sphericalHarmonicCoefficients: function() {
return imageBasedLighting.sphericalHarmonicCoefficients;
},
model_specularEnvironmentMaps: function() {
return imageBasedLighting.specularEnvironmentMapAtlas.texture;
},
model_specularEnvironmentMapsSize: function() {
return imageBasedLighting.specularEnvironmentMapAtlas.texture.dimensions;
},
model_specularEnvironmentMapsMaximumLOD: function() {
return imageBasedLighting.specularEnvironmentMapAtlas.maximumMipmapLevel;
}
};
renderResources.uniformMap = combine_default(uniformMap2, renderResources.uniformMap);
};
var ImageBasedLightingPipelineStage_default = ImageBasedLightingPipelineStage;
// packages/engine/Source/Scene/Model/ModelArticulationStage.js
var articulationEpsilon = Math_default.EPSILON16;
function ModelArticulationStage(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const stage = options.stage;
const runtimeArticulation = options.runtimeArticulation;
Check_default.typeOf.object("options.stage", stage);
Check_default.typeOf.object("options.runtimeArticulation", runtimeArticulation);
this._stage = stage;
this._runtimeArticulation = runtimeArticulation;
this._name = stage.name;
this._type = stage.type;
this._minimumValue = stage.minimumValue;
this._maximumValue = stage.maximumValue;
this._currentValue = stage.initialValue;
}
Object.defineProperties(ModelArticulationStage.prototype, {
/**
* The internal articulation stage that this runtime stage represents.
*
* @memberof ModelArticulationStage.prototype
* @type {ModelComponents.ArticulationStage}
* @readonly
*
* @private
*/
stage: {
get: function() {
return this._stage;
}
},
/**
* The runtime articulation that this stage belongs to.
*
* @memberof ModelArticulationStage.prototype
* @type {ModelArticulation}
* @readonly
*
* @private
*/
runtimeArticulation: {
get: function() {
return this._runtimeArticulation;
}
},
/**
* The name of this articulation stage.
*
* @memberof ModelArticulationStage.prototype
* @type {string}
* @readonly
*
* @private
*/
name: {
get: function() {
return this._name;
}
},
/**
* The type of this articulation stage. This specifies which of the
* node's properties is modified by the stage's value.
*
* @memberof ModelArticulationStage.prototype
* @type {ArticulationStageType}
* @readonly
*
* @private
*/
type: {
get: function() {
return this._type;
}
},
/**
* The minimum value of this articulation stage.
*
* @memberof ModelArticulationStage.prototype
* @type {number}
* @readonly
*
* @private
*/
minimumValue: {
get: function() {
return this._minimumValue;
}
},
/**
* The maximum value of this articulation stage.
*
* @memberof ModelArticulationStage.prototype
* @type {number}
* @readonly
*
* @private
*/
maximumValue: {
get: function() {
return this._maximumValue;
}
},
/**
* The current value of this articulation stage.
*
* @memberof ModelArticulationStage.prototype
* @type {number}
*
* @private
*/
currentValue: {
get: function() {
return this._currentValue;
},
set: function(value) {
Check_default.typeOf.number("value", value);
value = Math_default.clamp(value, this.minimumValue, this.maximumValue);
if (!Math_default.equalsEpsilon(
this._currentValue,
value,
articulationEpsilon
)) {
this._currentValue = value;
this.runtimeArticulation._dirty = true;
}
}
}
});
var scratchArticulationCartesian = new Cartesian3_default();
var scratchArticulationRotation = new Matrix3_default();
ModelArticulationStage.prototype.applyStageToMatrix = function(result) {
Check_default.typeOf.object("result", result);
const type = this.type;
const value = this.currentValue;
const cartesian11 = scratchArticulationCartesian;
let rotation;
switch (type) {
case ArticulationStageType_default.XROTATE:
rotation = Matrix3_default.fromRotationX(
Math_default.toRadians(value),
scratchArticulationRotation
);
result = Matrix4_default.multiplyByMatrix3(result, rotation, result);
break;
case ArticulationStageType_default.YROTATE:
rotation = Matrix3_default.fromRotationY(
Math_default.toRadians(value),
scratchArticulationRotation
);
result = Matrix4_default.multiplyByMatrix3(result, rotation, result);
break;
case ArticulationStageType_default.ZROTATE:
rotation = Matrix3_default.fromRotationZ(
Math_default.toRadians(value),
scratchArticulationRotation
);
result = Matrix4_default.multiplyByMatrix3(result, rotation, result);
break;
case ArticulationStageType_default.XTRANSLATE:
cartesian11.x = value;
cartesian11.y = 0;
cartesian11.z = 0;
result = Matrix4_default.multiplyByTranslation(result, cartesian11, result);
break;
case ArticulationStageType_default.YTRANSLATE:
cartesian11.x = 0;
cartesian11.y = value;
cartesian11.z = 0;
result = Matrix4_default.multiplyByTranslation(result, cartesian11, result);
break;
case ArticulationStageType_default.ZTRANSLATE:
cartesian11.x = 0;
cartesian11.y = 0;
cartesian11.z = value;
result = Matrix4_default.multiplyByTranslation(result, cartesian11, result);
break;
case ArticulationStageType_default.XSCALE:
cartesian11.x = value;
cartesian11.y = 1;
cartesian11.z = 1;
result = Matrix4_default.multiplyByScale(result, cartesian11, result);
break;
case ArticulationStageType_default.YSCALE:
cartesian11.x = 1;
cartesian11.y = value;
cartesian11.z = 1;
result = Matrix4_default.multiplyByScale(result, cartesian11, result);
break;
case ArticulationStageType_default.ZSCALE:
cartesian11.x = 1;
cartesian11.y = 1;
cartesian11.z = value;
result = Matrix4_default.multiplyByScale(result, cartesian11, result);
break;
case ArticulationStageType_default.UNIFORMSCALE:
result = Matrix4_default.multiplyByUniformScale(result, value, result);
break;
default:
break;
}
return result;
};
var ModelArticulationStage_default = ModelArticulationStage;
// packages/engine/Source/Scene/Model/ModelArticulation.js
function ModelArticulation(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const articulation = options.articulation;
const sceneGraph = options.sceneGraph;
Check_default.typeOf.object("options.articulation", articulation);
Check_default.typeOf.object("options.sceneGraph", sceneGraph);
this._articulation = articulation;
this._sceneGraph = sceneGraph;
this._name = articulation.name;
this._runtimeStages = [];
this._runtimeStagesByName = {};
this._runtimeNodes = [];
this._dirty = true;
initialize11(this);
}
Object.defineProperties(ModelArticulation.prototype, {
/**
* The internal articulation that this runtime articulation represents.
*
* @memberof ModelArticulation.prototype
* @type {ModelComponents.Articulation}
* @readonly
*
* @private
*/
articulation: {
get: function() {
return this._articulation;
}
},
/**
* The scene graph that this articulation belongs to.
*
* @memberof ModelArticulation.prototype
* @type {ModelSceneGraph}
* @readonly
*
* @private
*/
sceneGraph: {
get: function() {
return this._sceneGraph;
}
},
/**
* The name of this articulation.
*
* @memberof ModelArticulation.prototype
* @type {string}
* @readonly
*
* @private
*/
name: {
get: function() {
return this._name;
}
},
/**
* The runtime stages that belong to this articulation.
*
* @memberof ModelArticulation.prototype
* @type {ModelArticulationStage[]}
* @readonly
*
* @private
*/
runtimeStages: {
get: function() {
return this._runtimeStages;
}
},
/**
* The runtime nodes that are affected by this articulation.
*
* @memberof ModelArticulation.prototype
* @type {ModelRuntimeNode[]}
* @readonly
*
* @private
*/
runtimeNodes: {
get: function() {
return this._runtimeNodes;
}
}
});
function initialize11(runtimeArticulation) {
const articulation = runtimeArticulation.articulation;
const stages = articulation.stages;
const length3 = stages.length;
const runtimeStages = runtimeArticulation._runtimeStages;
const runtimeStagesByName = runtimeArticulation._runtimeStagesByName;
for (let i = 0; i < length3; i++) {
const stage = stages[i];
const runtimeStage = new ModelArticulationStage_default({
stage,
runtimeArticulation
});
runtimeStages.push(runtimeStage);
const stageName = stage.name;
runtimeStagesByName[stageName] = runtimeStage;
}
}
ModelArticulation.prototype.setArticulationStage = function(stageName, value) {
const stage = this._runtimeStagesByName[stageName];
if (defined_default(stage)) {
stage.currentValue = value;
}
};
var scratchArticulationMatrix = new Matrix4_default();
var scratchNodeMatrix = new Matrix4_default();
ModelArticulation.prototype.apply = function() {
if (!this._dirty) {
return;
}
this._dirty = false;
let articulationMatrix = Matrix4_default.clone(
Matrix4_default.IDENTITY,
scratchArticulationMatrix
);
let i;
const stages = this._runtimeStages;
const stagesLength = stages.length;
for (i = 0; i < stagesLength; i++) {
const stage = stages[i];
articulationMatrix = stage.applyStageToMatrix(articulationMatrix);
}
const nodes = this._runtimeNodes;
const nodesLength = nodes.length;
for (i = 0; i < nodesLength; i++) {
const node = nodes[i];
const transform3 = Matrix4_default.multiplyTransformation(
node.originalTransform,
articulationMatrix,
scratchNodeMatrix
);
node.transform = transform3;
}
};
var ModelArticulation_default = ModelArticulation;
// packages/engine/Source/Shaders/Model/ModelColorStageFS.js
var ModelColorStageFS_default = "void modelColorStage(inout czm_modelMaterial material)\n{\n material.diffuse = mix(material.diffuse, model_color.rgb, model_colorBlend);\n float highlight = ceil(model_colorBlend);\n material.diffuse *= mix(model_color.rgb, vec3(1.0), highlight);\n material.alpha *= model_color.a;\n}";
// packages/engine/Source/Scene/Model/ModelColorPipelineStage.js
var ModelColorPipelineStage = {
name: "ModelColorPipelineStage",
// Helps with debugging
COLOR_UNIFORM_NAME: "model_color",
COLOR_BLEND_UNIFORM_NAME: "model_colorBlend"
};
ModelColorPipelineStage.process = function(renderResources, model, frameState) {
const shaderBuilder = renderResources.shaderBuilder;
shaderBuilder.addDefine(
"HAS_MODEL_COLOR",
void 0,
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addFragmentLines(ModelColorStageFS_default);
const stageUniforms = {};
const color = model.color;
if (color.alpha === 0 && !model.hasSilhouette(frameState)) {
renderResources.renderStateOptions.colorMask = {
red: false,
green: false,
blue: false,
alpha: false
};
}
if (color.alpha < 1) {
renderResources.alphaOptions.pass = Pass_default.TRANSLUCENT;
}
shaderBuilder.addUniform(
"vec4",
ModelColorPipelineStage.COLOR_UNIFORM_NAME,
ShaderDestination_default.FRAGMENT
);
stageUniforms[ModelColorPipelineStage.COLOR_UNIFORM_NAME] = function() {
return model.color;
};
shaderBuilder.addUniform(
"float",
ModelColorPipelineStage.COLOR_BLEND_UNIFORM_NAME,
ShaderDestination_default.FRAGMENT
);
stageUniforms[ModelColorPipelineStage.COLOR_BLEND_UNIFORM_NAME] = function() {
return ColorBlendMode_default.getColorBlend(
model.colorBlendMode,
model.colorBlendAmount
);
};
renderResources.uniformMap = combine_default(
stageUniforms,
renderResources.uniformMap
);
};
var ModelColorPipelineStage_default = ModelColorPipelineStage;
// packages/engine/Source/Shaders/Model/ModelClippingPlanesStageFS.js
var ModelClippingPlanesStageFS_default = "#ifdef USE_CLIPPING_PLANES_FLOAT_TEXTURE\nvec4 getClippingPlane(\n highp sampler2D packedClippingPlanes,\n int clippingPlaneNumber,\n mat4 transform\n) {\n int pixY = clippingPlaneNumber / CLIPPING_PLANES_TEXTURE_WIDTH;\n int pixX = clippingPlaneNumber - (pixY * CLIPPING_PLANES_TEXTURE_WIDTH);\n float pixelWidth = 1.0 / float(CLIPPING_PLANES_TEXTURE_WIDTH);\n float pixelHeight = 1.0 / float(CLIPPING_PLANES_TEXTURE_HEIGHT);\n float u = (float(pixX) + 0.5) * pixelWidth; // sample from center of pixel\n float v = (float(pixY) + 0.5) * pixelHeight;\n vec4 plane = texture(packedClippingPlanes, vec2(u, v));\n return czm_transformPlane(plane, transform);\n}\n#else\n// Handle uint8 clipping texture instead\nvec4 getClippingPlane(\n highp sampler2D packedClippingPlanes,\n int clippingPlaneNumber,\n mat4 transform\n) {\n int clippingPlaneStartIndex = clippingPlaneNumber * 2; // clipping planes are two pixels each\n int pixY = clippingPlaneStartIndex / CLIPPING_PLANES_TEXTURE_WIDTH;\n int pixX = clippingPlaneStartIndex - (pixY * CLIPPING_PLANES_TEXTURE_WIDTH);\n float pixelWidth = 1.0 / float(CLIPPING_PLANES_TEXTURE_WIDTH);\n float pixelHeight = 1.0 / float(CLIPPING_PLANES_TEXTURE_HEIGHT);\n float u = (float(pixX) + 0.5) * pixelWidth; // sample from center of pixel\n float v = (float(pixY) + 0.5) * pixelHeight;\n vec4 oct32 = texture(packedClippingPlanes, vec2(u, v)) * 255.0;\n vec2 oct = vec2(oct32.x * 256.0 + oct32.y, oct32.z * 256.0 + oct32.w);\n vec4 plane;\n plane.xyz = czm_octDecode(oct, 65535.0);\n plane.w = czm_unpackFloat(texture(packedClippingPlanes, vec2(u + pixelWidth, v)));\n return czm_transformPlane(plane, transform);\n}\n#endif\n\nfloat clip(vec4 fragCoord, sampler2D clippingPlanes, mat4 clippingPlanesMatrix) {\n vec4 position = czm_windowToEyeCoordinates(fragCoord);\n vec3 clipNormal = vec3(0.0);\n vec3 clipPosition = vec3(0.0);\n float pixelWidth = czm_metersPerPixel(position);\n \n #ifdef UNION_CLIPPING_REGIONS\n float clipAmount; // For union planes, we want to get the min distance. So we set the initial value to the first plane distance in the loop below.\n #else\n float clipAmount = 0.0;\n bool clipped = true;\n #endif\n\n for (int i = 0; i < CLIPPING_PLANES_LENGTH; ++i) {\n vec4 clippingPlane = getClippingPlane(clippingPlanes, i, clippingPlanesMatrix);\n clipNormal = clippingPlane.xyz;\n clipPosition = -clippingPlane.w * clipNormal;\n float amount = dot(clipNormal, (position.xyz - clipPosition)) / pixelWidth;\n \n #ifdef UNION_CLIPPING_REGIONS\n clipAmount = czm_branchFreeTernary(i == 0, amount, min(amount, clipAmount));\n if (amount <= 0.0) {\n discard;\n }\n #else\n clipAmount = max(amount, clipAmount);\n clipped = clipped && (amount <= 0.0);\n #endif\n }\n\n #ifndef UNION_CLIPPING_REGIONS\n if (clipped) {\n discard;\n }\n #endif\n \n return clipAmount;\n}\n\nvoid modelClippingPlanesStage(inout vec4 color)\n{\n float clipDistance = clip(gl_FragCoord, model_clippingPlanes, model_clippingPlanesMatrix);\n vec4 clippingPlanesEdgeColor = vec4(1.0);\n clippingPlanesEdgeColor.rgb = model_clippingPlanesEdgeStyle.rgb;\n float clippingPlanesEdgeWidth = model_clippingPlanesEdgeStyle.a;\n \n if (clipDistance > 0.0 && clipDistance < clippingPlanesEdgeWidth) {\n color = clippingPlanesEdgeColor;\n }\n}\n";
// packages/engine/Source/Scene/Model/ModelClippingPlanesPipelineStage.js
var ModelClippingPlanesPipelineStage = {
name: "ModelClippingPlanesPipelineStage"
// Helps with debugging
};
var textureResolutionScratch2 = new Cartesian2_default();
ModelClippingPlanesPipelineStage.process = function(renderResources, model, frameState) {
const clippingPlanes = model.clippingPlanes;
const context = frameState.context;
const shaderBuilder = renderResources.shaderBuilder;
shaderBuilder.addDefine(
"HAS_CLIPPING_PLANES",
void 0,
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addDefine(
"CLIPPING_PLANES_LENGTH",
clippingPlanes.length,
ShaderDestination_default.FRAGMENT
);
if (clippingPlanes.unionClippingRegions) {
shaderBuilder.addDefine(
"UNION_CLIPPING_REGIONS",
void 0,
ShaderDestination_default.FRAGMENT
);
}
if (ClippingPlaneCollection_default.useFloatTexture(context)) {
shaderBuilder.addDefine(
"USE_CLIPPING_PLANES_FLOAT_TEXTURE",
void 0,
ShaderDestination_default.FRAGMENT
);
}
const textureResolution = ClippingPlaneCollection_default.getTextureResolution(
clippingPlanes,
context,
textureResolutionScratch2
);
shaderBuilder.addDefine(
"CLIPPING_PLANES_TEXTURE_WIDTH",
textureResolution.x,
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addDefine(
"CLIPPING_PLANES_TEXTURE_HEIGHT",
textureResolution.y,
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addUniform(
"sampler2D",
"model_clippingPlanes",
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addUniform(
"vec4",
"model_clippingPlanesEdgeStyle",
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addUniform(
"mat4",
"model_clippingPlanesMatrix",
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addFragmentLines(ModelClippingPlanesStageFS_default);
const uniformMap2 = {
model_clippingPlanes: function() {
return clippingPlanes.texture;
},
model_clippingPlanesEdgeStyle: function() {
const style = Color_default.clone(clippingPlanes.edgeColor);
style.alpha = clippingPlanes.edgeWidth;
return style;
},
model_clippingPlanesMatrix: function() {
return model._clippingPlanesMatrix;
}
};
renderResources.uniformMap = combine_default(uniformMap2, renderResources.uniformMap);
};
var ModelClippingPlanesPipelineStage_default = ModelClippingPlanesPipelineStage;
// packages/engine/Source/Scene/Model/ModelNode.js
function ModelNode(model, runtimeNode) {
Check_default.typeOf.object("model", model);
Check_default.typeOf.object("runtimeNode", runtimeNode);
this._model = model;
this._runtimeNode = runtimeNode;
}
Object.defineProperties(ModelNode.prototype, {
/**
* The value of the name
property of this node.
*
* @memberof ModelNode.prototype
*
* @type {string}
* @readonly
*/
name: {
get: function() {
return this._runtimeNode._name;
}
},
/**
* The index of the node in the glTF.
*
* @memberof ModelNode.prototype
*
* @type {number}
* @readonly
*/
id: {
get: function() {
return this._runtimeNode._id;
}
},
/**
* Determines if this node and its children will be shown.
*
* @memberof ModelNode.prototype
* @type {boolean}
*
* @default true
*/
show: {
get: function() {
return this._runtimeNode.show;
},
set: function(value) {
this._runtimeNode.show = value;
}
},
/**
* The node's 4x4 matrix transform from its local coordinates to
* its parent's. Setting the matrix to undefined will restore the
* node's original transform, and allow the node to be animated by
* any animations in the model again.
* * For changes to take effect, this property must be assigned to; * setting individual elements of the matrix will not work. *
* * @memberof ModelNode.prototype * @type {Matrix4} */ matrix: { get: function() { return this._runtimeNode.transform; }, set: function(value) { if (defined_default(value)) { this._runtimeNode.transform = value; this._runtimeNode.userAnimated = true; this._model._userAnimationDirty = true; } else { this._runtimeNode.transform = this.originalMatrix; this._runtimeNode.userAnimated = false; } } }, /** * Gets the node's original 4x4 matrix transform from its local * coordinates to its parent's, without any node transformations * or articulations applied. * * @memberof ModelNode.prototype * @type {Matrix4} */ originalMatrix: { get: function() { return this._runtimeNode.originalTransform; } } }); var ModelNode_default = ModelNode; // packages/engine/Source/Shaders/Model/InstancingStageCommon.js var InstancingStageCommon_default = "mat4 getInstancingTransform()\n{\n mat4 instancingTransform;\n\n #ifdef HAS_INSTANCE_MATRICES\n instancingTransform = mat4(\n a_instancingTransformRow0.x, a_instancingTransformRow1.x, a_instancingTransformRow2.x, 0.0, // Column 1\n a_instancingTransformRow0.y, a_instancingTransformRow1.y, a_instancingTransformRow2.y, 0.0, // Column 2\n a_instancingTransformRow0.z, a_instancingTransformRow1.z, a_instancingTransformRow2.z, 0.0, // Column 3\n a_instancingTransformRow0.w, a_instancingTransformRow1.w, a_instancingTransformRow2.w, 1.0 // Column 4\n );\n #else\n vec3 translation = vec3(0.0, 0.0, 0.0);\n vec3 scale = vec3(1.0, 1.0, 1.0);\n \n #ifdef HAS_INSTANCE_TRANSLATION\n translation = a_instanceTranslation;\n #endif\n #ifdef HAS_INSTANCE_SCALE\n scale = a_instanceScale;\n #endif\n\n instancingTransform = mat4(\n scale.x, 0.0, 0.0, 0.0,\n 0.0, scale.y, 0.0, 0.0,\n 0.0, 0.0, scale.z, 0.0,\n translation.x, translation.y, translation.z, 1.0\n ); \n #endif\n\n return instancingTransform;\n}\n\n#ifdef USE_2D_INSTANCING\nmat4 getInstancingTransform2D()\n{\n mat4 instancingTransform2D;\n\n #ifdef HAS_INSTANCE_MATRICES\n instancingTransform2D = mat4(\n a_instancingTransform2DRow0.x, a_instancingTransform2DRow1.x, a_instancingTransform2DRow2.x, 0.0, // Column 1\n a_instancingTransform2DRow0.y, a_instancingTransform2DRow1.y, a_instancingTransform2DRow2.y, 0.0, // Column 2\n a_instancingTransform2DRow0.z, a_instancingTransform2DRow1.z, a_instancingTransform2DRow2.z, 0.0, // Column 3\n a_instancingTransform2DRow0.w, a_instancingTransform2DRow1.w, a_instancingTransform2DRow2.w, 1.0 // Column 4\n );\n #else\n vec3 translation2D = vec3(0.0, 0.0, 0.0);\n vec3 scale = vec3(1.0, 1.0, 1.0);\n \n #ifdef HAS_INSTANCE_TRANSLATION\n translation2D = a_instanceTranslation2D;\n #endif\n #ifdef HAS_INSTANCE_SCALE\n scale = a_instanceScale;\n #endif\n\n instancingTransform2D = mat4(\n scale.x, 0.0, 0.0, 0.0,\n 0.0, scale.y, 0.0, 0.0,\n 0.0, 0.0, scale.z, 0.0,\n translation2D.x, translation2D.y, translation2D.z, 1.0\n ); \n #endif\n\n return instancingTransform2D;\n}\n#endif\n"; // packages/engine/Source/Shaders/Model/InstancingStageVS.js var InstancingStageVS_default = "void instancingStage(inout ProcessedAttributes attributes) \n{\n vec3 positionMC = attributes.positionMC;\n \n mat4 instancingTransform = getInstancingTransform();\n \n attributes.positionMC = (instancingTransform * vec4(positionMC, 1.0)).xyz;\n\n #ifdef HAS_NORMALS\n vec3 normalMC = attributes.normalMC;\n attributes.normalMC = (instancingTransform * vec4(normalMC, 0.0)).xyz;\n #endif\n\n #ifdef USE_2D_INSTANCING\n mat4 instancingTransform2D = getInstancingTransform2D();\n attributes.position2D = (instancingTransform2D * vec4(positionMC, 1.0)).xyz;\n #endif\n}\n"; // packages/engine/Source/Shaders/Model/LegacyInstancingStageVS.js var LegacyInstancingStageVS_default = "void legacyInstancingStage(\n inout ProcessedAttributes attributes,\n out mat4 instanceModelView,\n out mat3 instanceModelViewInverseTranspose)\n{\n vec3 positionMC = attributes.positionMC;\n\n mat4 instancingTransform = getInstancingTransform();\n \n mat4 instanceModel = instancingTransform * u_instance_nodeTransform;\n instanceModelView = u_instance_modifiedModelView;\n instanceModelViewInverseTranspose = mat3(u_instance_modifiedModelView * instanceModel);\n\n attributes.positionMC = (instanceModel * vec4(positionMC, 1.0)).xyz;\n \n #ifdef USE_2D_INSTANCING\n mat4 instancingTransform2D = getInstancingTransform2D();\n attributes.position2D = (instancingTransform2D * vec4(positionMC, 1.0)).xyz;\n #endif\n}\n"; // packages/engine/Source/Scene/Model/InstancingPipelineStage.js var modelViewScratch = new Matrix4_default(); var nodeTransformScratch = new Matrix4_default(); var modelView2DScratch = new Matrix4_default(); var InstancingPipelineStage = { name: "InstancingPipelineStage", // Helps with debugging // Expose some methods for testing _getInstanceTransformsAsMatrices: getInstanceTransformsAsMatrices, _transformsToTypedArray: transformsToTypedArray }; InstancingPipelineStage.process = function(renderResources, node, frameState) { const instances = node.instances; const count = instances.attributes[0].count; const shaderBuilder = renderResources.shaderBuilder; shaderBuilder.addDefine("HAS_INSTANCING"); shaderBuilder.addVertexLines(InstancingStageCommon_default); const model = renderResources.model; const sceneGraph = model.sceneGraph; const runtimeNode = renderResources.runtimeNode; const use2D = frameState.mode !== SceneMode_default.SCENE3D && !frameState.scene3DOnly && model._projectTo2D; const instancingVertexAttributes = []; processTransformAttributes( renderResources, frameState, instances, instancingVertexAttributes, use2D ); processFeatureIdAttributes( renderResources, frameState, instances, instancingVertexAttributes ); const uniformMap2 = {}; if (instances.transformInWorldSpace) { shaderBuilder.addDefine( "USE_LEGACY_INSTANCING", void 0, ShaderDestination_default.VERTEX ); shaderBuilder.addUniform( "mat4", "u_instance_modifiedModelView", ShaderDestination_default.VERTEX ); shaderBuilder.addUniform( "mat4", "u_instance_nodeTransform", ShaderDestination_default.VERTEX ); uniformMap2.u_instance_modifiedModelView = function() { let modifiedModelMatrix = Matrix4_default.multiplyTransformation( // For 3D Tiles, model.modelMatrix is the computed tile // transform (which includes tileset.modelMatrix). This always applies // for i3dm, since such models are always part of a tileset. model.modelMatrix, // For i3dm models, components.transform contains the RTC_CENTER // translation. sceneGraph.components.transform, modelViewScratch ); if (use2D) { return Matrix4_default.multiplyTransformation( frameState.context.uniformState.view3D, modifiedModelMatrix, modelViewScratch ); } if (frameState.mode !== SceneMode_default.SCENE3D) { modifiedModelMatrix = Transforms_default.basisTo2D( frameState.mapProjection, modifiedModelMatrix, modelViewScratch ); } return Matrix4_default.multiplyTransformation( frameState.context.uniformState.view, modifiedModelMatrix, modelViewScratch ); }; uniformMap2.u_instance_nodeTransform = function() { return Matrix4_default.multiplyTransformation( // glTF y-up to 3D Tiles z-up sceneGraph.axisCorrectionMatrix, // This transforms from the node's coordinate system to the root // of the node hierarchy runtimeNode.computedTransform, nodeTransformScratch ); }; shaderBuilder.addVertexLines(LegacyInstancingStageVS_default); } else { shaderBuilder.addVertexLines(InstancingStageVS_default); } if (use2D) { shaderBuilder.addDefine( "USE_2D_INSTANCING", void 0, ShaderDestination_default.VERTEX ); shaderBuilder.addUniform("mat4", "u_modelView2D", ShaderDestination_default.VERTEX); const context = frameState.context; const modelMatrix2D = Matrix4_default.fromTranslation( runtimeNode.instancingReferencePoint2D, new Matrix4_default() ); uniformMap2.u_modelView2D = function() { return Matrix4_default.multiplyTransformation( context.uniformState.view, modelMatrix2D, modelView2DScratch ); }; } renderResources.uniformMap = combine_default(uniformMap2, renderResources.uniformMap); renderResources.instanceCount = count; renderResources.attributes.push.apply( renderResources.attributes, instancingVertexAttributes ); }; var projectedTransformScratch = new Matrix4_default(); var projectedPositionScratch = new Cartesian3_default(); function projectTransformTo2D(transform3, modelMatrix, nodeTransform, frameState, result) { let projectedTransform = Matrix4_default.multiplyTransformation( modelMatrix, transform3, projectedTransformScratch ); projectedTransform = Matrix4_default.multiplyTransformation( projectedTransform, nodeTransform, projectedTransformScratch ); result = Transforms_default.basisTo2D( frameState.mapProjection, projectedTransform, result ); return result; } function projectPositionTo2D(position, modelMatrix, nodeTransform, frameState, result) { const translationMatrix = Matrix4_default.fromTranslation( position, projectedTransformScratch ); let projectedTransform = Matrix4_default.multiplyTransformation( modelMatrix, translationMatrix, projectedTransformScratch ); projectedTransform = Matrix4_default.multiplyTransformation( projectedTransform, nodeTransform, projectedTransformScratch ); const finalPosition = Matrix4_default.getTranslation( projectedTransform, projectedPositionScratch ); result = SceneTransforms_default.computeActualWgs84Position( frameState, finalPosition, result ); return result; } function getModelMatrixAndNodeTransform(renderResources, modelMatrix, nodeComputedTransform) { const model = renderResources.model; const sceneGraph = model.sceneGraph; const instances = renderResources.runtimeNode.node.instances; if (instances.transformInWorldSpace) { modelMatrix = Matrix4_default.multiplyTransformation( model.modelMatrix, sceneGraph.components.transform, modelMatrix ); nodeComputedTransform = Matrix4_default.multiplyTransformation( sceneGraph.axisCorrectionMatrix, renderResources.runtimeNode.computedTransform, nodeComputedTransform ); } else { modelMatrix = Matrix4_default.clone(sceneGraph.computedModelMatrix, modelMatrix); modelMatrix = Matrix4_default.multiplyTransformation( modelMatrix, renderResources.runtimeNode.computedTransform, modelMatrix ); nodeComputedTransform = Matrix4_default.clone( Matrix4_default.IDENTITY, nodeComputedTransform ); } } var modelMatrixScratch = new Matrix4_default(); var nodeComputedTransformScratch = new Matrix4_default(); var transformScratch2 = new Matrix4_default(); var positionScratch5 = new Cartesian3_default(); function projectTransformsTo2D(transforms, renderResources, frameState, result) { const modelMatrix = modelMatrixScratch; const nodeComputedTransform = nodeComputedTransformScratch; getModelMatrixAndNodeTransform( renderResources, modelMatrix, nodeComputedTransform ); const runtimeNode = renderResources.runtimeNode; const referencePoint = runtimeNode.instancingReferencePoint2D; const count = transforms.length; for (let i = 0; i < count; i++) { const transform3 = transforms[i]; const projectedTransform = projectTransformTo2D( transform3, modelMatrix, nodeComputedTransform, frameState, transformScratch2 ); const position = Matrix4_default.getTranslation( projectedTransform, positionScratch5 ); const finalTranslation = Cartesian3_default.subtract( position, referencePoint, position ); result[i] = Matrix4_default.setTranslation( projectedTransform, finalTranslation, result[i] ); } return result; } function projectTranslationsTo2D(translations, renderResources, frameState, result) { const modelMatrix = modelMatrixScratch; const nodeComputedTransform = nodeComputedTransformScratch; getModelMatrixAndNodeTransform( renderResources, modelMatrix, nodeComputedTransform ); const runtimeNode = renderResources.runtimeNode; const referencePoint = runtimeNode.instancingReferencePoint2D; const count = translations.length; for (let i = 0; i < count; i++) { const translation3 = translations[i]; const projectedPosition2 = projectPositionTo2D( translation3, modelMatrix, nodeComputedTransform, frameState, translation3 ); result[i] = Cartesian3_default.subtract( projectedPosition2, referencePoint, result[i] ); } return result; } var scratchProjectedMin = new Cartesian3_default(); var scratchProjectedMax = new Cartesian3_default(); function computeReferencePoint2D(renderResources, frameState) { const runtimeNode = renderResources.runtimeNode; const modelMatrix = renderResources.model.sceneGraph.computedModelMatrix; const transformedPositionMin = Matrix4_default.multiplyByPoint( modelMatrix, runtimeNode.instancingTranslationMin, scratchProjectedMin ); const projectedMin = SceneTransforms_default.computeActualWgs84Position( frameState, transformedPositionMin, transformedPositionMin ); const transformedPositionMax = Matrix4_default.multiplyByPoint( modelMatrix, runtimeNode.instancingTranslationMax, scratchProjectedMax ); const projectedMax = SceneTransforms_default.computeActualWgs84Position( frameState, transformedPositionMax, transformedPositionMax ); runtimeNode.instancingReferencePoint2D = Cartesian3_default.lerp( projectedMin, projectedMax, 0.5, new Cartesian3_default() ); } function transformsToTypedArray(transforms) { const elements = 12; const count = transforms.length; const transformsTypedArray = new Float32Array(count * elements); for (let i = 0; i < count; i++) { const transform3 = transforms[i]; const offset2 = elements * i; transformsTypedArray[offset2 + 0] = transform3[0]; transformsTypedArray[offset2 + 1] = transform3[4]; transformsTypedArray[offset2 + 2] = transform3[8]; transformsTypedArray[offset2 + 3] = transform3[12]; transformsTypedArray[offset2 + 4] = transform3[1]; transformsTypedArray[offset2 + 5] = transform3[5]; transformsTypedArray[offset2 + 6] = transform3[9]; transformsTypedArray[offset2 + 7] = transform3[13]; transformsTypedArray[offset2 + 8] = transform3[2]; transformsTypedArray[offset2 + 9] = transform3[6]; transformsTypedArray[offset2 + 10] = transform3[10]; transformsTypedArray[offset2 + 11] = transform3[14]; } return transformsTypedArray; } function translationsToTypedArray(translations) { const elements = 3; const count = translations.length; const transationsTypedArray = new Float32Array(count * elements); for (let i = 0; i < count; i++) { const translation3 = translations[i]; const offset2 = elements * i; transationsTypedArray[offset2 + 0] = translation3[0]; transationsTypedArray[offset2 + 1] = translation3[4]; transationsTypedArray[offset2 + 2] = translation3[8]; } return transationsTypedArray; } var translationScratch = new Cartesian3_default(); var rotationScratch = new Quaternion_default(); var scaleScratch = new Cartesian3_default(); function getInstanceTransformsAsMatrices(instances, count, renderResources) { const transforms = new Array(count); const translationAttribute = ModelUtility_default.getAttributeBySemantic( instances, InstanceAttributeSemantic_default.TRANSLATION ); const rotationAttribute = ModelUtility_default.getAttributeBySemantic( instances, InstanceAttributeSemantic_default.ROTATION ); const scaleAttribute = ModelUtility_default.getAttributeBySemantic( instances, InstanceAttributeSemantic_default.SCALE ); const instancingTranslationMax = new Cartesian3_default( -Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE ); const instancingTranslationMin = new Cartesian3_default( Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE ); const hasTranslation = defined_default(translationAttribute); const hasRotation = defined_default(rotationAttribute); const hasScale = defined_default(scaleAttribute); const translationTypedArray = hasTranslation ? translationAttribute.typedArray : new Float32Array(count * 3); let rotationTypedArray = hasRotation ? rotationAttribute.typedArray : new Float32Array(count * 4); if (hasRotation && rotationAttribute.normalized) { rotationTypedArray = AttributeCompression_default.dequantize( rotationTypedArray, rotationAttribute.componentDatatype, rotationAttribute.type, count ); } let scaleTypedArray; if (hasScale) { scaleTypedArray = scaleAttribute.typedArray; } else { scaleTypedArray = new Float32Array(count * 3); scaleTypedArray.fill(1); } for (let i = 0; i < count; i++) { const translation3 = new Cartesian3_default( translationTypedArray[i * 3], translationTypedArray[i * 3 + 1], translationTypedArray[i * 3 + 2], translationScratch ); Cartesian3_default.maximumByComponent( instancingTranslationMax, translation3, instancingTranslationMax ); Cartesian3_default.minimumByComponent( instancingTranslationMin, translation3, instancingTranslationMin ); const rotation = new Quaternion_default( rotationTypedArray[i * 4], rotationTypedArray[i * 4 + 1], rotationTypedArray[i * 4 + 2], hasRotation ? rotationTypedArray[i * 4 + 3] : 1, rotationScratch ); const scale = new Cartesian3_default( scaleTypedArray[i * 3], scaleTypedArray[i * 3 + 1], scaleTypedArray[i * 3 + 2], scaleScratch ); const transform3 = Matrix4_default.fromTranslationQuaternionRotationScale( translation3, rotation, scale, new Matrix4_default() ); transforms[i] = transform3; } const runtimeNode = renderResources.runtimeNode; runtimeNode.instancingTranslationMin = instancingTranslationMin; runtimeNode.instancingTranslationMax = instancingTranslationMax; if (hasTranslation) { translationAttribute.typedArray = void 0; } if (hasRotation) { rotationAttribute.typedArray = void 0; } if (hasScale) { scaleAttribute.typedArray = void 0; } return transforms; } function getInstanceTranslationsAsCartesian3s(translationAttribute, count, renderResources) { const instancingTranslations = new Array(count); const translationTypedArray = translationAttribute.typedArray; const instancingTranslationMin = new Cartesian3_default( Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE ); const instancingTranslationMax = new Cartesian3_default( -Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE ); for (let i = 0; i < count; i++) { const translation3 = new Cartesian3_default( translationTypedArray[i * 3], translationTypedArray[i * 3 + 1], translationTypedArray[i * 3 + 2] ); instancingTranslations[i] = translation3; Cartesian3_default.minimumByComponent( instancingTranslationMin, translation3, instancingTranslationMin ); Cartesian3_default.maximumByComponent( instancingTranslationMax, translation3, instancingTranslationMax ); } const runtimeNode = renderResources.runtimeNode; runtimeNode.instancingTranslationMin = instancingTranslationMin; runtimeNode.instancingTranslationMax = instancingTranslationMax; translationAttribute.typedArray = void 0; return instancingTranslations; } function createVertexBuffer2(typedArray, frameState) { const buffer = Buffer_default.createVertexBuffer({ context: frameState.context, typedArray, usage: BufferUsage_default.STATIC_DRAW }); buffer.vertexArrayDestroyable = false; return buffer; } function processTransformAttributes(renderResources, frameState, instances, instancingVertexAttributes, use2D) { const rotationAttribute = ModelUtility_default.getAttributeBySemantic( instances, InstanceAttributeSemantic_default.ROTATION ); if (defined_default(rotationAttribute)) { processTransformMatrixAttributes( renderResources, instances, instancingVertexAttributes, frameState, use2D ); } else { processTransformVec3Attributes( renderResources, instances, instancingVertexAttributes, frameState, use2D ); } } function processTransformMatrixAttributes(renderResources, instances, instancingVertexAttributes, frameState, use2D) { const shaderBuilder = renderResources.shaderBuilder; const count = instances.attributes[0].count; const model = renderResources.model; const runtimeNode = renderResources.runtimeNode; shaderBuilder.addDefine("HAS_INSTANCE_MATRICES"); const attributeString = "Transform"; let transforms; let buffer = runtimeNode.instancingTransformsBuffer; if (!defined_default(buffer)) { transforms = getInstanceTransformsAsMatrices( instances, count, renderResources ); const transformsTypedArray = transformsToTypedArray(transforms); buffer = createVertexBuffer2(transformsTypedArray, frameState); model._modelResources.push(buffer); runtimeNode.instancingTransformsBuffer = buffer; } processMatrixAttributes( renderResources, buffer, instancingVertexAttributes, attributeString ); if (!use2D) { return; } const frameStateCV = clone_default(frameState); frameStateCV.mode = SceneMode_default.COLUMBUS_VIEW; computeReferencePoint2D(renderResources, frameStateCV); let buffer2D = runtimeNode.instancingTransformsBuffer2D; if (!defined_default(buffer2D)) { const projectedTransforms = projectTransformsTo2D( transforms, renderResources, frameStateCV, transforms ); const projectedTypedArray = transformsToTypedArray(projectedTransforms); buffer2D = createVertexBuffer2(projectedTypedArray, frameState); model._modelResources.push(buffer2D); runtimeNode.instancingTransformsBuffer2D = buffer2D; } const attributeString2D = "Transform2D"; processMatrixAttributes( renderResources, buffer2D, instancingVertexAttributes, attributeString2D ); } function processTransformVec3Attributes(renderResources, instances, instancingVertexAttributes, frameState, use2D) { const shaderBuilder = renderResources.shaderBuilder; const runtimeNode = renderResources.runtimeNode; const translationAttribute = ModelUtility_default.getAttributeBySemantic( instances, InstanceAttributeSemantic_default.TRANSLATION ); const scaleAttribute = ModelUtility_default.getAttributeBySemantic( instances, InstanceAttributeSemantic_default.SCALE ); if (defined_default(scaleAttribute)) { shaderBuilder.addDefine("HAS_INSTANCE_SCALE"); const attributeString2 = "Scale"; processVec3Attribute( renderResources, scaleAttribute.buffer, scaleAttribute.byteOffset, scaleAttribute.byteStride, instancingVertexAttributes, attributeString2 ); } if (!defined_default(translationAttribute)) { return; } let instancingTranslations; const typedArray = translationAttribute.typedArray; if (defined_default(typedArray)) { instancingTranslations = getInstanceTranslationsAsCartesian3s( translationAttribute, translationAttribute.count, renderResources ); } else if (!defined_default(runtimeNode.instancingTranslationMin)) { runtimeNode.instancingTranslationMin = translationAttribute.min; runtimeNode.instancingTranslationMax = translationAttribute.max; } shaderBuilder.addDefine("HAS_INSTANCE_TRANSLATION"); const attributeString = "Translation"; processVec3Attribute( renderResources, translationAttribute.buffer, translationAttribute.byteOffset, translationAttribute.byteStride, instancingVertexAttributes, attributeString ); if (!use2D) { return; } const frameStateCV = clone_default(frameState); frameStateCV.mode = SceneMode_default.COLUMBUS_VIEW; computeReferencePoint2D(renderResources, frameStateCV); let buffer2D = runtimeNode.instancingTranslationBuffer2D; if (!defined_default(buffer2D)) { const projectedTranslations = projectTranslationsTo2D( instancingTranslations, renderResources, frameStateCV, instancingTranslations ); const projectedTypedArray = translationsToTypedArray(projectedTranslations); buffer2D = createVertexBuffer2(projectedTypedArray, frameState); renderResources.model._modelResources.push(buffer2D); runtimeNode.instancingTranslationBuffer2D = buffer2D; } const byteOffset = 0; const byteStride = void 0; const attributeString2D = "Translation2D"; processVec3Attribute( renderResources, buffer2D, byteOffset, byteStride, instancingVertexAttributes, attributeString2D ); } function processMatrixAttributes(renderResources, buffer, instancingVertexAttributes, attributeString) { const vertexSizeInFloats = 12; const componentByteSize = ComponentDatatype_default.getSizeInBytes( ComponentDatatype_default.FLOAT ); const strideInBytes = componentByteSize * vertexSizeInFloats; const matrixAttributes = [ { index: renderResources.attributeIndex++, vertexBuffer: buffer, componentsPerAttribute: 4, componentDatatype: ComponentDatatype_default.FLOAT, normalize: false, offsetInBytes: 0, strideInBytes, instanceDivisor: 1 }, { index: renderResources.attributeIndex++, vertexBuffer: buffer, componentsPerAttribute: 4, componentDatatype: ComponentDatatype_default.FLOAT, normalize: false, offsetInBytes: componentByteSize * 4, strideInBytes, instanceDivisor: 1 }, { index: renderResources.attributeIndex++, vertexBuffer: buffer, componentsPerAttribute: 4, componentDatatype: ComponentDatatype_default.FLOAT, normalize: false, offsetInBytes: componentByteSize * 8, strideInBytes, instanceDivisor: 1 } ]; const shaderBuilder = renderResources.shaderBuilder; shaderBuilder.addAttribute("vec4", `a_instancing${attributeString}Row0`); shaderBuilder.addAttribute("vec4", `a_instancing${attributeString}Row1`); shaderBuilder.addAttribute("vec4", `a_instancing${attributeString}Row2`); instancingVertexAttributes.push.apply( instancingVertexAttributes, matrixAttributes ); } function processVec3Attribute(renderResources, buffer, byteOffset, byteStride, instancingVertexAttributes, attributeString) { instancingVertexAttributes.push({ index: renderResources.attributeIndex++, vertexBuffer: buffer, componentsPerAttribute: 3, componentDatatype: ComponentDatatype_default.FLOAT, normalize: false, offsetInBytes: byteOffset, strideInBytes: byteStride, instanceDivisor: 1 }); const shaderBuilder = renderResources.shaderBuilder; shaderBuilder.addAttribute("vec3", `a_instance${attributeString}`); } function processFeatureIdAttributes(renderResources, frameState, instances, instancingVertexAttributes) { const attributes = instances.attributes; const shaderBuilder = renderResources.shaderBuilder; for (let i = 0; i < attributes.length; i++) { const attribute = attributes[i]; if (attribute.semantic !== InstanceAttributeSemantic_default.FEATURE_ID) { continue; } if (attribute.setIndex >= renderResources.featureIdVertexAttributeSetIndex) { renderResources.featureIdVertexAttributeSetIndex = attribute.setIndex + 1; } instancingVertexAttributes.push({ index: renderResources.attributeIndex++, vertexBuffer: attribute.buffer, componentsPerAttribute: AttributeType_default.getNumberOfComponents( attribute.type ), componentDatatype: attribute.componentDatatype, normalize: false, offsetInBytes: attribute.byteOffset, strideInBytes: attribute.byteStride, instanceDivisor: 1 }); shaderBuilder.addAttribute( "float", `a_instanceFeatureId_${attribute.setIndex}` ); } } var InstancingPipelineStage_default = InstancingPipelineStage; // packages/engine/Source/Scene/Model/ModelMatrixUpdateStage.js var ModelMatrixUpdateStage = {}; ModelMatrixUpdateStage.name = "ModelMatrixUpdateStage"; ModelMatrixUpdateStage.update = function(runtimeNode, sceneGraph, frameState) { const use2D = frameState.mode !== SceneMode_default.SCENE3D; if (use2D && sceneGraph._model._projectTo2D) { return; } if (runtimeNode._transformDirty) { const modelMatrix = use2D ? sceneGraph._computedModelMatrix2D : sceneGraph._computedModelMatrix; updateRuntimeNode( runtimeNode, sceneGraph, modelMatrix, runtimeNode.transformToRoot ); runtimeNode._transformDirty = false; } }; function updateRuntimeNode(runtimeNode, sceneGraph, modelMatrix, transformToRoot) { let i; transformToRoot = Matrix4_default.multiplyTransformation( transformToRoot, runtimeNode.transform, new Matrix4_default() ); runtimeNode.updateComputedTransform(); const primitivesLength = runtimeNode.runtimePrimitives.length; for (i = 0; i < primitivesLength; i++) { const runtimePrimitive = runtimeNode.runtimePrimitives[i]; const drawCommand = runtimePrimitive.drawCommand; drawCommand.modelMatrix = Matrix4_default.multiplyTransformation( modelMatrix, transformToRoot, drawCommand.modelMatrix ); drawCommand.cullFace = ModelUtility_default.getCullFace( drawCommand.modelMatrix, drawCommand.primitiveType ); } const childrenLength = runtimeNode.children.length; for (i = 0; i < childrenLength; i++) { const childRuntimeNode = sceneGraph._runtimeNodes[runtimeNode.children[i]]; childRuntimeNode._transformToRoot = Matrix4_default.clone( transformToRoot, childRuntimeNode._transformToRoot ); updateRuntimeNode( childRuntimeNode, sceneGraph, modelMatrix, transformToRoot ); childRuntimeNode._transformDirty = false; } } var ModelMatrixUpdateStage_default = ModelMatrixUpdateStage; // packages/engine/Source/Scene/Model/NodeStatisticsPipelineStage.js var NodeStatisticsPipelineStage = { name: "NodeStatisticsPipelineStage", // Helps with debugging // Expose some methods for testing _countInstancingAttributes: countInstancingAttributes, _countGeneratedBuffers: countGeneratedBuffers }; NodeStatisticsPipelineStage.process = function(renderResources, node, frameState) { const statistics2 = renderResources.model.statistics; const instances = node.instances; const runtimeNode = renderResources.runtimeNode; countInstancingAttributes(statistics2, instances); countGeneratedBuffers(statistics2, runtimeNode); }; function countInstancingAttributes(statistics2, instances) { if (!defined_default(instances)) { return; } const attributes = instances.attributes; const length3 = attributes.length; for (let i = 0; i < length3; i++) { const attribute = attributes[i]; if (defined_default(attribute.buffer)) { const hasCpuCopy = false; statistics2.addBuffer(attribute.buffer, hasCpuCopy); } } } function countGeneratedBuffers(statistics2, runtimeNode) { if (defined_default(runtimeNode.instancingTransformsBuffer)) { const hasCpuCopy = false; statistics2.addBuffer(runtimeNode.instancingTransformsBuffer, hasCpuCopy); } if (defined_default(runtimeNode.instancingTransformsBuffer2D)) { const hasCpuCopy = false; statistics2.addBuffer(runtimeNode.instancingTransformsBuffer2D, hasCpuCopy); } if (defined_default(runtimeNode.instancingTranslationBuffer2D)) { const hasCpuCopy = false; statistics2.addBuffer(runtimeNode.instancingTranslationBuffer2D, hasCpuCopy); } } var NodeStatisticsPipelineStage_default = NodeStatisticsPipelineStage; // packages/engine/Source/Scene/Model/ModelRuntimeNode.js function ModelRuntimeNode(options) { options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT); const node = options.node; const transform3 = options.transform; const transformToRoot = options.transformToRoot; const sceneGraph = options.sceneGraph; const children = options.children; Check_default.typeOf.object("options.node", node); Check_default.typeOf.object("options.transform", transform3); Check_default.typeOf.object("options.transformToRoot", transformToRoot); Check_default.typeOf.object("options.sceneGraph", sceneGraph); Check_default.typeOf.object("options.children", children); this._node = node; this._name = node.name; this._id = node.index; this._sceneGraph = sceneGraph; this._children = children; this._originalTransform = Matrix4_default.clone(transform3, this._originalTransform); this._transform = Matrix4_default.clone(transform3, this._transform); this._transformToRoot = Matrix4_default.clone(transformToRoot, this._transformToRoot); this._computedTransform = new Matrix4_default(); this._transformDirty = false; this._transformParameters = void 0; this._morphWeights = []; this._runtimeSkin = void 0; this._computedJointMatrices = []; this.show = true; this.userAnimated = false; this.pipelineStages = []; this.runtimePrimitives = []; this.updateStages = []; this.instancingTranslationMin = void 0; this.instancingTranslationMax = void 0; this.instancingTransformsBuffer = void 0; this.instancingTransformsBuffer2D = void 0; this.instancingTranslationBuffer2D = void 0; this.instancingReferencePoint2D = void 0; initialize12(this); } Object.defineProperties(ModelRuntimeNode.prototype, { /** * The internal node this runtime node represents. * * @memberof ModelRuntimeNode.prototype * @type {ModelComponents.Node} * @readonly * * @private */ node: { get: function() { return this._node; } }, /** * The scene graph this node belongs to. * * @memberof ModelRuntimeNode.prototype * @type {ModelSceneGraph} * @readonly * * @private */ sceneGraph: { get: function() { return this._sceneGraph; } }, /** * The indices of the children of this node in the scene graph. * * @memberof ModelRuntimeNode.prototype * @type {number[]} * @readonly * * @private */ children: { get: function() { return this._children; } }, /** * The node's local space transform. This can be changed externally via * the corresponding {@link ModelNode}, such that animation can be * driven by another source, not just an animation in the model's asset. * * @memberof ModelRuntimeNode.prototype * @type {Matrix4} * * @private */ transform: { get: function() { return this._transform; }, set: function(value) { this._transformDirty = true; this._transform = Matrix4_default.clone(value, this._transform); } }, /** * The transforms of all the node's ancestors, not including this node's * transform. * * @see ModelRuntimeNode#computedTransform * * @memberof ModelRuntimeNode.prototype * @type {Matrix4} * @readonly * * @private */ transformToRoot: { get: function() { return this._transformToRoot; } }, /** * A transform from the node's local space to the model's scene graph space. * This is the product of transformToRoot * transform. * * @memberof ModelRuntimeNode.prototype * @type {Matrix4} * @readonly * * @private */ computedTransform: { get: function() { return this._computedTransform; } }, /** * The node's original transform, as specified in the model. * Does not include transformations from the node's ancestors. * * @memberof ModelRuntimeNode.prototype * @type {Matrix4} * @readonly * * @private */ originalTransform: { get: function() { return this._originalTransform; } }, /** * The node's local space translation. This is used internally to allow * animations in the model's asset to affect the node's properties. * * If the node's transformation was originally described using a matrix * in the model, then this will return undefined. * * @memberof ModelRuntimeNode.prototype * @type {Cartesian3} * * @exception {DeveloperError} The translation of a node cannot be set if it was defined using a matrix in the model's asset. * * @private */ translation: { get: function() { return defined_default(this._transformParameters) ? this._transformParameters.translation : void 0; }, set: function(value) { const transformParameters = this._transformParameters; if (!defined_default(transformParameters)) { throw new DeveloperError_default( "The translation of a node cannot be set if it was defined using a matrix in the model." ); } const currentTranslation = transformParameters.translation; if (Cartesian3_default.equals(currentTranslation, value)) { return; } transformParameters.translation = Cartesian3_default.clone( value, transformParameters.translation ); updateTransformFromParameters(this, transformParameters); } }, /** * The node's local space rotation. This is used internally to allow * animations in the model's asset to affect the node's properties. * * If the node's transformation was originally described using a matrix * in the model, then this will return undefined. * * @memberof ModelRuntimeNode.prototype * @type {Quaternion} * * @exception {DeveloperError} The rotation of a node cannot be set if it was defined using a matrix in the model's asset. * * @private */ rotation: { get: function() { return defined_default(this._transformParameters) ? this._transformParameters.rotation : void 0; }, set: function(value) { const transformParameters = this._transformParameters; if (!defined_default(transformParameters)) { throw new DeveloperError_default( "The rotation of a node cannot be set if it was defined using a matrix in the model." ); } const currentRotation = transformParameters.rotation; if (Quaternion_default.equals(currentRotation, value)) { return; } transformParameters.rotation = Quaternion_default.clone( value, transformParameters.rotation ); updateTransformFromParameters(this, transformParameters); } }, /** * The node's local space scale. This is used internally to allow * animations in the model's asset to affect the node's properties. * * If the node's transformation was originally described using a matrix * in the model, then this will return undefined. * * @memberof ModelRuntimeNode.prototype * @type {Cartesian3} * * @exception {DeveloperError} The scale of a node cannot be set if it was defined using a matrix in the model's asset. * @private */ scale: { get: function() { return defined_default(this._transformParameters) ? this._transformParameters.scale : void 0; }, set: function(value) { const transformParameters = this._transformParameters; if (!defined_default(transformParameters)) { throw new DeveloperError_default( "The scale of a node cannot be set if it was defined using a matrix in the model." ); } const currentScale = transformParameters.scale; if (Cartesian3_default.equals(currentScale, value)) { return; } transformParameters.scale = Cartesian3_default.clone( value, transformParameters.scale ); updateTransformFromParameters(this, transformParameters); } }, /** * The node's morph weights. This is used internally to allow animations * in the model's asset to affect the node's properties. * * @memberof ModelRuntimeNode.prototype * @type {number[]} * * @private */ morphWeights: { get: function() { return this._morphWeights; }, set: function(value) { const valueLength = value.length; if (this._morphWeights.length !== valueLength) { throw new DeveloperError_default( "value must have the same length as the original weights array." ); } for (let i = 0; i < valueLength; i++) { this._morphWeights[i] = value[i]; } } }, /** * The skin applied to this node, if it exists. * * @memberof ModelRuntimeNode.prototype * @type {ModelSkin} * @readonly * * @private */ runtimeSkin: { get: function() { return this._runtimeSkin; } }, /** * The computed joint matrices of this node, derived from its skin. * * @memberof ModelRuntimeNode.prototype * @type {Matrix4[]} * @readonly * * @private */ computedJointMatrices: { get: function() { return this._computedJointMatrices; } } }); function initialize12(runtimeNode) { const transform3 = runtimeNode.transform; const transformToRoot = runtimeNode.transformToRoot; const computedTransform = runtimeNode._computedTransform; runtimeNode._computedTransform = Matrix4_default.multiply( transformToRoot, transform3, computedTransform ); const node = runtimeNode.node; if (!defined_default(node.matrix)) { runtimeNode._transformParameters = new TranslationRotationScale_default( node.translation, node.rotation, node.scale ); } if (defined_default(node.morphWeights)) { runtimeNode._morphWeights = node.morphWeights.slice(); } const articulationName = node.articulationName; if (defined_default(articulationName)) { const sceneGraph = runtimeNode.sceneGraph; const runtimeArticulations = sceneGraph._runtimeArticulations; const runtimeArticulation = runtimeArticulations[articulationName]; if (defined_default(runtimeArticulation)) { runtimeArticulation.runtimeNodes.push(runtimeNode); } } } function updateTransformFromParameters(runtimeNode, transformParameters) { runtimeNode._transformDirty = true; runtimeNode._transform = Matrix4_default.fromTranslationRotationScale( transformParameters, runtimeNode._transform ); } ModelRuntimeNode.prototype.getChild = function(index) { Check_default.typeOf.number("index", index); if (index < 0 || index >= this.children.length) { throw new DeveloperError_default( "index must be greater than or equal to 0 and less than the number of children." ); } return this.sceneGraph._runtimeNodes[this.children[index]]; }; ModelRuntimeNode.prototype.configurePipeline = function() { const node = this.node; const pipelineStages = this.pipelineStages; pipelineStages.length = 0; const updateStages = this.updateStages; updateStages.length = 0; if (defined_default(node.instances)) { pipelineStages.push(InstancingPipelineStage_default); } pipelineStages.push(NodeStatisticsPipelineStage_default); updateStages.push(ModelMatrixUpdateStage_default); }; ModelRuntimeNode.prototype.updateComputedTransform = function() { this._computedTransform = Matrix4_default.multiply( this._transformToRoot, this._transform, this._computedTransform ); }; ModelRuntimeNode.prototype.updateJointMatrices = function() { const runtimeSkin = this._runtimeSkin; if (!defined_default(runtimeSkin)) { return; } runtimeSkin.updateJointMatrices(); const computedJointMatrices = this._computedJointMatrices; const skinJointMatrices = runtimeSkin.jointMatrices; const length3 = skinJointMatrices.length; for (let i = 0; i < length3; i++) { if (!defined_default(computedJointMatrices[i])) { computedJointMatrices[i] = new Matrix4_default(); } const nodeWorldTransform = Matrix4_default.multiplyTransformation( this.transformToRoot, this.transform, computedJointMatrices[i] ); const inverseNodeWorldTransform = Matrix4_default.inverseTransformation( nodeWorldTransform, computedJointMatrices[i] ); computedJointMatrices[i] = Matrix4_default.multiplyTransformation( inverseNodeWorldTransform, skinJointMatrices[i], computedJointMatrices[i] ); } }; var ModelRuntimeNode_default = ModelRuntimeNode; // packages/engine/Source/Scene/Model/AlphaPipelineStage.js var AlphaPipelineStage = { name: "AlphaPipelineStage" // Helps with debugging }; AlphaPipelineStage.process = function(renderResources, primitive, frameState) { const alphaOptions = renderResources.alphaOptions; const model = renderResources.model; alphaOptions.pass = defaultValue_default(alphaOptions.pass, model.opaquePass); const renderStateOptions = renderResources.renderStateOptions; if (alphaOptions.pass === Pass_default.TRANSLUCENT) { renderStateOptions.cull.enabled = false; renderStateOptions.depthMask = false; renderStateOptions.blending = BlendingState_default.ALPHA_BLEND; } const shaderBuilder = renderResources.shaderBuilder; const uniformMap2 = renderResources.uniformMap; if (defined_default(alphaOptions.alphaCutoff)) { shaderBuilder.addDefine( "ALPHA_MODE_MASK", void 0, ShaderDestination_default.FRAGMENT ); shaderBuilder.addUniform( "float", "u_alphaCutoff", ShaderDestination_default.FRAGMENT ); uniformMap2.u_alphaCutoff = function() { return alphaOptions.alphaCutoff; }; } }; var AlphaPipelineStage_default = AlphaPipelineStage; // packages/engine/Source/Scene/Model/BatchTexturePipelineStage.js var BatchTexturePipelineStage = { name: "BatchTexturePipelineStage" // Helps with debugging }; BatchTexturePipelineStage.process = function(renderResources, primitive, frameState) { const shaderBuilder = renderResources.shaderBuilder; const batchTextureUniforms = {}; const model = renderResources.model; const featureTable = model.featureTables[model.featureTableId]; const featuresLength = featureTable.featuresLength; shaderBuilder.addUniform("int", "model_featuresLength"); batchTextureUniforms.model_featuresLength = function() { return featuresLength; }; const batchTexture = featureTable.batchTexture; shaderBuilder.addUniform("sampler2D", "model_batchTexture"); batchTextureUniforms.model_batchTexture = function() { return defaultValue_default(batchTexture.batchTexture, batchTexture.defaultTexture); }; shaderBuilder.addUniform("vec4", "model_textureStep"); batchTextureUniforms.model_textureStep = function() { return batchTexture.textureStep; }; if (batchTexture.textureDimensions.y > 1) { shaderBuilder.addDefine("MULTILINE_BATCH_TEXTURE"); shaderBuilder.addUniform("vec2", "model_textureDimensions"); batchTextureUniforms.model_textureDimensions = function() { return batchTexture.textureDimensions; }; } renderResources.uniformMap = combine_default( batchTextureUniforms, renderResources.uniformMap ); }; var BatchTexturePipelineStage_default = BatchTexturePipelineStage; // packages/engine/Source/Scene/Model/ClassificationPipelineStage.js var ClassificationPipelineStage = { name: "ClassificationPipelineStage" // Helps with debugging }; ClassificationPipelineStage.process = function(renderResources, primitive, frameState) { const shaderBuilder = renderResources.shaderBuilder; shaderBuilder.addDefine( "HAS_CLASSIFICATION", void 0, ShaderDestination_default.BOTH ); const runtimePrimitive = renderResources.runtimePrimitive; if (!defined_default(runtimePrimitive.batchLengths)) { createClassificationBatches(primitive, runtimePrimitive); } }; function createClassificationBatches(primitive, runtimePrimitive) { const positionAttribute = ModelUtility_default.getAttributeBySemantic( primitive, VertexAttributeSemantic_default.POSITION ); if (!defined_default(positionAttribute)) { throw new RuntimeError_default( "Primitives must have a position attribute to be used for classification." ); } let indicesArray; const indices2 = primitive.indices; const hasIndices = defined_default(indices2); if (hasIndices) { indicesArray = indices2.typedArray; indices2.typedArray = void 0; } const count = hasIndices ? indices2.count : positionAttribute.count; const featureIdAttribute = ModelUtility_default.getAttributeBySemantic( primitive, VertexAttributeSemantic_default.FEATURE_ID, 0 ); if (!defined_default(featureIdAttribute)) { runtimePrimitive.batchLengths = [count]; runtimePrimitive.batchOffsets = [0]; return; } const featureIds = featureIdAttribute.typedArray; featureIdAttribute.typedArray = void 0; const batchLengths = []; const batchOffsets = [0]; const firstIndex = hasIndices ? indicesArray[0] : 0; let currentBatchId = featureIds[firstIndex]; let currentOffset = 0; for (let i = 1; i < count; i++) { const index = hasIndices ? indicesArray[i] : i; const batchId = featureIds[index]; if (batchId !== currentBatchId) { const batchLength = i - currentOffset; const newOffset = i; batchLengths.push(batchLength); batchOffsets.push(newOffset); currentOffset = newOffset; currentBatchId = batchId; } } const finalBatchLength = count - currentOffset; batchLengths.push(finalBatchLength); runtimePrimitive.batchLengths = batchLengths; runtimePrimitive.batchOffsets = batchOffsets; } var ClassificationPipelineStage_default = ClassificationPipelineStage; // packages/engine/Source/Shaders/Model/CPUStylingStageVS.js var CPUStylingStageVS_default = "void filterByPassType(inout vec3 positionMC, vec4 featureColor)\n{\n bool styleTranslucent = (featureColor.a != 1.0);\n // Only render translucent features in the translucent pass (if the style or the original command has translucency).\n if (czm_pass == czm_passTranslucent && !styleTranslucent && !model_commandTranslucent)\n {\n // If the model has a translucent silhouette, it needs to render during the silhouette color command,\n // (i.e. the command where model_silhouettePass = true), even if the model isn't translucent.\n #ifdef HAS_SILHOUETTE\n positionMC *= float(model_silhouettePass);\n #else\n positionMC *= 0.0;\n #endif\n }\n // If the current pass is not the translucent pass and the style is not translucent, don't render the feature.\n else if (czm_pass != czm_passTranslucent && styleTranslucent)\n {\n positionMC *= 0.0;\n }\n}\n\nvoid cpuStylingStage(inout vec3 positionMC, inout SelectedFeature feature)\n{\n float show = ceil(feature.color.a);\n positionMC *= show;\n\n #if defined(HAS_SELECTED_FEATURE_ID_ATTRIBUTE) && !defined(HAS_CLASSIFICATION)\n filterByPassType(positionMC, feature.color);\n #endif\n}\n"; // packages/engine/Source/Shaders/Model/CPUStylingStageFS.js var CPUStylingStageFS_default = "void filterByPassType(vec4 featureColor)\n{\n bool styleTranslucent = (featureColor.a != 1.0);\n // Only render translucent features in the translucent pass (if the style or the original command has translucency).\n if (czm_pass == czm_passTranslucent && !styleTranslucent && !model_commandTranslucent)\n { \n // If the model has a translucent silhouette, it needs to render during the silhouette color command,\n // (i.e. the command where model_silhouettePass = true), even if the model isn't translucent.\n #ifdef HAS_SILHOUETTE\n if(!model_silhouettePass) {\n discard;\n }\n #else\n discard;\n #endif\n }\n // If the current pass is not the translucent pass and the style is not translucent, don't render the feature.\n else if (czm_pass != czm_passTranslucent && styleTranslucent)\n {\n discard;\n }\n}\n\nvoid cpuStylingStage(inout czm_modelMaterial material, SelectedFeature feature)\n{\n vec4 featureColor = feature.color;\n if (featureColor.a == 0.0)\n {\n discard;\n }\n\n // If a feature ID vertex attribute is used, the pass type filter is applied in the vertex shader.\n // So, we only apply in in the fragment shader if the feature ID texture is used.\n #if defined(HAS_SELECTED_FEATURE_ID_TEXTURE) && !defined(HAS_CLASSIFICATION)\n filterByPassType(featureColor);\n #endif\n\n featureColor = czm_gammaCorrect(featureColor);\n\n // Classification models compute the diffuse differently.\n #ifdef HAS_CLASSIFICATION\n material.diffuse = featureColor.rgb * featureColor.a;\n #else\n float highlight = ceil(model_colorBlend);\n material.diffuse *= mix(featureColor.rgb, vec3(1.0), highlight);\n #endif\n \n material.alpha *= featureColor.a;\n}\n"; // packages/engine/Source/Scene/Model/CPUStylingPipelineStage.js var CPUStylingPipelineStage = { name: "CPUStylingPipelineStage" // Helps with debugging }; CPUStylingPipelineStage.process = function(renderResources, primitive, frameState) { const model = renderResources.model; const shaderBuilder = renderResources.shaderBuilder; shaderBuilder.addVertexLines(CPUStylingStageVS_default); shaderBuilder.addFragmentLines(CPUStylingStageFS_default); shaderBuilder.addDefine("USE_CPU_STYLING", void 0, ShaderDestination_default.BOTH); if (!defined_default(model.color)) { shaderBuilder.addUniform( "float", ModelColorPipelineStage_default.COLOR_BLEND_UNIFORM_NAME, ShaderDestination_default.FRAGMENT ); renderResources.uniformMap[ModelColorPipelineStage_default.COLOR_BLEND_UNIFORM_NAME] = function() { return ColorBlendMode_default.getColorBlend( model.colorBlendMode, model.colorBlendAmount ); }; } shaderBuilder.addUniform( "bool", "model_commandTranslucent", ShaderDestination_default.BOTH ); renderResources.uniformMap.model_commandTranslucent = function() { return renderResources.alphaOptions.pass === Pass_default.TRANSLUCENT; }; }; var CPUStylingPipelineStage_default = CPUStylingPipelineStage; // packages/engine/Source/Scene/Model/CustomShaderMode.js var CustomShaderMode = { /** * The custom shader will be used to modify the results of the material stage * before lighting is applied. * * @type {string} * @constant */ MODIFY_MATERIAL: "MODIFY_MATERIAL", /** * The custom shader will be used instead of the material stage. This is a hint * to optimize out the material processing code. * * @type {string} * @constant */ REPLACE_MATERIAL: "REPLACE_MATERIAL" }; CustomShaderMode.getDefineName = function(customShaderMode) { return `CUSTOM_SHADER_${customShaderMode}`; }; var CustomShaderMode_default = Object.freeze(CustomShaderMode); // packages/engine/Source/Shaders/Model/CustomShaderStageVS.js var CustomShaderStageVS_default = "void customShaderStage(\n inout czm_modelVertexOutput vsOutput, \n inout ProcessedAttributes attributes, \n FeatureIds featureIds,\n Metadata metadata,\n MetadataClass metadataClass,\n MetadataStatistics metadataStatistics\n) {\n // VertexInput and initializeInputStruct() are dynamically generated in JS, \n // see CustomShaderPipelineStage.js\n VertexInput vsInput;\n initializeInputStruct(vsInput, attributes);\n vsInput.featureIds = featureIds;\n vsInput.metadata = metadata;\n vsInput.metadataClass = metadataClass;\n vsInput.metadataStatistics = metadataStatistics;\n vertexMain(vsInput, vsOutput);\n attributes.positionMC = vsOutput.positionMC;\n}\n"; // packages/engine/Source/Shaders/Model/CustomShaderStageFS.js var CustomShaderStageFS_default = "void customShaderStage(\n inout czm_modelMaterial material,\n ProcessedAttributes attributes,\n FeatureIds featureIds,\n Metadata metadata,\n MetadataClass metadataClass,\n MetadataStatistics metadataStatistics\n) {\n // FragmentInput and initializeInputStruct() are dynamically generated in JS, \n // see CustomShaderPipelineStage.js\n FragmentInput fsInput;\n initializeInputStruct(fsInput, attributes);\n fsInput.featureIds = featureIds;\n fsInput.metadata = metadata;\n fsInput.metadataClass = metadataClass;\n fsInput.metadataStatistics = metadataStatistics;\n fragmentMain(fsInput, material);\n}\n"; // packages/engine/Source/Shaders/Model/FeatureIdStageFS.js var FeatureIdStageFS_default = "void featureIdStage(out FeatureIds featureIds, ProcessedAttributes attributes) {\n initializeFeatureIds(featureIds, attributes);\n initializeFeatureIdAliases(featureIds);\n}\n"; // packages/engine/Source/Shaders/Model/FeatureIdStageVS.js var FeatureIdStageVS_default = "void featureIdStage(out FeatureIds featureIds, ProcessedAttributes attributes) \n{\n initializeFeatureIds(featureIds, attributes);\n initializeFeatureIdAliases(featureIds);\n setFeatureIdVaryings();\n}\n"; // packages/engine/Source/Scene/Model/FeatureIdPipelineStage.js var FeatureIdPipelineStage = { name: "FeatureIdPipelineStage", // Helps with debugging STRUCT_ID_FEATURE_IDS_VS: "FeatureIdsVS", STRUCT_ID_FEATURE_IDS_FS: "FeatureIdsFS", STRUCT_NAME_FEATURE_IDS: "FeatureIds", FUNCTION_ID_INITIALIZE_FEATURE_IDS_VS: "initializeFeatureIdsVS", FUNCTION_ID_INITIALIZE_FEATURE_IDS_FS: "initializeFeatureIdsFS", FUNCTION_ID_INITIALIZE_FEATURE_ID_ALIASES_VS: "initializeFeatureIdAliasesVS", FUNCTION_ID_INITIALIZE_FEATURE_ID_ALIASES_FS: "initializeFeatureIdAliasesFS", FUNCTION_SIGNATURE_INITIALIZE_FEATURE_IDS: "void initializeFeatureIds(out FeatureIds featureIds, ProcessedAttributes attributes)", FUNCTION_SIGNATURE_INITIALIZE_FEATURE_ID_ALIASES: "void initializeFeatureIdAliases(inout FeatureIds featureIds)", FUNCTION_ID_SET_FEATURE_ID_VARYINGS: "setFeatureIdVaryings", FUNCTION_SIGNATURE_SET_FEATURE_ID_VARYINGS: "void setFeatureIdVaryings()" }; FeatureIdPipelineStage.process = function(renderResources, primitive, frameState) { const shaderBuilder = renderResources.shaderBuilder; declareStructsAndFunctions(shaderBuilder); const instances = renderResources.runtimeNode.node.instances; if (defined_default(instances)) { processInstanceFeatureIds(renderResources, instances, frameState); } processPrimitiveFeatureIds(renderResources, primitive, frameState); shaderBuilder.addVertexLines(FeatureIdStageVS_default); shaderBuilder.addFragmentLines(FeatureIdStageFS_default); }; function declareStructsAndFunctions(shaderBuilder) { shaderBuilder.addStruct( FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_VS, FeatureIdPipelineStage.STRUCT_NAME_FEATURE_IDS, ShaderDestination_default.VERTEX ); shaderBuilder.addStruct( FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_FS, FeatureIdPipelineStage.STRUCT_NAME_FEATURE_IDS, ShaderDestination_default.FRAGMENT ); shaderBuilder.addFunction( FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_IDS_VS, FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_IDS, ShaderDestination_default.VERTEX ); shaderBuilder.addFunction( FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_IDS_FS, FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_IDS, ShaderDestination_default.FRAGMENT ); shaderBuilder.addFunction( FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_ID_ALIASES_VS, FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_ID_ALIASES, ShaderDestination_default.VERTEX ); shaderBuilder.addFunction( FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_ID_ALIASES_FS, FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_ID_ALIASES, ShaderDestination_default.FRAGMENT ); shaderBuilder.addFunction( FeatureIdPipelineStage.FUNCTION_ID_SET_FEATURE_ID_VARYINGS, FeatureIdPipelineStage.FUNCTION_SIGNATURE_SET_FEATURE_ID_VARYINGS, ShaderDestination_default.VERTEX ); } function processInstanceFeatureIds(renderResources, instances, frameState) { const featureIdsArray = instances.featureIds; const count = instances.attributes[0].count; for (let i = 0; i < featureIdsArray.length; i++) { const featureIds = featureIdsArray[i]; const variableName = featureIds.positionalLabel; if (featureIds instanceof ModelComponents_default.FeatureIdAttribute) { processInstanceAttribute(renderResources, featureIds, variableName); } else { const instanceDivisor = 1; processImplicitRange( renderResources, featureIds, variableName, count, instanceDivisor, frameState ); } const label = featureIds.label; if (defined_default(label)) { addAlias(renderResources, variableName, label, ShaderDestination_default.BOTH); } } } function processPrimitiveFeatureIds(renderResources, primitive, frameState) { const featureIdsArray = primitive.featureIds; const positionAttribute = ModelUtility_default.getAttributeBySemantic( primitive, VertexAttributeSemantic_default.POSITION ); const count = positionAttribute.count; for (let i = 0; i < featureIdsArray.length; i++) { const featureIds = featureIdsArray[i]; const variableName = featureIds.positionalLabel; let aliasDestination = ShaderDestination_default.BOTH; if (featureIds instanceof ModelComponents_default.FeatureIdAttribute) { processAttribute(renderResources, featureIds, variableName); } else if (featureIds instanceof ModelComponents_default.FeatureIdImplicitRange) { processImplicitRange( renderResources, featureIds, variableName, count, void 0, frameState ); } else { processTexture(renderResources, featureIds, variableName, i, frameState); aliasDestination = ShaderDestination_default.FRAGMENT; } const label = featureIds.label; if (defined_default(label)) { addAlias(renderResources, variableName, label, aliasDestination); } } } function processInstanceAttribute(renderResources, featureIdAttribute, variableName) { const shaderBuilder = renderResources.shaderBuilder; shaderBuilder.addStructField( FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_VS, "int", variableName ); shaderBuilder.addStructField( FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_FS, "int", variableName ); const setIndex = featureIdAttribute.setIndex; const prefix = variableName.replace(/_\d+$/, "_"); const attributeName = `a_${prefix}${setIndex}`; const varyingName = `v_${prefix}${setIndex}`; const vertexLine = `featureIds.${variableName} = int(czm_round(${attributeName}));`; const fragmentLine = `featureIds.${variableName} = int(czm_round(${varyingName}));`; shaderBuilder.addFunctionLines( FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_IDS_VS, [vertexLine] ); shaderBuilder.addFunctionLines( FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_IDS_FS, [fragmentLine] ); shaderBuilder.addVarying("float", varyingName); shaderBuilder.addFunctionLines( FeatureIdPipelineStage.FUNCTION_ID_SET_FEATURE_ID_VARYINGS, [`${varyingName} = ${attributeName};`] ); } function processAttribute(renderResources, featureIdAttribute, variableName) { const shaderBuilder = renderResources.shaderBuilder; shaderBuilder.addStructField( FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_VS, "int", variableName ); shaderBuilder.addStructField( FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_FS, "int", variableName ); const setIndex = featureIdAttribute.setIndex; const prefix = variableName.replace(/_\d+$/, "_"); const initializationLines = [ `featureIds.${variableName} = int(czm_round(attributes.${prefix}${setIndex}));` ]; shaderBuilder.addFunctionLines( FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_IDS_VS, initializationLines ); shaderBuilder.addFunctionLines( FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_IDS_FS, initializationLines ); } function processImplicitRange(renderResources, implicitFeatureIds, variableName, count, instanceDivisor, frameState) { generateImplicitFeatureIdAttribute( renderResources, implicitFeatureIds, count, instanceDivisor, frameState ); const shaderBuilder = renderResources.shaderBuilder; const implicitAttributeName = `a_implicit_${variableName}`; shaderBuilder.addAttribute("float", implicitAttributeName); const implicitVaryingName = `v_implicit_${variableName}`; shaderBuilder.addVarying("float", implicitVaryingName); shaderBuilder.addStructField( FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_VS, "int", variableName ); shaderBuilder.addStructField( FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_FS, "int", variableName ); shaderBuilder.addFunctionLines( FeatureIdPipelineStage.FUNCTION_ID_SET_FEATURE_ID_VARYINGS, [`${implicitVaryingName} = ${implicitAttributeName};`] ); shaderBuilder.addFunctionLines( FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_IDS_VS, [`featureIds.${variableName} = int(czm_round(${implicitAttributeName}));`] ); shaderBuilder.addFunctionLines( FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_IDS_FS, [`featureIds.${variableName} = int(czm_round(${implicitVaryingName}));`] ); } function processTexture(renderResources, featureIdTexture, variableName, index, frameState) { const uniformName = `u_featureIdTexture_${index}`; const uniformMap2 = renderResources.uniformMap; const textureReader = featureIdTexture.textureReader; uniformMap2[uniformName] = function() { return defaultValue_default( textureReader.texture, frameState.context.defaultTexture ); }; const channels = textureReader.channels; const shaderBuilder = renderResources.shaderBuilder; shaderBuilder.addStructField( FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_FS, "int", variableName ); shaderBuilder.addUniform( "sampler2D", uniformName, ShaderDestination_default.FRAGMENT ); const texCoord = `v_texCoord_${textureReader.texCoord}`; const textureRead = `texture(${uniformName}, ${texCoord}).${channels}`; const initializationLine = `featureIds.${variableName} = czm_unpackUint(${textureRead});`; shaderBuilder.addFunctionLines( FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_IDS_FS, [initializationLine] ); } function addAlias(renderResources, variableName, alias, shaderDestination) { const shaderBuilder = renderResources.shaderBuilder; const updateVS = ShaderDestination_default.includesVertexShader(shaderDestination); if (updateVS) { shaderBuilder.addStructField( FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_VS, "int", alias ); } shaderBuilder.addStructField( FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_FS, "int", alias ); const initializationLines = [ `featureIds.${alias} = featureIds.${variableName};` ]; if (updateVS) { shaderBuilder.addFunctionLines( FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_ID_ALIASES_VS, initializationLines ); } shaderBuilder.addFunctionLines( FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_ID_ALIASES_FS, initializationLines ); } function generateImplicitFeatureIdAttribute(renderResources, implicitFeatureIds, count, instanceDivisor, frameState) { const model = renderResources.model; let vertexBuffer; let value; if (defined_default(implicitFeatureIds.repeat)) { const typedArray = generateImplicitFeatureIdTypedArray( implicitFeatureIds, count ); vertexBuffer = Buffer_default.createVertexBuffer({ context: frameState.context, typedArray, usage: BufferUsage_default.STATIC_DRAW }); vertexBuffer.vertexArrayDestroyable = false; model._pipelineResources.push(vertexBuffer); const hasCpuCopy = false; model.statistics.addBuffer(vertexBuffer, hasCpuCopy); } else { value = [implicitFeatureIds.offset]; } const generatedFeatureIdAttribute = { index: renderResources.attributeIndex++, instanceDivisor, value, vertexBuffer, normalize: false, componentsPerAttribute: 1, componentDatatype: ComponentDatatype_default.FLOAT, strideInBytes: ComponentDatatype_default.getSizeInBytes(ComponentDatatype_default.FLOAT), offsetInBytes: 0 }; renderResources.attributes.push(generatedFeatureIdAttribute); } function generateImplicitFeatureIdTypedArray(implicitFeatureIds, count) { const offset2 = implicitFeatureIds.offset; const repeat = implicitFeatureIds.repeat; const typedArray = new Float32Array(count); for (let i = 0; i < count; i++) { typedArray[i] = offset2 + Math.floor(i / repeat); } return typedArray; } var FeatureIdPipelineStage_default = FeatureIdPipelineStage; // packages/engine/Source/Shaders/Model/MetadataStageFS.js var MetadataStageFS_default = "void metadataStage(\n out Metadata metadata,\n out MetadataClass metadataClass,\n out MetadataStatistics metadataStatistics,\n ProcessedAttributes attributes\n )\n{\n initializeMetadata(metadata, metadataClass, metadataStatistics, attributes);\n}\n"; // packages/engine/Source/Shaders/Model/MetadataStageVS.js var MetadataStageVS_default = "void metadataStage(\n out Metadata metadata,\n out MetadataClass metadataClass,\n out MetadataStatistics metadataStatistics,\n ProcessedAttributes attributes\n )\n{\n initializeMetadata(metadata, metadataClass, metadataStatistics, attributes);\n setMetadataVaryings();\n}\n"; // packages/engine/Source/Scene/Model/MetadataPipelineStage.js var MetadataPipelineStage = { name: "MetadataPipelineStage", STRUCT_ID_METADATA_VS: "MetadataVS", STRUCT_ID_METADATA_FS: "MetadataFS", STRUCT_NAME_METADATA: "Metadata", STRUCT_ID_METADATA_CLASS_VS: "MetadataClassVS", STRUCT_ID_METADATA_CLASS_FS: "MetadataClassFS", STRUCT_NAME_METADATA_CLASS: "MetadataClass", STRUCT_ID_METADATA_STATISTICS_VS: "MetadataStatisticsVS", STRUCT_ID_METADATA_STATISTICS_FS: "MetadataStatisticsFS", STRUCT_NAME_METADATA_STATISTICS: "MetadataStatistics", FUNCTION_ID_INITIALIZE_METADATA_VS: "initializeMetadataVS", FUNCTION_ID_INITIALIZE_METADATA_FS: "initializeMetadataFS", FUNCTION_SIGNATURE_INITIALIZE_METADATA: "void initializeMetadata(out Metadata metadata, out MetadataClass metadataClass, out MetadataStatistics metadataStatistics, ProcessedAttributes attributes)", FUNCTION_ID_SET_METADATA_VARYINGS: "setMetadataVaryings", FUNCTION_SIGNATURE_SET_METADATA_VARYINGS: "void setMetadataVaryings()", // Metadata class and statistics fields: // - some must be renamed to avoid reserved words // - some always have float/vec values, even for integer/ivec property types METADATA_CLASS_FIELDS: [ { specName: "noData", shaderName: "noData" }, { specName: "default", shaderName: "defaultValue" }, { specName: "min", shaderName: "minValue" }, { specName: "max", shaderName: "maxValue" } ], METADATA_STATISTICS_FIELDS: [ { specName: "min", shaderName: "minValue" }, { specName: "max", shaderName: "maxValue" }, { specName: "mean", shaderName: "mean", type: "float" }, { specName: "median", shaderName: "median" }, { specName: "standardDeviation", shaderName: "standardDeviation", type: "float" }, { specName: "variance", shaderName: "variance", type: "float" }, { specName: "sum", shaderName: "sum" } ] }; MetadataPipelineStage.process = function(renderResources, primitive, frameState) { const { shaderBuilder, model } = renderResources; const { structuralMetadata = {}, content } = model; const statistics2 = content?.tileset.metadataExtension?.statistics; const propertyAttributesInfo = getPropertyAttributesInfo( structuralMetadata.propertyAttributes, primitive, statistics2 ); const propertyTexturesInfo = getPropertyTexturesInfo( structuralMetadata.propertyTextures, statistics2 ); const allPropertyInfos = propertyAttributesInfo.concat(propertyTexturesInfo); declareMetadataTypeStructs(shaderBuilder, allPropertyInfos); declareStructsAndFunctions2(shaderBuilder); shaderBuilder.addVertexLines(MetadataStageVS_default); shaderBuilder.addFragmentLines(MetadataStageFS_default); for (let i = 0; i < propertyAttributesInfo.length; i++) { const info = propertyAttributesInfo[i]; processPropertyAttributeProperty(renderResources, info); } for (let i = 0; i < propertyTexturesInfo.length; i++) { const info = propertyTexturesInfo[i]; processPropertyTextureProperty(renderResources, info); } }; function getPropertyAttributesInfo(propertyAttributes, primitive, statistics2) { if (!defined_default(propertyAttributes)) { return []; } return propertyAttributes.flatMap( (propertyAttribute) => getPropertyAttributeInfo(propertyAttribute, primitive, statistics2) ); } function getPropertyAttributeInfo(propertyAttribute, primitive, statistics2) { const { getAttributeByName, getAttributeInfo, sanitizeGlslIdentifier } = ModelUtility_default; const classId = propertyAttribute.class.id; const classStatistics = statistics2?.classes[classId]; const propertiesArray = Object.entries(propertyAttribute.properties); const infoArray = new Array(propertiesArray.length); for (let i = 0; i < propertiesArray.length; i++) { const [propertyId, property] = propertiesArray[i]; const modelAttribute = getAttributeByName(primitive, property.attribute); const { glslType, variableName } = getAttributeInfo(modelAttribute); infoArray[i] = { metadataVariable: sanitizeGlslIdentifier(propertyId), property, type: property.classProperty.type, glslType, variableName, propertyStatistics: classStatistics?.properties[propertyId], shaderDestination: ShaderDestination_default.BOTH }; } return infoArray; } function getPropertyTexturesInfo(propertyTextures, statistics2) { if (!defined_default(propertyTextures)) { return []; } return propertyTextures.flatMap( (propertyTexture) => getPropertyTextureInfo(propertyTexture, statistics2) ); } function getPropertyTextureInfo(propertyTexture, statistics2) { const { sanitizeGlslIdentifier } = ModelUtility_default; const classId = propertyTexture.class.id; const classStatistics = statistics2?.classes[classId]; const propertiesArray = Object.entries( propertyTexture.properties ).filter(([id, property]) => property.isGpuCompatible()); const infoArray = new Array(propertiesArray.length); for (let i = 0; i < propertiesArray.length; i++) { const [propertyId, property] = propertiesArray[i]; infoArray[i] = { metadataVariable: sanitizeGlslIdentifier(propertyId), property, type: property.classProperty.type, glslType: property.getGlslType(), propertyStatistics: classStatistics?.properties[propertyId], shaderDestination: ShaderDestination_default.FRAGMENT }; } return infoArray; } function declareMetadataTypeStructs(shaderBuilder, propertyInfos) { const classTypes = /* @__PURE__ */ new Set(); const statisticsTypes = /* @__PURE__ */ new Set(); for (let i = 0; i < propertyInfos.length; i++) { const { type, glslType, propertyStatistics } = propertyInfos[i]; classTypes.add(glslType); if (!defined_default(propertyStatistics)) { continue; } if (type !== MetadataType_default.ENUM) { statisticsTypes.add(glslType); } } const classFields = MetadataPipelineStage.METADATA_CLASS_FIELDS; for (const metadataType of classTypes) { const classStructName = `${metadataType}MetadataClass`; declareTypeStruct(classStructName, metadataType, classFields); } const statisticsFields = MetadataPipelineStage.METADATA_STATISTICS_FIELDS; for (const metadataType of statisticsTypes) { const statisticsStructName = `${metadataType}MetadataStatistics`; declareTypeStruct(statisticsStructName, metadataType, statisticsFields); } function declareTypeStruct(structName, type, fields) { shaderBuilder.addStruct(structName, structName, ShaderDestination_default.BOTH); for (let i = 0; i < fields.length; i++) { const { shaderName } = fields[i]; const shaderType = fields[i].type === "float" ? convertToFloatComponents(type) : type; shaderBuilder.addStructField(structName, shaderType, shaderName); } } } var floatConversions = { int: "float", ivec2: "vec2", ivec3: "vec3", ivec4: "vec4" }; function convertToFloatComponents(type) { const converted = floatConversions[type]; return defined_default(converted) ? converted : type; } function declareStructsAndFunctions2(shaderBuilder) { shaderBuilder.addStruct( MetadataPipelineStage.STRUCT_ID_METADATA_VS, MetadataPipelineStage.STRUCT_NAME_METADATA, ShaderDestination_default.VERTEX ); shaderBuilder.addStruct( MetadataPipelineStage.STRUCT_ID_METADATA_FS, MetadataPipelineStage.STRUCT_NAME_METADATA, ShaderDestination_default.FRAGMENT ); shaderBuilder.addStruct( MetadataPipelineStage.STRUCT_ID_METADATA_CLASS_VS, MetadataPipelineStage.STRUCT_NAME_METADATA_CLASS, ShaderDestination_default.VERTEX ); shaderBuilder.addStruct( MetadataPipelineStage.STRUCT_ID_METADATA_CLASS_FS, MetadataPipelineStage.STRUCT_NAME_METADATA_CLASS, ShaderDestination_default.FRAGMENT ); shaderBuilder.addStruct( MetadataPipelineStage.STRUCT_ID_METADATA_STATISTICS_VS, MetadataPipelineStage.STRUCT_NAME_METADATA_STATISTICS, ShaderDestination_default.VERTEX ); shaderBuilder.addStruct( MetadataPipelineStage.STRUCT_ID_METADATA_STATISTICS_FS, MetadataPipelineStage.STRUCT_NAME_METADATA_STATISTICS, ShaderDestination_default.FRAGMENT ); shaderBuilder.addFunction( MetadataPipelineStage.FUNCTION_ID_INITIALIZE_METADATA_VS, MetadataPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_METADATA, ShaderDestination_default.VERTEX ); shaderBuilder.addFunction( MetadataPipelineStage.FUNCTION_ID_INITIALIZE_METADATA_FS, MetadataPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_METADATA, ShaderDestination_default.FRAGMENT ); shaderBuilder.addFunction( MetadataPipelineStage.FUNCTION_ID_SET_METADATA_VARYINGS, MetadataPipelineStage.FUNCTION_SIGNATURE_SET_METADATA_VARYINGS, ShaderDestination_default.VERTEX ); } function processPropertyAttributeProperty(renderResources, propertyInfo) { addPropertyAttributePropertyMetadata(renderResources, propertyInfo); addPropertyMetadataClass(renderResources.shaderBuilder, propertyInfo); addPropertyMetadataStatistics(renderResources.shaderBuilder, propertyInfo); } function addPropertyAttributePropertyMetadata(renderResources, propertyInfo) { const { shaderBuilder } = renderResources; const { metadataVariable, property, glslType } = propertyInfo; const valueExpression = addValueTransformUniforms({ valueExpression: `attributes.${propertyInfo.variableName}`, renderResources, glslType, metadataVariable, shaderDestination: ShaderDestination_default.BOTH, property }); shaderBuilder.addStructField( MetadataPipelineStage.STRUCT_ID_METADATA_VS, glslType, metadataVariable ); shaderBuilder.addStructField( MetadataPipelineStage.STRUCT_ID_METADATA_FS, glslType, metadataVariable ); const initializationLine = `metadata.${metadataVariable} = ${valueExpression};`; shaderBuilder.addFunctionLines( MetadataPipelineStage.FUNCTION_ID_INITIALIZE_METADATA_VS, [initializationLine] ); shaderBuilder.addFunctionLines( MetadataPipelineStage.FUNCTION_ID_INITIALIZE_METADATA_FS, [initializationLine] ); } function processPropertyTextureProperty(renderResources, propertyInfo) { addPropertyTexturePropertyMetadata(renderResources, propertyInfo); addPropertyMetadataClass(renderResources.shaderBuilder, propertyInfo); addPropertyMetadataStatistics(renderResources.shaderBuilder, propertyInfo); } function addPropertyTexturePropertyMetadata(renderResources, propertyInfo) { const { shaderBuilder, uniformMap: uniformMap2 } = renderResources; const { metadataVariable, glslType, property } = propertyInfo; const { texCoord, channels, index, texture } = property.textureReader; const textureUniformName = `u_propertyTexture_${index}`; if (!uniformMap2.hasOwnProperty(textureUniformName)) { shaderBuilder.addUniform( "sampler2D", textureUniformName, ShaderDestination_default.FRAGMENT ); uniformMap2[textureUniformName] = () => texture; } shaderBuilder.addStructField( MetadataPipelineStage.STRUCT_ID_METADATA_FS, glslType, metadataVariable ); const texCoordVariable = `attributes.texCoord_${texCoord}`; const valueExpression = `texture(${textureUniformName}, ${texCoordVariable}).${channels}`; const unpackedValue = property.unpackInShader(valueExpression); const transformedValue = addValueTransformUniforms({ valueExpression: unpackedValue, renderResources, glslType, metadataVariable, shaderDestination: ShaderDestination_default.FRAGMENT, property }); const initializationLine = `metadata.${metadataVariable} = ${transformedValue};`; shaderBuilder.addFunctionLines( MetadataPipelineStage.FUNCTION_ID_INITIALIZE_METADATA_FS, [initializationLine] ); } function addPropertyMetadataClass(shaderBuilder, propertyInfo) { const { classProperty } = propertyInfo.property; const { metadataVariable, glslType, shaderDestination } = propertyInfo; const assignments = getStructAssignments( MetadataPipelineStage.METADATA_CLASS_FIELDS, classProperty, `metadataClass.${metadataVariable}`, glslType ); const metadataType = `${glslType}MetadataClass`; shaderBuilder.addStructField( MetadataPipelineStage.STRUCT_ID_METADATA_CLASS_FS, metadataType, metadataVariable ); shaderBuilder.addFunctionLines( MetadataPipelineStage.FUNCTION_ID_INITIALIZE_METADATA_FS, assignments ); if (!ShaderDestination_default.includesVertexShader(shaderDestination)) { return; } shaderBuilder.addStructField( MetadataPipelineStage.STRUCT_ID_METADATA_CLASS_VS, metadataType, metadataVariable ); shaderBuilder.addFunctionLines( MetadataPipelineStage.FUNCTION_ID_INITIALIZE_METADATA_VS, assignments ); } function addPropertyMetadataStatistics(shaderBuilder, propertyInfo) { const { propertyStatistics } = propertyInfo; if (!defined_default(propertyStatistics)) { return; } const { metadataVariable, type, glslType } = propertyInfo; if (type === MetadataType_default.ENUM) { return; } const fields = MetadataPipelineStage.METADATA_STATISTICS_FIELDS; const struct = `metadataStatistics.${metadataVariable}`; const assignments = getStructAssignments( fields, propertyStatistics, struct, glslType ); const statisticsType = `${glslType}MetadataStatistics`; shaderBuilder.addStructField( MetadataPipelineStage.STRUCT_ID_METADATA_STATISTICS_FS, statisticsType, metadataVariable ); shaderBuilder.addFunctionLines( MetadataPipelineStage.FUNCTION_ID_INITIALIZE_METADATA_FS, assignments ); if (!ShaderDestination_default.includesVertexShader(propertyInfo.shaderDestination)) { return; } shaderBuilder.addStructField( MetadataPipelineStage.STRUCT_ID_METADATA_STATISTICS_VS, statisticsType, metadataVariable ); shaderBuilder.addFunctionLines( MetadataPipelineStage.FUNCTION_ID_INITIALIZE_METADATA_VS, assignments ); } function getStructAssignments(fieldNames, values, struct, type) { function constructAssignment(field) { const value = values[field.specName]; if (defined_default(value)) { return `${struct}.${field.shaderName} = ${type}(${value});`; } } return defined_default(values) ? fieldNames.map(constructAssignment).filter(defined_default) : []; } function addValueTransformUniforms(options) { const { valueExpression, property } = options; if (!property.hasValueTransform) { return valueExpression; } const metadataVariable = options.metadataVariable; const offsetUniformName = `u_${metadataVariable}_offset`; const scaleUniformName = `u_${metadataVariable}_scale`; const { shaderBuilder, uniformMap: uniformMap2 } = options.renderResources; const { glslType, shaderDestination } = options; shaderBuilder.addUniform(glslType, offsetUniformName, shaderDestination); shaderBuilder.addUniform(glslType, scaleUniformName, shaderDestination); const { offset: offset2, scale } = property; uniformMap2[offsetUniformName] = () => offset2; uniformMap2[scaleUniformName] = () => scale; return `czm_valueTransform(${offsetUniformName}, ${scaleUniformName}, ${valueExpression})`; } var MetadataPipelineStage_default = MetadataPipelineStage; // packages/engine/Source/Scene/Model/CustomShaderTranslucencyMode.js var CustomShaderTranslucencyMode = { /** * Inherit translucency settings from the primitive's material. If the primitive used a * translucent material, the custom shader will also be considered translucent. If the primitive * used an opaque material, the custom shader will be considered opaque. * * @type {number} * @constant */ INHERIT: 0, /** * Force the primitive to render the primitive as opaque, ignoring any material settings. * * @type {number} * @constant */ OPAQUE: 1, /** * Force the primitive to render the primitive as translucent, ignoring any material settings. * * @type {number} * @constant */ TRANSLUCENT: 2 }; var CustomShaderTranslucencyMode_default = Object.freeze(CustomShaderTranslucencyMode); // packages/engine/Source/Scene/Model/CustomShaderPipelineStage.js var CustomShaderPipelineStage = { name: "CustomShaderPipelineStage", // Helps with debugging STRUCT_ID_ATTRIBUTES_VS: "AttributesVS", STRUCT_ID_ATTRIBUTES_FS: "AttributesFS", STRUCT_NAME_ATTRIBUTES: "Attributes", STRUCT_ID_VERTEX_INPUT: "VertexInput", STRUCT_NAME_VERTEX_INPUT: "VertexInput", STRUCT_ID_FRAGMENT_INPUT: "FragmentInput", STRUCT_NAME_FRAGMENT_INPUT: "FragmentInput", FUNCTION_ID_INITIALIZE_INPUT_STRUCT_VS: "initializeInputStructVS", FUNCTION_SIGNATURE_INITIALIZE_INPUT_STRUCT_VS: "void initializeInputStruct(out VertexInput vsInput, ProcessedAttributes attributes)", FUNCTION_ID_INITIALIZE_INPUT_STRUCT_FS: "initializeInputStructFS", FUNCTION_SIGNATURE_INITIALIZE_INPUT_STRUCT_FS: "void initializeInputStruct(out FragmentInput fsInput, ProcessedAttributes attributes)", // Expose method for testing. _oneTimeWarning: oneTimeWarning_default }; CustomShaderPipelineStage.process = function(renderResources, primitive, frameState) { const shaderBuilder = renderResources.shaderBuilder; const customShader = renderResources.model.customShader; if (defined_default(customShader.lightingModel)) { renderResources.lightingOptions.lightingModel = customShader.lightingModel; } const alphaOptions = renderResources.alphaOptions; if (customShader.translucencyMode === CustomShaderTranslucencyMode_default.TRANSLUCENT) { alphaOptions.pass = Pass_default.TRANSLUCENT; } else if (customShader.translucencyMode === CustomShaderTranslucencyMode_default.OPAQUE) { alphaOptions.pass = void 0; } const generatedCode = generateShaderLines(customShader, primitive); if (!generatedCode.customShaderEnabled) { return; } addLinesToShader(shaderBuilder, customShader, generatedCode); if (generatedCode.shouldComputePositionWC) { shaderBuilder.addDefine( "COMPUTE_POSITION_WC_CUSTOM_SHADER", void 0, ShaderDestination_default.BOTH ); } if (defined_default(customShader.vertexShaderText)) { shaderBuilder.addDefine( "HAS_CUSTOM_VERTEX_SHADER", void 0, ShaderDestination_default.VERTEX ); } if (defined_default(customShader.fragmentShaderText)) { shaderBuilder.addDefine( "HAS_CUSTOM_FRAGMENT_SHADER", void 0, ShaderDestination_default.FRAGMENT ); const shaderModeDefine = CustomShaderMode_default.getDefineName(customShader.mode); shaderBuilder.addDefine( shaderModeDefine, void 0, ShaderDestination_default.FRAGMENT ); } const uniforms = customShader.uniforms; for (const uniformName in uniforms) { if (uniforms.hasOwnProperty(uniformName)) { const uniform = uniforms[uniformName]; shaderBuilder.addUniform(uniform.type, uniformName); } } const varyings = customShader.varyings; for (const varyingName in varyings) { if (varyings.hasOwnProperty(varyingName)) { const varyingType = varyings[varyingName]; shaderBuilder.addVarying(varyingType, varyingName); } } renderResources.uniformMap = combine_default( renderResources.uniformMap, customShader.uniformMap ); }; function getAttributesByName(attributes) { const names = {}; for (let i = 0; i < attributes.length; i++) { const attribute = attributes[i]; const attributeInfo = ModelUtility_default.getAttributeInfo(attribute); names[attributeInfo.variableName] = attributeInfo; } return names; } var attributeTypeLUT = { position: "vec3", normal: "vec3", tangent: "vec3", bitangent: "vec3", texCoord: "vec2", color: "vec4", joints: "ivec4", weights: "vec4" }; var attributeDefaultValueLUT = { position: "vec3(0.0)", normal: "vec3(0.0, 0.0, 1.0)", tangent: "vec3(1.0, 0.0, 0.0)", bitangent: "vec3(0.0, 1.0, 0.0)", texCoord: "vec2(0.0)", color: "vec4(1.0)", joints: "ivec4(0)", weights: "vec4(0.0)" }; function inferAttributeDefaults(attributeName) { let trimmed = attributeName.replace(/_[0-9]+$/, ""); trimmed = trimmed.replace(/(MC|EC)$/, ""); const glslType = attributeTypeLUT[trimmed]; const value = attributeDefaultValueLUT[trimmed]; if (!defined_default(glslType)) { return void 0; } return { attributeField: [glslType, attributeName], value }; } function generateVertexShaderLines(customShader, attributesByName, vertexLines) { const categories = partitionAttributes( attributesByName, customShader.usedVariablesVertex.attributeSet, false ); const addToShader = categories.addToShader; const needsDefault = categories.missingAttributes; let variableName; let vertexInitialization; const attributeFields = []; const initializationLines = []; for (variableName in addToShader) { if (addToShader.hasOwnProperty(variableName)) { const attributeInfo = addToShader[variableName]; const attributeField = [attributeInfo.glslType, variableName]; attributeFields.push(attributeField); vertexInitialization = `vsInput.attributes.${variableName} = attributes.${variableName};`; initializationLines.push(vertexInitialization); } } for (let i = 0; i < needsDefault.length; i++) { variableName = needsDefault[i]; const attributeDefaults = inferAttributeDefaults(variableName); if (!defined_default(attributeDefaults)) { CustomShaderPipelineStage._oneTimeWarning( "CustomShaderPipelineStage.incompatiblePrimitiveVS", `Primitive is missing attribute ${variableName}, disabling custom vertex shader` ); return; } attributeFields.push(attributeDefaults.attributeField); vertexInitialization = `vsInput.attributes.${variableName} = ${attributeDefaults.value};`; initializationLines.push(vertexInitialization); } vertexLines.enabled = true; vertexLines.attributeFields = attributeFields; vertexLines.initializationLines = initializationLines; } function generatePositionBuiltins(customShader) { const attributeFields = []; const initializationLines = []; const usedVariables = customShader.usedVariablesFragment.attributeSet; if (usedVariables.hasOwnProperty("positionWC")) { attributeFields.push(["vec3", "positionWC"]); initializationLines.push( "fsInput.attributes.positionWC = attributes.positionWC;" ); } if (usedVariables.hasOwnProperty("positionEC")) { attributeFields.push(["vec3", "positionEC"]); initializationLines.push( "fsInput.attributes.positionEC = attributes.positionEC;" ); } return { attributeFields, initializationLines }; } function generateFragmentShaderLines(customShader, attributesByName, fragmentLines) { const categories = partitionAttributes( attributesByName, customShader.usedVariablesFragment.attributeSet, true ); const addToShader = categories.addToShader; const needsDefault = categories.missingAttributes; let variableName; let fragmentInitialization; const attributeFields = []; const initializationLines = []; for (variableName in addToShader) { if (addToShader.hasOwnProperty(variableName)) { const attributeInfo = addToShader[variableName]; const attributeField = [attributeInfo.glslType, variableName]; attributeFields.push(attributeField); fragmentInitialization = `fsInput.attributes.${variableName} = attributes.${variableName};`; initializationLines.push(fragmentInitialization); } } for (let i = 0; i < needsDefault.length; i++) { variableName = needsDefault[i]; const attributeDefaults = inferAttributeDefaults(variableName); if (!defined_default(attributeDefaults)) { CustomShaderPipelineStage._oneTimeWarning( "CustomShaderPipelineStage.incompatiblePrimitiveFS", `Primitive is missing attribute ${variableName}, disabling custom fragment shader.` ); return; } attributeFields.push(attributeDefaults.attributeField); fragmentInitialization = `fsInput.attributes.${variableName} = ${attributeDefaults.value};`; initializationLines.push(fragmentInitialization); } const positionBuiltins = generatePositionBuiltins(customShader); fragmentLines.enabled = true; fragmentLines.attributeFields = attributeFields.concat( positionBuiltins.attributeFields ); fragmentLines.initializationLines = positionBuiltins.initializationLines.concat( initializationLines ); } var builtinAttributes = { positionWC: true, positionEC: true }; function partitionAttributes(primitiveAttributes, shaderAttributeSet, isFragmentShader) { let renamed; let attributeName; const addToShader = {}; for (attributeName in primitiveAttributes) { if (primitiveAttributes.hasOwnProperty(attributeName)) { const attribute = primitiveAttributes[attributeName]; renamed = attributeName; if (isFragmentShader && attributeName === "normalMC") { renamed = "normalEC"; } else if (isFragmentShader && attributeName === "tangentMC") { renamed = "tangentEC"; } if (shaderAttributeSet.hasOwnProperty(renamed)) { addToShader[renamed] = attribute; } } } const missingAttributes = []; for (attributeName in shaderAttributeSet) { if (shaderAttributeSet.hasOwnProperty(attributeName)) { if (builtinAttributes.hasOwnProperty(attributeName)) { continue; } renamed = attributeName; if (isFragmentShader && attributeName === "normalEC") { renamed = "normalMC"; } else if (isFragmentShader && attributeName === "tangentEC") { renamed = "tangentMC"; } if (!primitiveAttributes.hasOwnProperty(renamed)) { missingAttributes.push(attributeName); } } } return { addToShader, missingAttributes }; } function generateShaderLines(customShader, primitive) { const vertexLines = { enabled: false }; const fragmentLines = { enabled: false }; const attributesByName = getAttributesByName(primitive.attributes); if (defined_default(customShader.vertexShaderText)) { generateVertexShaderLines(customShader, attributesByName, vertexLines); } if (defined_default(customShader.fragmentShaderText)) { generateFragmentShaderLines(customShader, attributesByName, fragmentLines); } const attributeSetFS = customShader.usedVariablesFragment.attributeSet; const shouldComputePositionWC = attributeSetFS.hasOwnProperty("positionWC") && fragmentLines.enabled; return { vertexLines, fragmentLines, vertexLinesEnabled: vertexLines.enabled, fragmentLinesEnabled: fragmentLines.enabled, customShaderEnabled: vertexLines.enabled || fragmentLines.enabled, shouldComputePositionWC }; } function addVertexLinesToShader(shaderBuilder, vertexLines) { let i; let structId = CustomShaderPipelineStage.STRUCT_ID_ATTRIBUTES_VS; shaderBuilder.addStruct( structId, CustomShaderPipelineStage.STRUCT_NAME_ATTRIBUTES, ShaderDestination_default.VERTEX ); const attributeFields = vertexLines.attributeFields; for (i = 0; i < attributeFields.length; i++) { const field = attributeFields[i]; const glslType = field[0]; const variableName = field[1]; shaderBuilder.addStructField(structId, glslType, variableName); } structId = CustomShaderPipelineStage.STRUCT_ID_VERTEX_INPUT; shaderBuilder.addStruct( structId, CustomShaderPipelineStage.STRUCT_NAME_VERTEX_INPUT, ShaderDestination_default.VERTEX ); shaderBuilder.addStructField( structId, CustomShaderPipelineStage.STRUCT_NAME_ATTRIBUTES, "attributes" ); shaderBuilder.addStructField( structId, FeatureIdPipelineStage_default.STRUCT_NAME_FEATURE_IDS, "featureIds" ); shaderBuilder.addStructField( structId, MetadataPipelineStage_default.STRUCT_NAME_METADATA, "metadata" ); shaderBuilder.addStructField( structId, MetadataPipelineStage_default.STRUCT_NAME_METADATA_CLASS, "metadataClass" ); shaderBuilder.addStructField( structId, MetadataPipelineStage_default.STRUCT_NAME_METADATA_STATISTICS, "metadataStatistics" ); const functionId = CustomShaderPipelineStage.FUNCTION_ID_INITIALIZE_INPUT_STRUCT_VS; shaderBuilder.addFunction( functionId, CustomShaderPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_INPUT_STRUCT_VS, ShaderDestination_default.VERTEX ); const initializationLines = vertexLines.initializationLines; shaderBuilder.addFunctionLines(functionId, initializationLines); } function addFragmentLinesToShader(shaderBuilder, fragmentLines) { let i; let structId = CustomShaderPipelineStage.STRUCT_ID_ATTRIBUTES_FS; shaderBuilder.addStruct( structId, CustomShaderPipelineStage.STRUCT_NAME_ATTRIBUTES, ShaderDestination_default.FRAGMENT ); let field; let glslType; let variableName; const attributeFields = fragmentLines.attributeFields; for (i = 0; i < attributeFields.length; i++) { field = attributeFields[i]; glslType = field[0]; variableName = field[1]; shaderBuilder.addStructField(structId, glslType, variableName); } structId = CustomShaderPipelineStage.STRUCT_ID_FRAGMENT_INPUT; shaderBuilder.addStruct( structId, CustomShaderPipelineStage.STRUCT_NAME_FRAGMENT_INPUT, ShaderDestination_default.FRAGMENT ); shaderBuilder.addStructField( structId, CustomShaderPipelineStage.STRUCT_NAME_ATTRIBUTES, "attributes" ); shaderBuilder.addStructField( structId, FeatureIdPipelineStage_default.STRUCT_NAME_FEATURE_IDS, "featureIds" ); shaderBuilder.addStructField( structId, MetadataPipelineStage_default.STRUCT_NAME_METADATA, "metadata" ); shaderBuilder.addStructField( structId, MetadataPipelineStage_default.STRUCT_NAME_METADATA_CLASS, "metadataClass" ); shaderBuilder.addStructField( structId, MetadataPipelineStage_default.STRUCT_NAME_METADATA_STATISTICS, "metadataStatistics" ); const functionId = CustomShaderPipelineStage.FUNCTION_ID_INITIALIZE_INPUT_STRUCT_FS; shaderBuilder.addFunction( functionId, CustomShaderPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_INPUT_STRUCT_FS, ShaderDestination_default.FRAGMENT ); const initializationLines = fragmentLines.initializationLines; shaderBuilder.addFunctionLines(functionId, initializationLines); } var scratchShaderLines = []; function addLinesToShader(shaderBuilder, customShader, generatedCode) { const vertexLines = generatedCode.vertexLines; const shaderLines = scratchShaderLines; if (vertexLines.enabled) { addVertexLinesToShader(shaderBuilder, vertexLines); shaderLines.length = 0; shaderLines.push( "#line 0", customShader.vertexShaderText, CustomShaderStageVS_default ); shaderBuilder.addVertexLines(shaderLines); } const fragmentLines = generatedCode.fragmentLines; if (fragmentLines.enabled) { addFragmentLinesToShader(shaderBuilder, fragmentLines); shaderLines.length = 0; shaderLines.push( "#line 0", customShader.fragmentShaderText, CustomShaderStageFS_default ); shaderBuilder.addFragmentLines(shaderLines); } } var CustomShaderPipelineStage_default = CustomShaderPipelineStage; // packages/engine/Source/Scene/Model/DequantizationPipelineStage.js var DequantizationPipelineStage = { name: "DequantizationPipelineStage", // Helps with debugging FUNCTION_ID_DEQUANTIZATION_STAGE_VS: "dequantizationStage", FUNCTION_SIGNATURE_DEQUANTIZATION_STAGE_VS: "void dequantizationStage(inout ProcessedAttributes attributes)" }; DequantizationPipelineStage.process = function(renderResources, primitive, frameState) { const shaderBuilder = renderResources.shaderBuilder; const model = renderResources.model; const hasClassification = defined_default(model.classificationType); shaderBuilder.addDefine( "USE_DEQUANTIZATION", void 0, ShaderDestination_default.VERTEX ); shaderBuilder.addFunction( DequantizationPipelineStage.FUNCTION_ID_DEQUANTIZATION_STAGE_VS, DequantizationPipelineStage.FUNCTION_SIGNATURE_DEQUANTIZATION_STAGE_VS, ShaderDestination_default.VERTEX ); const attributes = primitive.attributes; for (let i = 0; i < attributes.length; i++) { const attribute = attributes[i]; const quantization = attribute.quantization; if (!defined_default(quantization)) { continue; } const isPositionAttribute = attribute.semantic === VertexAttributeSemantic_default.POSITION; const isTexcoordAttribute = attribute.semantic === VertexAttributeSemantic_default.TEXCOORD; if (hasClassification && !isPositionAttribute && !isTexcoordAttribute) { continue; } const attributeInfo = ModelUtility_default.getAttributeInfo(attribute); updateDequantizationFunction(shaderBuilder, attributeInfo); addDequantizationUniforms(renderResources, attributeInfo); } }; function addDequantizationUniforms(renderResources, attributeInfo) { const shaderBuilder = renderResources.shaderBuilder; const uniformMap2 = renderResources.uniformMap; const variableName = attributeInfo.variableName; const quantization = attributeInfo.attribute.quantization; if (quantization.octEncoded) { const normalizationRange = `model_normalizationRange_${variableName}`; shaderBuilder.addUniform( "float", normalizationRange, ShaderDestination_default.VERTEX ); uniformMap2[normalizationRange] = function() { return quantization.normalizationRange; }; } else { const offset2 = `model_quantizedVolumeOffset_${variableName}`; const stepSize = `model_quantizedVolumeStepSize_${variableName}`; const glslType = attributeInfo.glslType; shaderBuilder.addUniform(glslType, offset2, ShaderDestination_default.VERTEX); shaderBuilder.addUniform(glslType, stepSize, ShaderDestination_default.VERTEX); let quantizedVolumeOffset = quantization.quantizedVolumeOffset; let quantizedVolumeStepSize = quantization.quantizedVolumeStepSize; if (/^color_\d+$/.test(variableName)) { quantizedVolumeOffset = promoteToVec4(quantizedVolumeOffset, 0); quantizedVolumeStepSize = promoteToVec4(quantizedVolumeStepSize, 1); } uniformMap2[offset2] = function() { return quantizedVolumeOffset; }; uniformMap2[stepSize] = function() { return quantizedVolumeStepSize; }; } } function promoteToVec4(value, defaultAlpha) { if (value instanceof Cartesian4_default) { return value; } return new Cartesian4_default(value.x, value.y, value.z, defaultAlpha); } function updateDequantizationFunction(shaderBuilder, attributeInfo) { const variableName = attributeInfo.variableName; const quantization = attributeInfo.attribute.quantization; let line; if (quantization.octEncoded) { line = generateOctDecodeLine(variableName, quantization); } else { line = generateDequantizeLine(variableName); } shaderBuilder.addFunctionLines( DequantizationPipelineStage.FUNCTION_ID_DEQUANTIZATION_STAGE_VS, [line] ); } function generateOctDecodeLine(variableName, quantization) { const structField = `attributes.${variableName}`; const quantizedAttribute = `a_quantized_${variableName}`; const normalizationRange = `model_normalizationRange_${variableName}`; const swizzle = quantization.octEncodedZXY ? ".zxy" : ".xyz"; return `${structField} = czm_octDecode(${quantizedAttribute}, ${normalizationRange})${swizzle};`; } function generateDequantizeLine(variableName) { const structField = `attributes.${variableName}`; const quantizedAttribute = `a_quantized_${variableName}`; const offset2 = `model_quantizedVolumeOffset_${variableName}`; const stepSize = `model_quantizedVolumeStepSize_${variableName}`; return `${structField} = ${offset2} + ${quantizedAttribute} * ${stepSize};`; } var DequantizationPipelineStage_default = DequantizationPipelineStage; // packages/engine/Source/Shaders/Model/GeometryStageFS.js var GeometryStageFS_default = "void geometryStage(out ProcessedAttributes attributes)\n{\n attributes.positionMC = v_positionMC;\n attributes.positionEC = v_positionEC;\n\n #ifdef COMPUTE_POSITION_WC_CUSTOM_SHADER\n attributes.positionWC = v_positionWC;\n #endif\n\n #ifdef HAS_NORMALS\n // renormalize after interpolation\n attributes.normalEC = normalize(v_normalEC);\n #endif\n\n #ifdef HAS_TANGENTS\n attributes.tangentEC = normalize(v_tangentEC);\n #endif\n\n #ifdef HAS_BITANGENTS\n attributes.bitangentEC = normalize(v_bitangentEC);\n #endif\n\n // Everything else is dynamically generated in GeometryPipelineStage\n setDynamicVaryings(attributes);\n}\n"; // packages/engine/Source/Shaders/Model/GeometryStageVS.js var GeometryStageVS_default = "vec4 geometryStage(inout ProcessedAttributes attributes, mat4 modelView, mat3 normal) \n{\n vec4 computedPosition;\n\n // Compute positions in different coordinate systems\n vec3 positionMC = attributes.positionMC;\n v_positionMC = positionMC;\n v_positionEC = (modelView * vec4(positionMC, 1.0)).xyz;\n\n #if defined(USE_2D_POSITIONS) || defined(USE_2D_INSTANCING)\n vec3 position2D = attributes.position2D;\n vec3 positionEC = (u_modelView2D * vec4(position2D, 1.0)).xyz;\n computedPosition = czm_projection * vec4(positionEC, 1.0);\n #else\n computedPosition = czm_projection * vec4(v_positionEC, 1.0);\n #endif\n\n // Sometimes the custom shader and/or style needs this\n #if defined(COMPUTE_POSITION_WC_CUSTOM_SHADER) || defined(COMPUTE_POSITION_WC_STYLE)\n // Note that this is a 32-bit position which may result in jitter on small\n // scales.\n v_positionWC = (czm_model * vec4(positionMC, 1.0)).xyz;\n #endif\n\n #ifdef HAS_NORMALS\n v_normalEC = normalize(normal * attributes.normalMC);\n #endif\n\n #ifdef HAS_TANGENTS\n v_tangentEC = normalize(normal * attributes.tangentMC); \n #endif\n\n #ifdef HAS_BITANGENTS\n v_bitangentEC = normalize(normal * attributes.bitangentMC);\n #endif\n\n // All other varyings need to be dynamically generated in\n // GeometryPipelineStage\n setDynamicVaryings(attributes);\n \n return computedPosition;\n}\n"; // packages/engine/Source/Shaders/Model/SelectedFeatureIdStageCommon.js var SelectedFeatureIdStageCommon_default = "vec2 computeSt(float featureId)\n{\n float stepX = model_textureStep.x;\n float centerX = model_textureStep.y;\n\n #ifdef MULTILINE_BATCH_TEXTURE\n float stepY = model_textureStep.z;\n float centerY = model_textureStep.w;\n\n float xId = mod(featureId, model_textureDimensions.x); \n float yId = floor(featureId / model_textureDimensions.x);\n \n return vec2(centerX + (xId * stepX), centerY + (yId * stepY));\n #else\n return vec2(centerX + (featureId * stepX), 0.5);\n #endif\n}\n\nvoid selectedFeatureIdStage(out SelectedFeature feature, FeatureIds featureIds)\n{ \n int featureId = featureIds.SELECTED_FEATURE_ID;\n\n\n if (featureId < model_featuresLength)\n {\n vec2 featureSt = computeSt(float(featureId));\n\n feature.id = featureId;\n feature.st = featureSt;\n feature.color = texture(model_batchTexture, featureSt);\n }\n // Floating point comparisons can be unreliable in GLSL, so we\n // increment the feature ID to make sure it's always greater\n // then the model_featuresLength - a condition we check for in the\n // pick ID, to avoid sampling the pick texture if the feature ID is\n // greater than the number of features.\n else\n {\n feature.id = model_featuresLength + 1;\n feature.st = vec2(0.0);\n feature.color = vec4(1.0);\n }\n\n #ifdef HAS_NULL_FEATURE_ID\n if (featureId == model_nullFeatureId) {\n feature.id = featureId;\n feature.st = vec2(0.0);\n feature.color = vec4(1.0);\n }\n #endif\n}\n"; // packages/engine/Source/Scene/Model/SelectedFeatureIdPipelineStage.js var SelectedFeatureIdPipelineStage = { name: "SelectedFeatureIdPipelineStage", // Helps with debugging STRUCT_ID_SELECTED_FEATURE: "SelectedFeature", STRUCT_NAME_SELECTED_FEATURE: "SelectedFeature", FUNCTION_ID_FEATURE_VARYINGS_VS: "updateFeatureStructVS", FUNCTION_ID_FEATURE_VARYINGS_FS: "updateFeatureStructFS", FUNCTION_SIGNATURE_UPDATE_FEATURE: "void updateFeatureStruct(inout SelectedFeature feature)" }; SelectedFeatureIdPipelineStage.process = function(renderResources, primitive, frameState) { const shaderBuilder = renderResources.shaderBuilder; renderResources.hasPropertyTable = true; const model = renderResources.model; const node = renderResources.runtimeNode.node; const selectedFeatureIds = getSelectedFeatureIds(model, node, primitive); const shaderDestination = selectedFeatureIds.shaderDestination; shaderBuilder.addDefine( "HAS_SELECTED_FEATURE_ID", void 0, shaderDestination ); shaderBuilder.addDefine( "SELECTED_FEATURE_ID", selectedFeatureIds.variableName, shaderDestination ); shaderBuilder.addDefine( selectedFeatureIds.featureIdDefine, void 0, shaderDestination ); updateFeatureStruct(shaderBuilder); const nullFeatureId = selectedFeatureIds.featureIds.nullFeatureId; const uniformMap2 = renderResources.uniformMap; if (defined_default(nullFeatureId)) { shaderBuilder.addDefine( "HAS_NULL_FEATURE_ID", void 0, shaderDestination ); shaderBuilder.addUniform("int", "model_nullFeatureId", shaderDestination); uniformMap2.model_nullFeatureId = function() { return nullFeatureId; }; } if (selectedFeatureIds.shaderDestination === ShaderDestination_default.BOTH) { shaderBuilder.addVertexLines(SelectedFeatureIdStageCommon_default); } shaderBuilder.addFragmentLines(SelectedFeatureIdStageCommon_default); }; function getFeatureIdDefine(featureIds) { if (featureIds instanceof ModelComponents_default.FeatureIdTexture) { return "HAS_SELECTED_FEATURE_ID_TEXTURE"; } return "HAS_SELECTED_FEATURE_ID_ATTRIBUTE"; } function getShaderDestination(featureIds) { if (featureIds instanceof ModelComponents_default.FeatureIdTexture) { return ShaderDestination_default.FRAGMENT; } return ShaderDestination_default.BOTH; } function getSelectedFeatureIds(model, node, primitive) { let variableName; let featureIds; if (defined_default(node.instances)) { featureIds = ModelUtility_default.getFeatureIdsByLabel( node.instances.featureIds, model.instanceFeatureIdLabel ); if (defined_default(featureIds)) { variableName = defaultValue_default(featureIds.label, featureIds.positionalLabel); return { featureIds, variableName, shaderDestination: getShaderDestination(featureIds), featureIdDefine: getFeatureIdDefine(featureIds) }; } } featureIds = ModelUtility_default.getFeatureIdsByLabel( primitive.featureIds, model.featureIdLabel ); variableName = defaultValue_default(featureIds.label, featureIds.positionalLabel); return { featureIds, variableName, shaderDestination: getShaderDestination(featureIds), featureIdDefine: getFeatureIdDefine(featureIds) }; } function updateFeatureStruct(shaderBuilder) { shaderBuilder.addStructField( SelectedFeatureIdPipelineStage.STRUCT_ID_SELECTED_FEATURE, "int", "id" ); shaderBuilder.addStructField( SelectedFeatureIdPipelineStage.STRUCT_ID_SELECTED_FEATURE, "vec2", "st" ); shaderBuilder.addStructField( SelectedFeatureIdPipelineStage.STRUCT_ID_SELECTED_FEATURE, "vec4", "color" ); } var SelectedFeatureIdPipelineStage_default = SelectedFeatureIdPipelineStage; // packages/engine/Source/Scene/Model/GeometryPipelineStage.js var GeometryPipelineStage = { name: "GeometryPipelineStage", // Helps with debugging STRUCT_ID_PROCESSED_ATTRIBUTES_VS: "ProcessedAttributesVS", STRUCT_ID_PROCESSED_ATTRIBUTES_FS: "ProcessedAttributesFS", STRUCT_NAME_PROCESSED_ATTRIBUTES: "ProcessedAttributes", FUNCTION_ID_INITIALIZE_ATTRIBUTES: "initializeAttributes", FUNCTION_SIGNATURE_INITIALIZE_ATTRIBUTES: "void initializeAttributes(out ProcessedAttributes attributes)", FUNCTION_ID_SET_DYNAMIC_VARYINGS_VS: "setDynamicVaryingsVS", FUNCTION_ID_SET_DYNAMIC_VARYINGS_FS: "setDynamicVaryingsFS", FUNCTION_SIGNATURE_SET_DYNAMIC_VARYINGS: "void setDynamicVaryings(inout ProcessedAttributes attributes)" }; GeometryPipelineStage.process = function(renderResources, primitive, frameState) { const shaderBuilder = renderResources.shaderBuilder; const model = renderResources.model; shaderBuilder.addStruct( GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_VS, "ProcessedAttributes", ShaderDestination_default.VERTEX ); shaderBuilder.addStruct( GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_FS, "ProcessedAttributes", ShaderDestination_default.FRAGMENT ); shaderBuilder.addStruct( SelectedFeatureIdPipelineStage_default.STRUCT_ID_SELECTED_FEATURE, SelectedFeatureIdPipelineStage_default.STRUCT_NAME_SELECTED_FEATURE, ShaderDestination_default.BOTH ); shaderBuilder.addFunction( GeometryPipelineStage.FUNCTION_ID_INITIALIZE_ATTRIBUTES, GeometryPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_ATTRIBUTES, ShaderDestination_default.VERTEX ); shaderBuilder.addVarying("vec3", "v_positionWC"); shaderBuilder.addVarying("vec3", "v_positionEC"); shaderBuilder.addStructField( GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_FS, "vec3", "positionWC" ); shaderBuilder.addStructField( GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_FS, "vec3", "positionEC" ); shaderBuilder.addFunction( GeometryPipelineStage.FUNCTION_ID_SET_DYNAMIC_VARYINGS_VS, GeometryPipelineStage.FUNCTION_SIGNATURE_SET_DYNAMIC_VARYINGS, ShaderDestination_default.VERTEX ); shaderBuilder.addFunction( GeometryPipelineStage.FUNCTION_ID_SET_DYNAMIC_VARYINGS_FS, GeometryPipelineStage.FUNCTION_SIGNATURE_SET_DYNAMIC_VARYINGS, ShaderDestination_default.FRAGMENT ); const modelType = model.type; if (modelType === ModelType_default.TILE_PNTS) { shaderBuilder.addDefine( "HAS_SRGB_COLOR", void 0, ShaderDestination_default.FRAGMENT ); } const use2D = frameState.mode !== SceneMode_default.SCENE3D && !frameState.scene3DOnly && model._projectTo2D; const instanced = defined_default(renderResources.runtimeNode.node.instances); const incrementIndexFor2D = use2D && !instanced; const length3 = primitive.attributes.length; for (let i = 0; i < length3; i++) { const attribute = primitive.attributes[i]; const attributeLocationCount = AttributeType_default.getAttributeLocationCount( attribute.type ); if (!defined_default(attribute.buffer) && !defined_default(attribute.constant)) { throw new DeveloperError_default( "Attributes must be provided as a Buffer or constant value" ); } const isPositionAttribute = attribute.semantic === VertexAttributeSemantic_default.POSITION; let index; if (attributeLocationCount > 1) { index = renderResources.attributeIndex; renderResources.attributeIndex += attributeLocationCount; } else if (isPositionAttribute && !incrementIndexFor2D) { index = 0; } else { index = renderResources.attributeIndex++; } processAttribute2( renderResources, attribute, index, attributeLocationCount, use2D, instanced ); } handleBitangents(shaderBuilder, primitive.attributes); if (primitive.primitiveType === PrimitiveType_default.POINTS) { shaderBuilder.addDefine("PRIMITIVE_TYPE_POINTS"); } shaderBuilder.addVertexLines(GeometryStageVS_default); shaderBuilder.addFragmentLines(GeometryStageFS_default); }; function processAttribute2(renderResources, attribute, attributeIndex, attributeLocationCount, use2D, instanced) { const shaderBuilder = renderResources.shaderBuilder; const attributeInfo = ModelUtility_default.getAttributeInfo(attribute); const modifyFor2D = use2D && !instanced; if (attributeLocationCount > 1) { addMatrixAttributeToRenderResources( renderResources, attribute, attributeIndex, attributeLocationCount ); } else { addAttributeToRenderResources( renderResources, attribute, attributeIndex, modifyFor2D ); } addAttributeDeclaration(shaderBuilder, attributeInfo, modifyFor2D); addVaryingDeclaration(shaderBuilder, attributeInfo); if (defined_default(attribute.semantic)) { addSemanticDefine(shaderBuilder, attribute); } updateAttributesStruct(shaderBuilder, attributeInfo, use2D); updateInitializeAttributesFunction(shaderBuilder, attributeInfo, modifyFor2D); updateSetDynamicVaryingsFunction(shaderBuilder, attributeInfo); } function addSemanticDefine(shaderBuilder, attribute) { const semantic = attribute.semantic; const setIndex = attribute.setIndex; switch (semantic) { case VertexAttributeSemantic_default.NORMAL: shaderBuilder.addDefine("HAS_NORMALS"); break; case VertexAttributeSemantic_default.TANGENT: shaderBuilder.addDefine("HAS_TANGENTS"); break; case VertexAttributeSemantic_default.FEATURE_ID: shaderBuilder.addDefine(`HAS${semantic}_${setIndex}`); break; case VertexAttributeSemantic_default.TEXCOORD: case VertexAttributeSemantic_default.COLOR: shaderBuilder.addDefine(`HAS_${semantic}_${setIndex}`); } } function addAttributeToRenderResources(renderResources, attribute, attributeIndex, modifyFor2D) { const quantization = attribute.quantization; let type; let componentDatatype; if (defined_default(quantization)) { type = quantization.type; componentDatatype = quantization.componentDatatype; } else { type = attribute.type; componentDatatype = attribute.componentDatatype; } const semantic = attribute.semantic; const setIndex = attribute.setIndex; if (semantic === VertexAttributeSemantic_default.FEATURE_ID && setIndex >= renderResources.featureIdVertexAttributeSetIndex) { renderResources.featureIdVertexAttributeSetIndex = setIndex + 1; } const isPositionAttribute = semantic === VertexAttributeSemantic_default.POSITION; const index = isPositionAttribute ? 0 : attributeIndex; const componentsPerAttribute = AttributeType_default.getNumberOfComponents(type); const vertexAttribute = { index, value: defined_default(attribute.buffer) ? void 0 : attribute.constant, vertexBuffer: attribute.buffer, count: attribute.count, componentsPerAttribute, componentDatatype, offsetInBytes: attribute.byteOffset, strideInBytes: attribute.byteStride, normalize: attribute.normalized }; renderResources.attributes.push(vertexAttribute); if (!isPositionAttribute || !modifyFor2D) { return; } const buffer2D = renderResources.runtimePrimitive.positionBuffer2D; const positionAttribute2D = { index: attributeIndex, vertexBuffer: buffer2D, count: attribute.count, componentsPerAttribute, componentDatatype: ComponentDatatype_default.FLOAT, // Projected positions will always be floats. offsetInBytes: 0, strideInBytes: void 0, normalize: attribute.normalized }; renderResources.attributes.push(positionAttribute2D); } function addMatrixAttributeToRenderResources(renderResources, attribute, attributeIndex, columnCount) { const quantization = attribute.quantization; let type; let componentDatatype; if (defined_default(quantization)) { type = quantization.type; componentDatatype = quantization.componentDatatype; } else { type = attribute.type; componentDatatype = attribute.componentDatatype; } const normalized = attribute.normalized; const componentCount = AttributeType_default.getNumberOfComponents(type); const componentsPerColumn = componentCount / columnCount; const componentSizeInBytes = ComponentDatatype_default.getSizeInBytes( componentDatatype ); const columnLengthInBytes = componentsPerColumn * componentSizeInBytes; const strideInBytes = attribute.byteStride; for (let i = 0; i < columnCount; i++) { const offsetInBytes = attribute.byteOffset + i * columnLengthInBytes; const columnAttribute = { index: attributeIndex + i, vertexBuffer: attribute.buffer, componentsPerAttribute: componentsPerColumn, componentDatatype, offsetInBytes, strideInBytes, normalize: normalized }; renderResources.attributes.push(columnAttribute); } } function addVaryingDeclaration(shaderBuilder, attributeInfo) { const variableName = attributeInfo.variableName; let varyingName = `v_${variableName}`; let glslType; if (variableName === "normalMC") { varyingName = "v_normalEC"; glslType = attributeInfo.glslType; } else if (variableName === "tangentMC") { glslType = "vec3"; varyingName = "v_tangentEC"; } else { glslType = attributeInfo.glslType; } shaderBuilder.addVarying(glslType, varyingName); } function addAttributeDeclaration(shaderBuilder, attributeInfo, modifyFor2D) { const semantic = attributeInfo.attribute.semantic; const variableName = attributeInfo.variableName; let attributeName; let glslType; if (attributeInfo.isQuantized) { attributeName = `a_quantized_${variableName}`; glslType = attributeInfo.quantizedGlslType; } else { attributeName = `a_${variableName}`; glslType = attributeInfo.glslType; } const isPosition = semantic === VertexAttributeSemantic_default.POSITION; if (isPosition) { shaderBuilder.setPositionAttribute(glslType, attributeName); } else { shaderBuilder.addAttribute(glslType, attributeName); } if (isPosition && modifyFor2D) { shaderBuilder.addAttribute("vec3", "a_position2D"); } } function updateAttributesStruct(shaderBuilder, attributeInfo, use2D) { const vsStructId = GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_VS; const fsStructId = GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_FS; const variableName = attributeInfo.variableName; if (variableName === "tangentMC") { shaderBuilder.addStructField(vsStructId, "vec3", "tangentMC"); shaderBuilder.addStructField(vsStructId, "float", "tangentSignMC"); shaderBuilder.addStructField(fsStructId, "vec3", "tangentEC"); } else if (variableName === "normalMC") { shaderBuilder.addStructField(vsStructId, "vec3", "normalMC"); shaderBuilder.addStructField(fsStructId, "vec3", "normalEC"); } else { shaderBuilder.addStructField( vsStructId, attributeInfo.glslType, variableName ); shaderBuilder.addStructField( fsStructId, attributeInfo.glslType, variableName ); } if (variableName === "positionMC" && use2D) { shaderBuilder.addStructField(vsStructId, "vec3", "position2D"); } } function updateInitializeAttributesFunction(shaderBuilder, attributeInfo, use2D) { const functionId = GeometryPipelineStage.FUNCTION_ID_INITIALIZE_ATTRIBUTES; const variableName = attributeInfo.variableName; const use2DPosition = variableName === "positionMC" && use2D; if (use2DPosition) { const line = "attributes.position2D = a_position2D;"; shaderBuilder.addFunctionLines(functionId, [line]); } if (attributeInfo.isQuantized) { return; } const lines = []; if (variableName === "tangentMC") { lines.push("attributes.tangentMC = a_tangentMC.xyz;"); lines.push("attributes.tangentSignMC = a_tangentMC.w;"); } else { lines.push(`attributes.${variableName} = a_${variableName};`); } shaderBuilder.addFunctionLines(functionId, lines); } function updateSetDynamicVaryingsFunction(shaderBuilder, attributeInfo) { const semantic = attributeInfo.attribute.semantic; const setIndex = attributeInfo.attribute.setIndex; if (defined_default(semantic) && !defined_default(setIndex)) { return; } let functionId = GeometryPipelineStage.FUNCTION_ID_SET_DYNAMIC_VARYINGS_VS; const variableName = attributeInfo.variableName; let line = `v_${variableName} = attributes.${variableName};`; shaderBuilder.addFunctionLines(functionId, [line]); functionId = GeometryPipelineStage.FUNCTION_ID_SET_DYNAMIC_VARYINGS_FS; line = `attributes.${variableName} = v_${variableName};`; shaderBuilder.addFunctionLines(functionId, [line]); } function handleBitangents(shaderBuilder, attributes) { let hasNormals = false; let hasTangents = false; for (let i = 0; i < attributes.length; i++) { const attribute = attributes[i]; if (attribute.semantic === VertexAttributeSemantic_default.NORMAL) { hasNormals = true; } else if (attribute.semantic === VertexAttributeSemantic_default.TANGENT) { hasTangents = true; } } if (!hasNormals || !hasTangents) { return; } shaderBuilder.addDefine("HAS_BITANGENTS"); shaderBuilder.addVarying("vec3", "v_bitangentEC"); shaderBuilder.addStructField( GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_VS, "vec3", "bitangentMC" ); shaderBuilder.addStructField( GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_FS, "vec3", "bitangentEC" ); } var GeometryPipelineStage_default = GeometryPipelineStage; // packages/engine/Source/Shaders/Model/LightingStageFS.js var LightingStageFS_default = "#ifdef LIGHTING_PBR\nvec3 computePbrLighting(czm_modelMaterial inputMaterial, ProcessedAttributes attributes)\n{\n czm_pbrParameters pbrParameters;\n pbrParameters.diffuseColor = inputMaterial.diffuse;\n pbrParameters.f0 = inputMaterial.specular;\n pbrParameters.roughness = inputMaterial.roughness;\n \n #ifdef USE_CUSTOM_LIGHT_COLOR\n vec3 lightColorHdr = model_lightColorHdr;\n #else\n vec3 lightColorHdr = czm_lightColorHdr;\n #endif\n\n vec3 color = inputMaterial.diffuse;\n #ifdef HAS_NORMALS\n color = czm_pbrLighting(\n attributes.positionEC,\n inputMaterial.normalEC,\n czm_lightDirectionEC,\n lightColorHdr,\n pbrParameters\n );\n\n #ifdef USE_IBL_LIGHTING\n color += imageBasedLightingStage(\n attributes.positionEC,\n inputMaterial.normalEC,\n czm_lightDirectionEC,\n lightColorHdr,\n pbrParameters\n );\n #endif\n #endif\n\n color *= inputMaterial.occlusion;\n color += inputMaterial.emissive;\n\n // In HDR mode, the frame buffer is in linear color space. The\n // post-processing stages (see PostProcessStageCollection) will handle\n // tonemapping. However, if HDR is not enabled, we must tonemap else large\n // values may be clamped to 1.0\n #ifndef HDR \n color = czm_acesTonemapping(color);\n #endif \n\n return color;\n}\n#endif\n\nvoid lightingStage(inout czm_modelMaterial material, ProcessedAttributes attributes)\n{\n // Even though the lighting will only set the diffuse color,\n // pass all other properties so further stages have access to them.\n vec3 color = vec3(0.0);\n\n #ifdef LIGHTING_PBR\n color = computePbrLighting(material, attributes);\n #else // unlit\n color = material.diffuse;\n #endif\n\n #ifdef HAS_POINT_CLOUD_COLOR_STYLE\n // The colors resulting from point cloud styles are adjusted differently.\n color = czm_gammaCorrect(color);\n #elif !defined(HDR)\n // If HDR is not enabled, the frame buffer stores sRGB colors rather than\n // linear colors so the linear value must be converted.\n color = czm_linearToSrgb(color);\n #endif\n\n material.diffuse = color;\n}\n"; // packages/engine/Source/Scene/Model/LightingModel.js var LightingModel = { /** * Use unlit shading, i.e. skip lighting calculations. The model's * diffuse color (assumed to be linear RGB, not sRGB) is used directly * when computingout_FragColor
. The alpha mode is still
* applied.
*
* @type {number}
* @constant
*/
UNLIT: 0,
/**
* Use physically-based rendering lighting calculations. This includes
* both PBR metallic roughness and PBR specular glossiness. Image-based
* lighting is also applied when possible.
*
* @type {number}
* @constant
*/
PBR: 1
};
var LightingModel_default = Object.freeze(LightingModel);
// packages/engine/Source/Scene/Model/LightingPipelineStage.js
var LightingPipelineStage = {
name: "LightingPipelineStage"
// Helps with debugging
};
LightingPipelineStage.process = function(renderResources, primitive) {
const model = renderResources.model;
const lightingOptions = renderResources.lightingOptions;
const shaderBuilder = renderResources.shaderBuilder;
if (defined_default(model.lightColor)) {
shaderBuilder.addDefine(
"USE_CUSTOM_LIGHT_COLOR",
void 0,
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addUniform(
"vec3",
"model_lightColorHdr",
ShaderDestination_default.FRAGMENT
);
const uniformMap2 = renderResources.uniformMap;
uniformMap2.model_lightColorHdr = function() {
return model.lightColor;
};
}
const lightingModel = lightingOptions.lightingModel;
if (lightingModel === LightingModel_default.PBR) {
shaderBuilder.addDefine(
"LIGHTING_PBR",
void 0,
ShaderDestination_default.FRAGMENT
);
} else {
shaderBuilder.addDefine(
"LIGHTING_UNLIT",
void 0,
ShaderDestination_default.FRAGMENT
);
}
shaderBuilder.addFragmentLines(LightingStageFS_default);
};
var LightingPipelineStage_default = LightingPipelineStage;
// packages/engine/Source/Shaders/Model/MaterialStageFS.js
var MaterialStageFS_default = "// If the style color is white, it implies the feature has not been styled.\nbool isDefaultStyleColor(vec3 color)\n{\n return all(greaterThan(color, vec3(1.0 - czm_epsilon3)));\n}\n\nvec3 blend(vec3 sourceColor, vec3 styleColor, float styleColorBlend)\n{\n vec3 blendColor = mix(sourceColor, styleColor, styleColorBlend);\n vec3 color = isDefaultStyleColor(styleColor.rgb) ? sourceColor : blendColor;\n return color;\n}\n\nvec2 computeTextureTransform(vec2 texCoord, mat3 textureTransform)\n{\n return vec2(textureTransform * vec3(texCoord, 1.0));\n}\n\n#ifdef HAS_NORMALS\nvec3 computeNormal(ProcessedAttributes attributes)\n{\n // Geometry normal. This is already normalized \n vec3 ng = attributes.normalEC;\n\n vec3 normal = ng;\n #if defined(HAS_NORMAL_TEXTURE) && !defined(HAS_WIREFRAME)\n vec2 normalTexCoords = TEXCOORD_NORMAL;\n #ifdef HAS_NORMAL_TEXTURE_TRANSFORM\n normalTexCoords = computeTextureTransform(normalTexCoords, u_normalTextureTransform);\n #endif\n\n // If HAS_BITANGENTS is set, then HAS_TANGENTS is also set\n #ifdef HAS_BITANGENTS\n vec3 t = attributes.tangentEC;\n vec3 b = attributes.bitangentEC;\n mat3 tbn = mat3(t, b, ng);\n vec3 n = texture(u_normalTexture, normalTexCoords).rgb;\n normal = normalize(tbn * (2.0 * n - 1.0));\n #elif (__VERSION__ == 300 || defined(GL_OES_standard_derivatives))\n // If derivatives are available (not IE 10), compute tangents\n vec3 positionEC = attributes.positionEC;\n vec3 pos_dx = dFdx(positionEC);\n vec3 pos_dy = dFdy(positionEC);\n vec3 tex_dx = dFdx(vec3(normalTexCoords,0.0));\n vec3 tex_dy = dFdy(vec3(normalTexCoords,0.0));\n vec3 t = (tex_dy.t * pos_dx - tex_dx.t * pos_dy) / (tex_dx.s * tex_dy.t - tex_dy.s * tex_dx.t);\n t = normalize(t - ng * dot(ng, t));\n vec3 b = normalize(cross(ng, t));\n mat3 tbn = mat3(t, b, ng);\n vec3 n = texture(u_normalTexture, normalTexCoords).rgb;\n normal = normalize(tbn * (2.0 * n - 1.0));\n #endif\n #endif\n\n #ifdef HAS_DOUBLE_SIDED_MATERIAL\n if (czm_backFacing()) {\n normal = -normal;\n }\n #endif\n\n return normal;\n}\n#endif\n\nvoid materialStage(inout czm_modelMaterial material, ProcessedAttributes attributes, SelectedFeature feature)\n{\n #ifdef HAS_NORMALS\n material.normalEC = computeNormal(attributes);\n #endif\n\n vec4 baseColorWithAlpha = vec4(1.0);\n // Regardless of whether we use PBR, set a base color\n #ifdef HAS_BASE_COLOR_TEXTURE\n vec2 baseColorTexCoords = TEXCOORD_BASE_COLOR;\n\n #ifdef HAS_BASE_COLOR_TEXTURE_TRANSFORM\n baseColorTexCoords = computeTextureTransform(baseColorTexCoords, u_baseColorTextureTransform);\n #endif\n\n baseColorWithAlpha = czm_srgbToLinear(texture(u_baseColorTexture, baseColorTexCoords));\n\n #ifdef HAS_BASE_COLOR_FACTOR\n baseColorWithAlpha *= u_baseColorFactor;\n #endif\n #elif defined(HAS_BASE_COLOR_FACTOR)\n baseColorWithAlpha = u_baseColorFactor;\n #endif\n\n #ifdef HAS_POINT_CLOUD_COLOR_STYLE\n baseColorWithAlpha = v_pointCloudColor;\n #elif defined(HAS_COLOR_0)\n vec4 color = attributes.color_0;\n // .pnts files store colors in the sRGB color space\n #ifdef HAS_SRGB_COLOR\n color = czm_srgbToLinear(color);\n #endif\n baseColorWithAlpha *= color;\n #endif\n\n material.diffuse = baseColorWithAlpha.rgb;\n material.alpha = baseColorWithAlpha.a;\n\n #ifdef USE_CPU_STYLING\n material.diffuse = blend(material.diffuse, feature.color.rgb, model_colorBlend);\n #endif\n\n #ifdef HAS_OCCLUSION_TEXTURE\n vec2 occlusionTexCoords = TEXCOORD_OCCLUSION;\n #ifdef HAS_OCCLUSION_TEXTURE_TRANSFORM\n occlusionTexCoords = computeTextureTransform(occlusionTexCoords, u_occlusionTextureTransform);\n #endif\n material.occlusion = texture(u_occlusionTexture, occlusionTexCoords).r;\n #endif\n\n #ifdef HAS_EMISSIVE_TEXTURE\n vec2 emissiveTexCoords = TEXCOORD_EMISSIVE;\n #ifdef HAS_EMISSIVE_TEXTURE_TRANSFORM\n emissiveTexCoords = computeTextureTransform(emissiveTexCoords, u_emissiveTextureTransform);\n #endif\n\n vec3 emissive = czm_srgbToLinear(texture(u_emissiveTexture, emissiveTexCoords).rgb);\n #ifdef HAS_EMISSIVE_FACTOR\n emissive *= u_emissiveFactor;\n #endif\n material.emissive = emissive;\n #elif defined(HAS_EMISSIVE_FACTOR)\n material.emissive = u_emissiveFactor;\n #endif\n\n #if defined(LIGHTING_PBR) && defined(USE_SPECULAR_GLOSSINESS)\n #ifdef HAS_SPECULAR_GLOSSINESS_TEXTURE\n vec2 specularGlossinessTexCoords = TEXCOORD_SPECULAR_GLOSSINESS;\n #ifdef HAS_SPECULAR_GLOSSINESS_TEXTURE_TRANSFORM\n specularGlossinessTexCoords = computeTextureTransform(specularGlossinessTexCoords, u_specularGlossinessTextureTransform);\n #endif\n\n vec4 specularGlossiness = czm_srgbToLinear(texture(u_specularGlossinessTexture, specularGlossinessTexCoords));\n vec3 specular = specularGlossiness.rgb;\n float glossiness = specularGlossiness.a;\n #ifdef HAS_SPECULAR_FACTOR\n specular *= u_specularFactor;\n #endif\n\n #ifdef HAS_GLOSSINESS_FACTOR\n glossiness *= u_glossinessFactor;\n #endif\n #else\n #ifdef HAS_SPECULAR_FACTOR\n vec3 specular = clamp(u_specularFactor, vec3(0.0), vec3(1.0));\n #else\n vec3 specular = vec3(1.0);\n #endif\n\n #ifdef HAS_GLOSSINESS_FACTOR\n float glossiness = clamp(u_glossinessFactor, 0.0, 1.0);\n #else\n float glossiness = 1.0;\n #endif\n #endif\n\n #ifdef HAS_DIFFUSE_TEXTURE\n vec2 diffuseTexCoords = TEXCOORD_DIFFUSE;\n #ifdef HAS_DIFFUSE_TEXTURE_TRANSFORM\n diffuseTexCoords = computeTextureTransform(diffuseTexCoords, u_diffuseTextureTransform);\n #endif\n\n vec4 diffuse = czm_srgbToLinear(texture(u_diffuseTexture, diffuseTexCoords));\n #ifdef HAS_DIFFUSE_FACTOR\n diffuse *= u_diffuseFactor;\n #endif\n #elif defined(HAS_DIFFUSE_FACTOR)\n vec4 diffuse = clamp(u_diffuseFactor, vec4(0.0), vec4(1.0));\n #else\n vec4 diffuse = vec4(1.0);\n #endif\n czm_pbrParameters parameters = czm_pbrSpecularGlossinessMaterial(\n diffuse.rgb,\n specular,\n glossiness\n );\n material.diffuse = parameters.diffuseColor;\n // the specular glossiness extension's alpha overrides anything set\n // by the base material.\n material.alpha = diffuse.a;\n material.specular = parameters.f0;\n material.roughness = parameters.roughness;\n #elif defined(LIGHTING_PBR)\n #ifdef HAS_METALLIC_ROUGHNESS_TEXTURE\n vec2 metallicRoughnessTexCoords = TEXCOORD_METALLIC_ROUGHNESS;\n #ifdef HAS_METALLIC_ROUGHNESS_TEXTURE_TRANSFORM\n metallicRoughnessTexCoords = computeTextureTransform(metallicRoughnessTexCoords, u_metallicRoughnessTextureTransform);\n #endif\n\n vec3 metallicRoughness = texture(u_metallicRoughnessTexture, metallicRoughnessTexCoords).rgb;\n float metalness = clamp(metallicRoughness.b, 0.0, 1.0);\n float roughness = clamp(metallicRoughness.g, 0.04, 1.0);\n #ifdef HAS_METALLIC_FACTOR\n metalness *= u_metallicFactor;\n #endif\n\n #ifdef HAS_ROUGHNESS_FACTOR\n roughness *= u_roughnessFactor;\n #endif\n #else\n #ifdef HAS_METALLIC_FACTOR\n float metalness = clamp(u_metallicFactor, 0.0, 1.0);\n #else\n float metalness = 1.0;\n #endif\n\n #ifdef HAS_ROUGHNESS_FACTOR\n float roughness = clamp(u_roughnessFactor, 0.04, 1.0);\n #else\n float roughness = 1.0;\n #endif\n #endif\n czm_pbrParameters parameters = czm_pbrMetallicRoughnessMaterial(\n material.diffuse,\n metalness,\n roughness\n );\n material.diffuse = parameters.diffuseColor;\n material.specular = parameters.f0;\n material.roughness = parameters.roughness;\n #endif\n}\n";
// packages/engine/Source/Scene/Model/MaterialPipelineStage.js
var Material4 = ModelComponents_default.Material;
var MetallicRoughness3 = ModelComponents_default.MetallicRoughness;
var SpecularGlossiness3 = ModelComponents_default.SpecularGlossiness;
var MaterialPipelineStage = {
name: "MaterialPipelineStage",
// Helps with debugging
// Expose some methods for testing
_processTexture: processTexture2,
_processTextureTransform: processTextureTransform
};
MaterialPipelineStage.process = function(renderResources, primitive, frameState) {
const material = primitive.material;
const model = renderResources.model;
const hasClassification = defined_default(model.classificationType);
const disableTextures = hasClassification;
const uniformMap2 = renderResources.uniformMap;
const shaderBuilder = renderResources.shaderBuilder;
const defaultTexture = frameState.context.defaultTexture;
const defaultNormalTexture = frameState.context.defaultNormalTexture;
const defaultEmissiveTexture = frameState.context.defaultEmissiveTexture;
processMaterialUniforms(
material,
uniformMap2,
shaderBuilder,
defaultTexture,
defaultNormalTexture,
defaultEmissiveTexture,
disableTextures
);
if (defined_default(material.specularGlossiness)) {
processSpecularGlossinessUniforms(
material,
uniformMap2,
shaderBuilder,
defaultTexture,
disableTextures
);
} else {
processMetallicRoughnessUniforms(
material,
uniformMap2,
shaderBuilder,
defaultTexture,
disableTextures
);
}
const hasNormals = ModelUtility_default.getAttributeBySemantic(
primitive,
VertexAttributeSemantic_default.NORMAL
);
const lightingOptions = renderResources.lightingOptions;
if (material.unlit || !hasNormals || hasClassification) {
lightingOptions.lightingModel = LightingModel_default.UNLIT;
} else {
lightingOptions.lightingModel = LightingModel_default.PBR;
}
const cull = model.backFaceCulling && !material.doubleSided;
renderResources.renderStateOptions.cull.enabled = cull;
const alphaOptions = renderResources.alphaOptions;
if (material.alphaMode === AlphaMode_default.BLEND) {
alphaOptions.pass = Pass_default.TRANSLUCENT;
} else if (material.alphaMode === AlphaMode_default.MASK) {
alphaOptions.alphaCutoff = material.alphaCutoff;
}
shaderBuilder.addFragmentLines(MaterialStageFS_default);
if (material.doubleSided) {
shaderBuilder.addDefine(
"HAS_DOUBLE_SIDED_MATERIAL",
void 0,
ShaderDestination_default.BOTH
);
}
};
function processTextureTransform(shaderBuilder, uniformMap2, textureReader, uniformName, defineName) {
const transformDefine = `HAS_${defineName}_TEXTURE_TRANSFORM`;
shaderBuilder.addDefine(
transformDefine,
void 0,
ShaderDestination_default.FRAGMENT
);
const transformUniformName = `${uniformName}Transform`;
shaderBuilder.addUniform(
"mat3",
transformUniformName,
ShaderDestination_default.FRAGMENT
);
uniformMap2[transformUniformName] = function() {
return textureReader.transform;
};
}
function processTexture2(shaderBuilder, uniformMap2, textureReader, uniformName, defineName, defaultTexture) {
shaderBuilder.addUniform(
"sampler2D",
uniformName,
ShaderDestination_default.FRAGMENT
);
uniformMap2[uniformName] = function() {
return defaultValue_default(textureReader.texture, defaultTexture);
};
const textureDefine = `HAS_${defineName}_TEXTURE`;
shaderBuilder.addDefine(textureDefine, void 0, ShaderDestination_default.FRAGMENT);
const texCoordIndex = textureReader.texCoord;
const texCoordVarying = `v_texCoord_${texCoordIndex}`;
const texCoordDefine = `TEXCOORD_${defineName}`;
shaderBuilder.addDefine(
texCoordDefine,
texCoordVarying,
ShaderDestination_default.FRAGMENT
);
const textureTransform = textureReader.transform;
if (defined_default(textureTransform) && !Matrix3_default.equals(textureTransform, Matrix3_default.IDENTITY)) {
processTextureTransform(
shaderBuilder,
uniformMap2,
textureReader,
uniformName,
defineName
);
}
}
function processMaterialUniforms(material, uniformMap2, shaderBuilder, defaultTexture, defaultNormalTexture, defaultEmissiveTexture, disableTextures) {
const emissiveFactor = material.emissiveFactor;
if (defined_default(emissiveFactor) && !Cartesian3_default.equals(emissiveFactor, Material4.DEFAULT_EMISSIVE_FACTOR)) {
shaderBuilder.addUniform(
"vec3",
"u_emissiveFactor",
ShaderDestination_default.FRAGMENT
);
uniformMap2.u_emissiveFactor = function() {
return material.emissiveFactor;
};
shaderBuilder.addDefine(
"HAS_EMISSIVE_FACTOR",
void 0,
ShaderDestination_default.FRAGMENT
);
const emissiveTexture = material.emissiveTexture;
if (defined_default(emissiveTexture) && !disableTextures) {
processTexture2(
shaderBuilder,
uniformMap2,
emissiveTexture,
"u_emissiveTexture",
"EMISSIVE",
defaultEmissiveTexture
);
}
}
const normalTexture = material.normalTexture;
if (defined_default(normalTexture) && !disableTextures) {
processTexture2(
shaderBuilder,
uniformMap2,
normalTexture,
"u_normalTexture",
"NORMAL",
defaultNormalTexture
);
}
const occlusionTexture = material.occlusionTexture;
if (defined_default(occlusionTexture) && !disableTextures) {
processTexture2(
shaderBuilder,
uniformMap2,
occlusionTexture,
"u_occlusionTexture",
"OCCLUSION",
defaultTexture
);
}
}
function processSpecularGlossinessUniforms(material, uniformMap2, shaderBuilder, defaultTexture, disableTextures) {
const specularGlossiness = material.specularGlossiness;
shaderBuilder.addDefine(
"USE_SPECULAR_GLOSSINESS",
void 0,
ShaderDestination_default.FRAGMENT
);
const diffuseTexture = specularGlossiness.diffuseTexture;
if (defined_default(diffuseTexture) && !disableTextures) {
processTexture2(
shaderBuilder,
uniformMap2,
diffuseTexture,
"u_diffuseTexture",
"DIFFUSE",
defaultTexture
);
}
const diffuseFactor = specularGlossiness.diffuseFactor;
if (defined_default(diffuseFactor) && !Cartesian4_default.equals(diffuseFactor, SpecularGlossiness3.DEFAULT_DIFFUSE_FACTOR)) {
shaderBuilder.addUniform(
"vec4",
"u_diffuseFactor",
ShaderDestination_default.FRAGMENT
);
uniformMap2.u_diffuseFactor = function() {
return specularGlossiness.diffuseFactor;
};
shaderBuilder.addDefine(
"HAS_DIFFUSE_FACTOR",
void 0,
ShaderDestination_default.FRAGMENT
);
}
const specularGlossinessTexture = specularGlossiness.specularGlossinessTexture;
if (defined_default(specularGlossinessTexture) && !disableTextures) {
processTexture2(
shaderBuilder,
uniformMap2,
specularGlossinessTexture,
"u_specularGlossinessTexture",
"SPECULAR_GLOSSINESS",
defaultTexture
);
}
const specularFactor = specularGlossiness.specularFactor;
if (defined_default(specularFactor) && !Cartesian3_default.equals(
specularFactor,
SpecularGlossiness3.DEFAULT_SPECULAR_FACTOR
)) {
shaderBuilder.addUniform(
"vec3",
"u_specularFactor",
ShaderDestination_default.FRAGMENT
);
uniformMap2.u_specularFactor = function() {
return specularGlossiness.specularFactor;
};
shaderBuilder.addDefine(
"HAS_SPECULAR_FACTOR",
void 0,
ShaderDestination_default.FRAGMENT
);
}
const glossinessFactor = specularGlossiness.glossinessFactor;
if (defined_default(glossinessFactor) && glossinessFactor !== SpecularGlossiness3.DEFAULT_GLOSSINESS_FACTOR) {
shaderBuilder.addUniform(
"float",
"u_glossinessFactor",
ShaderDestination_default.FRAGMENT
);
uniformMap2.u_glossinessFactor = function() {
return specularGlossiness.glossinessFactor;
};
shaderBuilder.addDefine(
"HAS_GLOSSINESS_FACTOR",
void 0,
ShaderDestination_default.FRAGMENT
);
}
}
function processMetallicRoughnessUniforms(material, uniformMap2, shaderBuilder, defaultTexture, disableTextures) {
const metallicRoughness = material.metallicRoughness;
shaderBuilder.addDefine(
"USE_METALLIC_ROUGHNESS",
void 0,
ShaderDestination_default.FRAGMENT
);
const baseColorTexture = metallicRoughness.baseColorTexture;
if (defined_default(baseColorTexture) && !disableTextures) {
processTexture2(
shaderBuilder,
uniformMap2,
baseColorTexture,
"u_baseColorTexture",
"BASE_COLOR",
defaultTexture
);
}
const baseColorFactor = metallicRoughness.baseColorFactor;
if (defined_default(baseColorFactor) && !Cartesian4_default.equals(
baseColorFactor,
MetallicRoughness3.DEFAULT_BASE_COLOR_FACTOR
)) {
shaderBuilder.addUniform(
"vec4",
"u_baseColorFactor",
ShaderDestination_default.FRAGMENT
);
uniformMap2.u_baseColorFactor = function() {
return metallicRoughness.baseColorFactor;
};
shaderBuilder.addDefine(
"HAS_BASE_COLOR_FACTOR",
void 0,
ShaderDestination_default.FRAGMENT
);
}
const metallicRoughnessTexture = metallicRoughness.metallicRoughnessTexture;
if (defined_default(metallicRoughnessTexture) && !disableTextures) {
processTexture2(
shaderBuilder,
uniformMap2,
metallicRoughnessTexture,
"u_metallicRoughnessTexture",
"METALLIC_ROUGHNESS",
defaultTexture
);
}
const metallicFactor = metallicRoughness.metallicFactor;
if (defined_default(metallicFactor) && metallicFactor !== MetallicRoughness3.DEFAULT_METALLIC_FACTOR) {
shaderBuilder.addUniform(
"float",
"u_metallicFactor",
ShaderDestination_default.FRAGMENT
);
uniformMap2.u_metallicFactor = function() {
return metallicRoughness.metallicFactor;
};
shaderBuilder.addDefine(
"HAS_METALLIC_FACTOR",
void 0,
ShaderDestination_default.FRAGMENT
);
}
const roughnessFactor = metallicRoughness.roughnessFactor;
if (defined_default(roughnessFactor) && roughnessFactor !== MetallicRoughness3.DEFAULT_ROUGHNESS_FACTOR) {
shaderBuilder.addUniform(
"float",
"u_roughnessFactor",
ShaderDestination_default.FRAGMENT
);
uniformMap2.u_roughnessFactor = function() {
return metallicRoughness.roughnessFactor;
};
shaderBuilder.addDefine(
"HAS_ROUGHNESS_FACTOR",
void 0,
ShaderDestination_default.FRAGMENT
);
}
}
var MaterialPipelineStage_default = MaterialPipelineStage;
// packages/engine/Source/Shaders/Model/MorphTargetsStageVS.js
var MorphTargetsStageVS_default = "void morphTargetsStage(inout ProcessedAttributes attributes) \n{\n vec3 positionMC = attributes.positionMC;\n attributes.positionMC = getMorphedPosition(positionMC);\n\n #ifdef HAS_NORMALS\n vec3 normalMC = attributes.normalMC;\n attributes.normalMC = getMorphedNormal(normalMC);\n #endif\n\n #ifdef HAS_TANGENTS\n vec3 tangentMC = attributes.tangentMC;\n attributes.tangentMC = getMorphedTangent(tangentMC);\n #endif\n}";
// packages/engine/Source/Scene/Model/MorphTargetsPipelineStage.js
var MorphTargetsPipelineStage = {
name: "MorphTargetsPipelineStage",
// Helps with debugging
FUNCTION_ID_GET_MORPHED_POSITION: "getMorphedPosition",
FUNCTION_SIGNATURE_GET_MORPHED_POSITION: "vec3 getMorphedPosition(in vec3 position)",
FUNCTION_ID_GET_MORPHED_NORMAL: "getMorphedNormal",
FUNCTION_SIGNATURE_GET_MORPHED_NORMAL: "vec3 getMorphedNormal(in vec3 normal)",
FUNCTION_ID_GET_MORPHED_TANGENT: "getMorphedTangent",
FUNCTION_SIGNATURE_GET_MORPHED_TANGENT: "vec3 getMorphedTangent(in vec3 tangent)"
};
MorphTargetsPipelineStage.process = function(renderResources, primitive) {
const shaderBuilder = renderResources.shaderBuilder;
shaderBuilder.addDefine(
"HAS_MORPH_TARGETS",
void 0,
ShaderDestination_default.VERTEX
);
addGetMorphedAttributeFunctionDeclarations(shaderBuilder);
const morphTargetsLength = primitive.morphTargets.length;
for (let i = 0; i < morphTargetsLength; i++) {
const attributes = primitive.morphTargets[i].attributes;
const attributesLength = attributes.length;
for (let j = 0; j < attributesLength; j++) {
const attribute = attributes[j];
const semantic = attribute.semantic;
if (semantic !== VertexAttributeSemantic_default.POSITION && semantic !== VertexAttributeSemantic_default.NORMAL && semantic !== VertexAttributeSemantic_default.TANGENT) {
continue;
}
processMorphTargetAttribute(
renderResources,
attribute,
renderResources.attributeIndex,
i
);
renderResources.attributeIndex++;
}
}
addGetMorphedAttributeFunctionReturns(shaderBuilder);
const weights2 = renderResources.runtimeNode.morphWeights;
const weightsLength = weights2.length;
shaderBuilder.addUniform(
"float",
`u_morphWeights[${weightsLength}]`,
ShaderDestination_default.VERTEX
);
shaderBuilder.addVertexLines(MorphTargetsStageVS_default);
const uniformMap2 = {
u_morphWeights: function() {
return renderResources.runtimeNode.morphWeights;
}
};
renderResources.uniformMap = combine_default(uniformMap2, renderResources.uniformMap);
};
var scratchAttributeInfo = {
attributeString: void 0,
functionId: void 0
};
function processMorphTargetAttribute(renderResources, attribute, attributeIndex, morphTargetIndex) {
const shaderBuilder = renderResources.shaderBuilder;
addMorphTargetAttributeToRenderResources(
renderResources,
attribute,
attributeIndex
);
const attributeInfo = getMorphTargetAttributeInfo(
attribute,
scratchAttributeInfo
);
addMorphTargetAttributeDeclarationAndFunctionLine(
shaderBuilder,
attributeInfo,
morphTargetIndex
);
}
function addMorphTargetAttributeToRenderResources(renderResources, attribute, attributeIndex) {
const vertexAttribute = {
index: attributeIndex,
value: defined_default(attribute.buffer) ? void 0 : attribute.constant,
vertexBuffer: attribute.buffer,
componentsPerAttribute: AttributeType_default.getNumberOfComponents(attribute.type),
componentDatatype: attribute.componentDatatype,
offsetInBytes: attribute.byteOffset,
strideInBytes: attribute.byteStride,
normalize: attribute.normalized
};
renderResources.attributes.push(vertexAttribute);
}
function getMorphTargetAttributeInfo(attribute, result) {
const semantic = attribute.semantic;
switch (semantic) {
case VertexAttributeSemantic_default.POSITION:
result.attributeString = "Position";
result.functionId = MorphTargetsPipelineStage.FUNCTION_ID_GET_MORPHED_POSITION;
break;
case VertexAttributeSemantic_default.NORMAL:
result.attributeString = "Normal";
result.functionId = MorphTargetsPipelineStage.FUNCTION_ID_GET_MORPHED_NORMAL;
break;
case VertexAttributeSemantic_default.TANGENT:
result.attributeString = "Tangent";
result.functionId = MorphTargetsPipelineStage.FUNCTION_ID_GET_MORPHED_TANGENT;
break;
default:
break;
}
return result;
}
function addMorphTargetAttributeDeclarationAndFunctionLine(shaderBuilder, attributeInfo, morphTargetIndex) {
const attributeString = attributeInfo.attributeString;
const attributeName = `a_target${attributeString}_${morphTargetIndex}`;
const line = `morphed${attributeString} += u_morphWeights[${morphTargetIndex}] * a_target${attributeString}_${morphTargetIndex};`;
shaderBuilder.addAttribute("vec3", attributeName);
shaderBuilder.addFunctionLines(attributeInfo.functionId, [line]);
}
function addGetMorphedAttributeFunctionDeclarations(shaderBuilder) {
shaderBuilder.addFunction(
MorphTargetsPipelineStage.FUNCTION_ID_GET_MORPHED_POSITION,
MorphTargetsPipelineStage.FUNCTION_SIGNATURE_GET_MORPHED_POSITION,
ShaderDestination_default.VERTEX
);
const positionLine = "vec3 morphedPosition = position;";
shaderBuilder.addFunctionLines(
MorphTargetsPipelineStage.FUNCTION_ID_GET_MORPHED_POSITION,
[positionLine]
);
shaderBuilder.addFunction(
MorphTargetsPipelineStage.FUNCTION_ID_GET_MORPHED_NORMAL,
MorphTargetsPipelineStage.FUNCTION_SIGNATURE_GET_MORPHED_NORMAL,
ShaderDestination_default.VERTEX
);
const normalLine = "vec3 morphedNormal = normal;";
shaderBuilder.addFunctionLines(
MorphTargetsPipelineStage.FUNCTION_ID_GET_MORPHED_NORMAL,
[normalLine]
);
shaderBuilder.addFunction(
MorphTargetsPipelineStage.FUNCTION_ID_GET_MORPHED_TANGENT,
MorphTargetsPipelineStage.FUNCTION_SIGNATURE_GET_MORPHED_TANGENT,
ShaderDestination_default.VERTEX
);
const tangentLine = "vec3 morphedTangent = tangent;";
shaderBuilder.addFunctionLines(
MorphTargetsPipelineStage.FUNCTION_ID_GET_MORPHED_TANGENT,
[tangentLine]
);
}
function addGetMorphedAttributeFunctionReturns(shaderBuilder) {
const positionLine = "return morphedPosition;";
shaderBuilder.addFunctionLines(
MorphTargetsPipelineStage.FUNCTION_ID_GET_MORPHED_POSITION,
[positionLine]
);
const normalLine = "return morphedNormal;";
shaderBuilder.addFunctionLines(
MorphTargetsPipelineStage.FUNCTION_ID_GET_MORPHED_NORMAL,
[normalLine]
);
const tangentLine = "return morphedTangent;";
shaderBuilder.addFunctionLines(
MorphTargetsPipelineStage.FUNCTION_ID_GET_MORPHED_TANGENT,
[tangentLine]
);
}
var MorphTargetsPipelineStage_default = MorphTargetsPipelineStage;
// packages/engine/Source/Scene/Model/PickingPipelineStage.js
var PickingPipelineStage = {
name: "PickingPipelineStage"
// Helps with debugging
};
PickingPipelineStage.process = function(renderResources, primitive, frameState) {
const context = frameState.context;
const runtimeNode = renderResources.runtimeNode;
const shaderBuilder = renderResources.shaderBuilder;
const model = renderResources.model;
const instances = runtimeNode.node.instances;
if (renderResources.hasPropertyTable) {
processPickTexture(renderResources, primitive, instances, context);
} else if (defined_default(instances)) {
processInstancedPickIds(renderResources, context);
} else {
const pickObject = buildPickObject(renderResources);
const pickId = context.createPickId(pickObject);
model._pipelineResources.push(pickId);
model._pickIds.push(pickId);
shaderBuilder.addUniform(
"vec4",
"czm_pickColor",
ShaderDestination_default.FRAGMENT
);
const uniformMap2 = renderResources.uniformMap;
uniformMap2.czm_pickColor = function() {
return pickId.color;
};
renderResources.pickId = "czm_pickColor";
}
};
function buildPickObject(renderResources, instanceId) {
const model = renderResources.model;
if (defined_default(model.pickObject)) {
return model.pickObject;
}
const detailPickObject = {
model,
node: renderResources.runtimeNode,
primitive: renderResources.runtimePrimitive
};
let pickObject;
if (ModelType_default.is3DTiles(model.type)) {
const content = model.content;
pickObject = {
content,
primitive: content.tileset,
detail: detailPickObject
};
} else {
pickObject = {
primitive: model,
detail: detailPickObject
};
}
pickObject.id = model.id;
if (defined_default(instanceId)) {
pickObject.instanceId = instanceId;
}
return pickObject;
}
function processPickTexture(renderResources, primitive, instances) {
const model = renderResources.model;
let featureTableId;
let featureIdAttribute;
const featureIdLabel = model.featureIdLabel;
const instanceFeatureIdLabel = model.instanceFeatureIdLabel;
if (defined_default(model.featureTableId)) {
featureTableId = model.featureTableId;
} else if (defined_default(instances)) {
featureIdAttribute = ModelUtility_default.getFeatureIdsByLabel(
instances.featureIds,
instanceFeatureIdLabel
);
featureTableId = featureIdAttribute.propertyTableId;
} else {
featureIdAttribute = ModelUtility_default.getFeatureIdsByLabel(
primitive.featureIds,
featureIdLabel
);
featureTableId = featureIdAttribute.propertyTableId;
}
const featureTable = model.featureTables[featureTableId];
const shaderBuilder = renderResources.shaderBuilder;
shaderBuilder.addUniform(
"sampler2D",
"model_pickTexture",
ShaderDestination_default.FRAGMENT
);
const batchTexture = featureTable.batchTexture;
renderResources.uniformMap.model_pickTexture = function() {
return defaultValue_default(batchTexture.pickTexture, batchTexture.defaultTexture);
};
renderResources.pickId = "((selectedFeature.id < int(model_featuresLength)) ? texture(model_pickTexture, selectedFeature.st) : vec4(0.0))";
}
function processInstancedPickIds(renderResources, context) {
const instanceCount = renderResources.instanceCount;
const pickIds = new Array(instanceCount);
const pickIdsTypedArray = new Uint8Array(instanceCount * 4);
const model = renderResources.model;
const pipelineResources = model._pipelineResources;
for (let i = 0; i < instanceCount; i++) {
const pickObject = buildPickObject(renderResources, i);
const pickId = context.createPickId(pickObject);
pipelineResources.push(pickId);
pickIds[i] = pickId;
const pickColor = pickId.color;
pickIdsTypedArray[i * 4 + 0] = Color_default.floatToByte(pickColor.red);
pickIdsTypedArray[i * 4 + 1] = Color_default.floatToByte(pickColor.green);
pickIdsTypedArray[i * 4 + 2] = Color_default.floatToByte(pickColor.blue);
pickIdsTypedArray[i * 4 + 3] = Color_default.floatToByte(pickColor.alpha);
}
model._pickIds = pickIds;
const pickIdsBuffer = Buffer_default.createVertexBuffer({
context,
typedArray: pickIdsTypedArray,
usage: BufferUsage_default.STATIC_DRAW
});
pickIdsBuffer.vertexArrayDestroyable = false;
const hasCpuCopy = false;
model.statistics.addBuffer(pickIdsBuffer, hasCpuCopy);
pipelineResources.push(pickIdsBuffer);
const pickIdsVertexAttribute = {
index: renderResources.attributeIndex++,
vertexBuffer: pickIdsBuffer,
componentsPerAttribute: 4,
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
normalize: true,
offsetInBytes: 0,
strideInBytes: 0,
instanceDivisor: 1
};
renderResources.attributes.push(pickIdsVertexAttribute);
const shaderBuilder = renderResources.shaderBuilder;
shaderBuilder.addDefine("USE_PICKING", void 0, ShaderDestination_default.BOTH);
shaderBuilder.addAttribute("vec4", "a_pickColor");
shaderBuilder.addVarying("vec4", "v_pickColor");
renderResources.pickId = "v_pickColor";
}
var PickingPipelineStage_default = PickingPipelineStage;
// packages/engine/Source/Scene/Cesium3DTileRefine.js
var Cesium3DTileRefine = {
/**
* Render this tile and, if it doesn't meet the screen space error, also refine to its children.
*
* @type {number}
* @constant
*/
ADD: 0,
/**
* Render this tile or, if it doesn't meet the screen space error, refine to its descendants instead.
*
* @type {number}
* @constant
*/
REPLACE: 1
};
var Cesium3DTileRefine_default = Object.freeze(Cesium3DTileRefine);
// packages/engine/Source/Shaders/Model/PointCloudStylingStageVS.js
var PointCloudStylingStageVS_default = "float getPointSizeFromAttenuation(vec3 positionEC) {\n // Variables are packed into a single vector to minimize gl.uniformXXX() calls\n float pointSize = model_pointCloudParameters.x;\n float geometricError = model_pointCloudParameters.y;\n float depthMultiplier = model_pointCloudParameters.z;\n\n float depth = -positionEC.z;\n return min((geometricError / depth) * depthMultiplier, pointSize);\n}\n\n#ifdef HAS_POINT_CLOUD_SHOW_STYLE\nfloat pointCloudShowStylingStage(in ProcessedAttributes attributes, in Metadata metadata) {\n float tiles3d_tileset_time = model_pointCloudParameters.w;\n return float(getShowFromStyle(attributes, metadata, tiles3d_tileset_time));\n}\n#endif\n\n#ifdef HAS_POINT_CLOUD_COLOR_STYLE\nvec4 pointCloudColorStylingStage(in ProcessedAttributes attributes, in Metadata metadata) {\n float tiles3d_tileset_time = model_pointCloudParameters.w;\n return getColorFromStyle(attributes, metadata, tiles3d_tileset_time);\n}\n#endif\n\n#ifdef HAS_POINT_CLOUD_POINT_SIZE_STYLE\nfloat pointCloudPointSizeStylingStage(in ProcessedAttributes attributes, in Metadata metadata) {\n float tiles3d_tileset_time = model_pointCloudParameters.w;\n return float(getPointSizeFromStyle(attributes, metadata, tiles3d_tileset_time));\n}\n#elif defined(HAS_POINT_CLOUD_ATTENUATION)\nfloat pointCloudPointSizeStylingStage(in ProcessedAttributes attributes, in Metadata metadata) {\n return getPointSizeFromAttenuation(v_positionEC);\n}\n#endif\n\n#ifdef HAS_POINT_CLOUD_BACK_FACE_CULLING\nfloat pointCloudBackFaceCullingStage() {\n #if defined(HAS_NORMALS) && !defined(HAS_DOUBLE_SIDED_MATERIAL)\n // This needs to be computed in eye coordinates so we can't use attributes.normalMC\n return step(-v_normalEC.z, 0.0);\n #else\n return 1.0;\n #endif\n}\n#endif";
// packages/engine/Source/Scene/Model/PointCloudStylingPipelineStage.js
var scratchUniform = new Cartesian4_default();
var PointCloudStylingPipelineStage = {
name: "PointCloudStylingPipelineStage"
// Helps with debugging
};
PointCloudStylingPipelineStage.process = function(renderResources, primitive, frameState) {
const shaderBuilder = renderResources.shaderBuilder;
const model = renderResources.model;
const style = model.style;
const structuralMetadata = model.structuralMetadata;
const propertyAttributes = defined_default(structuralMetadata) ? structuralMetadata.propertyAttributes : void 0;
const hasFeatureTable = defined_default(model.featureTableId) && model.featureTables[model.featureTableId].featuresLength > 0;
const hasBatchTable = !defined_default(propertyAttributes) && hasFeatureTable;
if (defined_default(style) && !hasBatchTable) {
const variableSubstitutionMap = getVariableSubstitutionMap(
propertyAttributes
);
const shaderFunctionInfo = getStyleShaderFunctionInfo(
style,
variableSubstitutionMap
);
addShaderFunctionsAndDefines(shaderBuilder, shaderFunctionInfo);
const propertyNames = getPropertyNames(shaderFunctionInfo);
const usesNormalSemantic = propertyNames.indexOf("normalMC") >= 0;
const hasNormals = ModelUtility_default.getAttributeBySemantic(
primitive,
VertexAttributeSemantic_default.NORMAL
);
if (usesNormalSemantic && !hasNormals) {
throw new RuntimeError_default(
"Style references the NORMAL semantic but the point cloud does not have normals"
);
}
shaderBuilder.addDefine(
"COMPUTE_POSITION_WC_STYLE",
void 0,
ShaderDestination_default.VERTEX
);
const styleTranslucent = shaderFunctionInfo.styleTranslucent;
if (styleTranslucent) {
renderResources.alphaOptions.pass = Pass_default.TRANSLUCENT;
}
}
const pointCloudShading = model.pointCloudShading;
if (pointCloudShading.attenuation) {
shaderBuilder.addDefine(
"HAS_POINT_CLOUD_ATTENUATION",
void 0,
ShaderDestination_default.VERTEX
);
}
if (pointCloudShading.backFaceCulling) {
shaderBuilder.addDefine(
"HAS_POINT_CLOUD_BACK_FACE_CULLING",
void 0,
ShaderDestination_default.VERTEX
);
}
let content;
let is3DTiles;
let usesAddRefinement;
if (ModelType_default.is3DTiles(model.type)) {
is3DTiles = true;
content = model.content;
usesAddRefinement = content.tile.refine === Cesium3DTileRefine_default.ADD;
}
shaderBuilder.addUniform(
"vec4",
"model_pointCloudParameters",
ShaderDestination_default.VERTEX
);
shaderBuilder.addVertexLines(PointCloudStylingStageVS_default);
const uniformMap2 = renderResources.uniformMap;
uniformMap2.model_pointCloudParameters = function() {
const vec4 = scratchUniform;
let defaultPointSize = 1;
if (is3DTiles) {
defaultPointSize = usesAddRefinement ? 5 : content.tileset.maximumScreenSpaceError;
}
vec4.x = defaultValue_default(
pointCloudShading.maximumAttenuation,
defaultPointSize
);
vec4.x *= frameState.pixelRatio;
const geometricError = getGeometricError2(
renderResources,
primitive,
pointCloudShading,
content
);
vec4.y = geometricError * pointCloudShading.geometricErrorScale;
const context = frameState.context;
const frustum = frameState.camera.frustum;
let depthMultiplier;
if (frameState.mode === SceneMode_default.SCENE2D || frustum instanceof OrthographicFrustum_default) {
depthMultiplier = Number.POSITIVE_INFINITY;
} else {
depthMultiplier = context.drawingBufferHeight / frameState.camera.frustum.sseDenominator;
}
vec4.z = depthMultiplier;
if (is3DTiles) {
vec4.w = content.tileset.timeSinceLoad;
}
return vec4;
};
};
var scratchDimensions = new Cartesian3_default();
function getGeometricError2(renderResources, primitive, pointCloudShading, content) {
if (defined_default(content)) {
const geometricError = content.tile.geometricError;
if (geometricError > 0) {
return geometricError;
}
}
if (defined_default(pointCloudShading.baseResolution)) {
return pointCloudShading.baseResolution;
}
const positionAttribute = ModelUtility_default.getAttributeBySemantic(
primitive,
VertexAttributeSemantic_default.POSITION
);
const pointsLength = positionAttribute.count;
const nodeTransform = renderResources.runtimeNode.transform;
let dimensions = Cartesian3_default.subtract(
positionAttribute.max,
positionAttribute.min,
scratchDimensions
);
dimensions = Matrix4_default.multiplyByPointAsVector(
nodeTransform,
dimensions,
scratchDimensions
);
const volume = dimensions.x * dimensions.y * dimensions.z;
const geometricErrorEstimate = Math_default.cbrt(volume / pointsLength);
return geometricErrorEstimate;
}
var scratchShaderFunctionInfo = {
colorStyleFunction: void 0,
showStyleFunction: void 0,
pointSizeStyleFunction: void 0,
styleTranslucent: false
};
var builtinVariableSubstitutionMap = {
POSITION: "attributes.positionMC",
POSITION_ABSOLUTE: "v_positionWC",
COLOR: "attributes.color_0",
NORMAL: "attributes.normalMC"
};
function getVariableSubstitutionMap(propertyAttributes) {
const variableSubstitutionMap = clone_default(builtinVariableSubstitutionMap);
if (!defined_default(propertyAttributes)) {
return variableSubstitutionMap;
}
for (let i = 0; i < propertyAttributes.length; i++) {
const propertyAttribute = propertyAttributes[i];
const properties = propertyAttribute.properties;
for (const propertyId in properties) {
if (properties.hasOwnProperty(propertyId)) {
variableSubstitutionMap[propertyId] = `metadata.${propertyId}`;
}
}
}
return variableSubstitutionMap;
}
var parameterList = "ProcessedAttributes attributes, Metadata metadata, float tiles3d_tileset_time";
function getStyleShaderFunctionInfo(style, variableSubstitutionMap) {
const info = scratchShaderFunctionInfo;
const shaderState = {
translucent: false
};
info.colorStyleFunction = style.getColorShaderFunction(
`getColorFromStyle(${parameterList})`,
variableSubstitutionMap,
shaderState
);
info.showStyleFunction = style.getShowShaderFunction(
`getShowFromStyle(${parameterList})`,
variableSubstitutionMap,
shaderState
);
info.pointSizeStyleFunction = style.getPointSizeShaderFunction(
`getPointSizeFromStyle(${parameterList})`,
variableSubstitutionMap,
shaderState
);
info.styleTranslucent = defined_default(info.colorStyleFunction) && shaderState.translucent;
return info;
}
function addShaderFunctionsAndDefines(shaderBuilder, shaderFunctionInfo) {
const colorStyleFunction = shaderFunctionInfo.colorStyleFunction;
if (defined_default(colorStyleFunction)) {
shaderBuilder.addDefine(
"HAS_POINT_CLOUD_COLOR_STYLE",
void 0,
ShaderDestination_default.BOTH
);
shaderBuilder.addVertexLines(colorStyleFunction);
shaderBuilder.addVarying("vec4", "v_pointCloudColor");
}
const showStyleFunction = shaderFunctionInfo.showStyleFunction;
if (defined_default(showStyleFunction)) {
shaderBuilder.addDefine(
"HAS_POINT_CLOUD_SHOW_STYLE",
void 0,
ShaderDestination_default.VERTEX
);
shaderBuilder.addVertexLines(showStyleFunction);
}
const pointSizeStyleFunction = shaderFunctionInfo.pointSizeStyleFunction;
if (defined_default(pointSizeStyleFunction)) {
shaderBuilder.addDefine(
"HAS_POINT_CLOUD_POINT_SIZE_STYLE",
void 0,
ShaderDestination_default.VERTEX
);
shaderBuilder.addVertexLines(pointSizeStyleFunction);
}
}
function getBuiltinPropertyNames(source, propertyNames) {
const regex = /attributes\.(\w+)/g;
let matches = regex.exec(source);
while (matches !== null) {
const name = matches[1];
if (propertyNames.indexOf(name) === -1) {
propertyNames.push(name);
}
matches = regex.exec(source);
}
}
function getPropertyNames(shaderFunctionInfo) {
const colorStyleFunction = shaderFunctionInfo.colorStyleFunction;
const showStyleFunction = shaderFunctionInfo.showStyleFunction;
const pointSizeStyleFunction = shaderFunctionInfo.pointSizeStyleFunction;
const builtinPropertyNames = [];
if (defined_default(colorStyleFunction)) {
getBuiltinPropertyNames(colorStyleFunction, builtinPropertyNames);
}
if (defined_default(showStyleFunction)) {
getBuiltinPropertyNames(showStyleFunction, builtinPropertyNames);
}
if (defined_default(pointSizeStyleFunction)) {
getBuiltinPropertyNames(pointSizeStyleFunction, builtinPropertyNames);
}
return builtinPropertyNames;
}
var PointCloudStylingPipelineStage_default = PointCloudStylingPipelineStage;
// packages/engine/Source/Shaders/Model/PrimitiveOutlineStageVS.js
var PrimitiveOutlineStageVS_default = "void primitiveOutlineStage() {\n v_outlineCoordinates = a_outlineCoordinates;\n}\n";
// packages/engine/Source/Shaders/Model/PrimitiveOutlineStageFS.js
var PrimitiveOutlineStageFS_default = "void primitiveOutlineStage(inout czm_modelMaterial material) {\n if (!model_showOutline) {\n return;\n }\n\n float outlineX = \n texture(model_outlineTexture, vec2(v_outlineCoordinates.x, 0.5)).r;\n float outlineY = \n texture(model_outlineTexture, vec2(v_outlineCoordinates.y, 0.5)).r;\n float outlineZ = \n texture(model_outlineTexture, vec2(v_outlineCoordinates.z, 0.5)).r;\n float outlineness = max(outlineX, max(outlineY, outlineZ));\n\n material.diffuse = mix(material.diffuse, model_outlineColor.rgb, model_outlineColor.a * outlineness);\n}\n\n";
// packages/engine/Source/Scene/Model/PrimitiveOutlinePipelineStage.js
var PrimitiveOutlinePipelineStage = {
name: "PrimitiveOutlinePipelineStage"
// Helps with debugging
};
PrimitiveOutlinePipelineStage.process = function(renderResources, primitive, frameState) {
const shaderBuilder = renderResources.shaderBuilder;
const uniformMap2 = renderResources.uniformMap;
shaderBuilder.addDefine(
"HAS_PRIMITIVE_OUTLINE",
void 0,
ShaderDestination_default.BOTH
);
shaderBuilder.addAttribute("vec3", "a_outlineCoordinates");
shaderBuilder.addVarying("vec3", "v_outlineCoordinates");
const outlineCoordinates = primitive.outlineCoordinates;
const vertexAttribute = {
index: renderResources.attributeIndex++,
vertexBuffer: outlineCoordinates.buffer,
componentsPerAttribute: AttributeType_default.getNumberOfComponents(
outlineCoordinates.type
),
componentDatatype: outlineCoordinates.componentDatatype,
offsetInBytes: outlineCoordinates.byteOffset,
strideInBytes: outlineCoordinates.byteStride,
normalize: outlineCoordinates.normalized
};
renderResources.attributes.push(vertexAttribute);
shaderBuilder.addUniform(
"sampler2D",
"model_outlineTexture",
ShaderDestination_default.FRAGMENT
);
const outlineTexture = PrimitiveOutlineGenerator_default.createTexture(
frameState.context
);
uniformMap2.model_outlineTexture = function() {
return outlineTexture;
};
const model = renderResources.model;
shaderBuilder.addUniform(
"vec4",
"model_outlineColor",
ShaderDestination_default.FRAGMENT
);
uniformMap2.model_outlineColor = function() {
return model.outlineColor;
};
shaderBuilder.addUniform(
"bool",
"model_showOutline",
ShaderDestination_default.FRAGMENT
);
uniformMap2.model_showOutline = function() {
return model.showOutline;
};
shaderBuilder.addVertexLines(PrimitiveOutlineStageVS_default);
shaderBuilder.addFragmentLines(PrimitiveOutlineStageFS_default);
};
var PrimitiveOutlinePipelineStage_default = PrimitiveOutlinePipelineStage;
// packages/engine/Source/Scene/Model/PrimitiveStatisticsPipelineStage.js
var PrimitiveStatisticsPipelineStage = {
name: "PrimitiveStatisticsPipelineStage",
// Helps with debugging
// Expose some methods for testing
_countGeometry: countGeometry,
_count2DPositions: count2DPositions,
_countMorphTargetAttributes: countMorphTargetAttributes,
_countMaterialTextures: countMaterialTextures,
_countFeatureIdTextures: countFeatureIdTextures,
_countBinaryMetadata: countBinaryMetadata
};
PrimitiveStatisticsPipelineStage.process = function(renderResources, primitive, frameState) {
const model = renderResources.model;
const statistics2 = model.statistics;
countGeometry(statistics2, primitive);
count2DPositions(statistics2, renderResources.runtimePrimitive);
countMorphTargetAttributes(statistics2, primitive);
countMaterialTextures(statistics2, primitive.material);
countFeatureIdTextures(statistics2, primitive.featureIds);
countBinaryMetadata(statistics2, model);
};
function countGeometry(statistics2, primitive) {
const indicesCount = defined_default(primitive.indices) ? primitive.indices.count : ModelUtility_default.getAttributeBySemantic(primitive, "POSITION").count;
const primitiveType = primitive.primitiveType;
if (primitiveType === PrimitiveType_default.POINTS) {
statistics2.pointsLength += indicesCount;
} else if (PrimitiveType_default.isTriangles(primitiveType)) {
statistics2.trianglesLength += countTriangles(primitiveType, indicesCount);
}
const attributes = primitive.attributes;
const length3 = attributes.length;
for (let i = 0; i < length3; i++) {
const attribute = attributes[i];
if (defined_default(attribute.buffer)) {
const hasCpuCopy = defined_default(attribute.typedArray);
statistics2.addBuffer(attribute.buffer, hasCpuCopy);
}
}
const outlineCoordinates = primitive.outlineCoordinates;
if (defined_default(outlineCoordinates) && defined_default(outlineCoordinates.buffer)) {
const hasCpuCopy = false;
statistics2.addBuffer(outlineCoordinates.buffer, hasCpuCopy);
}
const indices2 = primitive.indices;
if (defined_default(indices2) && defined_default(indices2.buffer)) {
const hasCpuCopy = defined_default(indices2.typedArray);
statistics2.addBuffer(indices2.buffer, hasCpuCopy);
}
}
function countTriangles(primitiveType, indicesCount) {
switch (primitiveType) {
case PrimitiveType_default.TRIANGLES:
return indicesCount / 3;
case PrimitiveType_default.TRIANGLE_STRIP:
case PrimitiveType_default.TRIANGLE_FAN:
return Math.max(indicesCount - 2, 0);
default:
return 0;
}
}
function count2DPositions(statistics2, runtimePrimitive) {
const buffer2D = runtimePrimitive.positionBuffer2D;
if (defined_default(buffer2D)) {
const hasCpuCopy = true;
statistics2.addBuffer(buffer2D, hasCpuCopy);
}
}
function countMorphTargetAttributes(statistics2, primitive) {
const morphTargets = primitive.morphTargets;
if (!defined_default(morphTargets)) {
return;
}
const hasCpuCopy = false;
const morphTargetsLength = morphTargets.length;
for (let i = 0; i < morphTargetsLength; i++) {
const attributes = morphTargets[i].attributes;
const attributesLength = attributes.length;
for (let j = 0; j < attributesLength; j++) {
const attribute = attributes[j];
if (defined_default(attribute.buffer)) {
statistics2.addBuffer(attribute.buffer, hasCpuCopy);
}
}
}
}
function countMaterialTextures(statistics2, material) {
const textureReaders = getAllTextureReaders(material);
const length3 = textureReaders.length;
for (let i = 0; i < length3; i++) {
const textureReader = textureReaders[i];
if (defined_default(textureReader) && defined_default(textureReader.texture)) {
statistics2.addTexture(textureReader.texture);
}
}
}
function getAllTextureReaders(material) {
const metallicRoughness = material.metallicRoughness;
const textureReaders = [
material.emissiveTexture,
material.normalTexture,
material.occlusionTexture,
metallicRoughness.baseColorTexture,
metallicRoughness.metallicRoughnessTexture
];
const specularGlossiness = material.specularGlossiness;
if (defined_default(specularGlossiness)) {
textureReaders.push(specularGlossiness.diffuseTexture);
textureReaders.push(specularGlossiness.specularGlossinessTexture);
}
return textureReaders;
}
function countFeatureIdTextures(statistics2, featureIdSets) {
const length3 = featureIdSets.length;
for (let i = 0; i < length3; i++) {
const featureIds = featureIdSets[i];
if (featureIds instanceof ModelComponents_default.FeatureIdTexture) {
const textureReader = featureIds.textureReader;
if (defined_default(textureReader.texture)) {
statistics2.addTexture(textureReader.texture);
}
}
}
}
function countBinaryMetadata(statistics2, model) {
const structuralMetadata = model.structuralMetadata;
if (defined_default(structuralMetadata)) {
countPropertyTextures(statistics2, structuralMetadata);
statistics2.propertyTablesByteLength += structuralMetadata.propertyTablesByteLength;
}
const featureTables = model.featureTables;
if (!defined_default(featureTables)) {
return;
}
const length3 = featureTables.length;
for (let i = 0; i < length3; i++) {
const featureTable = featureTables[i];
statistics2.addBatchTexture(featureTable.batchTexture);
}
}
function countPropertyTextures(statistics2, structuralMetadata) {
const propertyTextures = structuralMetadata.propertyTextures;
if (!defined_default(propertyTextures)) {
return;
}
const texturesLength = propertyTextures.length;
for (let i = 0; i < texturesLength; i++) {
const propertyTexture = propertyTextures[i];
const properties = propertyTexture.properties;
for (const propertyId in properties) {
if (properties.hasOwnProperty(propertyId)) {
const property = properties[propertyId];
const textureReader = property.textureReader;
if (defined_default(textureReader.texture)) {
statistics2.addTexture(textureReader.texture);
}
}
}
}
}
var PrimitiveStatisticsPipelineStage_default = PrimitiveStatisticsPipelineStage;
// packages/engine/Source/Scene/Model/SceneMode2DPipelineStage.js
var scratchModelMatrix = new Matrix4_default();
var scratchModelView2D = new Matrix4_default();
var SceneMode2DPipelineStage = {
name: "SceneMode2DPipelineStage"
// Helps with debugging
};
SceneMode2DPipelineStage.process = function(renderResources, primitive, frameState) {
const positionAttribute = ModelUtility_default.getAttributeBySemantic(
primitive,
VertexAttributeSemantic_default.POSITION
);
const shaderBuilder = renderResources.shaderBuilder;
const model = renderResources.model;
const modelMatrix = model.sceneGraph.computedModelMatrix;
const nodeComputedTransform = renderResources.runtimeNode.computedTransform;
const computedModelMatrix = Matrix4_default.multiplyTransformation(
modelMatrix,
nodeComputedTransform,
scratchModelMatrix
);
const boundingSphere2D = computeBoundingSphere2D(
renderResources,
computedModelMatrix,
frameState
);
const runtimePrimitive = renderResources.runtimePrimitive;
runtimePrimitive.boundingSphere2D = boundingSphere2D;
const instances = renderResources.runtimeNode.node.instances;
if (defined_default(instances)) {
return;
}
if (defined_default(positionAttribute.typedArray)) {
const buffer2D = createPositionBufferFor2D(
positionAttribute,
computedModelMatrix,
boundingSphere2D,
frameState
);
runtimePrimitive.positionBuffer2D = buffer2D;
model._modelResources.push(buffer2D);
positionAttribute.typedArray = void 0;
}
shaderBuilder.addDefine(
"USE_2D_POSITIONS",
void 0,
ShaderDestination_default.VERTEX
);
shaderBuilder.addUniform("mat4", "u_modelView2D", ShaderDestination_default.VERTEX);
const modelMatrix2D = Matrix4_default.fromTranslation(
boundingSphere2D.center,
new Matrix4_default()
);
const context = frameState.context;
const uniformMap2 = {
u_modelView2D: function() {
return Matrix4_default.multiplyTransformation(
context.uniformState.view,
modelMatrix2D,
scratchModelView2D
);
}
};
renderResources.uniformMap = combine_default(uniformMap2, renderResources.uniformMap);
};
var scratchProjectedMin2 = new Cartesian3_default();
var scratchProjectedMax2 = new Cartesian3_default();
function computeBoundingSphere2D(renderResources, modelMatrix, frameState) {
const transformedPositionMin = Matrix4_default.multiplyByPoint(
modelMatrix,
renderResources.positionMin,
scratchProjectedMin2
);
const projectedMin = SceneTransforms_default.computeActualWgs84Position(
frameState,
transformedPositionMin,
transformedPositionMin
);
const transformedPositionMax = Matrix4_default.multiplyByPoint(
modelMatrix,
renderResources.positionMax,
scratchProjectedMax2
);
const projectedMax = SceneTransforms_default.computeActualWgs84Position(
frameState,
transformedPositionMax,
transformedPositionMax
);
return BoundingSphere_default.fromCornerPoints(
projectedMin,
projectedMax,
new BoundingSphere_default()
);
}
var scratchPosition2 = new Cartesian3_default();
function dequantizePositionsTypedArray(typedArray, quantization) {
const length3 = typedArray.length;
const dequantizedArray = new Float32Array(length3);
const quantizedVolumeOffset = quantization.quantizedVolumeOffset;
const quantizedVolumeStepSize = quantization.quantizedVolumeStepSize;
for (let i = 0; i < length3; i += 3) {
const initialPosition = Cartesian3_default.fromArray(
typedArray,
i,
scratchPosition2
);
const scaledPosition = Cartesian3_default.multiplyComponents(
initialPosition,
quantizedVolumeStepSize,
initialPosition
);
const dequantizedPosition = Cartesian3_default.add(
scaledPosition,
quantizedVolumeOffset,
scaledPosition
);
dequantizedArray[i] = dequantizedPosition.x;
dequantizedArray[i + 1] = dequantizedPosition.y;
dequantizedArray[i + 2] = dequantizedPosition.z;
}
return dequantizedArray;
}
function createPositionsTypedArrayFor2D(attribute, modelMatrix, referencePoint, frameState) {
let result;
if (defined_default(attribute.quantization)) {
result = dequantizePositionsTypedArray(
attribute.typedArray,
attribute.quantization
);
} else {
result = attribute.typedArray.slice();
}
const startIndex = attribute.byteOffset / Float32Array.BYTES_PER_ELEMENT;
const length3 = result.length;
const stride = defined_default(attribute.byteStride) ? attribute.byteStride / Float32Array.BYTES_PER_ELEMENT : 3;
for (let i = startIndex; i < length3; i += stride) {
const initialPosition = Cartesian3_default.fromArray(result, i, scratchPosition2);
if (isNaN(initialPosition.x) || isNaN(initialPosition.y) || isNaN(initialPosition.z)) {
continue;
}
const transformedPosition = Matrix4_default.multiplyByPoint(
modelMatrix,
initialPosition,
initialPosition
);
const projectedPosition2 = SceneTransforms_default.computeActualWgs84Position(
frameState,
transformedPosition,
transformedPosition
);
const relativePosition = Cartesian3_default.subtract(
projectedPosition2,
referencePoint,
projectedPosition2
);
result[i] = relativePosition.x;
result[i + 1] = relativePosition.y;
result[i + 2] = relativePosition.z;
}
return result;
}
function createPositionBufferFor2D(positionAttribute, modelMatrix, boundingSphere2D, frameState) {
const frameStateCV = clone_default(frameState);
frameStateCV.mode = SceneMode_default.COLUMBUS_VIEW;
const referencePoint = boundingSphere2D.center;
const projectedPositions = createPositionsTypedArrayFor2D(
positionAttribute,
modelMatrix,
referencePoint,
frameStateCV
);
const buffer = Buffer_default.createVertexBuffer({
context: frameState.context,
typedArray: projectedPositions,
usage: BufferUsage_default.STATIC_DRAW
});
buffer.vertexArrayDestroyable = false;
return buffer;
}
var SceneMode2DPipelineStage_default = SceneMode2DPipelineStage;
// packages/engine/Source/Shaders/Model/SkinningStageVS.js
var SkinningStageVS_default = "void skinningStage(inout ProcessedAttributes attributes) \n{\n mat4 skinningMatrix = getSkinningMatrix();\n mat3 skinningMatrixMat3 = mat3(skinningMatrix);\n\n vec4 positionMC = vec4(attributes.positionMC, 1.0);\n attributes.positionMC = vec3(skinningMatrix * positionMC);\n\n #ifdef HAS_NORMALS\n vec3 normalMC = attributes.normalMC;\n attributes.normalMC = skinningMatrixMat3 * normalMC;\n #endif\n\n #ifdef HAS_TANGENTS\n vec3 tangentMC = attributes.tangentMC;\n attributes.tangentMC = skinningMatrixMat3 * tangentMC;\n #endif\n}";
// packages/engine/Source/Scene/Model/SkinningPipelineStage.js
var SkinningPipelineStage = {
name: "SkinningPipelineStage",
// Helps with debugging
FUNCTION_ID_GET_SKINNING_MATRIX: "getSkinningMatrix",
FUNCTION_SIGNATURE_GET_SKINNING_MATRIX: "mat4 getSkinningMatrix()"
};
SkinningPipelineStage.process = function(renderResources, primitive) {
const shaderBuilder = renderResources.shaderBuilder;
shaderBuilder.addDefine("HAS_SKINNING", void 0, ShaderDestination_default.VERTEX);
addGetSkinningMatrixFunction(shaderBuilder, primitive);
const runtimeNode = renderResources.runtimeNode;
const jointMatrices = runtimeNode.computedJointMatrices;
shaderBuilder.addUniform(
"mat4",
`u_jointMatrices[${jointMatrices.length}]`,
ShaderDestination_default.VERTEX
);
shaderBuilder.addVertexLines(SkinningStageVS_default);
const uniformMap2 = {
u_jointMatrices: function() {
return runtimeNode.computedJointMatrices;
}
};
renderResources.uniformMap = combine_default(uniformMap2, renderResources.uniformMap);
};
function getMaximumAttributeSetIndex(primitive) {
let setIndex = -1;
const attributes = primitive.attributes;
const length3 = attributes.length;
for (let i = 0; i < length3; i++) {
const attribute = attributes[i];
const isJointsOrWeights = attribute.semantic === VertexAttributeSemantic_default.JOINTS || attribute.semantic === VertexAttributeSemantic_default.WEIGHTS;
if (!isJointsOrWeights) {
continue;
}
setIndex = Math.max(setIndex, attribute.setIndex);
}
return setIndex;
}
function addGetSkinningMatrixFunction(shaderBuilder, primitive) {
shaderBuilder.addFunction(
SkinningPipelineStage.FUNCTION_ID_GET_SKINNING_MATRIX,
SkinningPipelineStage.FUNCTION_SIGNATURE_GET_SKINNING_MATRIX,
ShaderDestination_default.VERTEX
);
const initialLine = "mat4 skinnedMatrix = mat4(0);";
shaderBuilder.addFunctionLines(
SkinningPipelineStage.FUNCTION_ID_GET_SKINNING_MATRIX,
[initialLine]
);
let setIndex;
let componentIndex;
const componentStrings = ["x", "y", "z", "w"];
const maximumSetIndex = getMaximumAttributeSetIndex(primitive);
for (setIndex = 0; setIndex <= maximumSetIndex; setIndex++) {
for (componentIndex = 0; componentIndex <= 3; componentIndex++) {
const component = componentStrings[componentIndex];
const line = `skinnedMatrix += a_weights_${setIndex}.${component} * u_jointMatrices[int(a_joints_${setIndex}.${component})];`;
shaderBuilder.addFunctionLines(
SkinningPipelineStage.FUNCTION_ID_GET_SKINNING_MATRIX,
[line]
);
}
}
const returnLine = "return skinnedMatrix;";
shaderBuilder.addFunctionLines(
SkinningPipelineStage.FUNCTION_ID_GET_SKINNING_MATRIX,
[returnLine]
);
}
var SkinningPipelineStage_default = SkinningPipelineStage;
// packages/engine/Source/Core/WireframeIndexGenerator.js
var WireframeIndexGenerator = {};
function createWireframeFromTriangles(vertexCount) {
const wireframeIndices = IndexDatatype_default.createTypedArray(
vertexCount,
vertexCount * 2
);
const length3 = vertexCount;
let index = 0;
for (let i = 0; i < length3; i += 3) {
wireframeIndices[index++] = i;
wireframeIndices[index++] = i + 1;
wireframeIndices[index++] = i + 1;
wireframeIndices[index++] = i + 2;
wireframeIndices[index++] = i + 2;
wireframeIndices[index++] = i;
}
return wireframeIndices;
}
function createWireframeFromTriangleIndices(vertexCount, originalIndices) {
const originalIndicesCount = originalIndices.length;
const wireframeIndices = IndexDatatype_default.createTypedArray(
vertexCount,
originalIndicesCount * 2
);
let index = 0;
for (let i = 0; i < originalIndicesCount; i += 3) {
const point0 = originalIndices[i];
const point1 = originalIndices[i + 1];
const point2 = originalIndices[i + 2];
wireframeIndices[index++] = point0;
wireframeIndices[index++] = point1;
wireframeIndices[index++] = point1;
wireframeIndices[index++] = point2;
wireframeIndices[index++] = point2;
wireframeIndices[index++] = point0;
}
return wireframeIndices;
}
function createWireframeFromTriangleStrip(vertexCount) {
const numberOfTriangles = vertexCount - 2;
const wireframeIndicesCount = 2 + numberOfTriangles * 4;
const wireframeIndices = IndexDatatype_default.createTypedArray(
vertexCount,
wireframeIndicesCount
);
let index = 0;
wireframeIndices[index++] = 0;
wireframeIndices[index++] = 1;
for (let i = 0; i < numberOfTriangles; i++) {
wireframeIndices[index++] = i + 1;
wireframeIndices[index++] = i + 2;
wireframeIndices[index++] = i + 2;
wireframeIndices[index++] = i;
}
return wireframeIndices;
}
function createWireframeFromTriangleStripIndices(vertexCount, originalIndices) {
const originalIndicesCount = originalIndices.length;
const numberOfTriangles = originalIndicesCount - 2;
const wireframeIndicesCount = 2 + numberOfTriangles * 4;
const wireframeIndices = IndexDatatype_default.createTypedArray(
vertexCount,
wireframeIndicesCount
);
let index = 0;
wireframeIndices[index++] = originalIndices[0];
wireframeIndices[index++] = originalIndices[1];
for (let i = 0; i < numberOfTriangles; i++) {
const point0 = originalIndices[i];
const point1 = originalIndices[i + 1];
const point2 = originalIndices[i + 2];
wireframeIndices[index++] = point1;
wireframeIndices[index++] = point2;
wireframeIndices[index++] = point2;
wireframeIndices[index++] = point0;
}
return wireframeIndices;
}
function createWireframeFromTriangleFan(vertexCount) {
const numberOfTriangles = vertexCount - 2;
const wireframeIndicesCount = 2 + numberOfTriangles * 4;
const wireframeIndices = IndexDatatype_default.createTypedArray(
vertexCount,
wireframeIndicesCount
);
let index = 0;
wireframeIndices[index++] = 0;
wireframeIndices[index++] = 1;
for (let i = 0; i < numberOfTriangles; i++) {
wireframeIndices[index++] = i + 1;
wireframeIndices[index++] = i + 2;
wireframeIndices[index++] = i + 2;
wireframeIndices[index++] = 0;
}
return wireframeIndices;
}
function createWireframeFromTriangleFanIndices(vertexCount, originalIndices) {
const originalIndicesCount = originalIndices.length;
const numberOfTriangles = originalIndicesCount - 2;
const wireframeIndicesCount = 2 + numberOfTriangles * 4;
const wireframeIndices = IndexDatatype_default.createTypedArray(
vertexCount,
wireframeIndicesCount
);
let index = 0;
const firstPoint = originalIndices[0];
wireframeIndices[index++] = firstPoint;
wireframeIndices[index++] = originalIndices[1];
for (let i = 0; i < numberOfTriangles; i++) {
const point1 = originalIndices[i + 1];
const point2 = originalIndices[i + 2];
wireframeIndices[index++] = point1;
wireframeIndices[index++] = point2;
wireframeIndices[index++] = point2;
wireframeIndices[index++] = firstPoint;
}
return wireframeIndices;
}
WireframeIndexGenerator.createWireframeIndices = function(primitiveType, vertexCount, originalIndices) {
const hasOriginalIndices = defined_default(originalIndices);
if (primitiveType === PrimitiveType_default.TRIANGLES) {
return hasOriginalIndices ? createWireframeFromTriangleIndices(vertexCount, originalIndices) : createWireframeFromTriangles(vertexCount);
}
if (primitiveType === PrimitiveType_default.TRIANGLE_STRIP) {
return hasOriginalIndices ? createWireframeFromTriangleStripIndices(vertexCount, originalIndices) : createWireframeFromTriangleStrip(vertexCount);
}
if (primitiveType === PrimitiveType_default.TRIANGLE_FAN) {
return hasOriginalIndices ? createWireframeFromTriangleFanIndices(vertexCount, originalIndices) : createWireframeFromTriangleFan(vertexCount);
}
return void 0;
};
WireframeIndexGenerator.getWireframeIndicesCount = function(primitiveType, originalCount) {
if (primitiveType === PrimitiveType_default.TRIANGLES) {
return originalCount * 2;
}
if (primitiveType === PrimitiveType_default.TRIANGLE_STRIP || primitiveType === PrimitiveType_default.TRIANGLE_FAN) {
const numberOfTriangles = originalCount - 2;
return 2 + numberOfTriangles * 4;
}
return originalCount;
};
var WireframeIndexGenerator_default = WireframeIndexGenerator;
// packages/engine/Source/Scene/Model/WireframePipelineStage.js
var WireframePipelineStage = {
name: "WireframePipelineStage"
// Helps with debugging
};
WireframePipelineStage.process = function(renderResources, primitive, frameState) {
const shaderBuilder = renderResources.shaderBuilder;
shaderBuilder.addDefine(
"HAS_WIREFRAME",
void 0,
ShaderDestination_default.FRAGMENT
);
const model = renderResources.model;
const wireframeIndexBuffer = createWireframeIndexBuffer(
primitive,
renderResources.indices,
frameState
);
model._pipelineResources.push(wireframeIndexBuffer);
renderResources.wireframeIndexBuffer = wireframeIndexBuffer;
const hasCpuCopy = false;
model.statistics.addBuffer(wireframeIndexBuffer, hasCpuCopy);
const originalPrimitiveType = renderResources.primitiveType;
const originalCount = renderResources.count;
renderResources.primitiveType = PrimitiveType_default.LINES;
renderResources.count = WireframeIndexGenerator_default.getWireframeIndicesCount(
originalPrimitiveType,
originalCount
);
};
function createWireframeIndexBuffer(primitive, indices2, frameState) {
const positionAttribute = ModelUtility_default.getAttributeBySemantic(
primitive,
VertexAttributeSemantic_default.POSITION
);
const vertexCount = positionAttribute.count;
const webgl2 = frameState.context.webgl2;
let originalIndices;
if (defined_default(indices2)) {
const indicesBuffer = indices2.buffer;
const indicesCount = indices2.count;
if (defined_default(indicesBuffer) && webgl2) {
const useUint8Array = indicesBuffer.sizeInBytes === indicesCount;
originalIndices = useUint8Array ? new Uint8Array(indicesCount) : IndexDatatype_default.createTypedArray(vertexCount, indicesCount);
indicesBuffer.getBufferData(originalIndices);
} else {
originalIndices = indices2.typedArray;
}
}
const primitiveType = primitive.primitiveType;
const wireframeIndices = WireframeIndexGenerator_default.createWireframeIndices(
primitiveType,
vertexCount,
originalIndices
);
const indexDatatype = IndexDatatype_default.fromSizeInBytes(
wireframeIndices.BYTES_PER_ELEMENT
);
return Buffer_default.createIndexBuffer({
context: frameState.context,
typedArray: wireframeIndices,
usage: BufferUsage_default.STATIC_DRAW,
indexDatatype
});
}
var WireframePipelineStage_default = WireframePipelineStage;
// packages/engine/Source/Scene/Model/ModelRuntimePrimitive.js
function ModelRuntimePrimitive(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const primitive = options.primitive;
const node = options.node;
const model = options.model;
Check_default.typeOf.object("options.primitive", primitive);
Check_default.typeOf.object("options.node", node);
Check_default.typeOf.object("options.model", model);
this.primitive = primitive;
this.node = node;
this.model = model;
this.pipelineStages = [];
this.drawCommand = void 0;
this.boundingSphere = void 0;
this.boundingSphere2D = void 0;
this.positionBuffer2D = void 0;
this.batchLengths = void 0;
this.batchOffsets = void 0;
this.updateStages = [];
}
ModelRuntimePrimitive.prototype.configurePipeline = function(frameState) {
const pipelineStages = this.pipelineStages;
pipelineStages.length = 0;
const primitive = this.primitive;
const node = this.node;
const model = this.model;
const customShader = model.customShader;
const style = model.style;
const useWebgl2 = frameState.context.webgl2;
const mode2 = frameState.mode;
const use2D = mode2 !== SceneMode_default.SCENE3D && !frameState.scene3DOnly && model._projectTo2D;
const hasMorphTargets = defined_default(primitive.morphTargets) && primitive.morphTargets.length > 0;
const hasSkinning = defined_default(node.skin);
const hasCustomShader = defined_default(customShader);
const hasCustomFragmentShader = hasCustomShader && defined_default(customShader.fragmentShaderText);
const materialsEnabled = !hasCustomFragmentShader || customShader.mode !== CustomShaderMode_default.REPLACE_MATERIAL;
const hasQuantization = ModelUtility_default.hasQuantizedAttributes(
primitive.attributes
);
const generateWireframeIndices = model.debugWireframe && PrimitiveType_default.isTriangles(primitive.primitiveType) && // Generating index buffers for wireframes is always possible in WebGL2.
// However, this will only work in WebGL1 if the model was constructed with
// enableDebugWireframe set to true.
(model._enableDebugWireframe || useWebgl2);
const pointCloudShading = model.pointCloudShading;
const hasAttenuation = defined_default(pointCloudShading) && pointCloudShading.attenuation;
const hasPointCloudBackFaceCulling = defined_default(pointCloudShading) && pointCloudShading.backFaceCulling;
const hasPointCloudStyle = primitive.primitiveType === PrimitiveType_default.POINTS && (defined_default(style) || hasAttenuation || hasPointCloudBackFaceCulling);
const hasOutlines = model._enableShowOutline && defined_default(primitive.outlineCoordinates);
const featureIdFlags = inspectFeatureIds(model, node, primitive);
const hasClassification = defined_default(model.classificationType);
if (use2D) {
pipelineStages.push(SceneMode2DPipelineStage_default);
}
pipelineStages.push(GeometryPipelineStage_default);
if (generateWireframeIndices) {
pipelineStages.push(WireframePipelineStage_default);
}
if (hasClassification) {
pipelineStages.push(ClassificationPipelineStage_default);
}
if (hasMorphTargets) {
pipelineStages.push(MorphTargetsPipelineStage_default);
}
if (hasSkinning) {
pipelineStages.push(SkinningPipelineStage_default);
}
if (hasPointCloudStyle) {
pipelineStages.push(PointCloudStylingPipelineStage_default);
}
if (hasQuantization) {
pipelineStages.push(DequantizationPipelineStage_default);
}
if (materialsEnabled) {
pipelineStages.push(MaterialPipelineStage_default);
}
pipelineStages.push(FeatureIdPipelineStage_default);
pipelineStages.push(MetadataPipelineStage_default);
if (featureIdFlags.hasPropertyTable) {
pipelineStages.push(SelectedFeatureIdPipelineStage_default);
pipelineStages.push(BatchTexturePipelineStage_default);
pipelineStages.push(CPUStylingPipelineStage_default);
}
if (hasCustomShader) {
pipelineStages.push(CustomShaderPipelineStage_default);
}
pipelineStages.push(LightingPipelineStage_default);
if (model.allowPicking) {
pipelineStages.push(PickingPipelineStage_default);
}
if (hasOutlines) {
pipelineStages.push(PrimitiveOutlinePipelineStage_default);
}
pipelineStages.push(AlphaPipelineStage_default);
pipelineStages.push(PrimitiveStatisticsPipelineStage_default);
return;
};
function inspectFeatureIds(model, node, primitive) {
let featureIds;
if (defined_default(node.instances)) {
featureIds = ModelUtility_default.getFeatureIdsByLabel(
node.instances.featureIds,
model.instanceFeatureIdLabel
);
if (defined_default(featureIds)) {
return {
hasFeatureIds: true,
hasPropertyTable: defined_default(featureIds.propertyTableId)
};
}
}
featureIds = ModelUtility_default.getFeatureIdsByLabel(
primitive.featureIds,
model.featureIdLabel
);
if (defined_default(featureIds)) {
return {
hasFeatureIds: true,
hasPropertyTable: defined_default(featureIds.propertyTableId)
};
}
return {
hasFeatureIds: false,
hasPropertyTable: false
};
}
var ModelRuntimePrimitive_default = ModelRuntimePrimitive;
// packages/engine/Source/Scene/Model/ModelSkin.js
function ModelSkin(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
Check_default.typeOf.object("options.skin", options.skin);
Check_default.typeOf.object("options.sceneGraph", options.sceneGraph);
this._sceneGraph = options.sceneGraph;
const skin = options.skin;
this._skin = skin;
this._inverseBindMatrices = void 0;
this._joints = [];
this._jointMatrices = [];
initialize13(this);
}
Object.defineProperties(ModelSkin.prototype, {
/**
* The internal skin this runtime skin represents.
*
* @memberof ModelSkin.prototype
* @type {ModelComponents.Skin}
* @readonly
*
* @private
*/
skin: {
get: function() {
return this._skin;
}
},
/**
* The scene graph this skin belongs to.
*
* @memberof ModelSkin.prototype
* @type {ModelSceneGraph}
* @readonly
*
* @private
*/
sceneGraph: {
get: function() {
return this._sceneGraph;
}
},
/**
* The inverse bind matrices of the skin.
*
* @memberof ModelSkin.prototype
* @type {Matrix4[]}
* @readonly
*
* @private
*/
inverseBindMatrices: {
get: function() {
return this._inverseBindMatrices;
}
},
/**
* The joints of the skin.
*
* @memberof ModelSkin.prototype
* @type {ModelRuntimeNode[]}
* @readonly
*
* @private
*/
joints: {
get: function() {
return this._joints;
}
},
/**
* The joint matrices for the skin, where each joint matrix is computed as
* jointMatrix = jointWorldTransform * inverseBindMatrix.
*
* Each node that references this skin is responsible for pre-multiplying its inverse
* world transform to the joint matrices for its own use.
*
* @memberof ModelSkin.prototype
* @type {Matrix4[]}
* @readonly
*
* @private
*/
jointMatrices: {
get: function() {
return this._jointMatrices;
}
}
});
function initialize13(runtimeSkin) {
const skin = runtimeSkin.skin;
const inverseBindMatrices = skin.inverseBindMatrices;
runtimeSkin._inverseBindMatrices = inverseBindMatrices;
const joints = skin.joints;
const length3 = joints.length;
const runtimeNodes = runtimeSkin.sceneGraph._runtimeNodes;
const runtimeJoints = runtimeSkin.joints;
const runtimeJointMatrices = runtimeSkin._jointMatrices;
for (let i = 0; i < length3; i++) {
const jointIndex = joints[i].index;
const runtimeNode = runtimeNodes[jointIndex];
runtimeJoints.push(runtimeNode);
const inverseBindMatrix = inverseBindMatrices[i];
const jointMatrix = computeJointMatrix(
runtimeNode,
inverseBindMatrix,
new Matrix4_default()
);
runtimeJointMatrices.push(jointMatrix);
}
}
function computeJointMatrix(joint, inverseBindMatrix, result) {
const jointWorldTransform = Matrix4_default.multiplyTransformation(
joint.transformToRoot,
joint.transform,
result
);
result = Matrix4_default.multiplyTransformation(
jointWorldTransform,
inverseBindMatrix,
result
);
return result;
}
ModelSkin.prototype.updateJointMatrices = function() {
const jointMatrices = this._jointMatrices;
const length3 = jointMatrices.length;
for (let i = 0; i < length3; i++) {
const joint = this.joints[i];
const inverseBindMatrix = this.inverseBindMatrices[i];
jointMatrices[i] = computeJointMatrix(
joint,
inverseBindMatrix,
jointMatrices[i]
);
}
};
var ModelSkin_default = ModelSkin;
// packages/engine/Source/Scene/Model/ModelAlphaOptions.js
function ModelAlphaOptions() {
this.pass = void 0;
this.alphaCutoff = void 0;
}
var ModelAlphaOptions_default = ModelAlphaOptions;
// packages/engine/Source/Scene/Model/ModelRenderResources.js
function ModelRenderResources(model) {
Check_default.typeOf.object("model", model);
this.shaderBuilder = new ShaderBuilder_default();
this.model = model;
this.uniformMap = {};
this.alphaOptions = new ModelAlphaOptions_default();
this.renderStateOptions = RenderState_default.getState(
RenderState_default.fromCache({
depthTest: {
enabled: true,
func: DepthFunction_default.LESS_OR_EQUAL
}
})
);
this.hasSilhouette = false;
this.hasSkipLevelOfDetail = false;
}
var ModelRenderResources_default = ModelRenderResources;
// packages/engine/Source/Shaders/Model/ModelSilhouetteStageFS.js
var ModelSilhouetteStageFS_default = "void silhouetteStage(inout vec4 color) {\n if(model_silhouettePass) {\n color = czm_gammaCorrect(model_silhouetteColor);\n }\n}";
// packages/engine/Source/Shaders/Model/ModelSilhouetteStageVS.js
var ModelSilhouetteStageVS_default = "void silhouetteStage(in ProcessedAttributes attributes, inout vec4 positionClip) {\n #ifdef HAS_NORMALS\n if(model_silhouettePass) {\n vec3 normal = normalize(czm_normal3D * attributes.normalMC);\n normal.x *= czm_projection[0][0];\n normal.y *= czm_projection[1][1];\n positionClip.xy += normal.xy * positionClip.w * model_silhouetteSize * czm_pixelRatio / czm_viewport.z;\n }\n #endif\n}\n";
// packages/engine/Source/Scene/Model/ModelSilhouettePipelineStage.js
var ModelSilhouettePipelineStage = {
name: "ModelSilhouettePipelineStage"
// Helps with debugging
};
ModelSilhouettePipelineStage.silhouettesLength = 0;
ModelSilhouettePipelineStage.process = function(renderResources, model, frameState) {
if (!defined_default(model._silhouetteId)) {
model._silhouetteId = ++ModelSilhouettePipelineStage.silhouettesLength;
}
const shaderBuilder = renderResources.shaderBuilder;
shaderBuilder.addDefine("HAS_SILHOUETTE", void 0, ShaderDestination_default.BOTH);
shaderBuilder.addVertexLines(ModelSilhouetteStageVS_default);
shaderBuilder.addFragmentLines(ModelSilhouetteStageFS_default);
shaderBuilder.addUniform(
"vec4",
"model_silhouetteColor",
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addUniform(
"float",
"model_silhouetteSize",
ShaderDestination_default.VERTEX
);
shaderBuilder.addUniform(
"bool",
"model_silhouettePass",
ShaderDestination_default.BOTH
);
const uniformMap2 = {
model_silhouetteColor: function() {
return model.silhouetteColor;
},
model_silhouetteSize: function() {
return model.silhouetteSize;
},
model_silhouettePass: function() {
return false;
}
};
renderResources.uniformMap = combine_default(uniformMap2, renderResources.uniformMap);
renderResources.hasSilhouette = true;
};
var ModelSilhouettePipelineStage_default = ModelSilhouettePipelineStage;
// packages/engine/Source/Shaders/Model/ModelSplitterStageFS.js
var ModelSplitterStageFS_default = "void modelSplitterStage()\n{\n // Don't split when rendering the shadow map, because it is rendered from\n // the perspective of a totally different camera.\n#ifndef SHADOW_MAP\n if (model_splitDirection < 0.0 && gl_FragCoord.x > czm_splitPosition) discard;\n if (model_splitDirection > 0.0 && gl_FragCoord.x < czm_splitPosition) discard;\n#endif\n}\n";
// packages/engine/Source/Scene/Model/ModelSplitterPipelineStage.js
var ModelSplitterPipelineStage = {
name: "ModelSplitterPipelineStage",
// Helps with debugging
SPLIT_DIRECTION_UNIFORM_NAME: "model_splitDirection"
};
ModelSplitterPipelineStage.process = function(renderResources, model, frameState) {
const shaderBuilder = renderResources.shaderBuilder;
shaderBuilder.addDefine(
"HAS_MODEL_SPLITTER",
void 0,
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addFragmentLines(ModelSplitterStageFS_default);
const stageUniforms = {};
shaderBuilder.addUniform(
"float",
ModelSplitterPipelineStage.SPLIT_DIRECTION_UNIFORM_NAME,
ShaderDestination_default.FRAGMENT
);
stageUniforms[ModelSplitterPipelineStage.SPLIT_DIRECTION_UNIFORM_NAME] = function() {
return model.splitDirection;
};
renderResources.uniformMap = combine_default(
stageUniforms,
renderResources.uniformMap
);
};
var ModelSplitterPipelineStage_default = ModelSplitterPipelineStage;
// packages/engine/Source/Scene/Model/NodeRenderResources.js
function NodeRenderResources(modelRenderResources, runtimeNode) {
Check_default.typeOf.object("modelRenderResources", modelRenderResources);
Check_default.typeOf.object("runtimeNode", runtimeNode);
this.model = modelRenderResources.model;
this.shaderBuilder = modelRenderResources.shaderBuilder.clone();
this.uniformMap = clone_default(modelRenderResources.uniformMap);
this.alphaOptions = clone_default(modelRenderResources.alphaOptions);
this.renderStateOptions = clone_default(
modelRenderResources.renderStateOptions,
true
);
this.hasSilhouette = modelRenderResources.hasSilhouette;
this.hasSkipLevelOfDetail = modelRenderResources.hasSkipLevelOfDetail;
this.runtimeNode = runtimeNode;
this.attributes = [];
this.attributeIndex = 1;
this.featureIdVertexAttributeSetIndex = 0;
this.instanceCount = 0;
}
var NodeRenderResources_default = NodeRenderResources;
// packages/engine/Source/Scene/Model/ModelLightingOptions.js
function ModelLightingOptions(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this.lightingModel = defaultValue_default(options.lightingModel, LightingModel_default.UNLIT);
}
var ModelLightingOptions_default = ModelLightingOptions;
// packages/engine/Source/Scene/Model/PrimitiveRenderResources.js
function PrimitiveRenderResources(nodeRenderResources, runtimePrimitive) {
Check_default.typeOf.object("nodeRenderResources", nodeRenderResources);
Check_default.typeOf.object("runtimePrimitive", runtimePrimitive);
this.model = nodeRenderResources.model;
this.runtimeNode = nodeRenderResources.runtimeNode;
this.attributes = nodeRenderResources.attributes.slice();
this.attributeIndex = nodeRenderResources.attributeIndex;
this.featureIdVertexAttributeSetIndex = nodeRenderResources.featureIdVertexAttributeSetIndex;
this.uniformMap = clone_default(nodeRenderResources.uniformMap);
this.alphaOptions = clone_default(nodeRenderResources.alphaOptions);
this.renderStateOptions = clone_default(nodeRenderResources.renderStateOptions, true);
this.hasSilhouette = nodeRenderResources.hasSilhouette;
this.hasSkipLevelOfDetail = nodeRenderResources.hasSkipLevelOfDetail;
this.shaderBuilder = nodeRenderResources.shaderBuilder.clone();
this.instanceCount = nodeRenderResources.instanceCount;
this.runtimePrimitive = runtimePrimitive;
const primitive = runtimePrimitive.primitive;
this.count = defined_default(primitive.indices) ? primitive.indices.count : ModelUtility_default.getAttributeBySemantic(primitive, "POSITION").count;
this.hasPropertyTable = false;
this.indices = primitive.indices;
this.wireframeIndexBuffer = void 0;
this.primitiveType = primitive.primitiveType;
const positionMinMax = ModelUtility_default.getPositionMinMax(
primitive,
this.runtimeNode.instancingTranslationMin,
this.runtimeNode.instancingTranslationMax
);
this.positionMin = Cartesian3_default.clone(positionMinMax.min, new Cartesian3_default());
this.positionMax = Cartesian3_default.clone(positionMinMax.max, new Cartesian3_default());
this.boundingSphere = BoundingSphere_default.fromCornerPoints(
this.positionMin,
this.positionMax,
new BoundingSphere_default()
);
this.lightingOptions = new ModelLightingOptions_default();
this.pickId = void 0;
}
var PrimitiveRenderResources_default = PrimitiveRenderResources;
// packages/engine/Source/Scene/Model/ModelSceneGraph.js
function ModelSceneGraph(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const components = options.modelComponents;
Check_default.typeOf.object("options.model", options.model);
Check_default.typeOf.object("options.modelComponents", components);
this._model = options.model;
this._components = components;
this._pipelineStages = [];
this._updateStages = [];
this._runtimeNodes = [];
this._rootNodes = [];
this._skinnedNodes = [];
this._runtimeSkins = [];
this.modelPipelineStages = [];
this._boundingSphere = void 0;
this._boundingSphere2D = void 0;
this._computedModelMatrix = Matrix4_default.clone(Matrix4_default.IDENTITY);
this._computedModelMatrix2D = Matrix4_default.clone(Matrix4_default.IDENTITY);
this._axisCorrectionMatrix = ModelUtility_default.getAxisCorrectionMatrix(
components.upAxis,
components.forwardAxis,
new Matrix4_default()
);
this._runtimeArticulations = {};
initialize14(this);
}
Object.defineProperties(ModelSceneGraph.prototype, {
/**
* The model components this scene graph represents.
*
* @type {ModelComponents}
* @readonly
*
* @private
*/
components: {
get: function() {
return this._components;
}
},
/**
* The axis-corrected model matrix.
*
* @type {Matrix4}
* @readonly
*
* @private
*/
computedModelMatrix: {
get: function() {
return this._computedModelMatrix;
}
},
/**
* A matrix to correct from y-up in some model formats (e.g. glTF) to the
* z-up coordinate system Cesium uses.
*
* @type {Matrix4}
* @readonly
*
* @private
*/
axisCorrectionMatrix: {
get: function() {
return this._axisCorrectionMatrix;
}
},
/**
* The bounding sphere containing all the primitives in the scene graph
* in model space.
*
* @type {BoundingSphere}
* @readonly
*
* @private
*/
boundingSphere: {
get: function() {
return this._boundingSphere;
}
}
});
function initialize14(sceneGraph) {
const components = sceneGraph._components;
const scene = components.scene;
const model = sceneGraph._model;
const modelMatrix = model.modelMatrix;
computeModelMatrix(sceneGraph, modelMatrix);
const articulations = components.articulations;
const articulationsLength = articulations.length;
const runtimeArticulations = sceneGraph._runtimeArticulations;
for (let i = 0; i < articulationsLength; i++) {
const articulation = articulations[i];
const runtimeArticulation = new ModelArticulation_default({
articulation,
sceneGraph
});
const name = runtimeArticulation.name;
runtimeArticulations[name] = runtimeArticulation;
}
const nodes = components.nodes;
const nodesLength = nodes.length;
sceneGraph._runtimeNodes = new Array(nodesLength);
const rootNodes = scene.nodes;
const rootNodesLength = rootNodes.length;
const transformToRoot = Matrix4_default.IDENTITY;
for (let i = 0; i < rootNodesLength; i++) {
const rootNode = scene.nodes[i];
const rootNodeIndex = traverseAndCreateSceneGraph(
sceneGraph,
rootNode,
transformToRoot
);
sceneGraph._rootNodes.push(rootNodeIndex);
}
const skins = components.skins;
const runtimeSkins = sceneGraph._runtimeSkins;
const skinsLength = skins.length;
for (let i = 0; i < skinsLength; i++) {
const skin = skins[i];
runtimeSkins.push(
new ModelSkin_default({
skin,
sceneGraph
})
);
}
const skinnedNodes = sceneGraph._skinnedNodes;
const skinnedNodesLength = skinnedNodes.length;
for (let i = 0; i < skinnedNodesLength; i++) {
const skinnedNodeIndex = skinnedNodes[i];
const skinnedNode = sceneGraph._runtimeNodes[skinnedNodeIndex];
const skin = nodes[skinnedNodeIndex].skin;
const skinIndex = skin.index;
skinnedNode._runtimeSkin = runtimeSkins[skinIndex];
skinnedNode.updateJointMatrices();
}
sceneGraph.applyArticulations();
}
function computeModelMatrix(sceneGraph, modelMatrix) {
const components = sceneGraph._components;
const model = sceneGraph._model;
sceneGraph._computedModelMatrix = Matrix4_default.multiplyTransformation(
modelMatrix,
components.transform,
sceneGraph._computedModelMatrix
);
sceneGraph._computedModelMatrix = Matrix4_default.multiplyTransformation(
sceneGraph._computedModelMatrix,
sceneGraph._axisCorrectionMatrix,
sceneGraph._computedModelMatrix
);
sceneGraph._computedModelMatrix = Matrix4_default.multiplyByUniformScale(
sceneGraph._computedModelMatrix,
model.computedScale,
sceneGraph._computedModelMatrix
);
}
var scratchComputedTranslation = new Cartesian3_default();
function computeModelMatrix2D(sceneGraph, frameState) {
const computedModelMatrix = sceneGraph._computedModelMatrix;
const translation3 = Matrix4_default.getTranslation(
computedModelMatrix,
scratchComputedTranslation
);
if (!Cartesian3_default.equals(translation3, Cartesian3_default.ZERO)) {
sceneGraph._computedModelMatrix2D = Transforms_default.basisTo2D(
frameState.mapProjection,
computedModelMatrix,
sceneGraph._computedModelMatrix2D
);
} else {
const center = sceneGraph.boundingSphere.center;
const to2D = Transforms_default.wgs84To2DModelMatrix(
frameState.mapProjection,
center,
sceneGraph._computedModelMatrix2D
);
sceneGraph._computedModelMatrix2D = Matrix4_default.multiply(
to2D,
computedModelMatrix,
sceneGraph._computedModelMatrix2D
);
}
sceneGraph._boundingSphere2D = BoundingSphere_default.transform(
sceneGraph._boundingSphere,
sceneGraph._computedModelMatrix2D,
sceneGraph._boundingSphere2D
);
}
function traverseAndCreateSceneGraph(sceneGraph, node, transformToRoot) {
const childrenIndices = [];
const transform3 = ModelUtility_default.getNodeTransform(node);
const childrenLength = node.children.length;
for (let i = 0; i < childrenLength; i++) {
const childNode = node.children[i];
const childNodeTransformToRoot = Matrix4_default.multiplyTransformation(
transformToRoot,
transform3,
new Matrix4_default()
);
const childIndex = traverseAndCreateSceneGraph(
sceneGraph,
childNode,
childNodeTransformToRoot
);
childrenIndices.push(childIndex);
}
const runtimeNode = new ModelRuntimeNode_default({
node,
transform: transform3,
transformToRoot,
children: childrenIndices,
sceneGraph
});
const primitivesLength = node.primitives.length;
for (let i = 0; i < primitivesLength; i++) {
runtimeNode.runtimePrimitives.push(
new ModelRuntimePrimitive_default({
primitive: node.primitives[i],
node,
model: sceneGraph._model
})
);
}
const index = node.index;
sceneGraph._runtimeNodes[index] = runtimeNode;
if (defined_default(node.skin)) {
sceneGraph._skinnedNodes.push(index);
}
const name = node.name;
if (defined_default(name)) {
const model = sceneGraph._model;
const publicNode = new ModelNode_default(model, runtimeNode);
model._nodesByName[name] = publicNode;
}
return index;
}
var scratchModelPositionMin = new Cartesian3_default();
var scratchModelPositionMax = new Cartesian3_default();
var scratchPrimitivePositionMin = new Cartesian3_default();
var scratchPrimitivePositionMax = new Cartesian3_default();
ModelSceneGraph.prototype.buildDrawCommands = function(frameState) {
const model = this._model;
const modelRenderResources = new ModelRenderResources_default(model);
model.statistics.clear();
this.configurePipeline(frameState);
const modelPipelineStages = this.modelPipelineStages;
let i, j, k;
for (i = 0; i < modelPipelineStages.length; i++) {
const modelPipelineStage = modelPipelineStages[i];
modelPipelineStage.process(modelRenderResources, model, frameState);
}
const modelPositionMin = Cartesian3_default.fromElements(
Number.MAX_VALUE,
Number.MAX_VALUE,
Number.MAX_VALUE,
scratchModelPositionMin
);
const modelPositionMax = Cartesian3_default.fromElements(
-Number.MAX_VALUE,
-Number.MAX_VALUE,
-Number.MAX_VALUE,
scratchModelPositionMax
);
for (i = 0; i < this._runtimeNodes.length; i++) {
const runtimeNode = this._runtimeNodes[i];
if (!defined_default(runtimeNode)) {
continue;
}
runtimeNode.configurePipeline();
const nodePipelineStages = runtimeNode.pipelineStages;
const nodeRenderResources = new NodeRenderResources_default(
modelRenderResources,
runtimeNode
);
for (j = 0; j < nodePipelineStages.length; j++) {
const nodePipelineStage = nodePipelineStages[j];
nodePipelineStage.process(
nodeRenderResources,
runtimeNode.node,
frameState
);
}
const nodeTransform = runtimeNode.computedTransform;
for (j = 0; j < runtimeNode.runtimePrimitives.length; j++) {
const runtimePrimitive = runtimeNode.runtimePrimitives[j];
runtimePrimitive.configurePipeline(frameState);
const primitivePipelineStages = runtimePrimitive.pipelineStages;
const primitiveRenderResources = new PrimitiveRenderResources_default(
nodeRenderResources,
runtimePrimitive
);
for (k = 0; k < primitivePipelineStages.length; k++) {
const primitivePipelineStage = primitivePipelineStages[k];
primitivePipelineStage.process(
primitiveRenderResources,
runtimePrimitive.primitive,
frameState
);
}
runtimePrimitive.boundingSphere = BoundingSphere_default.clone(
primitiveRenderResources.boundingSphere,
new BoundingSphere_default()
);
const primitivePositionMin = Matrix4_default.multiplyByPoint(
nodeTransform,
primitiveRenderResources.positionMin,
scratchPrimitivePositionMin
);
const primitivePositionMax = Matrix4_default.multiplyByPoint(
nodeTransform,
primitiveRenderResources.positionMax,
scratchPrimitivePositionMax
);
Cartesian3_default.minimumByComponent(
modelPositionMin,
primitivePositionMin,
modelPositionMin
);
Cartesian3_default.maximumByComponent(
modelPositionMax,
primitivePositionMax,
modelPositionMax
);
const drawCommand = buildDrawCommand_default(
primitiveRenderResources,
frameState
);
runtimePrimitive.drawCommand = drawCommand;
}
}
this._boundingSphere = BoundingSphere_default.fromCornerPoints(
modelPositionMin,
modelPositionMax,
new BoundingSphere_default()
);
this._boundingSphere = BoundingSphere_default.transformWithoutScale(
this._boundingSphere,
this._axisCorrectionMatrix,
this._boundingSphere
);
this._boundingSphere = BoundingSphere_default.transform(
this._boundingSphere,
this._components.transform,
this._boundingSphere
);
model._boundingSphere = BoundingSphere_default.transform(
this._boundingSphere,
model.modelMatrix,
model._boundingSphere
);
model._initialRadius = model._boundingSphere.radius;
model._boundingSphere.radius *= model._clampedScale;
};
ModelSceneGraph.prototype.configurePipeline = function(frameState) {
const modelPipelineStages = this.modelPipelineStages;
modelPipelineStages.length = 0;
const model = this._model;
if (defined_default(model.color)) {
modelPipelineStages.push(ModelColorPipelineStage_default);
}
if (defined_default(model.classificationType)) {
return;
}
if (model.imageBasedLighting.enabled) {
modelPipelineStages.push(ImageBasedLightingPipelineStage_default);
}
if (model.isClippingEnabled()) {
modelPipelineStages.push(ModelClippingPlanesPipelineStage_default);
}
if (model.hasSilhouette(frameState)) {
modelPipelineStages.push(ModelSilhouettePipelineStage_default);
}
if (defined_default(model.splitDirection) && model.splitDirection !== SplitDirection_default.NONE) {
modelPipelineStages.push(ModelSplitterPipelineStage_default);
}
if (ModelType_default.is3DTiles(model.type)) {
modelPipelineStages.push(TilesetPipelineStage_default);
}
};
ModelSceneGraph.prototype.update = function(frameState, updateForAnimations) {
let i, j, k;
for (i = 0; i < this._runtimeNodes.length; i++) {
const runtimeNode = this._runtimeNodes[i];
if (!defined_default(runtimeNode)) {
continue;
}
for (j = 0; j < runtimeNode.updateStages.length; j++) {
const nodeUpdateStage = runtimeNode.updateStages[j];
nodeUpdateStage.update(runtimeNode, this, frameState);
}
const disableAnimations = frameState.mode !== SceneMode_default.SCENE3D && this._model._projectTo2D;
if (updateForAnimations && !disableAnimations) {
this.updateJointMatrices();
}
for (j = 0; j < runtimeNode.runtimePrimitives.length; j++) {
const runtimePrimitive = runtimeNode.runtimePrimitives[j];
for (k = 0; k < runtimePrimitive.updateStages.length; k++) {
const stage = runtimePrimitive.updateStages[k];
stage.update(runtimePrimitive, this);
}
}
}
};
ModelSceneGraph.prototype.updateModelMatrix = function(modelMatrix, frameState) {
computeModelMatrix(this, modelMatrix);
if (frameState.mode !== SceneMode_default.SCENE3D) {
computeModelMatrix2D(this, frameState);
}
const rootNodes = this._rootNodes;
for (let i = 0; i < rootNodes.length; i++) {
const node = this._runtimeNodes[rootNodes[i]];
node._transformDirty = true;
}
};
ModelSceneGraph.prototype.updateJointMatrices = function() {
const skinnedNodes = this._skinnedNodes;
const length3 = skinnedNodes.length;
for (let i = 0; i < length3; i++) {
const nodeIndex = skinnedNodes[i];
const runtimeNode = this._runtimeNodes[nodeIndex];
runtimeNode.updateJointMatrices();
}
};
function traverseSceneGraph(sceneGraph, runtimeNode, visibleNodesOnly, callback, callbackOptions) {
if (visibleNodesOnly && !runtimeNode.show) {
return;
}
const childrenLength = runtimeNode.children.length;
for (let i = 0; i < childrenLength; i++) {
const childRuntimeNode = runtimeNode.getChild(i);
traverseSceneGraph(
sceneGraph,
childRuntimeNode,
visibleNodesOnly,
callback,
callbackOptions
);
}
const runtimePrimitives = runtimeNode.runtimePrimitives;
const runtimePrimitivesLength = runtimePrimitives.length;
for (let j = 0; j < runtimePrimitivesLength; j++) {
const runtimePrimitive = runtimePrimitives[j];
callback(runtimePrimitive, callbackOptions);
}
}
function forEachRuntimePrimitive(sceneGraph, visibleNodesOnly, callback, callbackOptions) {
const rootNodes = sceneGraph._rootNodes;
const rootNodesLength = rootNodes.length;
for (let i = 0; i < rootNodesLength; i++) {
const rootNodeIndex = rootNodes[i];
const runtimeNode = sceneGraph._runtimeNodes[rootNodeIndex];
traverseSceneGraph(
sceneGraph,
runtimeNode,
visibleNodesOnly,
callback,
callbackOptions
);
}
}
var scratchBackFaceCullingOptions = {
backFaceCulling: void 0
};
ModelSceneGraph.prototype.updateBackFaceCulling = function(backFaceCulling) {
const backFaceCullingOptions = scratchBackFaceCullingOptions;
backFaceCullingOptions.backFaceCulling = backFaceCulling;
forEachRuntimePrimitive(
this,
false,
updatePrimitiveBackFaceCulling,
backFaceCullingOptions
);
};
function updatePrimitiveBackFaceCulling(runtimePrimitive, options) {
const drawCommand = runtimePrimitive.drawCommand;
drawCommand.backFaceCulling = options.backFaceCulling;
}
var scratchShadowOptions = {
shadowMode: void 0
};
ModelSceneGraph.prototype.updateShadows = function(shadowMode) {
const shadowOptions = scratchShadowOptions;
shadowOptions.shadowMode = shadowMode;
forEachRuntimePrimitive(this, false, updatePrimitiveShadows, shadowOptions);
};
function updatePrimitiveShadows(runtimePrimitive, options) {
const drawCommand = runtimePrimitive.drawCommand;
drawCommand.shadows = options.shadowMode;
}
var scratchShowBoundingVolumeOptions = {
debugShowBoundingVolume: void 0
};
ModelSceneGraph.prototype.updateShowBoundingVolume = function(debugShowBoundingVolume2) {
const showBoundingVolumeOptions = scratchShowBoundingVolumeOptions;
showBoundingVolumeOptions.debugShowBoundingVolume = debugShowBoundingVolume2;
forEachRuntimePrimitive(
this,
false,
updatePrimitiveShowBoundingVolume,
showBoundingVolumeOptions
);
};
function updatePrimitiveShowBoundingVolume(runtimePrimitive, options) {
const drawCommand = runtimePrimitive.drawCommand;
drawCommand.debugShowBoundingVolume = options.debugShowBoundingVolume;
}
var scratchSilhouetteCommands = [];
var scratchPushDrawCommandOptions = {
frameState: void 0,
hasSilhouette: void 0
};
ModelSceneGraph.prototype.pushDrawCommands = function(frameState) {
const silhouetteCommands = scratchSilhouetteCommands;
silhouetteCommands.length = 0;
const pushDrawCommandOptions = scratchPushDrawCommandOptions;
pushDrawCommandOptions.hasSilhouette = this._model.hasSilhouette(frameState);
pushDrawCommandOptions.frameState = frameState;
forEachRuntimePrimitive(
this,
true,
pushPrimitiveDrawCommands,
pushDrawCommandOptions
);
frameState.commandList.push.apply(frameState.commandList, silhouetteCommands);
};
function pushPrimitiveDrawCommands(runtimePrimitive, options) {
const frameState = options.frameState;
const hasSilhouette = options.hasSilhouette;
const passes = frameState.passes;
const silhouetteCommands = scratchSilhouetteCommands;
const primitiveDrawCommand = runtimePrimitive.drawCommand;
primitiveDrawCommand.pushCommands(frameState, frameState.commandList);
if (hasSilhouette && !passes.pick) {
primitiveDrawCommand.pushSilhouetteCommands(frameState, silhouetteCommands);
}
}
ModelSceneGraph.prototype.setArticulationStage = function(articulationStageKey, value) {
const names = articulationStageKey.split(" ");
if (names.length !== 2) {
return;
}
const articulationName = names[0];
const stageName = names[1];
const runtimeArticulation = this._runtimeArticulations[articulationName];
if (defined_default(runtimeArticulation)) {
runtimeArticulation.setArticulationStage(stageName, value);
}
};
ModelSceneGraph.prototype.applyArticulations = function() {
const runtimeArticulations = this._runtimeArticulations;
for (const articulationName in runtimeArticulations) {
if (runtimeArticulations.hasOwnProperty(articulationName)) {
const articulation = runtimeArticulations[articulationName];
articulation.apply();
}
}
};
var ModelSceneGraph_default = ModelSceneGraph;
// packages/engine/Source/Scene/Model/ModelStatistics.js
function ModelStatistics() {
this.pointsLength = 0;
this.trianglesLength = 0;
this.geometryByteLength = 0;
this.texturesByteLength = 0;
this.propertyTablesByteLength = 0;
this._bufferIdSet = {};
this._textureIdSet = {};
this._batchTextureIdMap = new AssociativeArray_default();
}
Object.defineProperties(ModelStatistics.prototype, {
/**
* Total size of the batch textures used for picking and styling.
* Batch textures are created asynchronously, so this iterates
* over the textures to ensure their memory values are accurate.
*
* @memberof ModelStatistics.prototype
*
* @type {number}
* @readonly
*
* @private
*/
batchTexturesByteLength: {
get: function() {
const length3 = this._batchTextureIdMap.length;
const values = this._batchTextureIdMap.values;
let memory = 0;
for (let i = 0; i < length3; i++) {
memory += values[i].byteLength;
}
return memory;
}
}
});
ModelStatistics.prototype.clear = function() {
this.pointsLength = 0;
this.trianglesLength = 0;
this.geometryByteLength = 0;
this.texturesByteLength = 0;
this.propertyTablesByteLength = 0;
this._bufferIdSet = {};
this._textureIdSet = {};
this._batchTextureIdMap.removeAll();
};
ModelStatistics.prototype.addBuffer = function(buffer, hasCpuCopy) {
Check_default.typeOf.object("buffer", buffer);
Check_default.typeOf.bool("hasCpuCopy", hasCpuCopy);
if (!this._bufferIdSet.hasOwnProperty(buffer._id)) {
const copies = hasCpuCopy ? 2 : 1;
this.geometryByteLength += buffer.sizeInBytes * copies;
}
this._bufferIdSet[buffer._id] = true;
};
ModelStatistics.prototype.addTexture = function(texture) {
Check_default.typeOf.object("texture", texture);
if (!this._textureIdSet.hasOwnProperty(texture._id)) {
this.texturesByteLength += texture.sizeInBytes;
}
this._textureIdSet[texture._id] = true;
};
ModelStatistics.prototype.addBatchTexture = function(batchTexture) {
Check_default.typeOf.object("batchTexture", batchTexture);
if (!this._batchTextureIdMap.contains(batchTexture._id)) {
this._batchTextureIdMap.set(batchTexture._id, batchTexture);
}
};
var ModelStatistics_default = ModelStatistics;
// packages/engine/Source/Scene/Model/PntsLoader.js
var import_mersenne_twister2 = __toESM(require_mersenne_twister(), 1);
// packages/engine/Source/Scene/PntsParser.js
var PntsParser = {};
var sizeOfUint326 = Uint32Array.BYTES_PER_ELEMENT;
PntsParser.parse = function(arrayBuffer, byteOffset) {
byteOffset = defaultValue_default(byteOffset, 0);
Check_default.defined("arrayBuffer", arrayBuffer);
const uint8Array = new Uint8Array(arrayBuffer);
const view = new DataView(arrayBuffer);
byteOffset += sizeOfUint326;
const version2 = view.getUint32(byteOffset, true);
if (version2 !== 1) {
throw new RuntimeError_default(
`Only Point Cloud tile version 1 is supported. Version ${version2} is not.`
);
}
byteOffset += sizeOfUint326;
byteOffset += sizeOfUint326;
const featureTableJsonByteLength = view.getUint32(byteOffset, true);
if (featureTableJsonByteLength === 0) {
throw new RuntimeError_default(
"Feature table must have a byte length greater than zero"
);
}
byteOffset += sizeOfUint326;
const featureTableBinaryByteLength = view.getUint32(byteOffset, true);
byteOffset += sizeOfUint326;
const batchTableJsonByteLength = view.getUint32(byteOffset, true);
byteOffset += sizeOfUint326;
const batchTableBinaryByteLength = view.getUint32(byteOffset, true);
byteOffset += sizeOfUint326;
const featureTableJson = getJsonFromTypedArray_default(
uint8Array,
byteOffset,
featureTableJsonByteLength
);
byteOffset += featureTableJsonByteLength;
const featureTableBinary = new Uint8Array(
arrayBuffer,
byteOffset,
featureTableBinaryByteLength
);
byteOffset += featureTableBinaryByteLength;
let batchTableJson;
let batchTableBinary;
if (batchTableJsonByteLength > 0) {
batchTableJson = getJsonFromTypedArray_default(
uint8Array,
byteOffset,
batchTableJsonByteLength
);
byteOffset += batchTableJsonByteLength;
if (batchTableBinaryByteLength > 0) {
batchTableBinary = new Uint8Array(
arrayBuffer,
byteOffset,
batchTableBinaryByteLength
);
byteOffset += batchTableBinaryByteLength;
}
}
const featureTable = new Cesium3DTileFeatureTable_default(
featureTableJson,
featureTableBinary
);
const pointsLength = featureTable.getGlobalProperty("POINTS_LENGTH");
featureTable.featuresLength = pointsLength;
if (!defined_default(pointsLength)) {
throw new RuntimeError_default(
"Feature table global property: POINTS_LENGTH must be defined"
);
}
let rtcCenter = featureTable.getGlobalProperty(
"RTC_CENTER",
ComponentDatatype_default.FLOAT,
3
);
if (defined_default(rtcCenter)) {
rtcCenter = Cartesian3_default.unpack(rtcCenter);
}
const parsedContent = parseDracoProperties(featureTable, batchTableJson);
parsedContent.rtcCenter = rtcCenter;
parsedContent.pointsLength = pointsLength;
if (!parsedContent.hasPositions) {
const positions = parsePositions(featureTable);
parsedContent.positions = positions;
parsedContent.hasPositions = parsedContent.hasPositions || defined_default(positions);
}
if (!parsedContent.hasPositions) {
throw new RuntimeError_default(
"Either POSITION or POSITION_QUANTIZED must be defined."
);
}
if (!parsedContent.hasNormals) {
const normals = parseNormals(featureTable);
parsedContent.normals = normals;
parsedContent.hasNormals = parsedContent.hasNormals || defined_default(normals);
}
if (!parsedContent.hasColors) {
const colors = parseColors(featureTable);
parsedContent.colors = colors;
parsedContent.hasColors = parsedContent.hasColors || defined_default(colors);
parsedContent.hasConstantColor = defined_default(parsedContent.constantColor);
parsedContent.isTranslucent = defined_default(colors) && colors.isTranslucent;
}
if (!parsedContent.hasBatchIds) {
const batchIds = parseBatchIds(featureTable);
parsedContent.batchIds = batchIds;
parsedContent.hasBatchIds = parsedContent.hasBatchIds || defined_default(batchIds);
}
if (parsedContent.hasBatchIds) {
const batchLength = featureTable.getGlobalProperty("BATCH_LENGTH");
if (!defined_default(batchLength)) {
throw new RuntimeError_default(
"Global property: BATCH_LENGTH must be defined when BATCH_ID is defined."
);
}
parsedContent.batchLength = batchLength;
}
if (defined_default(batchTableBinary)) {
batchTableBinary = new Uint8Array(batchTableBinary);
parsedContent.batchTableJson = batchTableJson;
parsedContent.batchTableBinary = batchTableBinary;
}
return parsedContent;
};
function parseDracoProperties(featureTable, batchTableJson) {
const featureTableJson = featureTable.json;
let dracoBuffer;
let dracoFeatureTableProperties;
let dracoBatchTableProperties;
const featureTableDraco = defined_default(featureTableJson.extensions) ? featureTableJson.extensions["3DTILES_draco_point_compression"] : void 0;
const batchTableDraco = defined_default(batchTableJson) && defined_default(batchTableJson.extensions) ? batchTableJson.extensions["3DTILES_draco_point_compression"] : void 0;
if (defined_default(batchTableDraco)) {
dracoBatchTableProperties = batchTableDraco.properties;
}
let hasPositions;
let hasColors;
let hasNormals;
let hasBatchIds;
let isTranslucent;
if (defined_default(featureTableDraco)) {
dracoFeatureTableProperties = featureTableDraco.properties;
const dracoByteOffset = featureTableDraco.byteOffset;
const dracoByteLength = featureTableDraco.byteLength;
if (!defined_default(dracoFeatureTableProperties) || !defined_default(dracoByteOffset) || !defined_default(dracoByteLength)) {
throw new RuntimeError_default(
"Draco properties, byteOffset, and byteLength must be defined"
);
}
dracoBuffer = featureTable.buffer.slice(
dracoByteOffset,
dracoByteOffset + dracoByteLength
);
hasPositions = defined_default(dracoFeatureTableProperties.POSITION);
hasColors = defined_default(dracoFeatureTableProperties.RGB) || defined_default(dracoFeatureTableProperties.RGBA);
hasNormals = defined_default(dracoFeatureTableProperties.NORMAL);
hasBatchIds = defined_default(dracoFeatureTableProperties.BATCH_ID);
isTranslucent = defined_default(dracoFeatureTableProperties.RGBA);
}
let draco;
if (defined_default(dracoBuffer)) {
draco = {
buffer: dracoBuffer,
featureTableProperties: dracoFeatureTableProperties,
batchTableProperties: dracoBatchTableProperties,
properties: combine_default(
dracoFeatureTableProperties,
dracoBatchTableProperties
),
dequantizeInShader: true
};
}
return {
draco,
hasPositions,
hasColors,
isTranslucent,
hasNormals,
hasBatchIds
};
}
function parsePositions(featureTable) {
const featureTableJson = featureTable.json;
let positions;
if (defined_default(featureTableJson.POSITION)) {
positions = featureTable.getPropertyArray(
"POSITION",
ComponentDatatype_default.FLOAT,
3
);
return {
name: VertexAttributeSemantic_default.POSITION,
semantic: VertexAttributeSemantic_default.POSITION,
typedArray: positions,
isQuantized: false,
componentDatatype: ComponentDatatype_default.FLOAT,
type: AttributeType_default.VEC3
};
} else if (defined_default(featureTableJson.POSITION_QUANTIZED)) {
positions = featureTable.getPropertyArray(
"POSITION_QUANTIZED",
ComponentDatatype_default.UNSIGNED_SHORT,
3
);
const quantizedVolumeScale = featureTable.getGlobalProperty(
"QUANTIZED_VOLUME_SCALE",
ComponentDatatype_default.FLOAT,
3
);
if (!defined_default(quantizedVolumeScale)) {
throw new RuntimeError_default(
"Global property: QUANTIZED_VOLUME_SCALE must be defined for quantized positions."
);
}
const quantizedRange = (1 << 16) - 1;
const quantizedVolumeOffset = featureTable.getGlobalProperty(
"QUANTIZED_VOLUME_OFFSET",
ComponentDatatype_default.FLOAT,
3
);
if (!defined_default(quantizedVolumeOffset)) {
throw new RuntimeError_default(
"Global property: QUANTIZED_VOLUME_OFFSET must be defined for quantized positions."
);
}
return {
name: VertexAttributeSemantic_default.POSITION,
semantic: VertexAttributeSemantic_default.POSITION,
typedArray: positions,
isQuantized: true,
componentDatatype: ComponentDatatype_default.FLOAT,
type: AttributeType_default.VEC3,
quantizedRange,
quantizedVolumeOffset: Cartesian3_default.unpack(quantizedVolumeOffset),
quantizedVolumeScale: Cartesian3_default.unpack(quantizedVolumeScale),
quantizedComponentDatatype: ComponentDatatype_default.UNSIGNED_SHORT,
quantizedType: AttributeType_default.VEC3
};
}
}
function parseColors(featureTable) {
const featureTableJson = featureTable.json;
let colors;
if (defined_default(featureTableJson.RGBA)) {
colors = featureTable.getPropertyArray(
"RGBA",
ComponentDatatype_default.UNSIGNED_BYTE,
4
);
return {
name: VertexAttributeSemantic_default.COLOR,
semantic: VertexAttributeSemantic_default.COLOR,
setIndex: 0,
typedArray: colors,
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
type: AttributeType_default.VEC4,
normalized: true,
isRGB565: false,
isTranslucent: true
};
} else if (defined_default(featureTableJson.RGB)) {
colors = featureTable.getPropertyArray(
"RGB",
ComponentDatatype_default.UNSIGNED_BYTE,
3
);
return {
name: "COLOR",
semantic: VertexAttributeSemantic_default.COLOR,
setIndex: 0,
typedArray: colors,
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
type: AttributeType_default.VEC3,
normalized: true,
isRGB565: false,
isTranslucent: false
};
} else if (defined_default(featureTableJson.RGB565)) {
colors = featureTable.getPropertyArray(
"RGB565",
ComponentDatatype_default.UNSIGNED_SHORT,
1
);
return {
name: "COLOR",
semantic: VertexAttributeSemantic_default.COLOR,
setIndex: 0,
typedArray: colors,
// These settings are for the Model implementation
// which decodes on the CPU and uploads a VEC3 of float colors.
// PointCloud does the decoding on the GPU so uploads a
// UNSIGNED_SHORT instead.
componentDatatype: ComponentDatatype_default.FLOAT,
type: AttributeType_default.VEC3,
normalized: false,
isRGB565: true,
isTranslucent: false
};
} else if (defined_default(featureTableJson.CONSTANT_RGBA)) {
const constantRGBA = featureTable.getGlobalProperty(
"CONSTANT_RGBA",
ComponentDatatype_default.UNSIGNED_BYTE,
4
);
const alpha = constantRGBA[3];
const constantColor = Color_default.fromBytes(
constantRGBA[0],
constantRGBA[1],
constantRGBA[2],
alpha
);
const isTranslucent = alpha < 255;
return {
name: VertexAttributeSemantic_default.COLOR,
semantic: VertexAttributeSemantic_default.COLOR,
setIndex: 0,
constantColor,
componentDatatype: ComponentDatatype_default.FLOAT,
type: AttributeType_default.VEC4,
isQuantized: false,
isTranslucent
};
}
return void 0;
}
function parseNormals(featureTable) {
const featureTableJson = featureTable.json;
let normals;
if (defined_default(featureTableJson.NORMAL)) {
normals = featureTable.getPropertyArray(
"NORMAL",
ComponentDatatype_default.FLOAT,
3
);
return {
name: VertexAttributeSemantic_default.NORMAL,
semantic: VertexAttributeSemantic_default.NORMAL,
typedArray: normals,
octEncoded: false,
octEncodedZXY: false,
componentDatatype: ComponentDatatype_default.FLOAT,
type: AttributeType_default.VEC3
};
} else if (defined_default(featureTableJson.NORMAL_OCT16P)) {
normals = featureTable.getPropertyArray(
"NORMAL_OCT16P",
ComponentDatatype_default.UNSIGNED_BYTE,
2
);
const quantizationBits = 8;
return {
name: VertexAttributeSemantic_default.NORMAL,
semantic: VertexAttributeSemantic_default.NORMAL,
typedArray: normals,
octEncoded: true,
octEncodedZXY: false,
quantizedRange: (1 << quantizationBits) - 1,
quantizedType: AttributeType_default.VEC2,
quantizedComponentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentDatatype: ComponentDatatype_default.FLOAT,
type: AttributeType_default.VEC3
};
}
return void 0;
}
function parseBatchIds(featureTable) {
const featureTableJson = featureTable.json;
if (defined_default(featureTableJson.BATCH_ID)) {
const batchIds = featureTable.getPropertyArray(
"BATCH_ID",
ComponentDatatype_default.UNSIGNED_SHORT,
1
);
return {
name: VertexAttributeSemantic_default.FEATURE_ID,
semantic: VertexAttributeSemantic_default.FEATURE_ID,
setIndex: 0,
typedArray: batchIds,
componentDatatype: ComponentDatatype_default.fromTypedArray(batchIds),
type: AttributeType_default.SCALAR
};
}
return void 0;
}
var PntsParser_default = PntsParser;
// packages/engine/Source/Scene/Model/PntsLoader.js
var Components3 = ModelComponents_default.Components;
var Scene3 = ModelComponents_default.Scene;
var Node5 = ModelComponents_default.Node;
var Primitive4 = ModelComponents_default.Primitive;
var Attribute4 = ModelComponents_default.Attribute;
var Quantization2 = ModelComponents_default.Quantization;
var FeatureIdAttribute5 = ModelComponents_default.FeatureIdAttribute;
var Material5 = ModelComponents_default.Material;
var MetallicRoughness4 = ModelComponents_default.MetallicRoughness;
function PntsLoader(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const arrayBuffer = options.arrayBuffer;
const byteOffset = defaultValue_default(options.byteOffset, 0);
Check_default.typeOf.object("options.arrayBuffer", arrayBuffer);
this._arrayBuffer = arrayBuffer;
this._byteOffset = byteOffset;
this._loadAttributesFor2D = defaultValue_default(options.loadAttributesFor2D, false);
this._parsedContent = void 0;
this._decodePromise = void 0;
this._decodedAttributes = void 0;
this._promise = void 0;
this._error = void 0;
this._state = ResourceLoaderState_default.UNLOADED;
this._buffers = [];
this._components = void 0;
this._transform = Matrix4_default.IDENTITY;
}
if (defined_default(Object.create)) {
PntsLoader.prototype = Object.create(ResourceLoader_default.prototype);
PntsLoader.prototype.constructor = PntsLoader;
}
Object.defineProperties(PntsLoader.prototype, {
/**
* The cache key of the resource
*
* @memberof PntsLoader.prototype
*
* @type {string}
* @readonly
* @private
*/
cacheKey: {
get: function() {
return void 0;
}
},
/**
* The loaded components.
*
* @memberof PntsLoader.prototype
*
* @type {ModelComponents.Components}
* @readonly
* @private
*/
components: {
get: function() {
return this._components;
}
},
/**
* A world-space transform to apply to the primitives.
* See {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification/TileFormats/PointCloud#global-semantics}
*
* @memberof PntsLoader.prototype
*
* @type {Matrix4}
* @readonly
* @private
*/
transform: {
get: function() {
return this._transform;
}
}
});
PntsLoader.prototype.load = function() {
if (defined_default(this._promise)) {
return this._promise;
}
this._parsedContent = PntsParser_default.parse(this._arrayBuffer, this._byteOffset);
this._state = ResourceLoaderState_default.PROCESSING;
this._promise = Promise.resolve(this);
};
PntsLoader.prototype.process = function(frameState) {
if (defined_default(this._error)) {
const error = this._error;
this._error = void 0;
throw error;
}
if (this._state === ResourceLoaderState_default.READY) {
return true;
}
if (this._state === ResourceLoaderState_default.PROCESSING) {
if (defined_default(this._decodePromise)) {
return false;
}
this._decodePromise = decodeDraco(this, frameState.context);
}
return false;
};
function decodeDraco(loader, context) {
const parsedContent = loader._parsedContent;
const draco = parsedContent.draco;
let decodePromise;
if (!defined_default(draco)) {
decodePromise = Promise.resolve();
} else {
decodePromise = DracoLoader_default.decodePointCloud(draco, context);
}
if (!defined_default(decodePromise)) {
return;
}
loader._decodePromise = decodePromise;
return decodePromise.then(function(decodeDracoResult) {
if (loader.isDestroyed()) {
return;
}
if (defined_default(decodeDracoResult)) {
processDracoAttributes(loader, draco, decodeDracoResult);
}
makeComponents(loader, context);
loader._state = ResourceLoaderState_default.READY;
return loader;
}).catch(function(error) {
loader.unload();
loader._state = ResourceLoaderState_default.FAILED;
const errorMessage = "Failed to load Draco pnts";
loader._error = loader.getError(errorMessage, error);
});
}
function processDracoAttributes(loader, draco, result) {
loader._state = ResourceLoaderState_default.READY;
const parsedContent = loader._parsedContent;
let attribute;
if (defined_default(result.POSITION)) {
attribute = {
name: "POSITION",
semantic: VertexAttributeSemantic_default.POSITION,
typedArray: result.POSITION.array,
componentDatatype: ComponentDatatype_default.FLOAT,
type: AttributeType_default.VEC3,
isQuantized: false
};
if (defined_default(result.POSITION.data.quantization)) {
const quantization = result.POSITION.data.quantization;
const range = quantization.range;
const quantizedVolumeScale = Cartesian3_default.fromElements(range, range, range);
const quantizedVolumeOffset = Cartesian3_default.unpack(quantization.minValues);
const quantizedRange = (1 << quantization.quantizationBits) - 1;
attribute.isQuantized = true;
attribute.quantizedRange = quantizedRange;
attribute.quantizedVolumeOffset = quantizedVolumeOffset;
attribute.quantizedVolumeScale = quantizedVolumeScale;
attribute.quantizedComponentDatatype = quantizedRange <= 255 ? ComponentDatatype_default.UNSIGNED_BYTE : ComponentDatatype_default.UNSIGNED_SHORT;
attribute.quantizedType = AttributeType_default.VEC3;
}
parsedContent.positions = attribute;
}
if (defined_default(result.NORMAL)) {
attribute = {
name: "NORMAL",
semantic: VertexAttributeSemantic_default.NORMAL,
typedArray: result.NORMAL.array,
componentDatatype: ComponentDatatype_default.FLOAT,
type: AttributeType_default.VEC3,
isQuantized: false,
octEncoded: false,
octEncodedZXY: false
};
if (defined_default(result.NORMAL.data.quantization)) {
const octEncodedRange = (1 << result.NORMAL.data.quantization.quantizationBits) - 1;
attribute.quantizedRange = octEncodedRange;
attribute.octEncoded = true;
attribute.octEncodedZXY = true;
attribute.quantizedComponentDatatype = ComponentDatatype_default.UNSIGNED_BYTE;
attribute.quantizedType = AttributeType_default.VEC2;
}
parsedContent.normals = attribute;
}
if (defined_default(result.RGBA)) {
parsedContent.colors = {
name: "COLOR",
semantic: VertexAttributeSemantic_default.COLOR,
setIndex: 0,
typedArray: result.RGBA.array,
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
type: AttributeType_default.VEC4,
normalized: true,
isTranslucent: true
};
} else if (defined_default(result.RGB)) {
parsedContent.colors = {
name: "COLOR",
semantic: VertexAttributeSemantic_default.COLOR,
setIndex: 0,
typedArray: result.RGB.array,
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
type: AttributeType_default.VEC3,
normalized: true,
isTranslucent: false
};
}
if (defined_default(result.BATCH_ID)) {
const batchIds = result.BATCH_ID.array;
parsedContent.batchIds = {
name: "_FEATURE_ID",
semantic: VertexAttributeSemantic_default.FEATURE_ID,
setIndex: 0,
typedArray: batchIds,
componentDatatype: ComponentDatatype_default.fromTypedArray(batchIds),
type: AttributeType_default.SCALAR
};
}
let batchTableJson = parsedContent.batchTableJson;
const batchTableProperties = draco.batchTableProperties;
for (const name in batchTableProperties) {
if (batchTableProperties.hasOwnProperty(name)) {
const property = result[name];
if (!defined_default(batchTableJson)) {
batchTableJson = {};
}
parsedContent.hasDracoBatchTable = true;
const data = property.data;
batchTableJson[name] = {
byteOffset: data.byteOffset,
// Draco returns the results like glTF values, but here
// we want to transcode to a batch table. It's redundant
// but necessary to use parseBatchTable()
type: transcodeAttributeType(data.componentsPerAttribute),
componentType: transcodeComponentType2(data.componentDatatype),
// Each property is stored as a separate typed array, so
// store it here. parseBatchTable() will check for this
// instead of the entire binary body.
typedArray: property.array
};
}
}
parsedContent.batchTableJson = batchTableJson;
}
function transcodeAttributeType(componentsPerAttribute) {
switch (componentsPerAttribute) {
case 1:
return "SCALAR";
case 2:
return "VEC2";
case 3:
return "VEC3";
case 4:
return "VEC4";
default:
throw new DeveloperError_default(
"componentsPerAttribute must be a number from 1-4"
);
}
}
function transcodeComponentType2(value) {
switch (value) {
case WebGLConstants_default.BYTE:
return "BYTE";
case WebGLConstants_default.UNSIGNED_BYTE:
return "UNSIGNED_BYTE";
case WebGLConstants_default.SHORT:
return "SHORT";
case WebGLConstants_default.UNSIGNED_SHORT:
return "UNSIGNED_SHORT";
case WebGLConstants_default.INT:
return "INT";
case WebGLConstants_default.UNSIGNED_INT:
return "UNSIGNED_INT";
case WebGLConstants_default.DOUBLE:
return "DOUBLE";
case WebGLConstants_default.FLOAT:
return "FLOAT";
default:
throw new DeveloperError_default("value is not a valid WebGL constant");
}
}
function makeAttribute(loader, attributeInfo, context) {
let typedArray = attributeInfo.typedArray;
let quantization;
if (attributeInfo.octEncoded) {
quantization = new Quantization2();
quantization.octEncoded = attributeInfo.octEncoded;
quantization.octEncodedZXY = attributeInfo.octEncodedZXY;
quantization.normalizationRange = attributeInfo.quantizedRange;
quantization.type = attributeInfo.quantizedType;
quantization.componentDatatype = attributeInfo.quantizedComponentDatatype;
}
if (attributeInfo.isQuantized) {
quantization = new Quantization2();
const normalizationRange = attributeInfo.quantizedRange;
quantization.normalizationRange = normalizationRange;
quantization.quantizedVolumeOffset = Cartesian3_default.ZERO;
const quantizedVolumeDimensions = attributeInfo.quantizedVolumeScale;
quantization.quantizedVolumeDimensions = quantizedVolumeDimensions;
quantization.quantizedVolumeStepSize = Cartesian3_default.divideByScalar(
quantizedVolumeDimensions,
normalizationRange,
new Cartesian3_default()
);
quantization.componentDatatype = attributeInfo.quantizedComponentDatatype;
quantization.type = attributeInfo.quantizedType;
}
const attribute = new Attribute4();
attribute.name = attributeInfo.name;
attribute.semantic = attributeInfo.semantic;
attribute.setIndex = attributeInfo.setIndex;
attribute.componentDatatype = attributeInfo.componentDatatype;
attribute.type = attributeInfo.type;
attribute.normalized = defaultValue_default(attributeInfo.normalized, false);
attribute.min = attributeInfo.min;
attribute.max = attributeInfo.max;
attribute.quantization = quantization;
if (attributeInfo.isRGB565) {
typedArray = AttributeCompression_default.decodeRGB565(typedArray);
}
if (defined_default(attributeInfo.constantColor)) {
const packedColor = new Array(4);
attribute.constant = Color_default.pack(attributeInfo.constantColor, packedColor);
} else {
const buffer = Buffer_default.createVertexBuffer({
typedArray,
context,
usage: BufferUsage_default.STATIC_DRAW
});
buffer.vertexArrayDestroyable = false;
loader._buffers.push(buffer);
attribute.buffer = buffer;
}
const loadAttributesFor2D = loader._loadAttributesFor2D;
if (attribute.semantic === VertexAttributeSemantic_default.POSITION && loadAttributesFor2D) {
attribute.typedArray = typedArray;
}
return attribute;
}
var randomNumberGenerator2;
var randomValues;
function getRandomValues(samplesLength) {
if (!defined_default(randomValues)) {
randomNumberGenerator2 = new import_mersenne_twister2.default(0);
randomValues = new Array(samplesLength);
for (let i = 0; i < samplesLength; ++i) {
randomValues[i] = randomNumberGenerator2.random();
}
}
return randomValues;
}
var scratchMin3 = new Cartesian3_default();
var scratchMax3 = new Cartesian3_default();
var scratchPosition3 = new Cartesian3_default();
function computeApproximateExtrema(positions) {
const positionsArray = positions.typedArray;
const maximumSamplesLength = 20;
const pointsLength = positionsArray.length / 3;
const samplesLength = Math.min(pointsLength, maximumSamplesLength);
const randomValues3 = getRandomValues(maximumSamplesLength);
const maxValue = Number.MAX_VALUE;
const minValue = -Number.MAX_VALUE;
let min3 = Cartesian3_default.fromElements(maxValue, maxValue, maxValue, scratchMin3);
let max3 = Cartesian3_default.fromElements(minValue, minValue, minValue, scratchMax3);
let i;
let index;
let position;
if (positions.isQuantized) {
min3 = Cartesian3_default.ZERO;
max3 = positions.quantizedVolumeScale;
} else {
for (i = 0; i < samplesLength; ++i) {
index = Math.floor(randomValues3[i] * pointsLength);
position = Cartesian3_default.unpack(positionsArray, index * 3, scratchPosition3);
Cartesian3_default.minimumByComponent(min3, position, min3);
Cartesian3_default.maximumByComponent(max3, position, max3);
}
}
positions.min = Cartesian3_default.clone(min3);
positions.max = Cartesian3_default.clone(max3);
}
var defaultColorAttribute = {
name: VertexAttributeSemantic_default.COLOR,
semantic: VertexAttributeSemantic_default.COLOR,
setIndex: 0,
constantColor: Color_default.DARKGRAY,
componentDatatype: ComponentDatatype_default.FLOAT,
type: AttributeType_default.VEC4,
isQuantized: false,
isTranslucent: false
};
function makeAttributes(loader, parsedContent, context) {
const attributes = [];
let attribute;
const positions = parsedContent.positions;
if (defined_default(positions)) {
computeApproximateExtrema(positions);
attribute = makeAttribute(loader, positions, context);
attribute.count = parsedContent.pointsLength;
attributes.push(attribute);
}
if (defined_default(parsedContent.normals)) {
attribute = makeAttribute(loader, parsedContent.normals, context);
attributes.push(attribute);
}
if (defined_default(parsedContent.colors)) {
attribute = makeAttribute(loader, parsedContent.colors, context);
attributes.push(attribute);
} else {
attribute = makeAttribute(loader, defaultColorAttribute, context);
attributes.push(attribute);
}
if (defined_default(parsedContent.batchIds)) {
attribute = makeAttribute(loader, parsedContent.batchIds, context);
attributes.push(attribute);
}
return attributes;
}
function makeStructuralMetadata(parsedContent, customAttributeOutput) {
const batchLength = parsedContent.batchLength;
const pointsLength = parsedContent.pointsLength;
const batchTableBinary = parsedContent.batchTableBinary;
const parseAsPropertyAttributes = !defined_default(parsedContent.batchIds);
if (defined_default(batchTableBinary) || parsedContent.hasDracoBatchTable) {
const count = defaultValue_default(batchLength, pointsLength);
return parseBatchTable_default({
count,
batchTable: parsedContent.batchTableJson,
binaryBody: batchTableBinary,
parseAsPropertyAttributes,
customAttributeOutput
});
}
return new StructuralMetadata_default({
schema: {},
propertyTables: []
});
}
function makeComponents(loader, context) {
const parsedContent = loader._parsedContent;
const metallicRoughness = new MetallicRoughness4();
metallicRoughness.metallicFactor = 0;
metallicRoughness.roughnessFactor = 0.9;
const material = new Material5();
material.metallicRoughness = metallicRoughness;
const colors = parsedContent.colors;
if (defined_default(colors) && colors.isTranslucent) {
material.alphaMode = AlphaMode_default.BLEND;
}
const isUnlit = !defined_default(parsedContent.normals);
material.unlit = isUnlit;
const primitive = new Primitive4();
primitive.attributes = makeAttributes(loader, parsedContent, context);
primitive.primitiveType = PrimitiveType_default.POINTS;
primitive.material = material;
if (defined_default(parsedContent.batchIds)) {
const featureIdAttribute = new FeatureIdAttribute5();
featureIdAttribute.propertyTableId = 0;
featureIdAttribute.setIndex = 0;
featureIdAttribute.positionalLabel = "featureId_0";
primitive.featureIds.push(featureIdAttribute);
}
const node = new Node5();
node.index = 0;
node.primitives = [primitive];
const scene = new Scene3();
scene.nodes = [node];
scene.upAxis = Axis_default.Z;
scene.forwardAxis = Axis_default.X;
const components = new Components3();
components.scene = scene;
components.nodes = [node];
const customAttributeOutput = [];
components.structuralMetadata = makeStructuralMetadata(
parsedContent,
customAttributeOutput
);
if (customAttributeOutput.length > 0) {
addPropertyAttributesToPrimitive(
loader,
primitive,
customAttributeOutput,
context
);
}
if (defined_default(parsedContent.rtcCenter)) {
components.transform = Matrix4_default.multiplyByTranslation(
components.transform,
parsedContent.rtcCenter,
components.transform
);
}
const positions = parsedContent.positions;
if (defined_default(positions) && positions.isQuantized) {
components.transform = Matrix4_default.multiplyByTranslation(
components.transform,
positions.quantizedVolumeOffset,
components.transform
);
}
loader._components = components;
loader._parsedContent = void 0;
loader._arrayBuffer = void 0;
}
function addPropertyAttributesToPrimitive(loader, primitive, customAttributes, context) {
const attributes = primitive.attributes;
const length3 = customAttributes.length;
for (let i = 0; i < length3; i++) {
const customAttribute = customAttributes[i];
const buffer = Buffer_default.createVertexBuffer({
typedArray: customAttribute.typedArray,
context,
usage: BufferUsage_default.STATIC_DRAW
});
buffer.vertexArrayDestroyable = false;
loader._buffers.push(buffer);
customAttribute.buffer = buffer;
customAttribute.typedArray = void 0;
attributes.push(customAttribute);
}
primitive.propertyAttributeIds = [0];
}
PntsLoader.prototype.unload = function() {
const buffers = this._buffers;
for (let i = 0; i < buffers.length; i++) {
buffers[i].destroy();
}
buffers.length = 0;
this._components = void 0;
this._parsedContent = void 0;
this._arrayBuffer = void 0;
};
var PntsLoader_default = PntsLoader;
// packages/engine/Source/Scene/Model/Model.js
function Model(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
Check_default.typeOf.object("options.loader", options.loader);
Check_default.typeOf.object("options.resource", options.resource);
this._loader = options.loader;
this._resource = options.resource;
this.type = defaultValue_default(options.type, ModelType_default.GLTF);
this.modelMatrix = Matrix4_default.clone(
defaultValue_default(options.modelMatrix, Matrix4_default.IDENTITY)
);
this._modelMatrix = Matrix4_default.clone(this.modelMatrix);
this._scale = defaultValue_default(options.scale, 1);
this._minimumPixelSize = defaultValue_default(options.minimumPixelSize, 0);
this._maximumScale = options.maximumScale;
this._clampedScale = defined_default(this._maximumScale) ? Math.min(this._scale, this._maximumScale) : this._scale;
this._computedScale = this._clampedScale;
this._updateModelMatrix = false;
this.referenceMatrix = void 0;
this._iblReferenceFrameMatrix = Matrix3_default.clone(Matrix3_default.IDENTITY);
this._resourcesLoaded = false;
this._drawCommandsBuilt = false;
this._ready = false;
this._customShader = options.customShader;
this._content = options.content;
this._texturesLoaded = false;
this._defaultTexture = void 0;
this._activeAnimations = new ModelAnimationCollection_default(this);
this._clampAnimations = defaultValue_default(options.clampAnimations, true);
this._userAnimationDirty = false;
this._id = options.id;
this._idDirty = false;
this._color = Color_default.clone(options.color);
this._colorBlendMode = defaultValue_default(
options.colorBlendMode,
ColorBlendMode_default.HIGHLIGHT
);
this._colorBlendAmount = defaultValue_default(options.colorBlendAmount, 0.5);
const silhouetteColor = defaultValue_default(options.silhouetteColor, Color_default.RED);
this._silhouetteColor = Color_default.clone(silhouetteColor);
this._silhouetteSize = defaultValue_default(options.silhouetteSize, 0);
this._silhouetteDirty = false;
this._silhouetteId = void 0;
this._cull = defaultValue_default(options.cull, true);
this._opaquePass = defaultValue_default(options.opaquePass, Pass_default.OPAQUE);
this._allowPicking = defaultValue_default(options.allowPicking, true);
this._show = defaultValue_default(options.show, true);
this._style = void 0;
this._styleDirty = false;
this._styleCommandsNeeded = void 0;
let featureIdLabel = defaultValue_default(options.featureIdLabel, "featureId_0");
if (typeof featureIdLabel === "number") {
featureIdLabel = `featureId_${featureIdLabel}`;
}
this._featureIdLabel = featureIdLabel;
let instanceFeatureIdLabel = defaultValue_default(
options.instanceFeatureIdLabel,
"instanceFeatureId_0"
);
if (typeof instanceFeatureIdLabel === "number") {
instanceFeatureIdLabel = `instanceFeatureId_${instanceFeatureIdLabel}`;
}
this._instanceFeatureIdLabel = instanceFeatureIdLabel;
this._featureTables = [];
this._featureTableId = void 0;
this._featureTableIdDirty = true;
this._pipelineResources = [];
this._modelResources = [];
this._pickIds = [];
this._boundingSphere = new BoundingSphere_default();
this._initialRadius = void 0;
this._heightReference = defaultValue_default(
options.heightReference,
HeightReference_default.NONE
);
this._heightDirty = this._heightReference !== HeightReference_default.NONE;
this._removeUpdateHeightCallback = void 0;
this._clampedModelMatrix = void 0;
const scene = options.scene;
if (defined_default(scene) && defined_default(scene.terrainProviderChanged)) {
this._terrainProviderChangedCallback = scene.terrainProviderChanged.addEventListener(
function() {
this._heightDirty = true;
},
this
);
}
this._scene = scene;
this._distanceDisplayCondition = options.distanceDisplayCondition;
const pointCloudShading = new PointCloudShading_default(options.pointCloudShading);
this._pointCloudShading = pointCloudShading;
this._attenuation = pointCloudShading.attenuation;
this._pointCloudBackFaceCulling = pointCloudShading.backFaceCulling;
const clippingPlanes = options.clippingPlanes;
if (defined_default(clippingPlanes) && clippingPlanes.owner === void 0) {
ClippingPlaneCollection_default.setOwner(clippingPlanes, this, "_clippingPlanes");
} else {
this._clippingPlanes = clippingPlanes;
}
this._clippingPlanesState = 0;
this._clippingPlanesMatrix = Matrix4_default.clone(Matrix4_default.IDENTITY);
this._lightColor = Cartesian3_default.clone(options.lightColor);
this._imageBasedLighting = defined_default(options.imageBasedLighting) ? options.imageBasedLighting : new ImageBasedLighting_default();
this._shouldDestroyImageBasedLighting = !defined_default(options.imageBasedLighting);
this._backFaceCulling = defaultValue_default(options.backFaceCulling, true);
this._backFaceCullingDirty = false;
this._shadows = defaultValue_default(options.shadows, ShadowMode_default.ENABLED);
this._shadowsDirty = false;
this._debugShowBoundingVolumeDirty = false;
this._debugShowBoundingVolume = defaultValue_default(
options.debugShowBoundingVolume,
false
);
this._enableDebugWireframe = defaultValue_default(
options.enableDebugWireframe,
false
);
this._enableShowOutline = defaultValue_default(options.enableShowOutline, true);
this._debugWireframe = defaultValue_default(options.debugWireframe, false);
if (this._debugWireframe === true && this._enableDebugWireframe === false && this.type === ModelType_default.GLTF) {
oneTimeWarning_default(
"model-debug-wireframe-ignored",
"enableDebugWireframe must be set to true in Model.fromGltf, otherwise debugWireframe will be ignored."
);
}
let credit = options.credit;
if (typeof credit === "string") {
credit = new Credit_default(credit);
}
this._credit = credit;
this._resourceCredits = [];
this._gltfCredits = [];
this._showCreditsOnScreen = defaultValue_default(options.showCreditsOnScreen, false);
this._showCreditsOnScreenDirty = true;
this._splitDirection = defaultValue_default(
options.splitDirection,
SplitDirection_default.NONE
);
this._enableShowOutline = defaultValue_default(options.enableShowOutline, true);
this.showOutline = defaultValue_default(options.showOutline, true);
this.outlineColor = defaultValue_default(options.outlineColor, Color_default.BLACK);
this._classificationType = options.classificationType;
this._statistics = new ModelStatistics_default();
this._sceneMode = void 0;
this._projectTo2D = defaultValue_default(options.projectTo2D, false);
this._skipLevelOfDetail = false;
this._ignoreCommands = defaultValue_default(options.ignoreCommands, false);
this._texturesLoadedPromise = void 0;
this._completeLoad = void 0;
this._rejectLoad = void 0;
this._completeTexturesLoad = void 0;
this._rejectTexturesLoad = void 0;
if (!defined_default(this._loader._promise)) {
this._readyPromise = new Promise((resolve2, reject) => {
this._completeLoad = () => {
resolve2(this);
return false;
};
this._rejectLoad = (error) => {
reject(error);
return false;
};
});
if (this._loader instanceof PntsLoader_default) {
this._texturesLoadedPromise = Promise.resolve(this);
} else {
this._texturesLoadedPromise = new Promise((resolve2, reject) => {
this._completeTexturesLoad = () => {
resolve2(this);
return false;
};
this._rejectTexturesLoad = (error) => {
reject(error);
return false;
};
});
}
this._loader.load().catch((error) => {
if (this.isDestroyed() || !defined_default(this._loader) || this._loader.isDestroyed()) {
return;
}
this._rejectLoad = this._rejectLoad(
ModelUtility_default.getError("model", this._resource, error)
);
});
} else {
this._readyPromise = Promise.resolve(this);
this._texturesLoadedPromise = Promise.resolve(this);
}
this._errorEvent = new Event_default();
this._readyEvent = new Event_default();
this._texturesReadyEvent = new Event_default();
this._sceneGraph = void 0;
this._nodesByName = {};
this.pickObject = options.pickObject;
}
function handleError9(model, error) {
if (model._errorEvent.numberOfListeners > 0) {
model._errorEvent.raiseEvent(error);
return;
}
console.log(error);
}
function createModelFeatureTables(model, structuralMetadata) {
const featureTables = model._featureTables;
const propertyTables = structuralMetadata.propertyTables;
const length3 = propertyTables.length;
for (let i = 0; i < length3; i++) {
const propertyTable = propertyTables[i];
const modelFeatureTable = new ModelFeatureTable_default({
model,
propertyTable
});
featureTables.push(modelFeatureTable);
}
return featureTables;
}
function selectFeatureTableId(components, model) {
const featureIdLabel = model._featureIdLabel;
const instanceFeatureIdLabel = model._instanceFeatureIdLabel;
let i, j;
let featureIdAttribute;
let node;
for (i = 0; i < components.nodes.length; i++) {
node = components.nodes[i];
if (defined_default(node.instances)) {
featureIdAttribute = ModelUtility_default.getFeatureIdsByLabel(
node.instances.featureIds,
instanceFeatureIdLabel
);
if (defined_default(featureIdAttribute) && defined_default(featureIdAttribute.propertyTableId)) {
return featureIdAttribute.propertyTableId;
}
}
}
for (i = 0; i < components.nodes.length; i++) {
node = components.nodes[i];
for (j = 0; j < node.primitives.length; j++) {
const primitive = node.primitives[j];
const featureIds = ModelUtility_default.getFeatureIdsByLabel(
primitive.featureIds,
featureIdLabel
);
if (defined_default(featureIds)) {
return featureIds.propertyTableId;
}
}
}
if (model._featureTables.length === 1) {
return 0;
}
}
function isColorAlphaDirty(currentColor, previousColor) {
if (!defined_default(currentColor) && !defined_default(previousColor)) {
return false;
}
if (defined_default(currentColor) !== defined_default(previousColor)) {
return true;
}
const currentAlpha = currentColor.alpha;
const previousAlpha = previousColor.alpha;
return Math.floor(currentAlpha) !== Math.floor(previousAlpha) || Math.ceil(currentAlpha) !== Math.ceil(previousAlpha);
}
Object.defineProperties(Model.prototype, {
/**
* When true
, this model is ready to render, i.e., the external binary, image,
* and shader files were downloaded and the WebGL resources were created.
*
* @memberof Model.prototype
*
* @type {boolean}
* @readonly
*
* @default false
*/
ready: {
get: function() {
return this._ready;
}
},
/**
* Gets an event that is raised when the model encounters an asynchronous rendering error. By subscribing
* to the event, you will be notified of the error and can potentially recover from it. Event listeners
* are passed an instance of {@link ModelError}.
* @memberof Model.prototype
* @type {Event}
* @readonly
*/
errorEvent: {
get: function() {
return this._errorEvent;
}
},
/**
* Gets an event that is raised when the model is loaded and ready for rendering, i.e. when the external resources
* have been downloaded and the WebGL resources are created. Event listeners
* are passed an instance of the {@link Model}.
*
* * If {@link Model.incrementallyLoadTextures} is true, this event will be raised before all textures are loaded and ready for rendering. Subscribe to {@link Model.texturesReadyEvent} to be notified when the textures are ready. *
* * @memberof Model.prototype * @type {Event} * @readonly */ readyEvent: { get: function() { return this._readyEvent; } }, /** * Returns true if textures are loaded separately from the other glTF resources. * * @memberof GltfLoader.prototype * * @type {boolean} * @readonly * @private */ incrementallyLoadTextures: { get: function() { return defaultValue_default(this._loader.incrementallyLoadTextures, false); } }, /** * Gets an event that, if {@link Model.incrementallyLoadTextures} is true, is raised when the model textures are loaded and ready for rendering, i.e. when the external resources * have been downloaded and the WebGL resources are created. Event listeners * are passed an instance of the {@link Model}. * * @memberof Model.prototype * @type {Event} * @readonly */ texturesReadyEvent: { get: function() { return this._texturesReadyEvent; } }, /** * Gets the promise that will be resolved when this model is ready to render, i.e. when the external resources * have been downloaded and the WebGL resources are created. ** This promise is resolved at the end of the frame before the first frame the model is rendered in. *
* * @memberof Model.prototype * * @type {PromiseincrementallyLoadTextures
is true this may resolve after
* promise
resolves.
*
* @memberof Model.prototype
*
* @type {Promisetrue
, each primitive is pickable with {@link Scene#pick}. When false
, GPU memory is saved.
*
* @memberof Model.prototype
*
* @type {boolean}
* @readonly
*
* @private
*/
allowPicking: {
get: function() {
return this._allowPicking;
}
},
/**
* The style to apply to the features in the model. Cannot be applied if a {@link CustomShader} is also applied.
*
* @memberof Model.prototype
*
* @type {Cesium3DTileStyle}
*/
style: {
get: function() {
return this._style;
},
set: function(value) {
this._style = value;
this._styleDirty = true;
}
},
/**
* The color to blend with the model's rendered color.
*
* @memberof Model.prototype
*
* @type {Color}
*
* @default undefined
*/
color: {
get: function() {
return this._color;
},
set: function(value) {
if (isColorAlphaDirty(value, this._color)) {
this.resetDrawCommands();
}
this._color = Color_default.clone(value, this._color);
}
},
/**
* Defines how the color blends with the model.
*
* @memberof Model.prototype
*
* @type {Cesium3DTileColorBlendMode|ColorBlendMode}
*
* @default ColorBlendMode.HIGHLIGHT
*/
colorBlendMode: {
get: function() {
return this._colorBlendMode;
},
set: function(value) {
this._colorBlendMode = value;
}
},
/**
* Value used to determine the color strength when the colorBlendMode
is MIX
. A value of 0.0 results in the model's rendered color while a value of 1.0 results in a solid color, with any value in-between resulting in a mix of the two.
*
* @memberof Model.prototype
*
* @type {number}
*
* @default 0.5
*/
colorBlendAmount: {
get: function() {
return this._colorBlendAmount;
},
set: function(value) {
this._colorBlendAmount = value;
}
},
/**
* The silhouette color.
*
* @memberof Model.prototype
*
* @type {Color}
*
* @default Color.RED
*/
silhouetteColor: {
get: function() {
return this._silhouetteColor;
},
set: function(value) {
if (!Color_default.equals(value, this._silhouetteColor)) {
const alphaDirty = isColorAlphaDirty(value, this._silhouetteColor);
this._silhouetteDirty = this._silhouetteDirty || alphaDirty;
}
this._silhouetteColor = Color_default.clone(value, this._silhouetteColor);
}
},
/**
* The size of the silhouette in pixels.
*
* @memberof Model.prototype
*
* @type {number}
*
* @default 0.0
*/
silhouetteSize: {
get: function() {
return this._silhouetteSize;
},
set: function(value) {
if (value !== this._silhouetteSize) {
const currentSize = this._silhouetteSize;
const sizeDirty = value > 0 && currentSize === 0 || value === 0 && currentSize > 0;
this._silhouetteDirty = this._silhouetteDirty || sizeDirty;
this._backFaceCullingDirty = this._backFaceCullingDirty || sizeDirty;
}
this._silhouetteSize = value;
}
},
/**
* Gets the model's bounding sphere in world space. This does not take into account
* glTF animations, skins, or morph targets. It also does not account for
* {@link Model#minimumPixelSize}.
*
* @memberof Model.prototype
*
* @type {BoundingSphere}
* @readonly
*/
boundingSphere: {
get: function() {
if (!this._ready) {
throw new DeveloperError_default(
"The model is not loaded. Use Model.readyEvent or wait for Model.ready to be true."
);
}
const modelMatrix = defined_default(this._clampedModelMatrix) ? this._clampedModelMatrix : this.modelMatrix;
updateBoundingSphere(this, modelMatrix);
return this._boundingSphere;
}
},
/**
* This property is for debugging only; it is not for production use nor is it optimized.
* * Draws the bounding sphere for each draw command in the model. *
* * @memberof Model.prototype * * @type {boolean} * * @default false */ debugShowBoundingVolume: { get: function() { return this._debugShowBoundingVolume; }, set: function(value) { if (this._debugShowBoundingVolume !== value) { this._debugShowBoundingVolumeDirty = true; } this._debugShowBoundingVolume = value; } }, /** * This property is for debugging only; it is not for production use nor is it optimized. ** Draws the model in wireframe. *
* * @memberof Model.prototype * * @type {boolean} * * @default false */ debugWireframe: { get: function() { return this._debugWireframe; }, set: function(value) { if (this._debugWireframe !== value) { this.resetDrawCommands(); } this._debugWireframe = value; if (this._debugWireframe === true && this._enableDebugWireframe === false && this.type === ModelType_default.GLTF) { oneTimeWarning_default( "model-debug-wireframe-ignored", "enableDebugWireframe must be set to true in Model.fromGltfAsync, otherwise debugWireframe will be ignored." ); } } }, /** * Whether or not to render the model. * * @memberof Model.prototype * * @type {boolean} * * @default true */ show: { get: function() { return this._show; }, set: function(value) { this._show = value; } }, /** * Label of the feature ID set to use for picking and styling. ** For EXT_mesh_features, this is the feature ID's label property, or * "featureId_N" (where N is the index in the featureIds array) when not * specified. EXT_feature_metadata did not have a label field, so such * feature ID sets are always labeled "featureId_N" where N is the index in * the list of all feature Ids, where feature ID attributes are listed before * feature ID textures. *
** If featureIdLabel is set to an integer N, it is converted to * the string "featureId_N" automatically. If both per-primitive and * per-instance feature IDs are present, the instance feature IDs take * priority. *
* * @memberof Model.prototype * * @type {string} * @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. */ featureIdLabel: { get: function() { return this._featureIdLabel; }, set: function(value) { if (typeof value === "number") { value = `featureId_${value}`; } Check_default.typeOf.string("value", value); if (value !== this._featureIdLabel) { this._featureTableIdDirty = true; } this._featureIdLabel = value; } }, /** * Label of the instance feature ID set used for picking and styling. ** If instanceFeatureIdLabel is set to an integer N, it is converted to * the string "instanceFeatureId_N" automatically. * If both per-primitive and per-instance feature IDs are present, the * instance feature IDs take priority. *
* * @memberof Model.prototype * * @type {string} * @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. */ instanceFeatureIdLabel: { get: function() { return this._instanceFeatureIdLabel; }, set: function(value) { if (typeof value === "number") { value = `instanceFeatureId_${value}`; } Check_default.typeOf.string("value", value); if (value !== this._instanceFeatureIdLabel) { this._featureTableIdDirty = true; } this._instanceFeatureIdLabel = value; } }, /** * The {@link ClippingPlaneCollection} used to selectively disable rendering the model. * * @memberof Model.prototype * * @type {ClippingPlaneCollection} */ clippingPlanes: { get: function() { return this._clippingPlanes; }, set: function(value) { if (value !== this._clippingPlanes) { ClippingPlaneCollection_default.setOwner(value, this, "_clippingPlanes"); this.resetDrawCommands(); } } }, /** * The light color when shading the model. Whenundefined
the scene's light color is used instead.
*
* Disabling additional light sources by setting
* model.imageBasedLighting.imageBasedLightingFactor = new Cartesian2(0.0, 0.0)
* will make the model much darker. Here, increasing the intensity of the light source will make the model brighter.
*
1.0
increase the size of the model; values
* less than 1.0
decrease.
*
* @memberof Model.prototype
*
* @type {number}
*
* @default 1.0
*/
scale: {
get: function() {
return this._scale;
},
set: function(value) {
if (value !== this._scale) {
this._updateModelMatrix = true;
}
this._scale = value;
}
},
/**
* The true scale of the model after being affected by the model's scale,
* minimum pixel size, and maximum scale parameters.
*
* @memberof Model.prototype
*
* @type {number}
* @readonly
*
* @private
*/
computedScale: {
get: function() {
return this._computedScale;
}
},
/**
* The approximate minimum pixel size of the model regardless of zoom.
* This can be used to ensure that a model is visible even when the viewer
* zooms out. When 0.0
, no minimum size is enforced.
*
* @memberof Model.prototype
*
* @type {number}
*
* @default 0.0
*/
minimumPixelSize: {
get: function() {
return this._minimumPixelSize;
},
set: function(value) {
if (value !== this._minimumPixelSize) {
this._updateModelMatrix = true;
}
this._minimumPixelSize = value;
}
},
/**
* The maximum scale size for a model. This can be used to give
* an upper limit to the {@link Model#minimumPixelSize}, ensuring that the model
* is never an unreasonable scale.
*
* @memberof Model.prototype
*
* @type {number}
*/
maximumScale: {
get: function() {
return this._maximumScale;
},
set: function(value) {
if (value !== this._maximumScale) {
this._updateModelMatrix = true;
}
this._maximumScale = value;
}
},
/**
* Determines whether the model casts or receives shadows from light sources.
* @memberof Model.prototype
*
* @type {ShadowMode}
*
* @default ShadowMode.ENABLED
*/
shadows: {
get: function() {
return this._shadows;
},
set: function(value) {
if (value !== this._shadows) {
this._shadowsDirty = true;
}
this._shadows = value;
}
},
/**
* Gets the credit that will be displayed for the model.
*
* @memberof Model.prototype
*
* @type {Credit}
* @readonly
*/
credit: {
get: function() {
return this._credit;
}
},
/**
* Gets or sets whether the credits of the model will be displayed
* on the screen.
*
* @memberof Model.prototype
*
* @type {boolean}
*
* @default false
*/
showCreditsOnScreen: {
get: function() {
return this._showCreditsOnScreen;
},
set: function(value) {
if (this._showCreditsOnScreen !== value) {
this._showCreditsOnScreenDirty = true;
}
this._showCreditsOnScreen = value;
}
},
/**
* The {@link SplitDirection} to apply to this model.
*
* @memberof Model.prototype
*
* @type {SplitDirection}
*
* @default {@link SplitDirection.NONE}
*/
splitDirection: {
get: function() {
return this._splitDirection;
},
set: function(value) {
if (this._splitDirection !== value) {
this.resetDrawCommands();
}
this._splitDirection = value;
}
},
/**
* Gets the model's classification type. This determines whether terrain,
* 3D Tiles, or both will be classified by this model.
* * Additionally, there are a few requirements/limitations: *
EXT_mesh_gpu_instancing
extension.x
increases from
* left to right, and y
increases from top to bottom.
* default ![]() |
* b.pixeloffset = new Cartesian2(50, 25); ![]() |
*
x
points towards the viewer's right, y
points up, and
* z
points into the screen. Eye coordinates use the same scale as world and model coordinates,
* which is typically meters.
* ![]() |
* ![]() |
*
b.eyeOffset = new Cartesian3(0.0, 8000000.0, 0.0);
1.0
does not change the size of the billboard; a scale greater than
* 1.0
enlarges the billboard; a positive scale less than 1.0
shrinks
* the billboard.
* 0.5
, 1.0
,
* and 2.0
.
* 0.0
makes the billboard transparent, and 1.0
makes the billboard opaque.
* default ![]() |
* alpha : 0.5 ![]() |
*
value
's red
, green
,
* blue
, and alpha
properties as shown in Example 1. These components range from 0.0
* (no intensity) to 1.0
(full intensity).
* @memberof Billboard.prototype
* @type {Color}
*
* @example
* // Example 1. Assign yellow.
* b.color = Cesium.Color.YELLOW;
*
* @example
* // Example 2. Make a billboard 50% translucent.
* b.color = new Cesium.Color(1.0, 1.0, 1.0, 0.5);
*/
color: {
get: function() {
return this._color;
},
set: function(value) {
Check_default.typeOf.object("value", value);
const color = this._color;
if (!Color_default.equals(color, value)) {
Color_default.clone(value, color);
makeDirty(this, COLOR_INDEX);
}
}
},
/**
* Gets or sets the rotation angle in radians.
* @memberof Billboard.prototype
* @type {number}
*/
rotation: {
get: function() {
return this._rotation;
},
set: function(value) {
Check_default.typeOf.number("value", value);
if (this._rotation !== value) {
this._rotation = value;
makeDirty(this, ROTATION_INDEX);
}
}
},
/**
* Gets or sets the aligned axis in world space. The aligned axis is the unit vector that the billboard up vector points towards.
* The default is the zero vector, which means the billboard is aligned to the screen up vector.
* @memberof Billboard.prototype
* @type {Cartesian3}
* @example
* // Example 1.
* // Have the billboard up vector point north
* billboard.alignedAxis = Cesium.Cartesian3.UNIT_Z;
*
* @example
* // Example 2.
* // Have the billboard point east.
* billboard.alignedAxis = Cesium.Cartesian3.UNIT_Z;
* billboard.rotation = -Cesium.Math.PI_OVER_TWO;
*
* @example
* // Example 3.
* // Reset the aligned axis
* billboard.alignedAxis = Cesium.Cartesian3.ZERO;
*/
alignedAxis: {
get: function() {
return this._alignedAxis;
},
set: function(value) {
Check_default.typeOf.object("value", value);
const alignedAxis = this._alignedAxis;
if (!Cartesian3_default.equals(alignedAxis, value)) {
Cartesian3_default.clone(value, alignedAxis);
makeDirty(this, ALIGNED_AXIS_INDEX);
}
}
},
/**
* Gets or sets a width for the billboard. If undefined, the image width will be used.
* @memberof Billboard.prototype
* @type {number}
*/
width: {
get: function() {
return defaultValue_default(this._width, this._imageWidth);
},
set: function(value) {
if (defined_default(value)) {
Check_default.typeOf.number("value", value);
}
if (this._width !== value) {
this._width = value;
makeDirty(this, IMAGE_INDEX_INDEX);
}
}
},
/**
* Gets or sets a height for the billboard. If undefined, the image height will be used.
* @memberof Billboard.prototype
* @type {number}
*/
height: {
get: function() {
return defaultValue_default(this._height, this._imageHeight);
},
set: function(value) {
if (defined_default(value)) {
Check_default.typeOf.number("value", value);
}
if (this._height !== value) {
this._height = value;
makeDirty(this, IMAGE_INDEX_INDEX);
}
}
},
/**
* Gets or sets if the billboard size is in meters or pixels. true
to size the billboard in meters;
* otherwise, the size is in pixels.
* @memberof Billboard.prototype
* @type {boolean}
* @default false
*/
sizeInMeters: {
get: function() {
return this._sizeInMeters;
},
set: function(value) {
Check_default.typeOf.bool("value", value);
if (this._sizeInMeters !== value) {
this._sizeInMeters = value;
makeDirty(this, COLOR_INDEX);
}
}
},
/**
* Gets or sets the condition specifying at what distance from the camera that this billboard will be displayed.
* @memberof Billboard.prototype
* @type {DistanceDisplayCondition}
* @default undefined
*/
distanceDisplayCondition: {
get: function() {
return this._distanceDisplayCondition;
},
set: function(value) {
if (!DistanceDisplayCondition_default.equals(value, this._distanceDisplayCondition)) {
if (defined_default(value)) {
Check_default.typeOf.object("value", value);
if (value.far <= value.near) {
throw new DeveloperError_default(
"far distance must be greater than near distance."
);
}
}
this._distanceDisplayCondition = DistanceDisplayCondition_default.clone(
value,
this._distanceDisplayCondition
);
makeDirty(this, DISTANCE_DISPLAY_CONDITION);
}
}
},
/**
* Gets or sets the distance from the camera at which to disable the depth test to, for example, prevent clipping against terrain.
* When set to zero, the depth test is always applied. When set to Number.POSITIVE_INFINITY, the depth test is never applied.
* @memberof Billboard.prototype
* @type {number}
*/
disableDepthTestDistance: {
get: function() {
return this._disableDepthTestDistance;
},
set: function(value) {
if (defined_default(value)) {
Check_default.typeOf.number("value", value);
if (value < 0) {
throw new DeveloperError_default(
"disableDepthTestDistance must be greater than or equal to 0.0."
);
}
}
if (this._disableDepthTestDistance !== value) {
this._disableDepthTestDistance = value;
makeDirty(this, DISABLE_DEPTH_DISTANCE);
}
}
},
/**
* Gets or sets the user-defined object returned when the billboard is picked.
* @memberof Billboard.prototype
* @type {object}
*/
id: {
get: function() {
return this._id;
},
set: function(value) {
this._id = value;
if (defined_default(this._pickId)) {
this._pickId.object.id = value;
}
}
},
/**
* The primitive to return when picking this billboard.
* @memberof Billboard.prototype
* @private
*/
pickPrimitive: {
get: function() {
return this._pickPrimitive;
},
set: function(value) {
this._pickPrimitive = value;
if (defined_default(this._pickId)) {
this._pickId.object.primitive = value;
}
}
},
/**
* @private
*/
pickId: {
get: function() {
return this._pickId;
}
},
/**
* * Gets or sets the image to be used for this billboard. If a texture has already been created for the * given image, the existing texture is used. *
** This property can be set to a loaded Image, a URL which will be loaded as an Image automatically, * a canvas, or another billboard's image property (from the same billboard collection). *
* * @memberof Billboard.prototype * @type {string} * @example * // load an image from a URL * b.image = 'some/image/url.png'; * * // assuming b1 and b2 are billboards in the same billboard collection, * // use the same image for both billboards. * b2.image = b1.image; */ image: { get: function() { return this._imageId; }, set: function(value) { if (!defined_default(value)) { this._imageIndex = -1; this._imageSubRegion = void 0; this._imageId = void 0; this._image = void 0; this._imageIndexPromise = void 0; makeDirty(this, IMAGE_INDEX_INDEX); } else if (typeof value === "string") { this.setImage(value, value); } else if (value instanceof Resource_default) { this.setImage(value.url, value); } else if (defined_default(value.src)) { this.setImage(value.src, value); } else { this.setImage(createGuid_default(), value); } } }, /** * Whentrue
, this billboard is ready to render, i.e., the image
* has been downloaded and the WebGL resources are created.
*
* @memberof Billboard.prototype
*
* @type {boolean}
* @readonly
*
* @default false
*/
ready: {
get: function() {
return this._imageIndex !== -1;
}
},
/**
* Keeps track of the position of the billboard based on the height reference.
* @memberof Billboard.prototype
* @type {Cartesian3}
* @private
*/
_clampedPosition: {
get: function() {
return this._actualClampedPosition;
},
set: function(value) {
this._actualClampedPosition = Cartesian3_default.clone(
value,
this._actualClampedPosition
);
makeDirty(this, POSITION_INDEX);
}
},
/**
* Determines whether or not this billboard will be shown or hidden because it was clustered.
* @memberof Billboard.prototype
* @type {boolean}
* @private
*/
clusterShow: {
get: function() {
return this._clusterShow;
},
set: function(value) {
if (this._clusterShow !== value) {
this._clusterShow = value;
makeDirty(this, SHOW_INDEX);
}
}
},
/**
* The outline color of this Billboard. Effective only for SDF billboards like Label glyphs.
* @memberof Billboard.prototype
* @type {Color}
* @private
*/
outlineColor: {
get: function() {
return this._outlineColor;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
const outlineColor = this._outlineColor;
if (!Color_default.equals(outlineColor, value)) {
Color_default.clone(value, outlineColor);
makeDirty(this, SDF_INDEX);
}
}
},
/**
* The outline width of this Billboard in pixels. Effective only for SDF billboards like Label glyphs.
* @memberof Billboard.prototype
* @type {number}
* @private
*/
outlineWidth: {
get: function() {
return this._outlineWidth;
},
set: function(value) {
if (this._outlineWidth !== value) {
this._outlineWidth = value;
makeDirty(this, SDF_INDEX);
}
}
}
});
Billboard.prototype.getPickId = function(context) {
if (!defined_default(this._pickId)) {
this._pickId = context.createPickId({
primitive: this._pickPrimitive,
collection: this._collection,
id: this._id
});
}
return this._pickId;
};
Billboard.prototype._updateClamping = function() {
Billboard._updateClamping(this._billboardCollection, this);
};
var scratchCartographic4 = new Cartographic_default();
var scratchPosition5 = new Cartesian3_default();
Billboard._updateClamping = function(collection, owner) {
const scene = collection._scene;
if (!defined_default(scene) || !defined_default(scene.globe)) {
if (owner._heightReference !== HeightReference_default.NONE) {
throw new DeveloperError_default(
"Height reference is not supported without a scene and globe."
);
}
return;
}
const globe = scene.globe;
const ellipsoid = globe.ellipsoid;
const surface = globe._surface;
const mode2 = scene.frameState.mode;
const modeChanged = mode2 !== owner._mode;
owner._mode = mode2;
if ((owner._heightReference === HeightReference_default.NONE || modeChanged) && defined_default(owner._removeCallbackFunc)) {
owner._removeCallbackFunc();
owner._removeCallbackFunc = void 0;
owner._clampedPosition = void 0;
}
if (owner._heightReference === HeightReference_default.NONE || !defined_default(owner._position)) {
return;
}
const position = ellipsoid.cartesianToCartographic(owner._position);
if (!defined_default(position)) {
owner._actualClampedPosition = void 0;
return;
}
if (defined_default(owner._removeCallbackFunc)) {
owner._removeCallbackFunc();
}
function updateFunction(clampedPosition) {
if (owner._heightReference === HeightReference_default.RELATIVE_TO_GROUND) {
if (owner._mode === SceneMode_default.SCENE3D) {
const clampedCart = ellipsoid.cartesianToCartographic(
clampedPosition,
scratchCartographic4
);
clampedCart.height += position.height;
ellipsoid.cartographicToCartesian(clampedCart, clampedPosition);
} else {
clampedPosition.x += position.height;
}
}
owner._clampedPosition = Cartesian3_default.clone(
clampedPosition,
owner._clampedPosition
);
}
owner._removeCallbackFunc = surface.updateHeight(position, updateFunction);
Cartographic_default.clone(position, scratchCartographic4);
const height = globe.getHeight(position);
if (defined_default(height)) {
scratchCartographic4.height = height;
}
ellipsoid.cartographicToCartesian(scratchCartographic4, scratchPosition5);
updateFunction(scratchPosition5);
};
Billboard.prototype._loadImage = function() {
const atlas = this._billboardCollection._textureAtlas;
const imageId = this._imageId;
const image = this._image;
const imageSubRegion = this._imageSubRegion;
let imageIndexPromise;
const that = this;
function completeImageLoad(index) {
if (that._imageId !== imageId || that._image !== image || !BoundingRectangle_default.equals(that._imageSubRegion, imageSubRegion)) {
return;
}
const textureCoordinates = atlas.textureCoordinates[index];
that._imageWidth = atlas.texture.width * textureCoordinates.width;
that._imageHeight = atlas.texture.height * textureCoordinates.height;
that._imageIndex = index;
that._ready = true;
that._image = void 0;
that._imageIndexPromise = void 0;
makeDirty(that, IMAGE_INDEX_INDEX);
}
if (defined_default(image)) {
const index = atlas.getImageIndex(imageId);
if (defined_default(index)) {
completeImageLoad(index);
return;
}
imageIndexPromise = atlas.addImage(imageId, image);
}
if (defined_default(imageSubRegion)) {
imageIndexPromise = atlas.addSubRegion(imageId, imageSubRegion);
}
this._imageIndexPromise = imageIndexPromise;
if (!defined_default(imageIndexPromise)) {
return;
}
imageIndexPromise.then(completeImageLoad).catch(function(error) {
console.error(`Error loading image for billboard: ${error}`);
that._imageIndexPromise = void 0;
});
};
Billboard.prototype.setImage = function(id, image) {
if (!defined_default(id)) {
throw new DeveloperError_default("id is required.");
}
if (!defined_default(image)) {
throw new DeveloperError_default("image is required.");
}
if (this._imageId === id) {
return;
}
this._imageIndex = -1;
this._imageSubRegion = void 0;
this._imageId = id;
this._image = image;
if (defined_default(this._billboardCollection._textureAtlas)) {
this._loadImage();
}
};
Billboard.prototype.setImageSubRegion = function(id, subRegion) {
if (!defined_default(id)) {
throw new DeveloperError_default("id is required.");
}
if (!defined_default(subRegion)) {
throw new DeveloperError_default("subRegion is required.");
}
if (this._imageId === id && BoundingRectangle_default.equals(this._imageSubRegion, subRegion)) {
return;
}
this._imageIndex = -1;
this._imageId = id;
this._imageSubRegion = BoundingRectangle_default.clone(subRegion);
if (defined_default(this._billboardCollection._textureAtlas)) {
this._loadImage();
}
};
Billboard.prototype._setTranslate = function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
const translate = this._translate;
if (!Cartesian2_default.equals(translate, value)) {
Cartesian2_default.clone(value, translate);
makeDirty(this, PIXEL_OFFSET_INDEX);
}
};
Billboard.prototype._getActualPosition = function() {
return defined_default(this._clampedPosition) ? this._clampedPosition : this._actualPosition;
};
Billboard.prototype._setActualPosition = function(value) {
if (!defined_default(this._clampedPosition)) {
Cartesian3_default.clone(value, this._actualPosition);
}
makeDirty(this, POSITION_INDEX);
};
var tempCartesian3 = new Cartesian4_default();
Billboard._computeActualPosition = function(billboard, position, frameState, modelMatrix) {
if (defined_default(billboard._clampedPosition)) {
if (frameState.mode !== billboard._mode) {
billboard._updateClamping();
}
return billboard._clampedPosition;
} else if (frameState.mode === SceneMode_default.SCENE3D) {
return position;
}
Matrix4_default.multiplyByPoint(modelMatrix, position, tempCartesian3);
return SceneTransforms_default.computeActualWgs84Position(frameState, tempCartesian3);
};
var scratchCartesian35 = new Cartesian3_default();
Billboard._computeScreenSpacePosition = function(modelMatrix, position, eyeOffset, pixelOffset, scene, result) {
const positionWorld = Matrix4_default.multiplyByPoint(
modelMatrix,
position,
scratchCartesian35
);
const positionWC2 = SceneTransforms_default.wgs84WithEyeOffsetToWindowCoordinates(
scene,
positionWorld,
eyeOffset,
result
);
if (!defined_default(positionWC2)) {
return void 0;
}
Cartesian2_default.add(positionWC2, pixelOffset, positionWC2);
return positionWC2;
};
var scratchPixelOffset = new Cartesian2_default(0, 0);
Billboard.prototype.computeScreenSpacePosition = function(scene, result) {
const billboardCollection = this._billboardCollection;
if (!defined_default(result)) {
result = new Cartesian2_default();
}
if (!defined_default(billboardCollection)) {
throw new DeveloperError_default(
"Billboard must be in a collection. Was it removed?"
);
}
if (!defined_default(scene)) {
throw new DeveloperError_default("scene is required.");
}
Cartesian2_default.clone(this._pixelOffset, scratchPixelOffset);
Cartesian2_default.add(scratchPixelOffset, this._translate, scratchPixelOffset);
let modelMatrix = billboardCollection.modelMatrix;
let position = this._position;
if (defined_default(this._clampedPosition)) {
position = this._clampedPosition;
if (scene.mode !== SceneMode_default.SCENE3D) {
const projection = scene.mapProjection;
const ellipsoid = projection.ellipsoid;
const cart = projection.unproject(position, scratchCartographic4);
position = ellipsoid.cartographicToCartesian(cart, scratchCartesian35);
modelMatrix = Matrix4_default.IDENTITY;
}
}
const windowCoordinates = Billboard._computeScreenSpacePosition(
modelMatrix,
position,
this._eyeOffset,
scratchPixelOffset,
scene,
result
);
return windowCoordinates;
};
Billboard.getScreenSpaceBoundingBox = function(billboard, screenSpacePosition, result) {
let width = billboard.width;
let height = billboard.height;
const scale = billboard.scale;
width *= scale;
height *= scale;
let x = screenSpacePosition.x;
if (billboard.horizontalOrigin === HorizontalOrigin_default.RIGHT) {
x -= width;
} else if (billboard.horizontalOrigin === HorizontalOrigin_default.CENTER) {
x -= width * 0.5;
}
let y = screenSpacePosition.y;
if (billboard.verticalOrigin === VerticalOrigin_default.BOTTOM || billboard.verticalOrigin === VerticalOrigin_default.BASELINE) {
y -= height;
} else if (billboard.verticalOrigin === VerticalOrigin_default.CENTER) {
y -= height * 0.5;
}
if (!defined_default(result)) {
result = new BoundingRectangle_default();
}
result.x = x;
result.y = y;
result.width = width;
result.height = height;
return result;
};
Billboard.prototype.equals = function(other) {
return this === other || defined_default(other) && this._id === other._id && Cartesian3_default.equals(this._position, other._position) && this._imageId === other._imageId && this._show === other._show && this._scale === other._scale && this._verticalOrigin === other._verticalOrigin && this._horizontalOrigin === other._horizontalOrigin && this._heightReference === other._heightReference && BoundingRectangle_default.equals(this._imageSubRegion, other._imageSubRegion) && Color_default.equals(this._color, other._color) && Cartesian2_default.equals(this._pixelOffset, other._pixelOffset) && Cartesian2_default.equals(this._translate, other._translate) && Cartesian3_default.equals(this._eyeOffset, other._eyeOffset) && NearFarScalar_default.equals(this._scaleByDistance, other._scaleByDistance) && NearFarScalar_default.equals(
this._translucencyByDistance,
other._translucencyByDistance
) && NearFarScalar_default.equals(
this._pixelOffsetScaleByDistance,
other._pixelOffsetScaleByDistance
) && DistanceDisplayCondition_default.equals(
this._distanceDisplayCondition,
other._distanceDisplayCondition
) && this._disableDepthTestDistance === other._disableDepthTestDistance;
};
Billboard.prototype._destroy = function() {
if (defined_default(this._customData)) {
this._billboardCollection._scene.globe._surface.removeTileCustomData(
this._customData
);
this._customData = void 0;
}
if (defined_default(this._removeCallbackFunc)) {
this._removeCallbackFunc();
this._removeCallbackFunc = void 0;
}
this.image = void 0;
this._pickId = this._pickId && this._pickId.destroy();
this._billboardCollection = void 0;
};
var Billboard_default = Billboard;
// packages/engine/Source/Scene/BlendOption.js
var BlendOption = {
/**
* The billboards, points, or labels in the collection are completely opaque.
* @type {number}
* @constant
*/
OPAQUE: 0,
/**
* The billboards, points, or labels in the collection are completely translucent.
* @type {number}
* @constant
*/
TRANSLUCENT: 1,
/**
* The billboards, points, or labels in the collection are both opaque and translucent.
* @type {number}
* @constant
*/
OPAQUE_AND_TRANSLUCENT: 2
};
var BlendOption_default = Object.freeze(BlendOption);
// packages/engine/Source/Scene/SDFSettings.js
var SDFSettings = {
/**
* The font size in pixels
*
* @type {number}
* @constant
*/
FONT_SIZE: 48,
/**
* Whitespace padding around glyphs.
*
* @type {number}
* @constant
*/
PADDING: 10,
/**
* How many pixels around the glyph shape to use for encoding distance
*
* @type {number}
* @constant
*/
RADIUS: 8,
/**
* How much of the radius (relative) is used for the inside part the glyph.
*
* @type {number}
* @constant
*/
CUTOFF: 0.25
};
var SDFSettings_default = Object.freeze(SDFSettings);
// packages/engine/Source/Scene/TextureAtlas.js
function TextureAtlasNode(bottomLeft, topRight, childNode1, childNode2, imageIndex) {
this.bottomLeft = defaultValue_default(bottomLeft, Cartesian2_default.ZERO);
this.topRight = defaultValue_default(topRight, Cartesian2_default.ZERO);
this.childNode1 = childNode1;
this.childNode2 = childNode2;
this.imageIndex = imageIndex;
}
var defaultInitialSize = new Cartesian2_default(16, 16);
function TextureAtlas(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const borderWidthInPixels = defaultValue_default(options.borderWidthInPixels, 1);
const initialSize = defaultValue_default(options.initialSize, defaultInitialSize);
if (!defined_default(options.context)) {
throw new DeveloperError_default("context is required.");
}
if (borderWidthInPixels < 0) {
throw new DeveloperError_default(
"borderWidthInPixels must be greater than or equal to zero."
);
}
if (initialSize.x < 1 || initialSize.y < 1) {
throw new DeveloperError_default("initialSize must be greater than zero.");
}
this._context = options.context;
this._pixelFormat = defaultValue_default(options.pixelFormat, PixelFormat_default.RGBA);
this._borderWidthInPixels = borderWidthInPixels;
this._textureCoordinates = [];
this._guid = createGuid_default();
this._idHash = {};
this._indexHash = {};
this._initialSize = initialSize;
this._root = void 0;
}
Object.defineProperties(TextureAtlas.prototype, {
/**
* The amount of spacing between adjacent images in pixels.
* @memberof TextureAtlas.prototype
* @type {number}
*/
borderWidthInPixels: {
get: function() {
return this._borderWidthInPixels;
}
},
/**
* An array of {@link BoundingRectangle} texture coordinate regions for all the images in the texture atlas.
* The x and y values of the rectangle correspond to the bottom-left corner of the texture coordinate.
* The coordinates are in the order that the corresponding images were added to the atlas.
* @memberof TextureAtlas.prototype
* @type {BoundingRectangle[]}
*/
textureCoordinates: {
get: function() {
return this._textureCoordinates;
}
},
/**
* The texture that all of the images are being written to.
* @memberof TextureAtlas.prototype
* @type {Texture}
*/
texture: {
get: function() {
if (!defined_default(this._texture)) {
this._texture = new Texture_default({
context: this._context,
width: this._initialSize.x,
height: this._initialSize.y,
pixelFormat: this._pixelFormat
});
}
return this._texture;
}
},
/**
* The number of images in the texture atlas. This value increases
* every time addImage or addImages is called.
* Texture coordinates are subject to change if the texture atlas resizes, so it is
* important to check {@link TextureAtlas#getGUID} before using old values.
* @memberof TextureAtlas.prototype
* @type {number}
*/
numberOfImages: {
get: function() {
return this._textureCoordinates.length;
}
},
/**
* The atlas' globally unique identifier (GUID).
* The GUID changes whenever the texture atlas is modified.
* Classes that use a texture atlas should check if the GUID
* has changed before processing the atlas data.
* @memberof TextureAtlas.prototype
* @type {string}
*/
guid: {
get: function() {
return this._guid;
}
}
});
function resizeAtlas(textureAtlas, image) {
const context = textureAtlas._context;
const numImages = textureAtlas.numberOfImages;
const scalingFactor = 2;
const borderWidthInPixels = textureAtlas._borderWidthInPixels;
if (numImages > 0) {
const oldAtlasWidth = textureAtlas._texture.width;
const oldAtlasHeight = textureAtlas._texture.height;
const atlasWidth = scalingFactor * (oldAtlasWidth + image.width + borderWidthInPixels);
const atlasHeight = scalingFactor * (oldAtlasHeight + image.height + borderWidthInPixels);
const widthRatio = oldAtlasWidth / atlasWidth;
const heightRatio = oldAtlasHeight / atlasHeight;
const nodeBottomRight = new TextureAtlasNode(
new Cartesian2_default(oldAtlasWidth + borderWidthInPixels, borderWidthInPixels),
new Cartesian2_default(atlasWidth, oldAtlasHeight)
);
const nodeBottomHalf = new TextureAtlasNode(
new Cartesian2_default(),
new Cartesian2_default(atlasWidth, oldAtlasHeight),
textureAtlas._root,
nodeBottomRight
);
const nodeTopHalf = new TextureAtlasNode(
new Cartesian2_default(borderWidthInPixels, oldAtlasHeight + borderWidthInPixels),
new Cartesian2_default(atlasWidth, atlasHeight)
);
const nodeMain = new TextureAtlasNode(
new Cartesian2_default(),
new Cartesian2_default(atlasWidth, atlasHeight),
nodeBottomHalf,
nodeTopHalf
);
for (let i = 0; i < textureAtlas._textureCoordinates.length; i++) {
const texCoord = textureAtlas._textureCoordinates[i];
if (defined_default(texCoord)) {
texCoord.x *= widthRatio;
texCoord.y *= heightRatio;
texCoord.width *= widthRatio;
texCoord.height *= heightRatio;
}
}
const newTexture = new Texture_default({
context: textureAtlas._context,
width: atlasWidth,
height: atlasHeight,
pixelFormat: textureAtlas._pixelFormat
});
const framebuffer = new Framebuffer_default({
context,
colorTextures: [textureAtlas._texture],
destroyAttachments: false
});
framebuffer._bind();
newTexture.copyFromFramebuffer(0, 0, 0, 0, atlasWidth, atlasHeight);
framebuffer._unBind();
framebuffer.destroy();
textureAtlas._texture = textureAtlas._texture && textureAtlas._texture.destroy();
textureAtlas._texture = newTexture;
textureAtlas._root = nodeMain;
} else {
let initialWidth = scalingFactor * (image.width + 2 * borderWidthInPixels);
let initialHeight = scalingFactor * (image.height + 2 * borderWidthInPixels);
if (initialWidth < textureAtlas._initialSize.x) {
initialWidth = textureAtlas._initialSize.x;
}
if (initialHeight < textureAtlas._initialSize.y) {
initialHeight = textureAtlas._initialSize.y;
}
textureAtlas._texture = textureAtlas._texture && textureAtlas._texture.destroy();
textureAtlas._texture = new Texture_default({
context: textureAtlas._context,
width: initialWidth,
height: initialHeight,
pixelFormat: textureAtlas._pixelFormat
});
textureAtlas._root = new TextureAtlasNode(
new Cartesian2_default(borderWidthInPixels, borderWidthInPixels),
new Cartesian2_default(initialWidth, initialHeight)
);
}
}
function findNode(textureAtlas, node, image) {
if (!defined_default(node)) {
return void 0;
}
if (!defined_default(node.childNode1) && !defined_default(node.childNode2)) {
if (defined_default(node.imageIndex)) {
return void 0;
}
const nodeWidth = node.topRight.x - node.bottomLeft.x;
const nodeHeight = node.topRight.y - node.bottomLeft.y;
const widthDifference = nodeWidth - image.width;
const heightDifference = nodeHeight - image.height;
if (widthDifference < 0 || heightDifference < 0) {
return void 0;
}
if (widthDifference === 0 && heightDifference === 0) {
return node;
}
if (widthDifference > heightDifference) {
node.childNode1 = new TextureAtlasNode(
new Cartesian2_default(node.bottomLeft.x, node.bottomLeft.y),
new Cartesian2_default(node.bottomLeft.x + image.width, node.topRight.y)
);
const childNode2BottomLeftX = node.bottomLeft.x + image.width + textureAtlas._borderWidthInPixels;
if (childNode2BottomLeftX < node.topRight.x) {
node.childNode2 = new TextureAtlasNode(
new Cartesian2_default(childNode2BottomLeftX, node.bottomLeft.y),
new Cartesian2_default(node.topRight.x, node.topRight.y)
);
}
} else {
node.childNode1 = new TextureAtlasNode(
new Cartesian2_default(node.bottomLeft.x, node.bottomLeft.y),
new Cartesian2_default(node.topRight.x, node.bottomLeft.y + image.height)
);
const childNode2BottomLeftY = node.bottomLeft.y + image.height + textureAtlas._borderWidthInPixels;
if (childNode2BottomLeftY < node.topRight.y) {
node.childNode2 = new TextureAtlasNode(
new Cartesian2_default(node.bottomLeft.x, childNode2BottomLeftY),
new Cartesian2_default(node.topRight.x, node.topRight.y)
);
}
}
return findNode(textureAtlas, node.childNode1, image);
}
return findNode(textureAtlas, node.childNode1, image) || findNode(textureAtlas, node.childNode2, image);
}
function addImage(textureAtlas, image, index) {
const node = findNode(textureAtlas, textureAtlas._root, image);
if (defined_default(node)) {
node.imageIndex = index;
const atlasWidth = textureAtlas._texture.width;
const atlasHeight = textureAtlas._texture.height;
const nodeWidth = node.topRight.x - node.bottomLeft.x;
const nodeHeight = node.topRight.y - node.bottomLeft.y;
const x = node.bottomLeft.x / atlasWidth;
const y = node.bottomLeft.y / atlasHeight;
const w = nodeWidth / atlasWidth;
const h = nodeHeight / atlasHeight;
textureAtlas._textureCoordinates[index] = new BoundingRectangle_default(x, y, w, h);
textureAtlas._texture.copyFrom({
source: image,
xOffset: node.bottomLeft.x,
yOffset: node.bottomLeft.y
});
} else {
resizeAtlas(textureAtlas, image);
addImage(textureAtlas, image, index);
}
textureAtlas._guid = createGuid_default();
}
function getIndex(atlas, image) {
if (!defined_default(atlas) || atlas.isDestroyed()) {
return -1;
}
const index = atlas.numberOfImages;
addImage(atlas, image, index);
return index;
}
TextureAtlas.prototype.getImageIndex = function(id) {
if (!defined_default(id)) {
throw new DeveloperError_default("id is required.");
}
return this._indexHash[id];
};
TextureAtlas.prototype.addImageSync = function(id, image) {
if (!defined_default(id)) {
throw new DeveloperError_default("id is required.");
}
if (!defined_default(image)) {
throw new DeveloperError_default("image is required.");
}
let index = this._indexHash[id];
if (defined_default(index)) {
return index;
}
index = getIndex(this, image);
this._idHash[id] = Promise.resolve(index);
this._indexHash[id] = index;
return index;
};
TextureAtlas.prototype.addImage = function(id, image) {
if (!defined_default(id)) {
throw new DeveloperError_default("id is required.");
}
if (!defined_default(image)) {
throw new DeveloperError_default("image is required.");
}
let indexPromise = this._idHash[id];
if (defined_default(indexPromise)) {
return indexPromise;
}
if (typeof image === "function") {
image = image(id);
if (!defined_default(image)) {
throw new DeveloperError_default("image is required.");
}
} else if (typeof image === "string" || image instanceof Resource_default) {
const resource = Resource_default.createIfNeeded(image);
image = resource.fetchImage();
}
const that = this;
indexPromise = Promise.resolve(image).then(function(image2) {
const index = getIndex(that, image2);
that._indexHash[id] = index;
return index;
});
this._idHash[id] = indexPromise;
return indexPromise;
};
TextureAtlas.prototype.addSubRegion = function(id, subRegion) {
if (!defined_default(id)) {
throw new DeveloperError_default("id is required.");
}
if (!defined_default(subRegion)) {
throw new DeveloperError_default("subRegion is required.");
}
const indexPromise = this._idHash[id];
if (!defined_default(indexPromise)) {
throw new RuntimeError_default(`image with id "${id}" not found in the atlas.`);
}
const that = this;
return Promise.resolve(indexPromise).then(function(index) {
if (index === -1) {
return -1;
}
const atlasWidth = that._texture.width;
const atlasHeight = that._texture.height;
const baseRegion = that._textureCoordinates[index];
const x = baseRegion.x + subRegion.x / atlasWidth;
const y = baseRegion.y + subRegion.y / atlasHeight;
const w = subRegion.width / atlasWidth;
const h = subRegion.height / atlasHeight;
const newIndex = that._textureCoordinates.push(new BoundingRectangle_default(x, y, w, h)) - 1;
that._indexHash[id] = newIndex;
that._guid = createGuid_default();
return newIndex;
});
};
TextureAtlas.prototype.isDestroyed = function() {
return false;
};
TextureAtlas.prototype.destroy = function() {
this._texture = this._texture && this._texture.destroy();
return destroyObject_default(this);
};
var TextureAtlas_default = TextureAtlas;
// packages/engine/Source/Scene/BillboardCollection.js
var SHOW_INDEX2 = Billboard_default.SHOW_INDEX;
var POSITION_INDEX2 = Billboard_default.POSITION_INDEX;
var PIXEL_OFFSET_INDEX2 = Billboard_default.PIXEL_OFFSET_INDEX;
var EYE_OFFSET_INDEX2 = Billboard_default.EYE_OFFSET_INDEX;
var HORIZONTAL_ORIGIN_INDEX2 = Billboard_default.HORIZONTAL_ORIGIN_INDEX;
var VERTICAL_ORIGIN_INDEX2 = Billboard_default.VERTICAL_ORIGIN_INDEX;
var SCALE_INDEX2 = Billboard_default.SCALE_INDEX;
var IMAGE_INDEX_INDEX2 = Billboard_default.IMAGE_INDEX_INDEX;
var COLOR_INDEX2 = Billboard_default.COLOR_INDEX;
var ROTATION_INDEX2 = Billboard_default.ROTATION_INDEX;
var ALIGNED_AXIS_INDEX2 = Billboard_default.ALIGNED_AXIS_INDEX;
var SCALE_BY_DISTANCE_INDEX2 = Billboard_default.SCALE_BY_DISTANCE_INDEX;
var TRANSLUCENCY_BY_DISTANCE_INDEX2 = Billboard_default.TRANSLUCENCY_BY_DISTANCE_INDEX;
var PIXEL_OFFSET_SCALE_BY_DISTANCE_INDEX2 = Billboard_default.PIXEL_OFFSET_SCALE_BY_DISTANCE_INDEX;
var DISTANCE_DISPLAY_CONDITION_INDEX = Billboard_default.DISTANCE_DISPLAY_CONDITION;
var DISABLE_DEPTH_DISTANCE2 = Billboard_default.DISABLE_DEPTH_DISTANCE;
var TEXTURE_COORDINATE_BOUNDS = Billboard_default.TEXTURE_COORDINATE_BOUNDS;
var SDF_INDEX2 = Billboard_default.SDF_INDEX;
var NUMBER_OF_PROPERTIES = Billboard_default.NUMBER_OF_PROPERTIES;
var attributeLocations;
var attributeLocationsBatched = {
positionHighAndScale: 0,
positionLowAndRotation: 1,
compressedAttribute0: 2,
// pixel offset, translate, horizontal origin, vertical origin, show, direction, texture coordinates
compressedAttribute1: 3,
// aligned axis, translucency by distance, image width
compressedAttribute2: 4,
// image height, color, pick color, size in meters, valid aligned axis, 13 bits free
eyeOffset: 5,
// 4 bytes free
scaleByDistance: 6,
pixelOffsetScaleByDistance: 7,
compressedAttribute3: 8,
textureCoordinateBoundsOrLabelTranslate: 9,
a_batchId: 10,
sdf: 11
};
var attributeLocationsInstanced = {
direction: 0,
positionHighAndScale: 1,
positionLowAndRotation: 2,
// texture offset in w
compressedAttribute0: 3,
compressedAttribute1: 4,
compressedAttribute2: 5,
eyeOffset: 6,
// texture range in w
scaleByDistance: 7,
pixelOffsetScaleByDistance: 8,
compressedAttribute3: 9,
textureCoordinateBoundsOrLabelTranslate: 10,
a_batchId: 11,
sdf: 12
};
function BillboardCollection(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this._scene = options.scene;
this._batchTable = options.batchTable;
this._textureAtlas = void 0;
this._textureAtlasGUID = void 0;
this._destroyTextureAtlas = true;
this._sp = void 0;
this._spTranslucent = void 0;
this._rsOpaque = void 0;
this._rsTranslucent = void 0;
this._vaf = void 0;
this._billboards = [];
this._billboardsToUpdate = [];
this._billboardsToUpdateIndex = 0;
this._billboardsRemoved = false;
this._createVertexArray = false;
this._shaderRotation = false;
this._compiledShaderRotation = false;
this._shaderAlignedAxis = false;
this._compiledShaderAlignedAxis = false;
this._shaderScaleByDistance = false;
this._compiledShaderScaleByDistance = false;
this._shaderTranslucencyByDistance = false;
this._compiledShaderTranslucencyByDistance = false;
this._shaderPixelOffsetScaleByDistance = false;
this._compiledShaderPixelOffsetScaleByDistance = false;
this._shaderDistanceDisplayCondition = false;
this._compiledShaderDistanceDisplayCondition = false;
this._shaderDisableDepthDistance = false;
this._compiledShaderDisableDepthDistance = false;
this._shaderClampToGround = false;
this._compiledShaderClampToGround = false;
this._propertiesChanged = new Uint32Array(NUMBER_OF_PROPERTIES);
this._maxSize = 0;
this._maxEyeOffset = 0;
this._maxScale = 1;
this._maxPixelOffset = 0;
this._allHorizontalCenter = true;
this._allVerticalCenter = true;
this._allSizedInMeters = true;
this._baseVolume = new BoundingSphere_default();
this._baseVolumeWC = new BoundingSphere_default();
this._baseVolume2D = new BoundingSphere_default();
this._boundingVolume = new BoundingSphere_default();
this._boundingVolumeDirty = false;
this._colorCommands = [];
this.show = defaultValue_default(options.show, true);
this.modelMatrix = Matrix4_default.clone(
defaultValue_default(options.modelMatrix, Matrix4_default.IDENTITY)
);
this._modelMatrix = Matrix4_default.clone(Matrix4_default.IDENTITY);
this.debugShowBoundingVolume = defaultValue_default(
options.debugShowBoundingVolume,
false
);
this.debugShowTextureAtlas = defaultValue_default(
options.debugShowTextureAtlas,
false
);
this.blendOption = defaultValue_default(
options.blendOption,
BlendOption_default.OPAQUE_AND_TRANSLUCENT
);
this._blendOption = void 0;
this._mode = SceneMode_default.SCENE3D;
this._buffersUsage = [
BufferUsage_default.STATIC_DRAW,
// SHOW_INDEX
BufferUsage_default.STATIC_DRAW,
// POSITION_INDEX
BufferUsage_default.STATIC_DRAW,
// PIXEL_OFFSET_INDEX
BufferUsage_default.STATIC_DRAW,
// EYE_OFFSET_INDEX
BufferUsage_default.STATIC_DRAW,
// HORIZONTAL_ORIGIN_INDEX
BufferUsage_default.STATIC_DRAW,
// VERTICAL_ORIGIN_INDEX
BufferUsage_default.STATIC_DRAW,
// SCALE_INDEX
BufferUsage_default.STATIC_DRAW,
// IMAGE_INDEX_INDEX
BufferUsage_default.STATIC_DRAW,
// COLOR_INDEX
BufferUsage_default.STATIC_DRAW,
// ROTATION_INDEX
BufferUsage_default.STATIC_DRAW,
// ALIGNED_AXIS_INDEX
BufferUsage_default.STATIC_DRAW,
// SCALE_BY_DISTANCE_INDEX
BufferUsage_default.STATIC_DRAW,
// TRANSLUCENCY_BY_DISTANCE_INDEX
BufferUsage_default.STATIC_DRAW,
// PIXEL_OFFSET_SCALE_BY_DISTANCE_INDEX
BufferUsage_default.STATIC_DRAW,
// DISTANCE_DISPLAY_CONDITION_INDEX
BufferUsage_default.STATIC_DRAW
// TEXTURE_COORDINATE_BOUNDS
];
this._highlightColor = Color_default.clone(Color_default.WHITE);
const that = this;
this._uniforms = {
u_atlas: function() {
return that._textureAtlas.texture;
},
u_highlightColor: function() {
return that._highlightColor;
}
};
const scene = this._scene;
if (defined_default(scene) && defined_default(scene.terrainProviderChanged)) {
this._removeCallbackFunc = scene.terrainProviderChanged.addEventListener(
function() {
const billboards = this._billboards;
const length3 = billboards.length;
for (let i = 0; i < length3; ++i) {
if (defined_default(billboards[i])) {
billboards[i]._updateClamping();
}
}
},
this
);
}
}
Object.defineProperties(BillboardCollection.prototype, {
/**
* Returns the number of billboards in this collection. This is commonly used with
* {@link BillboardCollection#get} to iterate over all the billboards
* in the collection.
* @memberof BillboardCollection.prototype
* @type {number}
*/
length: {
get: function() {
removeBillboards(this);
return this._billboards.length;
}
},
/**
* Gets or sets the textureAtlas.
* @memberof BillboardCollection.prototype
* @type {TextureAtlas}
* @private
*/
textureAtlas: {
get: function() {
return this._textureAtlas;
},
set: function(value) {
if (this._textureAtlas !== value) {
this._textureAtlas = this._destroyTextureAtlas && this._textureAtlas && this._textureAtlas.destroy();
this._textureAtlas = value;
this._createVertexArray = true;
}
}
},
/**
* Gets or sets a value which determines if the texture atlas is
* destroyed when the collection is destroyed.
*
* If the texture atlas is used by more than one collection, set this to false
,
* and explicitly destroy the atlas to avoid attempting to destroy it multiple times.
*
* @memberof BillboardCollection.prototype
* @type {boolean}
* @private
*
* @example
* // Set destroyTextureAtlas
* // Destroy a billboard collection but not its texture atlas.
*
* const atlas = new TextureAtlas({
* scene : scene,
* images : images
* });
* billboards.textureAtlas = atlas;
* billboards.destroyTextureAtlas = false;
* billboards = billboards.destroy();
* console.log(atlas.isDestroyed()); // False
*/
destroyTextureAtlas: {
get: function() {
return this._destroyTextureAtlas;
},
set: function(value) {
this._destroyTextureAtlas = value;
}
}
});
function destroyBillboards(billboards) {
const length3 = billboards.length;
for (let i = 0; i < length3; ++i) {
if (billboards[i]) {
billboards[i]._destroy();
}
}
}
BillboardCollection.prototype.add = function(options) {
const billboard = new Billboard_default(options, this);
billboard._index = this._billboards.length;
this._billboards.push(billboard);
this._createVertexArray = true;
return billboard;
};
BillboardCollection.prototype.remove = function(billboard) {
if (this.contains(billboard)) {
this._billboards[billboard._index] = void 0;
this._billboardsRemoved = true;
this._createVertexArray = true;
billboard._destroy();
return true;
}
return false;
};
BillboardCollection.prototype.removeAll = function() {
destroyBillboards(this._billboards);
this._billboards = [];
this._billboardsToUpdate = [];
this._billboardsToUpdateIndex = 0;
this._billboardsRemoved = false;
this._createVertexArray = true;
};
function removeBillboards(billboardCollection) {
if (billboardCollection._billboardsRemoved) {
billboardCollection._billboardsRemoved = false;
const newBillboards = [];
const billboards = billboardCollection._billboards;
const length3 = billboards.length;
for (let i = 0, j = 0; i < length3; ++i) {
const billboard = billboards[i];
if (defined_default(billboard)) {
billboard._index = j++;
newBillboards.push(billboard);
}
}
billboardCollection._billboards = newBillboards;
}
}
BillboardCollection.prototype._updateBillboard = function(billboard, propertyChanged) {
if (!billboard._dirty) {
this._billboardsToUpdate[this._billboardsToUpdateIndex++] = billboard;
}
++this._propertiesChanged[propertyChanged];
};
BillboardCollection.prototype.contains = function(billboard) {
return defined_default(billboard) && billboard._billboardCollection === this;
};
BillboardCollection.prototype.get = function(index) {
Check_default.typeOf.number("index", index);
removeBillboards(this);
return this._billboards[index];
};
var getIndexBuffer2;
function getIndexBufferBatched(context) {
const sixteenK = 16 * 1024;
let indexBuffer = context.cache.billboardCollection_indexBufferBatched;
if (defined_default(indexBuffer)) {
return indexBuffer;
}
const length3 = sixteenK * 6 - 6;
const indices2 = new Uint16Array(length3);
for (let i = 0, j = 0; i < length3; i += 6, j += 4) {
indices2[i] = j;
indices2[i + 1] = j + 1;
indices2[i + 2] = j + 2;
indices2[i + 3] = j + 0;
indices2[i + 4] = j + 2;
indices2[i + 5] = j + 3;
}
indexBuffer = Buffer_default.createIndexBuffer({
context,
typedArray: indices2,
usage: BufferUsage_default.STATIC_DRAW,
indexDatatype: IndexDatatype_default.UNSIGNED_SHORT
});
indexBuffer.vertexArrayDestroyable = false;
context.cache.billboardCollection_indexBufferBatched = indexBuffer;
return indexBuffer;
}
function getIndexBufferInstanced(context) {
let indexBuffer = context.cache.billboardCollection_indexBufferInstanced;
if (defined_default(indexBuffer)) {
return indexBuffer;
}
indexBuffer = Buffer_default.createIndexBuffer({
context,
typedArray: new Uint16Array([0, 1, 2, 0, 2, 3]),
usage: BufferUsage_default.STATIC_DRAW,
indexDatatype: IndexDatatype_default.UNSIGNED_SHORT
});
indexBuffer.vertexArrayDestroyable = false;
context.cache.billboardCollection_indexBufferInstanced = indexBuffer;
return indexBuffer;
}
function getVertexBufferInstanced(context) {
let vertexBuffer = context.cache.billboardCollection_vertexBufferInstanced;
if (defined_default(vertexBuffer)) {
return vertexBuffer;
}
vertexBuffer = Buffer_default.createVertexBuffer({
context,
typedArray: new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]),
usage: BufferUsage_default.STATIC_DRAW
});
vertexBuffer.vertexArrayDestroyable = false;
context.cache.billboardCollection_vertexBufferInstanced = vertexBuffer;
return vertexBuffer;
}
BillboardCollection.prototype.computeNewBuffersUsage = function() {
const buffersUsage = this._buffersUsage;
let usageChanged = false;
const properties = this._propertiesChanged;
for (let k = 0; k < NUMBER_OF_PROPERTIES; ++k) {
const newUsage = properties[k] === 0 ? BufferUsage_default.STATIC_DRAW : BufferUsage_default.STREAM_DRAW;
usageChanged = usageChanged || buffersUsage[k] !== newUsage;
buffersUsage[k] = newUsage;
}
return usageChanged;
};
function createVAF(context, numberOfBillboards, buffersUsage, instanced, batchTable, sdf) {
const attributes = [
{
index: attributeLocations.positionHighAndScale,
componentsPerAttribute: 4,
componentDatatype: ComponentDatatype_default.FLOAT,
usage: buffersUsage[POSITION_INDEX2]
},
{
index: attributeLocations.positionLowAndRotation,
componentsPerAttribute: 4,
componentDatatype: ComponentDatatype_default.FLOAT,
usage: buffersUsage[POSITION_INDEX2]
},
{
index: attributeLocations.compressedAttribute0,
componentsPerAttribute: 4,
componentDatatype: ComponentDatatype_default.FLOAT,
usage: buffersUsage[PIXEL_OFFSET_INDEX2]
},
{
index: attributeLocations.compressedAttribute1,
componentsPerAttribute: 4,
componentDatatype: ComponentDatatype_default.FLOAT,
usage: buffersUsage[TRANSLUCENCY_BY_DISTANCE_INDEX2]
},
{
index: attributeLocations.compressedAttribute2,
componentsPerAttribute: 4,
componentDatatype: ComponentDatatype_default.FLOAT,
usage: buffersUsage[COLOR_INDEX2]
},
{
index: attributeLocations.eyeOffset,
componentsPerAttribute: 4,
componentDatatype: ComponentDatatype_default.FLOAT,
usage: buffersUsage[EYE_OFFSET_INDEX2]
},
{
index: attributeLocations.scaleByDistance,
componentsPerAttribute: 4,
componentDatatype: ComponentDatatype_default.FLOAT,
usage: buffersUsage[SCALE_BY_DISTANCE_INDEX2]
},
{
index: attributeLocations.pixelOffsetScaleByDistance,
componentsPerAttribute: 4,
componentDatatype: ComponentDatatype_default.FLOAT,
usage: buffersUsage[PIXEL_OFFSET_SCALE_BY_DISTANCE_INDEX2]
},
{
index: attributeLocations.compressedAttribute3,
componentsPerAttribute: 4,
componentDatatype: ComponentDatatype_default.FLOAT,
usage: buffersUsage[DISTANCE_DISPLAY_CONDITION_INDEX]
},
{
index: attributeLocations.textureCoordinateBoundsOrLabelTranslate,
componentsPerAttribute: 4,
componentDatatype: ComponentDatatype_default.FLOAT,
usage: buffersUsage[TEXTURE_COORDINATE_BOUNDS]
}
];
if (instanced) {
attributes.push({
index: attributeLocations.direction,
componentsPerAttribute: 2,
componentDatatype: ComponentDatatype_default.FLOAT,
vertexBuffer: getVertexBufferInstanced(context)
});
}
if (defined_default(batchTable)) {
attributes.push({
index: attributeLocations.a_batchId,
componentsPerAttribute: 1,
componentDatatype: ComponentDatatype_default.FLOAT,
bufferUsage: BufferUsage_default.STATIC_DRAW
});
}
if (sdf) {
attributes.push({
index: attributeLocations.sdf,
componentsPerAttribute: 2,
componentDatatype: ComponentDatatype_default.FLOAT,
usage: buffersUsage[SDF_INDEX2]
});
}
const sizeInVertices = instanced ? numberOfBillboards : 4 * numberOfBillboards;
return new VertexArrayFacade_default(context, attributes, sizeInVertices, instanced);
}
var writePositionScratch = new EncodedCartesian3_default();
function writePositionScaleAndRotation(billboardCollection, frameState, textureAtlasCoordinates, vafWriters, billboard) {
let i;
const positionHighWriter = vafWriters[attributeLocations.positionHighAndScale];
const positionLowWriter = vafWriters[attributeLocations.positionLowAndRotation];
const position = billboard._getActualPosition();
if (billboardCollection._mode === SceneMode_default.SCENE3D) {
BoundingSphere_default.expand(
billboardCollection._baseVolume,
position,
billboardCollection._baseVolume
);
billboardCollection._boundingVolumeDirty = true;
}
EncodedCartesian3_default.fromCartesian(position, writePositionScratch);
const scale = billboard.scale;
const rotation = billboard.rotation;
if (rotation !== 0) {
billboardCollection._shaderRotation = true;
}
billboardCollection._maxScale = Math.max(
billboardCollection._maxScale,
scale
);
const high = writePositionScratch.high;
const low = writePositionScratch.low;
if (billboardCollection._instanced) {
i = billboard._index;
positionHighWriter(i, high.x, high.y, high.z, scale);
positionLowWriter(i, low.x, low.y, low.z, rotation);
} else {
i = billboard._index * 4;
positionHighWriter(i + 0, high.x, high.y, high.z, scale);
positionHighWriter(i + 1, high.x, high.y, high.z, scale);
positionHighWriter(i + 2, high.x, high.y, high.z, scale);
positionHighWriter(i + 3, high.x, high.y, high.z, scale);
positionLowWriter(i + 0, low.x, low.y, low.z, rotation);
positionLowWriter(i + 1, low.x, low.y, low.z, rotation);
positionLowWriter(i + 2, low.x, low.y, low.z, rotation);
positionLowWriter(i + 3, low.x, low.y, low.z, rotation);
}
}
var scratchCartesian24 = new Cartesian2_default();
var UPPER_BOUND = 32768;
var LEFT_SHIFT16 = 65536;
var LEFT_SHIFT12 = 4096;
var LEFT_SHIFT8 = 256;
var LEFT_SHIFT7 = 128;
var LEFT_SHIFT5 = 32;
var LEFT_SHIFT3 = 8;
var LEFT_SHIFT2 = 4;
var RIGHT_SHIFT8 = 1 / 256;
var LOWER_LEFT = 0;
var LOWER_RIGHT = 2;
var UPPER_RIGHT = 3;
var UPPER_LEFT = 1;
function writeCompressedAttrib0(billboardCollection, frameState, textureAtlasCoordinates, vafWriters, billboard) {
let i;
const writer = vafWriters[attributeLocations.compressedAttribute0];
const pixelOffset = billboard.pixelOffset;
const pixelOffsetX = pixelOffset.x;
const pixelOffsetY = pixelOffset.y;
const translate = billboard._translate;
const translateX = translate.x;
const translateY = translate.y;
billboardCollection._maxPixelOffset = Math.max(
billboardCollection._maxPixelOffset,
Math.abs(pixelOffsetX + translateX),
Math.abs(-pixelOffsetY + translateY)
);
const horizontalOrigin = billboard.horizontalOrigin;
let verticalOrigin = billboard._verticalOrigin;
let show = billboard.show && billboard.clusterShow;
if (billboard.color.alpha === 0) {
show = false;
}
if (verticalOrigin === VerticalOrigin_default.BASELINE) {
verticalOrigin = VerticalOrigin_default.BOTTOM;
}
billboardCollection._allHorizontalCenter = billboardCollection._allHorizontalCenter && horizontalOrigin === HorizontalOrigin_default.CENTER;
billboardCollection._allVerticalCenter = billboardCollection._allVerticalCenter && verticalOrigin === VerticalOrigin_default.CENTER;
let bottomLeftX = 0;
let bottomLeftY = 0;
let width = 0;
let height = 0;
const index = billboard._imageIndex;
if (index !== -1) {
const imageRectangle = textureAtlasCoordinates[index];
if (!defined_default(imageRectangle)) {
throw new DeveloperError_default(`Invalid billboard image index: ${index}`);
}
bottomLeftX = imageRectangle.x;
bottomLeftY = imageRectangle.y;
width = imageRectangle.width;
height = imageRectangle.height;
}
const topRightX = bottomLeftX + width;
const topRightY = bottomLeftY + height;
let compressed0 = Math.floor(
Math_default.clamp(pixelOffsetX, -UPPER_BOUND, UPPER_BOUND) + UPPER_BOUND
) * LEFT_SHIFT7;
compressed0 += (horizontalOrigin + 1) * LEFT_SHIFT5;
compressed0 += (verticalOrigin + 1) * LEFT_SHIFT3;
compressed0 += (show ? 1 : 0) * LEFT_SHIFT2;
let compressed1 = Math.floor(
Math_default.clamp(pixelOffsetY, -UPPER_BOUND, UPPER_BOUND) + UPPER_BOUND
) * LEFT_SHIFT8;
let compressed2 = Math.floor(
Math_default.clamp(translateX, -UPPER_BOUND, UPPER_BOUND) + UPPER_BOUND
) * LEFT_SHIFT8;
const tempTanslateY = (Math_default.clamp(translateY, -UPPER_BOUND, UPPER_BOUND) + UPPER_BOUND) * RIGHT_SHIFT8;
const upperTranslateY = Math.floor(tempTanslateY);
const lowerTranslateY = Math.floor(
(tempTanslateY - upperTranslateY) * LEFT_SHIFT8
);
compressed1 += upperTranslateY;
compressed2 += lowerTranslateY;
scratchCartesian24.x = bottomLeftX;
scratchCartesian24.y = bottomLeftY;
const compressedTexCoordsLL = AttributeCompression_default.compressTextureCoordinates(
scratchCartesian24
);
scratchCartesian24.x = topRightX;
const compressedTexCoordsLR = AttributeCompression_default.compressTextureCoordinates(
scratchCartesian24
);
scratchCartesian24.y = topRightY;
const compressedTexCoordsUR = AttributeCompression_default.compressTextureCoordinates(
scratchCartesian24
);
scratchCartesian24.x = bottomLeftX;
const compressedTexCoordsUL = AttributeCompression_default.compressTextureCoordinates(
scratchCartesian24
);
if (billboardCollection._instanced) {
i = billboard._index;
writer(i, compressed0, compressed1, compressed2, compressedTexCoordsLL);
} else {
i = billboard._index * 4;
writer(
i + 0,
compressed0 + LOWER_LEFT,
compressed1,
compressed2,
compressedTexCoordsLL
);
writer(
i + 1,
compressed0 + LOWER_RIGHT,
compressed1,
compressed2,
compressedTexCoordsLR
);
writer(
i + 2,
compressed0 + UPPER_RIGHT,
compressed1,
compressed2,
compressedTexCoordsUR
);
writer(
i + 3,
compressed0 + UPPER_LEFT,
compressed1,
compressed2,
compressedTexCoordsUL
);
}
}
function writeCompressedAttrib1(billboardCollection, frameState, textureAtlasCoordinates, vafWriters, billboard) {
let i;
const writer = vafWriters[attributeLocations.compressedAttribute1];
const alignedAxis = billboard.alignedAxis;
if (!Cartesian3_default.equals(alignedAxis, Cartesian3_default.ZERO)) {
billboardCollection._shaderAlignedAxis = true;
}
let near = 0;
let nearValue = 1;
let far = 1;
let farValue = 1;
const translucency = billboard.translucencyByDistance;
if (defined_default(translucency)) {
near = translucency.near;
nearValue = translucency.nearValue;
far = translucency.far;
farValue = translucency.farValue;
if (nearValue !== 1 || farValue !== 1) {
billboardCollection._shaderTranslucencyByDistance = true;
}
}
let width = 0;
const index = billboard._imageIndex;
if (index !== -1) {
const imageRectangle = textureAtlasCoordinates[index];
if (!defined_default(imageRectangle)) {
throw new DeveloperError_default(`Invalid billboard image index: ${index}`);
}
width = imageRectangle.width;
}
const textureWidth = billboardCollection._textureAtlas.texture.width;
const imageWidth = Math.round(
defaultValue_default(billboard.width, textureWidth * width)
);
billboardCollection._maxSize = Math.max(
billboardCollection._maxSize,
imageWidth
);
let compressed0 = Math_default.clamp(imageWidth, 0, LEFT_SHIFT16);
let compressed1 = 0;
if (Math.abs(Cartesian3_default.magnitudeSquared(alignedAxis) - 1) < Math_default.EPSILON6) {
compressed1 = AttributeCompression_default.octEncodeFloat(alignedAxis);
}
nearValue = Math_default.clamp(nearValue, 0, 1);
nearValue = nearValue === 1 ? 255 : nearValue * 255 | 0;
compressed0 = compressed0 * LEFT_SHIFT8 + nearValue;
farValue = Math_default.clamp(farValue, 0, 1);
farValue = farValue === 1 ? 255 : farValue * 255 | 0;
compressed1 = compressed1 * LEFT_SHIFT8 + farValue;
if (billboardCollection._instanced) {
i = billboard._index;
writer(i, compressed0, compressed1, near, far);
} else {
i = billboard._index * 4;
writer(i + 0, compressed0, compressed1, near, far);
writer(i + 1, compressed0, compressed1, near, far);
writer(i + 2, compressed0, compressed1, near, far);
writer(i + 3, compressed0, compressed1, near, far);
}
}
function writeCompressedAttrib2(billboardCollection, frameState, textureAtlasCoordinates, vafWriters, billboard) {
let i;
const writer = vafWriters[attributeLocations.compressedAttribute2];
const color = billboard.color;
const pickColor = !defined_default(billboardCollection._batchTable) ? billboard.getPickId(frameState.context).color : Color_default.WHITE;
const sizeInMeters = billboard.sizeInMeters ? 1 : 0;
const validAlignedAxis = Math.abs(Cartesian3_default.magnitudeSquared(billboard.alignedAxis) - 1) < Math_default.EPSILON6 ? 1 : 0;
billboardCollection._allSizedInMeters = billboardCollection._allSizedInMeters && sizeInMeters === 1;
let height = 0;
const index = billboard._imageIndex;
if (index !== -1) {
const imageRectangle = textureAtlasCoordinates[index];
if (!defined_default(imageRectangle)) {
throw new DeveloperError_default(`Invalid billboard image index: ${index}`);
}
height = imageRectangle.height;
}
const dimensions = billboardCollection._textureAtlas.texture.dimensions;
const imageHeight = Math.round(
defaultValue_default(billboard.height, dimensions.y * height)
);
billboardCollection._maxSize = Math.max(
billboardCollection._maxSize,
imageHeight
);
let labelHorizontalOrigin = defaultValue_default(
billboard._labelHorizontalOrigin,
-2
);
labelHorizontalOrigin += 2;
const compressed3 = imageHeight * LEFT_SHIFT2 + labelHorizontalOrigin;
let red = Color_default.floatToByte(color.red);
let green = Color_default.floatToByte(color.green);
let blue = Color_default.floatToByte(color.blue);
const compressed0 = red * LEFT_SHIFT16 + green * LEFT_SHIFT8 + blue;
red = Color_default.floatToByte(pickColor.red);
green = Color_default.floatToByte(pickColor.green);
blue = Color_default.floatToByte(pickColor.blue);
const compressed1 = red * LEFT_SHIFT16 + green * LEFT_SHIFT8 + blue;
let compressed2 = Color_default.floatToByte(color.alpha) * LEFT_SHIFT16 + Color_default.floatToByte(pickColor.alpha) * LEFT_SHIFT8;
compressed2 += sizeInMeters * 2 + validAlignedAxis;
if (billboardCollection._instanced) {
i = billboard._index;
writer(i, compressed0, compressed1, compressed2, compressed3);
} else {
i = billboard._index * 4;
writer(i + 0, compressed0, compressed1, compressed2, compressed3);
writer(i + 1, compressed0, compressed1, compressed2, compressed3);
writer(i + 2, compressed0, compressed1, compressed2, compressed3);
writer(i + 3, compressed0, compressed1, compressed2, compressed3);
}
}
function writeEyeOffset(billboardCollection, frameState, textureAtlasCoordinates, vafWriters, billboard) {
let i;
const writer = vafWriters[attributeLocations.eyeOffset];
const eyeOffset = billboard.eyeOffset;
let eyeOffsetZ = eyeOffset.z;
if (billboard._heightReference !== HeightReference_default.NONE) {
eyeOffsetZ *= 1.005;
}
billboardCollection._maxEyeOffset = Math.max(
billboardCollection._maxEyeOffset,
Math.abs(eyeOffset.x),
Math.abs(eyeOffset.y),
Math.abs(eyeOffsetZ)
);
if (billboardCollection._instanced) {
let width = 0;
let height = 0;
const index = billboard._imageIndex;
if (index !== -1) {
const imageRectangle = textureAtlasCoordinates[index];
if (!defined_default(imageRectangle)) {
throw new DeveloperError_default(`Invalid billboard image index: ${index}`);
}
width = imageRectangle.width;
height = imageRectangle.height;
}
scratchCartesian24.x = width;
scratchCartesian24.y = height;
const compressedTexCoordsRange = AttributeCompression_default.compressTextureCoordinates(
scratchCartesian24
);
i = billboard._index;
writer(i, eyeOffset.x, eyeOffset.y, eyeOffsetZ, compressedTexCoordsRange);
} else {
i = billboard._index * 4;
writer(i + 0, eyeOffset.x, eyeOffset.y, eyeOffsetZ, 0);
writer(i + 1, eyeOffset.x, eyeOffset.y, eyeOffsetZ, 0);
writer(i + 2, eyeOffset.x, eyeOffset.y, eyeOffsetZ, 0);
writer(i + 3, eyeOffset.x, eyeOffset.y, eyeOffsetZ, 0);
}
}
function writeScaleByDistance(billboardCollection, frameState, textureAtlasCoordinates, vafWriters, billboard) {
let i;
const writer = vafWriters[attributeLocations.scaleByDistance];
let near = 0;
let nearValue = 1;
let far = 1;
let farValue = 1;
const scale = billboard.scaleByDistance;
if (defined_default(scale)) {
near = scale.near;
nearValue = scale.nearValue;
far = scale.far;
farValue = scale.farValue;
if (nearValue !== 1 || farValue !== 1) {
billboardCollection._shaderScaleByDistance = true;
}
}
if (billboardCollection._instanced) {
i = billboard._index;
writer(i, near, nearValue, far, farValue);
} else {
i = billboard._index * 4;
writer(i + 0, near, nearValue, far, farValue);
writer(i + 1, near, nearValue, far, farValue);
writer(i + 2, near, nearValue, far, farValue);
writer(i + 3, near, nearValue, far, farValue);
}
}
function writePixelOffsetScaleByDistance(billboardCollection, frameState, textureAtlasCoordinates, vafWriters, billboard) {
let i;
const writer = vafWriters[attributeLocations.pixelOffsetScaleByDistance];
let near = 0;
let nearValue = 1;
let far = 1;
let farValue = 1;
const pixelOffsetScale = billboard.pixelOffsetScaleByDistance;
if (defined_default(pixelOffsetScale)) {
near = pixelOffsetScale.near;
nearValue = pixelOffsetScale.nearValue;
far = pixelOffsetScale.far;
farValue = pixelOffsetScale.farValue;
if (nearValue !== 1 || farValue !== 1) {
billboardCollection._shaderPixelOffsetScaleByDistance = true;
}
}
if (billboardCollection._instanced) {
i = billboard._index;
writer(i, near, nearValue, far, farValue);
} else {
i = billboard._index * 4;
writer(i + 0, near, nearValue, far, farValue);
writer(i + 1, near, nearValue, far, farValue);
writer(i + 2, near, nearValue, far, farValue);
writer(i + 3, near, nearValue, far, farValue);
}
}
function writeCompressedAttribute3(billboardCollection, frameState, textureAtlasCoordinates, vafWriters, billboard) {
let i;
const writer = vafWriters[attributeLocations.compressedAttribute3];
let near = 0;
let far = Number.MAX_VALUE;
const distanceDisplayCondition = billboard.distanceDisplayCondition;
if (defined_default(distanceDisplayCondition)) {
near = distanceDisplayCondition.near;
far = distanceDisplayCondition.far;
near *= near;
far *= far;
billboardCollection._shaderDistanceDisplayCondition = true;
}
let disableDepthTestDistance = billboard.disableDepthTestDistance;
const clampToGround = billboard.heightReference === HeightReference_default.CLAMP_TO_GROUND && frameState.context.depthTexture;
if (!defined_default(disableDepthTestDistance)) {
disableDepthTestDistance = clampToGround ? 5e3 : 0;
}
disableDepthTestDistance *= disableDepthTestDistance;
if (clampToGround || disableDepthTestDistance > 0) {
billboardCollection._shaderDisableDepthDistance = true;
if (disableDepthTestDistance === Number.POSITIVE_INFINITY) {
disableDepthTestDistance = -1;
}
}
let imageHeight;
let imageWidth;
if (!defined_default(billboard._labelDimensions)) {
let height = 0;
let width = 0;
const index = billboard._imageIndex;
if (index !== -1) {
const imageRectangle = textureAtlasCoordinates[index];
if (!defined_default(imageRectangle)) {
throw new DeveloperError_default(`Invalid billboard image index: ${index}`);
}
height = imageRectangle.height;
width = imageRectangle.width;
}
imageHeight = Math.round(
defaultValue_default(
billboard.height,
billboardCollection._textureAtlas.texture.dimensions.y * height
)
);
const textureWidth = billboardCollection._textureAtlas.texture.width;
imageWidth = Math.round(
defaultValue_default(billboard.width, textureWidth * width)
);
} else {
imageWidth = billboard._labelDimensions.x;
imageHeight = billboard._labelDimensions.y;
}
const w = Math.floor(Math_default.clamp(imageWidth, 0, LEFT_SHIFT12));
const h = Math.floor(Math_default.clamp(imageHeight, 0, LEFT_SHIFT12));
const dimensions = w * LEFT_SHIFT12 + h;
if (billboardCollection._instanced) {
i = billboard._index;
writer(i, near, far, disableDepthTestDistance, dimensions);
} else {
i = billboard._index * 4;
writer(i + 0, near, far, disableDepthTestDistance, dimensions);
writer(i + 1, near, far, disableDepthTestDistance, dimensions);
writer(i + 2, near, far, disableDepthTestDistance, dimensions);
writer(i + 3, near, far, disableDepthTestDistance, dimensions);
}
}
function writeTextureCoordinateBoundsOrLabelTranslate(billboardCollection, frameState, textureAtlasCoordinates, vafWriters, billboard) {
if (billboard.heightReference === HeightReference_default.CLAMP_TO_GROUND) {
const scene = billboardCollection._scene;
const context = frameState.context;
const globeTranslucent = frameState.globeTranslucencyState.translucent;
const depthTestAgainstTerrain = defined_default(scene.globe) && scene.globe.depthTestAgainstTerrain;
billboardCollection._shaderClampToGround = context.depthTexture && !globeTranslucent && depthTestAgainstTerrain;
}
let i;
const writer = vafWriters[attributeLocations.textureCoordinateBoundsOrLabelTranslate];
if (ContextLimits_default.maximumVertexTextureImageUnits > 0) {
let translateX = 0;
let translateY = 0;
if (defined_default(billboard._labelTranslate)) {
translateX = billboard._labelTranslate.x;
translateY = billboard._labelTranslate.y;
}
if (billboardCollection._instanced) {
i = billboard._index;
writer(i, translateX, translateY, 0, 0);
} else {
i = billboard._index * 4;
writer(i + 0, translateX, translateY, 0, 0);
writer(i + 1, translateX, translateY, 0, 0);
writer(i + 2, translateX, translateY, 0, 0);
writer(i + 3, translateX, translateY, 0, 0);
}
return;
}
let minX = 0;
let minY = 0;
let width = 0;
let height = 0;
const index = billboard._imageIndex;
if (index !== -1) {
const imageRectangle = textureAtlasCoordinates[index];
if (!defined_default(imageRectangle)) {
throw new DeveloperError_default(`Invalid billboard image index: ${index}`);
}
minX = imageRectangle.x;
minY = imageRectangle.y;
width = imageRectangle.width;
height = imageRectangle.height;
}
const maxX = minX + width;
const maxY = minY + height;
if (billboardCollection._instanced) {
i = billboard._index;
writer(i, minX, minY, maxX, maxY);
} else {
i = billboard._index * 4;
writer(i + 0, minX, minY, maxX, maxY);
writer(i + 1, minX, minY, maxX, maxY);
writer(i + 2, minX, minY, maxX, maxY);
writer(i + 3, minX, minY, maxX, maxY);
}
}
function writeBatchId(billboardCollection, frameState, textureAtlasCoordinates, vafWriters, billboard) {
if (!defined_default(billboardCollection._batchTable)) {
return;
}
const writer = vafWriters[attributeLocations.a_batchId];
const id = billboard._batchIndex;
let i;
if (billboardCollection._instanced) {
i = billboard._index;
writer(i, id);
} else {
i = billboard._index * 4;
writer(i + 0, id);
writer(i + 1, id);
writer(i + 2, id);
writer(i + 3, id);
}
}
function writeSDF(billboardCollection, frameState, textureAtlasCoordinates, vafWriters, billboard) {
if (!billboardCollection._sdf) {
return;
}
let i;
const writer = vafWriters[attributeLocations.sdf];
const outlineColor = billboard.outlineColor;
const outlineWidth = billboard.outlineWidth;
const red = Color_default.floatToByte(outlineColor.red);
const green = Color_default.floatToByte(outlineColor.green);
const blue = Color_default.floatToByte(outlineColor.blue);
const compressed0 = red * LEFT_SHIFT16 + green * LEFT_SHIFT8 + blue;
const outlineDistance = outlineWidth / SDFSettings_default.RADIUS;
const compressed1 = Color_default.floatToByte(outlineColor.alpha) * LEFT_SHIFT16 + Color_default.floatToByte(outlineDistance) * LEFT_SHIFT8;
if (billboardCollection._instanced) {
i = billboard._index;
writer(i, compressed0, compressed1);
} else {
i = billboard._index * 4;
writer(i + 0, compressed0 + LOWER_LEFT, compressed1);
writer(i + 1, compressed0 + LOWER_RIGHT, compressed1);
writer(i + 2, compressed0 + UPPER_RIGHT, compressed1);
writer(i + 3, compressed0 + UPPER_LEFT, compressed1);
}
}
function writeBillboard(billboardCollection, frameState, textureAtlasCoordinates, vafWriters, billboard) {
writePositionScaleAndRotation(
billboardCollection,
frameState,
textureAtlasCoordinates,
vafWriters,
billboard
);
writeCompressedAttrib0(
billboardCollection,
frameState,
textureAtlasCoordinates,
vafWriters,
billboard
);
writeCompressedAttrib1(
billboardCollection,
frameState,
textureAtlasCoordinates,
vafWriters,
billboard
);
writeCompressedAttrib2(
billboardCollection,
frameState,
textureAtlasCoordinates,
vafWriters,
billboard
);
writeEyeOffset(
billboardCollection,
frameState,
textureAtlasCoordinates,
vafWriters,
billboard
);
writeScaleByDistance(
billboardCollection,
frameState,
textureAtlasCoordinates,
vafWriters,
billboard
);
writePixelOffsetScaleByDistance(
billboardCollection,
frameState,
textureAtlasCoordinates,
vafWriters,
billboard
);
writeCompressedAttribute3(
billboardCollection,
frameState,
textureAtlasCoordinates,
vafWriters,
billboard
);
writeTextureCoordinateBoundsOrLabelTranslate(
billboardCollection,
frameState,
textureAtlasCoordinates,
vafWriters,
billboard
);
writeBatchId(
billboardCollection,
frameState,
textureAtlasCoordinates,
vafWriters,
billboard
);
writeSDF(
billboardCollection,
frameState,
textureAtlasCoordinates,
vafWriters,
billboard
);
}
function recomputeActualPositions(billboardCollection, billboards, length3, frameState, modelMatrix, recomputeBoundingVolume) {
let boundingVolume;
if (frameState.mode === SceneMode_default.SCENE3D) {
boundingVolume = billboardCollection._baseVolume;
billboardCollection._boundingVolumeDirty = true;
} else {
boundingVolume = billboardCollection._baseVolume2D;
}
const positions = [];
for (let i = 0; i < length3; ++i) {
const billboard = billboards[i];
const position = billboard.position;
const actualPosition = Billboard_default._computeActualPosition(
billboard,
position,
frameState,
modelMatrix
);
if (defined_default(actualPosition)) {
billboard._setActualPosition(actualPosition);
if (recomputeBoundingVolume) {
positions.push(actualPosition);
} else {
BoundingSphere_default.expand(boundingVolume, actualPosition, boundingVolume);
}
}
}
if (recomputeBoundingVolume) {
BoundingSphere_default.fromPoints(positions, boundingVolume);
}
}
function updateMode(billboardCollection, frameState) {
const mode2 = frameState.mode;
const billboards = billboardCollection._billboards;
const billboardsToUpdate = billboardCollection._billboardsToUpdate;
const modelMatrix = billboardCollection._modelMatrix;
if (billboardCollection._createVertexArray || billboardCollection._mode !== mode2 || mode2 !== SceneMode_default.SCENE3D && !Matrix4_default.equals(modelMatrix, billboardCollection.modelMatrix)) {
billboardCollection._mode = mode2;
Matrix4_default.clone(billboardCollection.modelMatrix, modelMatrix);
billboardCollection._createVertexArray = true;
if (mode2 === SceneMode_default.SCENE3D || mode2 === SceneMode_default.SCENE2D || mode2 === SceneMode_default.COLUMBUS_VIEW) {
recomputeActualPositions(
billboardCollection,
billboards,
billboards.length,
frameState,
modelMatrix,
true
);
}
} else if (mode2 === SceneMode_default.MORPHING) {
recomputeActualPositions(
billboardCollection,
billboards,
billboards.length,
frameState,
modelMatrix,
true
);
} else if (mode2 === SceneMode_default.SCENE2D || mode2 === SceneMode_default.COLUMBUS_VIEW) {
recomputeActualPositions(
billboardCollection,
billboardsToUpdate,
billboardCollection._billboardsToUpdateIndex,
frameState,
modelMatrix,
false
);
}
}
function updateBoundingVolume(collection, frameState, boundingVolume) {
let pixelScale = 1;
if (!collection._allSizedInMeters || collection._maxPixelOffset !== 0) {
pixelScale = frameState.camera.getPixelSize(
boundingVolume,
frameState.context.drawingBufferWidth,
frameState.context.drawingBufferHeight
);
}
let size = pixelScale * collection._maxScale * collection._maxSize * 2;
if (collection._allHorizontalCenter && collection._allVerticalCenter) {
size *= 0.5;
}
const offset2 = pixelScale * collection._maxPixelOffset + collection._maxEyeOffset;
boundingVolume.radius += size + offset2;
}
function createDebugCommand(billboardCollection, context) {
const fs = "uniform sampler2D billboard_texture; \nin vec2 v_textureCoordinates; \nvoid main() \n{ \n out_FragColor = texture(billboard_texture, v_textureCoordinates); \n} \n";
const drawCommand = context.createViewportQuadCommand(fs, {
uniformMap: {
billboard_texture: function() {
return billboardCollection._textureAtlas.texture;
}
}
});
drawCommand.pass = Pass_default.OVERLAY;
return drawCommand;
}
var scratchWriterArray = [];
BillboardCollection.prototype.update = function(frameState) {
removeBillboards(this);
if (!this.show) {
return;
}
let billboards = this._billboards;
let billboardsLength = billboards.length;
const context = frameState.context;
this._instanced = context.instancedArrays;
attributeLocations = this._instanced ? attributeLocationsInstanced : attributeLocationsBatched;
getIndexBuffer2 = this._instanced ? getIndexBufferInstanced : getIndexBufferBatched;
let textureAtlas = this._textureAtlas;
if (!defined_default(textureAtlas)) {
textureAtlas = this._textureAtlas = new TextureAtlas_default({
context
});
for (let ii = 0; ii < billboardsLength; ++ii) {
billboards[ii]._loadImage();
}
}
const textureAtlasCoordinates = textureAtlas.textureCoordinates;
if (textureAtlasCoordinates.length === 0) {
return;
}
updateMode(this, frameState);
billboards = this._billboards;
billboardsLength = billboards.length;
const billboardsToUpdate = this._billboardsToUpdate;
const billboardsToUpdateLength = this._billboardsToUpdateIndex;
const properties = this._propertiesChanged;
const textureAtlasGUID = textureAtlas.guid;
const createVertexArray7 = this._createVertexArray || this._textureAtlasGUID !== textureAtlasGUID;
this._textureAtlasGUID = textureAtlasGUID;
let vafWriters;
const pass = frameState.passes;
const picking = pass.pick;
if (createVertexArray7 || !picking && this.computeNewBuffersUsage()) {
this._createVertexArray = false;
for (let k = 0; k < NUMBER_OF_PROPERTIES; ++k) {
properties[k] = 0;
}
this._vaf = this._vaf && this._vaf.destroy();
if (billboardsLength > 0) {
this._vaf = createVAF(
context,
billboardsLength,
this._buffersUsage,
this._instanced,
this._batchTable,
this._sdf
);
vafWriters = this._vaf.writers;
for (let i = 0; i < billboardsLength; ++i) {
const billboard = this._billboards[i];
billboard._dirty = false;
writeBillboard(
this,
frameState,
textureAtlasCoordinates,
vafWriters,
billboard
);
}
this._vaf.commit(getIndexBuffer2(context));
}
this._billboardsToUpdateIndex = 0;
} else if (billboardsToUpdateLength > 0) {
const writers = scratchWriterArray;
writers.length = 0;
if (properties[POSITION_INDEX2] || properties[ROTATION_INDEX2] || properties[SCALE_INDEX2]) {
writers.push(writePositionScaleAndRotation);
}
if (properties[IMAGE_INDEX_INDEX2] || properties[PIXEL_OFFSET_INDEX2] || properties[HORIZONTAL_ORIGIN_INDEX2] || properties[VERTICAL_ORIGIN_INDEX2] || properties[SHOW_INDEX2]) {
writers.push(writeCompressedAttrib0);
if (this._instanced) {
writers.push(writeEyeOffset);
}
}
if (properties[IMAGE_INDEX_INDEX2] || properties[ALIGNED_AXIS_INDEX2] || properties[TRANSLUCENCY_BY_DISTANCE_INDEX2]) {
writers.push(writeCompressedAttrib1);
writers.push(writeCompressedAttrib2);
}
if (properties[IMAGE_INDEX_INDEX2] || properties[COLOR_INDEX2]) {
writers.push(writeCompressedAttrib2);
}
if (properties[EYE_OFFSET_INDEX2]) {
writers.push(writeEyeOffset);
}
if (properties[SCALE_BY_DISTANCE_INDEX2]) {
writers.push(writeScaleByDistance);
}
if (properties[PIXEL_OFFSET_SCALE_BY_DISTANCE_INDEX2]) {
writers.push(writePixelOffsetScaleByDistance);
}
if (properties[DISTANCE_DISPLAY_CONDITION_INDEX] || properties[DISABLE_DEPTH_DISTANCE2] || properties[IMAGE_INDEX_INDEX2] || properties[POSITION_INDEX2]) {
writers.push(writeCompressedAttribute3);
}
if (properties[IMAGE_INDEX_INDEX2] || properties[POSITION_INDEX2]) {
writers.push(writeTextureCoordinateBoundsOrLabelTranslate);
}
if (properties[SDF_INDEX2]) {
writers.push(writeSDF);
}
const numWriters = writers.length;
vafWriters = this._vaf.writers;
if (billboardsToUpdateLength / billboardsLength > 0.1) {
for (let m = 0; m < billboardsToUpdateLength; ++m) {
const b = billboardsToUpdate[m];
b._dirty = false;
for (let n = 0; n < numWriters; ++n) {
writers[n](this, frameState, textureAtlasCoordinates, vafWriters, b);
}
}
this._vaf.commit(getIndexBuffer2(context));
} else {
for (let h = 0; h < billboardsToUpdateLength; ++h) {
const bb = billboardsToUpdate[h];
bb._dirty = false;
for (let o = 0; o < numWriters; ++o) {
writers[o](this, frameState, textureAtlasCoordinates, vafWriters, bb);
}
if (this._instanced) {
this._vaf.subCommit(bb._index, 1);
} else {
this._vaf.subCommit(bb._index * 4, 4);
}
}
this._vaf.endSubCommits();
}
this._billboardsToUpdateIndex = 0;
}
if (billboardsToUpdateLength > billboardsLength * 1.5) {
billboardsToUpdate.length = billboardsLength;
}
if (!defined_default(this._vaf) || !defined_default(this._vaf.va)) {
return;
}
if (this._boundingVolumeDirty) {
this._boundingVolumeDirty = false;
BoundingSphere_default.transform(
this._baseVolume,
this.modelMatrix,
this._baseVolumeWC
);
}
let boundingVolume;
let modelMatrix = Matrix4_default.IDENTITY;
if (frameState.mode === SceneMode_default.SCENE3D) {
modelMatrix = this.modelMatrix;
boundingVolume = BoundingSphere_default.clone(
this._baseVolumeWC,
this._boundingVolume
);
} else {
boundingVolume = BoundingSphere_default.clone(
this._baseVolume2D,
this._boundingVolume
);
}
updateBoundingVolume(this, frameState, boundingVolume);
const blendOptionChanged = this._blendOption !== this.blendOption;
this._blendOption = this.blendOption;
if (blendOptionChanged) {
if (this._blendOption === BlendOption_default.OPAQUE || this._blendOption === BlendOption_default.OPAQUE_AND_TRANSLUCENT) {
this._rsOpaque = RenderState_default.fromCache({
depthTest: {
enabled: true,
func: WebGLConstants_default.LESS
},
depthMask: true
});
} else {
this._rsOpaque = void 0;
}
const useTranslucentDepthMask = this._blendOption === BlendOption_default.TRANSLUCENT;
if (this._blendOption === BlendOption_default.TRANSLUCENT || this._blendOption === BlendOption_default.OPAQUE_AND_TRANSLUCENT) {
this._rsTranslucent = RenderState_default.fromCache({
depthTest: {
enabled: true,
func: useTranslucentDepthMask ? WebGLConstants_default.LEQUAL : WebGLConstants_default.LESS
},
depthMask: useTranslucentDepthMask,
blending: BlendingState_default.ALPHA_BLEND
});
} else {
this._rsTranslucent = void 0;
}
}
this._shaderDisableDepthDistance = this._shaderDisableDepthDistance || frameState.minimumDisableDepthTestDistance !== 0;
let vsSource;
let fsSource;
let vs;
let fs;
let vertDefines;
const supportVSTextureReads = ContextLimits_default.maximumVertexTextureImageUnits > 0;
if (blendOptionChanged || this._shaderRotation !== this._compiledShaderRotation || this._shaderAlignedAxis !== this._compiledShaderAlignedAxis || this._shaderScaleByDistance !== this._compiledShaderScaleByDistance || this._shaderTranslucencyByDistance !== this._compiledShaderTranslucencyByDistance || this._shaderPixelOffsetScaleByDistance !== this._compiledShaderPixelOffsetScaleByDistance || this._shaderDistanceDisplayCondition !== this._compiledShaderDistanceDisplayCondition || this._shaderDisableDepthDistance !== this._compiledShaderDisableDepthDistance || this._shaderClampToGround !== this._compiledShaderClampToGround || this._sdf !== this._compiledSDF) {
vsSource = BillboardCollectionVS_default;
fsSource = BillboardCollectionFS_default;
vertDefines = [];
if (defined_default(this._batchTable)) {
vertDefines.push("VECTOR_TILE");
vsSource = this._batchTable.getVertexShaderCallback(
false,
"a_batchId",
void 0
)(vsSource);
fsSource = this._batchTable.getFragmentShaderCallback(
false,
void 0
)(fsSource);
}
vs = new ShaderSource_default({
defines: vertDefines,
sources: [vsSource]
});
if (this._instanced) {
vs.defines.push("INSTANCED");
}
if (this._shaderRotation) {
vs.defines.push("ROTATION");
}
if (this._shaderAlignedAxis) {
vs.defines.push("ALIGNED_AXIS");
}
if (this._shaderScaleByDistance) {
vs.defines.push("EYE_DISTANCE_SCALING");
}
if (this._shaderTranslucencyByDistance) {
vs.defines.push("EYE_DISTANCE_TRANSLUCENCY");
}
if (this._shaderPixelOffsetScaleByDistance) {
vs.defines.push("EYE_DISTANCE_PIXEL_OFFSET");
}
if (this._shaderDistanceDisplayCondition) {
vs.defines.push("DISTANCE_DISPLAY_CONDITION");
}
if (this._shaderDisableDepthDistance) {
vs.defines.push("DISABLE_DEPTH_DISTANCE");
}
if (this._shaderClampToGround) {
if (supportVSTextureReads) {
vs.defines.push("VERTEX_DEPTH_CHECK");
} else {
vs.defines.push("FRAGMENT_DEPTH_CHECK");
}
}
const sdfEdge = 1 - SDFSettings_default.CUTOFF;
if (this._sdf) {
vs.defines.push("SDF");
}
const vectorFragDefine = defined_default(this._batchTable) ? "VECTOR_TILE" : "";
if (this._blendOption === BlendOption_default.OPAQUE_AND_TRANSLUCENT) {
fs = new ShaderSource_default({
defines: ["OPAQUE", vectorFragDefine],
sources: [fsSource]
});
if (this._shaderClampToGround) {
if (supportVSTextureReads) {
fs.defines.push("VERTEX_DEPTH_CHECK");
} else {
fs.defines.push("FRAGMENT_DEPTH_CHECK");
}
}
if (this._sdf) {
fs.defines.push("SDF");
fs.defines.push(`SDF_EDGE ${sdfEdge}`);
}
this._sp = ShaderProgram_default.replaceCache({
context,
shaderProgram: this._sp,
vertexShaderSource: vs,
fragmentShaderSource: fs,
attributeLocations
});
fs = new ShaderSource_default({
defines: ["TRANSLUCENT", vectorFragDefine],
sources: [fsSource]
});
if (this._shaderClampToGround) {
if (supportVSTextureReads) {
fs.defines.push("VERTEX_DEPTH_CHECK");
} else {
fs.defines.push("FRAGMENT_DEPTH_CHECK");
}
}
if (this._sdf) {
fs.defines.push("SDF");
fs.defines.push(`SDF_EDGE ${sdfEdge}`);
}
this._spTranslucent = ShaderProgram_default.replaceCache({
context,
shaderProgram: this._spTranslucent,
vertexShaderSource: vs,
fragmentShaderSource: fs,
attributeLocations
});
}
if (this._blendOption === BlendOption_default.OPAQUE) {
fs = new ShaderSource_default({
defines: [vectorFragDefine],
sources: [fsSource]
});
if (this._shaderClampToGround) {
if (supportVSTextureReads) {
fs.defines.push("VERTEX_DEPTH_CHECK");
} else {
fs.defines.push("FRAGMENT_DEPTH_CHECK");
}
}
if (this._sdf) {
fs.defines.push("SDF");
fs.defines.push(`SDF_EDGE ${sdfEdge}`);
}
this._sp = ShaderProgram_default.replaceCache({
context,
shaderProgram: this._sp,
vertexShaderSource: vs,
fragmentShaderSource: fs,
attributeLocations
});
}
if (this._blendOption === BlendOption_default.TRANSLUCENT) {
fs = new ShaderSource_default({
defines: [vectorFragDefine],
sources: [fsSource]
});
if (this._shaderClampToGround) {
if (supportVSTextureReads) {
fs.defines.push("VERTEX_DEPTH_CHECK");
} else {
fs.defines.push("FRAGMENT_DEPTH_CHECK");
}
}
if (this._sdf) {
fs.defines.push("SDF");
fs.defines.push(`SDF_EDGE ${sdfEdge}`);
}
this._spTranslucent = ShaderProgram_default.replaceCache({
context,
shaderProgram: this._spTranslucent,
vertexShaderSource: vs,
fragmentShaderSource: fs,
attributeLocations
});
}
this._compiledShaderRotation = this._shaderRotation;
this._compiledShaderAlignedAxis = this._shaderAlignedAxis;
this._compiledShaderScaleByDistance = this._shaderScaleByDistance;
this._compiledShaderTranslucencyByDistance = this._shaderTranslucencyByDistance;
this._compiledShaderPixelOffsetScaleByDistance = this._shaderPixelOffsetScaleByDistance;
this._compiledShaderDistanceDisplayCondition = this._shaderDistanceDisplayCondition;
this._compiledShaderDisableDepthDistance = this._shaderDisableDepthDistance;
this._compiledShaderClampToGround = this._shaderClampToGround;
this._compiledSDF = this._sdf;
}
const commandList = frameState.commandList;
if (pass.render || pass.pick) {
const colorList = this._colorCommands;
const opaque = this._blendOption === BlendOption_default.OPAQUE;
const opaqueAndTranslucent = this._blendOption === BlendOption_default.OPAQUE_AND_TRANSLUCENT;
const va = this._vaf.va;
const vaLength = va.length;
let uniforms = this._uniforms;
let pickId;
if (defined_default(this._batchTable)) {
uniforms = this._batchTable.getUniformMapCallback()(uniforms);
pickId = this._batchTable.getPickId();
} else {
pickId = "v_pickColor";
}
colorList.length = vaLength;
const totalLength = opaqueAndTranslucent ? vaLength * 2 : vaLength;
for (let j = 0; j < totalLength; ++j) {
let command = colorList[j];
if (!defined_default(command)) {
command = colorList[j] = new DrawCommand_default();
}
const opaqueCommand = opaque || opaqueAndTranslucent && j % 2 === 0;
command.pass = opaqueCommand || !opaqueAndTranslucent ? Pass_default.OPAQUE : Pass_default.TRANSLUCENT;
command.owner = this;
const index = opaqueAndTranslucent ? Math.floor(j / 2) : j;
command.boundingVolume = boundingVolume;
command.modelMatrix = modelMatrix;
command.count = va[index].indicesCount;
command.shaderProgram = opaqueCommand ? this._sp : this._spTranslucent;
command.uniformMap = uniforms;
command.vertexArray = va[index].va;
command.renderState = opaqueCommand ? this._rsOpaque : this._rsTranslucent;
command.debugShowBoundingVolume = this.debugShowBoundingVolume;
command.pickId = pickId;
if (this._instanced) {
command.count = 6;
command.instanceCount = billboardsLength;
}
commandList.push(command);
}
if (this.debugShowTextureAtlas) {
if (!defined_default(this.debugCommand)) {
this.debugCommand = createDebugCommand(this, frameState.context);
}
commandList.push(this.debugCommand);
}
}
};
BillboardCollection.prototype.isDestroyed = function() {
return false;
};
BillboardCollection.prototype.destroy = function() {
if (defined_default(this._removeCallbackFunc)) {
this._removeCallbackFunc();
this._removeCallbackFunc = void 0;
}
this._textureAtlas = this._destroyTextureAtlas && this._textureAtlas && this._textureAtlas.destroy();
this._sp = this._sp && this._sp.destroy();
this._spTranslucent = this._spTranslucent && this._spTranslucent.destroy();
this._vaf = this._vaf && this._vaf.destroy();
destroyBillboards(this._billboards);
return destroyObject_default(this);
};
var BillboardCollection_default = BillboardCollection;
// packages/engine/Source/Scene/createBillboardPointCallback.js
function createBillboardPointCallback(centerAlpha, cssColor, cssOutlineColor, cssOutlineWidth, pixelSize) {
return function() {
const canvas = document.createElement("canvas");
const length3 = pixelSize + 2 * cssOutlineWidth;
canvas.height = canvas.width = length3;
const context2D = canvas.getContext("2d");
context2D.clearRect(0, 0, length3, length3);
if (cssOutlineWidth !== 0) {
context2D.beginPath();
context2D.arc(length3 / 2, length3 / 2, length3 / 2, 0, 2 * Math.PI, true);
context2D.closePath();
context2D.fillStyle = cssOutlineColor;
context2D.fill();
if (centerAlpha < 1) {
context2D.save();
context2D.globalCompositeOperation = "destination-out";
context2D.beginPath();
context2D.arc(
length3 / 2,
length3 / 2,
pixelSize / 2,
0,
2 * Math.PI,
true
);
context2D.closePath();
context2D.fillStyle = "black";
context2D.fill();
context2D.restore();
}
}
context2D.beginPath();
context2D.arc(length3 / 2, length3 / 2, pixelSize / 2, 0, 2 * Math.PI, true);
context2D.closePath();
context2D.fillStyle = cssColor;
context2D.fill();
return canvas;
};
}
var createBillboardPointCallback_default = createBillboardPointCallback;
// packages/engine/Source/Scene/Cesium3DTilePointFeature.js
function Cesium3DTilePointFeature(content, batchId, billboard, label, polyline) {
this._content = content;
this._billboard = billboard;
this._label = label;
this._polyline = polyline;
this._batchId = batchId;
this._billboardImage = void 0;
this._billboardColor = void 0;
this._billboardOutlineColor = void 0;
this._billboardOutlineWidth = void 0;
this._billboardSize = void 0;
this._pointSize = void 0;
this._color = void 0;
this._pointSize = void 0;
this._pointOutlineColor = void 0;
this._pointOutlineWidth = void 0;
this._heightOffset = void 0;
this._pickIds = new Array(3);
setBillboardImage(this);
}
var scratchCartographic5 = new Cartographic_default();
Object.defineProperties(Cesium3DTilePointFeature.prototype, {
/**
* Gets or sets if the feature will be shown. This is set for all features
* when a style's show is evaluated.
*
* @memberof Cesium3DTilePointFeature.prototype
*
* @type {boolean}
*
* @default true
*/
show: {
get: function() {
return this._label.show;
},
set: function(value) {
this._label.show = value;
this._billboard.show = value;
this._polyline.show = value;
}
},
/**
* Gets or sets the color of the point of this feature.
*
* Only applied when image
is undefined
.
*
* Only applied when image
is undefined
.
*
* Only applied when image
is undefined
.
*
* Only applied when image
is undefined
.
*
* The color will be applied to the label if labelText
is defined.
*
* The outline color will be applied to the label if labelText
is defined.
*
* The outline width will be applied to the point if labelText
is defined.
*
* Only applied when the labelText
is defined.
*
* Only applied when labelText
is defined.
*
* Only applied when labelText
is defined.
*
* Only applied when labelText
is defined.
*
* Only applied when labelText
is defined.
*
* Only applied when heightOffset
is defined.
*
* Only applied when heightOffset
is defined.
*
primitive
property. This returns
* the tileset containing the feature.
*
* @memberof Cesium3DTilePointFeature.prototype
*
* @type {Cesium3DTileset}
*
* @readonly
*/
primitive: {
get: function() {
return this._content.tileset;
}
},
/**
* @private
*/
pickIds: {
get: function() {
const ids = this._pickIds;
ids[0] = this._billboard.pickId;
ids[1] = this._label.pickId;
ids[2] = this._polyline.pickId;
return ids;
}
}
});
Cesium3DTilePointFeature.defaultColor = Color_default.WHITE;
Cesium3DTilePointFeature.defaultPointOutlineColor = Color_default.BLACK;
Cesium3DTilePointFeature.defaultPointOutlineWidth = 0;
Cesium3DTilePointFeature.defaultPointSize = 8;
function setBillboardImage(feature2) {
const b = feature2._billboard;
if (defined_default(feature2._billboardImage) && feature2._billboardImage !== b.image) {
b.image = feature2._billboardImage;
return;
}
if (defined_default(feature2._billboardImage)) {
return;
}
const newColor = defaultValue_default(
feature2._color,
Cesium3DTilePointFeature.defaultColor
);
const newOutlineColor = defaultValue_default(
feature2._pointOutlineColor,
Cesium3DTilePointFeature.defaultPointOutlineColor
);
const newOutlineWidth = defaultValue_default(
feature2._pointOutlineWidth,
Cesium3DTilePointFeature.defaultPointOutlineWidth
);
const newPointSize = defaultValue_default(
feature2._pointSize,
Cesium3DTilePointFeature.defaultPointSize
);
const currentColor = feature2._billboardColor;
const currentOutlineColor = feature2._billboardOutlineColor;
const currentOutlineWidth = feature2._billboardOutlineWidth;
const currentPointSize = feature2._billboardSize;
if (Color_default.equals(newColor, currentColor) && Color_default.equals(newOutlineColor, currentOutlineColor) && newOutlineWidth === currentOutlineWidth && newPointSize === currentPointSize) {
return;
}
feature2._billboardColor = Color_default.clone(newColor, feature2._billboardColor);
feature2._billboardOutlineColor = Color_default.clone(
newOutlineColor,
feature2._billboardOutlineColor
);
feature2._billboardOutlineWidth = newOutlineWidth;
feature2._billboardSize = newPointSize;
const centerAlpha = newColor.alpha;
const cssColor = newColor.toCssColorString();
const cssOutlineColor = newOutlineColor.toCssColorString();
const textureId = JSON.stringify([
cssColor,
newPointSize,
cssOutlineColor,
newOutlineWidth
]);
b.setImage(
textureId,
createBillboardPointCallback_default(
centerAlpha,
cssColor,
cssOutlineColor,
newOutlineWidth,
newPointSize
)
);
}
Cesium3DTilePointFeature.prototype.hasProperty = function(name) {
return this._content.batchTable.hasProperty(this._batchId, name);
};
Cesium3DTilePointFeature.prototype.getPropertyIds = function(results) {
return this._content.batchTable.getPropertyIds(this._batchId, results);
};
Cesium3DTilePointFeature.prototype.getProperty = function(name) {
return this._content.batchTable.getProperty(this._batchId, name);
};
Cesium3DTilePointFeature.prototype.getPropertyInherited = function(name) {
return Cesium3DTileFeature_default.getPropertyInherited(
this._content,
this._batchId,
name
);
};
Cesium3DTilePointFeature.prototype.setProperty = function(name, value) {
this._content.batchTable.setProperty(this._batchId, name, value);
this._content.featurePropertiesDirty = true;
};
Cesium3DTilePointFeature.prototype.isExactClass = function(className) {
return this._content.batchTable.isExactClass(this._batchId, className);
};
Cesium3DTilePointFeature.prototype.isClass = function(className) {
return this._content.batchTable.isClass(this._batchId, className);
};
Cesium3DTilePointFeature.prototype.getExactClassName = function() {
return this._content.batchTable.getExactClassName(this._batchId);
};
var Cesium3DTilePointFeature_default = Cesium3DTilePointFeature;
// packages/engine/Source/Core/writeTextToCanvas.js
function measureText(context2D, textString, font, stroke, fill) {
const metrics = context2D.measureText(textString);
const isSpace = !/\S/.test(textString);
if (!isSpace) {
const fontSize = document.defaultView.getComputedStyle(context2D.canvas).getPropertyValue("font-size").replace("px", "");
const canvas = document.createElement("canvas");
const padding = 100;
const width = metrics.width + padding | 0;
const height = 3 * fontSize;
const baseline = height / 2;
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext("2d");
ctx.font = font;
ctx.fillStyle = "white";
ctx.fillRect(0, 0, canvas.width + 1, canvas.height + 1);
if (stroke) {
ctx.strokeStyle = "black";
ctx.lineWidth = context2D.lineWidth;
ctx.strokeText(textString, padding / 2, baseline);
}
if (fill) {
ctx.fillStyle = "black";
ctx.fillText(textString, padding / 2, baseline);
}
const pixelData = ctx.getImageData(0, 0, width, height).data;
const length3 = pixelData.length;
const width4 = width * 4;
let i, j;
let ascent, descent;
for (i = 0; i < length3; ++i) {
if (pixelData[i] !== 255) {
ascent = i / width4 | 0;
break;
}
}
for (i = length3 - 1; i >= 0; --i) {
if (pixelData[i] !== 255) {
descent = i / width4 | 0;
break;
}
}
let minx = -1;
for (i = 0; i < width && minx === -1; ++i) {
for (j = 0; j < height; ++j) {
const pixelIndex = i * 4 + j * width4;
if (pixelData[pixelIndex] !== 255 || pixelData[pixelIndex + 1] !== 255 || pixelData[pixelIndex + 2] !== 255 || pixelData[pixelIndex + 3] !== 255) {
minx = i;
break;
}
}
}
return {
width: metrics.width,
height: descent - ascent,
ascent: baseline - ascent,
descent: descent - baseline,
minx: minx - padding / 2
};
}
return {
width: metrics.width,
height: 0,
ascent: 0,
descent: 0,
minx: 0
};
}
var imageSmoothingEnabledName;
function writeTextToCanvas(text, options) {
if (!defined_default(text)) {
throw new DeveloperError_default("text is required.");
}
if (text === "") {
return void 0;
}
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const font = defaultValue_default(options.font, "10px sans-serif");
const stroke = defaultValue_default(options.stroke, false);
const fill = defaultValue_default(options.fill, true);
const strokeWidth = defaultValue_default(options.strokeWidth, 1);
const backgroundColor = defaultValue_default(
options.backgroundColor,
Color_default.TRANSPARENT
);
const padding = defaultValue_default(options.padding, 0);
const doublePadding = padding * 2;
const canvas = document.createElement("canvas");
canvas.width = 1;
canvas.height = 1;
canvas.style.font = font;
const context2D = canvas.getContext("2d", { willReadFrequently: true });
if (!defined_default(imageSmoothingEnabledName)) {
if (defined_default(context2D.imageSmoothingEnabled)) {
imageSmoothingEnabledName = "imageSmoothingEnabled";
} else if (defined_default(context2D.mozImageSmoothingEnabled)) {
imageSmoothingEnabledName = "mozImageSmoothingEnabled";
} else if (defined_default(context2D.webkitImageSmoothingEnabled)) {
imageSmoothingEnabledName = "webkitImageSmoothingEnabled";
} else if (defined_default(context2D.msImageSmoothingEnabled)) {
imageSmoothingEnabledName = "msImageSmoothingEnabled";
}
}
context2D.font = font;
context2D.lineJoin = "round";
context2D.lineWidth = strokeWidth;
context2D[imageSmoothingEnabledName] = false;
canvas.style.visibility = "hidden";
document.body.appendChild(canvas);
const dimensions = measureText(context2D, text, font, stroke, fill);
canvas.dimensions = dimensions;
document.body.removeChild(canvas);
canvas.style.visibility = "";
const x = -dimensions.minx;
const width = Math.ceil(dimensions.width) + x + doublePadding;
const height = dimensions.height + doublePadding;
const baseline = height - dimensions.ascent + padding;
const y = height - baseline + doublePadding;
canvas.width = width;
canvas.height = height;
context2D.font = font;
context2D.lineJoin = "round";
context2D.lineWidth = strokeWidth;
context2D[imageSmoothingEnabledName] = false;
if (backgroundColor !== Color_default.TRANSPARENT) {
context2D.fillStyle = backgroundColor.toCssColorString();
context2D.fillRect(0, 0, canvas.width, canvas.height);
}
if (stroke) {
const strokeColor = defaultValue_default(options.strokeColor, Color_default.BLACK);
context2D.strokeStyle = strokeColor.toCssColorString();
context2D.strokeText(text, x + padding, y);
}
if (fill) {
const fillColor = defaultValue_default(options.fillColor, Color_default.WHITE);
context2D.fillStyle = fillColor.toCssColorString();
context2D.fillText(text, x + padding, y);
}
return canvas;
}
var writeTextToCanvas_default = writeTextToCanvas;
// packages/engine/Source/Scene/LabelCollection.js
var import_bitmap_sdf = __toESM(require_bitmap_sdf(), 1);
// packages/engine/Source/Scene/LabelStyle.js
var LabelStyle = {
/**
* Fill the text of the label, but do not outline.
*
* @type {number}
* @constant
*/
FILL: 0,
/**
* Outline the text of the label, but do not fill.
*
* @type {number}
* @constant
*/
OUTLINE: 1,
/**
* Fill and outline the text of the label.
*
* @type {number}
* @constant
*/
FILL_AND_OUTLINE: 2
};
var LabelStyle_default = Object.freeze(LabelStyle);
// packages/engine/Source/Scene/Label.js
var fontInfoCache = {};
var fontInfoCacheLength = 0;
var fontInfoCacheMaxSize = 256;
var defaultBackgroundColor = new Color_default(0.165, 0.165, 0.165, 0.8);
var defaultBackgroundPadding = new Cartesian2_default(7, 5);
var textTypes = Object.freeze({
LTR: 0,
RTL: 1,
WEAK: 2,
BRACKETS: 3
});
function rebindAllGlyphs(label) {
if (!label._rebindAllGlyphs && !label._repositionAllGlyphs) {
label._labelCollection._labelsToUpdate.push(label);
}
label._rebindAllGlyphs = true;
}
function repositionAllGlyphs(label) {
if (!label._rebindAllGlyphs && !label._repositionAllGlyphs) {
label._labelCollection._labelsToUpdate.push(label);
}
label._repositionAllGlyphs = true;
}
function getCSSValue(element, property) {
return document.defaultView.getComputedStyle(element, null).getPropertyValue(property);
}
function parseFont(label) {
let fontInfo = fontInfoCache[label._font];
if (!defined_default(fontInfo)) {
const div = document.createElement("div");
div.style.position = "absolute";
div.style.opacity = 0;
div.style.font = label._font;
document.body.appendChild(div);
let lineHeight = parseFloat(getCSSValue(div, "line-height"));
if (isNaN(lineHeight)) {
lineHeight = void 0;
}
fontInfo = {
family: getCSSValue(div, "font-family"),
size: getCSSValue(div, "font-size").replace("px", ""),
style: getCSSValue(div, "font-style"),
weight: getCSSValue(div, "font-weight"),
lineHeight
};
document.body.removeChild(div);
if (fontInfoCacheLength < fontInfoCacheMaxSize) {
fontInfoCache[label._font] = fontInfo;
fontInfoCacheLength++;
}
}
label._fontFamily = fontInfo.family;
label._fontSize = fontInfo.size;
label._fontStyle = fontInfo.style;
label._fontWeight = fontInfo.weight;
label._lineHeight = fontInfo.lineHeight;
}
function Label(options, labelCollection) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
if (defined_default(options.disableDepthTestDistance) && options.disableDepthTestDistance < 0) {
throw new DeveloperError_default(
"disableDepthTestDistance must be greater than 0.0."
);
}
let translucencyByDistance = options.translucencyByDistance;
let pixelOffsetScaleByDistance = options.pixelOffsetScaleByDistance;
let scaleByDistance = options.scaleByDistance;
let distanceDisplayCondition = options.distanceDisplayCondition;
if (defined_default(translucencyByDistance)) {
if (translucencyByDistance.far <= translucencyByDistance.near) {
throw new DeveloperError_default(
"translucencyByDistance.far must be greater than translucencyByDistance.near."
);
}
translucencyByDistance = NearFarScalar_default.clone(translucencyByDistance);
}
if (defined_default(pixelOffsetScaleByDistance)) {
if (pixelOffsetScaleByDistance.far <= pixelOffsetScaleByDistance.near) {
throw new DeveloperError_default(
"pixelOffsetScaleByDistance.far must be greater than pixelOffsetScaleByDistance.near."
);
}
pixelOffsetScaleByDistance = NearFarScalar_default.clone(
pixelOffsetScaleByDistance
);
}
if (defined_default(scaleByDistance)) {
if (scaleByDistance.far <= scaleByDistance.near) {
throw new DeveloperError_default(
"scaleByDistance.far must be greater than scaleByDistance.near."
);
}
scaleByDistance = NearFarScalar_default.clone(scaleByDistance);
}
if (defined_default(distanceDisplayCondition)) {
if (distanceDisplayCondition.far <= distanceDisplayCondition.near) {
throw new DeveloperError_default(
"distanceDisplayCondition.far must be greater than distanceDisplayCondition.near."
);
}
distanceDisplayCondition = DistanceDisplayCondition_default.clone(
distanceDisplayCondition
);
}
this._renderedText = void 0;
this._text = void 0;
this._show = defaultValue_default(options.show, true);
this._font = defaultValue_default(options.font, "30px sans-serif");
this._fillColor = Color_default.clone(defaultValue_default(options.fillColor, Color_default.WHITE));
this._outlineColor = Color_default.clone(
defaultValue_default(options.outlineColor, Color_default.BLACK)
);
this._outlineWidth = defaultValue_default(options.outlineWidth, 1);
this._showBackground = defaultValue_default(options.showBackground, false);
this._backgroundColor = Color_default.clone(
defaultValue_default(options.backgroundColor, defaultBackgroundColor)
);
this._backgroundPadding = Cartesian2_default.clone(
defaultValue_default(options.backgroundPadding, defaultBackgroundPadding)
);
this._style = defaultValue_default(options.style, LabelStyle_default.FILL);
this._verticalOrigin = defaultValue_default(
options.verticalOrigin,
VerticalOrigin_default.BASELINE
);
this._horizontalOrigin = defaultValue_default(
options.horizontalOrigin,
HorizontalOrigin_default.LEFT
);
this._pixelOffset = Cartesian2_default.clone(
defaultValue_default(options.pixelOffset, Cartesian2_default.ZERO)
);
this._eyeOffset = Cartesian3_default.clone(
defaultValue_default(options.eyeOffset, Cartesian3_default.ZERO)
);
this._position = Cartesian3_default.clone(
defaultValue_default(options.position, Cartesian3_default.ZERO)
);
this._scale = defaultValue_default(options.scale, 1);
this._id = options.id;
this._translucencyByDistance = translucencyByDistance;
this._pixelOffsetScaleByDistance = pixelOffsetScaleByDistance;
this._scaleByDistance = scaleByDistance;
this._heightReference = defaultValue_default(
options.heightReference,
HeightReference_default.NONE
);
this._distanceDisplayCondition = distanceDisplayCondition;
this._disableDepthTestDistance = options.disableDepthTestDistance;
this._labelCollection = labelCollection;
this._glyphs = [];
this._backgroundBillboard = void 0;
this._batchIndex = void 0;
this._rebindAllGlyphs = true;
this._repositionAllGlyphs = true;
this._actualClampedPosition = void 0;
this._removeCallbackFunc = void 0;
this._mode = void 0;
this._clusterShow = true;
this.text = defaultValue_default(options.text, "");
this._relativeSize = 1;
parseFont(this);
this._updateClamping();
}
Object.defineProperties(Label.prototype, {
/**
* Determines if this label will be shown. Use this to hide or show a label, instead
* of removing it and re-adding it to the collection.
* @memberof Label.prototype
* @type {boolean}
* @default true
*/
show: {
get: function() {
return this._show;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
if (this._show !== value) {
this._show = value;
const glyphs = this._glyphs;
for (let i = 0, len = glyphs.length; i < len; i++) {
const billboard = glyphs[i].billboard;
if (defined_default(billboard)) {
billboard.show = value;
}
}
const backgroundBillboard = this._backgroundBillboard;
if (defined_default(backgroundBillboard)) {
backgroundBillboard.show = value;
}
}
}
},
/**
* Gets or sets the Cartesian position of this label.
* @memberof Label.prototype
* @type {Cartesian3}
*/
position: {
get: function() {
return this._position;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
const position = this._position;
if (!Cartesian3_default.equals(position, value)) {
Cartesian3_default.clone(value, position);
const glyphs = this._glyphs;
for (let i = 0, len = glyphs.length; i < len; i++) {
const billboard = glyphs[i].billboard;
if (defined_default(billboard)) {
billboard.position = value;
}
}
const backgroundBillboard = this._backgroundBillboard;
if (defined_default(backgroundBillboard)) {
backgroundBillboard.position = value;
}
this._updateClamping();
}
}
},
/**
* Gets or sets the height reference of this billboard.
* @memberof Label.prototype
* @type {HeightReference}
* @default HeightReference.NONE
*/
heightReference: {
get: function() {
return this._heightReference;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
if (value !== this._heightReference) {
this._heightReference = value;
const glyphs = this._glyphs;
for (let i = 0, len = glyphs.length; i < len; i++) {
const billboard = glyphs[i].billboard;
if (defined_default(billboard)) {
billboard.heightReference = value;
}
}
const backgroundBillboard = this._backgroundBillboard;
if (defined_default(backgroundBillboard)) {
backgroundBillboard.heightReference = value;
}
repositionAllGlyphs(this);
this._updateClamping();
}
}
},
/**
* Gets or sets the text of this label.
* @memberof Label.prototype
* @type {string}
*/
text: {
get: function() {
return this._text;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
if (this._text !== value) {
this._text = value;
const renderedValue = value.replace(/\u00ad/g, "");
this._renderedText = Label.enableRightToLeftDetection ? reverseRtl(renderedValue) : renderedValue;
rebindAllGlyphs(this);
}
}
},
/**
* Gets or sets the font used to draw this label. Fonts are specified using the same syntax as the CSS 'font' property.
* @memberof Label.prototype
* @type {string}
* @default '30px sans-serif'
* @see {@link http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#text-styles|HTML canvas 2D context text styles}
*/
font: {
get: function() {
return this._font;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
if (this._font !== value) {
this._font = value;
rebindAllGlyphs(this);
parseFont(this);
}
}
},
/**
* Gets or sets the fill color of this label.
* @memberof Label.prototype
* @type {Color}
* @default Color.WHITE
* @see {@link http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#fill-and-stroke-styles|HTML canvas 2D context fill and stroke styles}
*/
fillColor: {
get: function() {
return this._fillColor;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
const fillColor = this._fillColor;
if (!Color_default.equals(fillColor, value)) {
Color_default.clone(value, fillColor);
rebindAllGlyphs(this);
}
}
},
/**
* Gets or sets the outline color of this label.
* @memberof Label.prototype
* @type {Color}
* @default Color.BLACK
* @see {@link http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#fill-and-stroke-styles|HTML canvas 2D context fill and stroke styles}
*/
outlineColor: {
get: function() {
return this._outlineColor;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
const outlineColor = this._outlineColor;
if (!Color_default.equals(outlineColor, value)) {
Color_default.clone(value, outlineColor);
rebindAllGlyphs(this);
}
}
},
/**
* Gets or sets the outline width of this label.
* @memberof Label.prototype
* @type {number}
* @default 1.0
* @see {@link http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#fill-and-stroke-styles|HTML canvas 2D context fill and stroke styles}
*/
outlineWidth: {
get: function() {
return this._outlineWidth;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
if (this._outlineWidth !== value) {
this._outlineWidth = value;
rebindAllGlyphs(this);
}
}
},
/**
* Determines if a background behind this label will be shown.
* @memberof Label.prototype
* @default false
* @type {boolean}
*/
showBackground: {
get: function() {
return this._showBackground;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
if (this._showBackground !== value) {
this._showBackground = value;
rebindAllGlyphs(this);
}
}
},
/**
* Gets or sets the background color of this label.
* @memberof Label.prototype
* @type {Color}
* @default new Color(0.165, 0.165, 0.165, 0.8)
*/
backgroundColor: {
get: function() {
return this._backgroundColor;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
const backgroundColor = this._backgroundColor;
if (!Color_default.equals(backgroundColor, value)) {
Color_default.clone(value, backgroundColor);
const backgroundBillboard = this._backgroundBillboard;
if (defined_default(backgroundBillboard)) {
backgroundBillboard.color = backgroundColor;
}
}
}
},
/**
* Gets or sets the background padding, in pixels, of this label. The x
value
* controls horizontal padding, and the y
value controls vertical padding.
* @memberof Label.prototype
* @type {Cartesian2}
* @default new Cartesian2(7, 5)
*/
backgroundPadding: {
get: function() {
return this._backgroundPadding;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
const backgroundPadding = this._backgroundPadding;
if (!Cartesian2_default.equals(backgroundPadding, value)) {
Cartesian2_default.clone(value, backgroundPadding);
repositionAllGlyphs(this);
}
}
},
/**
* Gets or sets the style of this label.
* @memberof Label.prototype
* @type {LabelStyle}
* @default LabelStyle.FILL
*/
style: {
get: function() {
return this._style;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
if (this._style !== value) {
this._style = value;
rebindAllGlyphs(this);
}
}
},
/**
* Gets or sets the pixel offset in screen space from the origin of this label. This is commonly used
* to align multiple labels and billboards at the same position, e.g., an image and text. The
* screen space origin is the top, left corner of the canvas; x
increases from
* left to right, and y
increases from top to bottom.
* default ![]() |
* l.pixeloffset = new Cartesian2(25, 75); ![]() |
*
x
points towards the viewer's right, y
points up, and
* z
points into the screen. Eye coordinates use the same scale as world and model coordinates,
* which is typically meters.
* ![]() |
* ![]() |
*
l.eyeOffset = new Cartesian3(0.0, 8000000.0, 0.0);
1.0
does not change the size of the label; a scale greater than
* 1.0
enlarges the label; a positive scale less than 1.0
shrinks
* the label.
* 0.5
, 1.0
,
* and 2.0
.
* b3dm
*
* @type {string}
* @constant
* @private
*/
BATCHED_3D_MODEL: "b3dm",
/**
* An Instanced 3D Model. This is a binary format with magic number
* i3dm
*
* @type {string}
* @constant
* @private
*/
INSTANCED_3D_MODEL: "i3dm",
/**
* A Composite model. This is a binary format with magic number
* cmpt
*
* @type {string}
* @constant
* @private
*/
COMPOSITE: "cmpt",
/**
* A Point Cloud model. This is a binary format with magic number
* pnts
*
* @type {string}
* @constant
* @private
*/
POINT_CLOUD: "pnts",
/**
* Vector tiles. This is a binary format with magic number
* vctr
*
* @type {string}
* @constant
* @private
*/
VECTOR: "vctr",
/**
* Geometry tiles. This is a binary format with magic number
* geom
*
* @type {string}
* @constant
* @private
*/
GEOMETRY: "geom",
/**
* A glTF model in JSON + external BIN form. This is treated
* as a JSON format.
*
* @type {string}
* @constant
* @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.
*/
GLTF: "gltf",
/**
* The binary form of a glTF file. Internally, the magic number is
* changed from glTF
to glb
to distinguish it from
* the JSON glTF format.
*
* @type {string}
* @constant
* @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.
*/
GLTF_BINARY: "glb",
/**
* For implicit tiling, availability bitstreams are stored in binary subtree files.
* The magic number is subt
*
* @type {string}
* @constant
* @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.
*/
IMPLICIT_SUBTREE: "subt",
/**
* For implicit tiling. Subtrees can also be represented as JSON files.
*
* @type {string}
* @constant
* @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.
*/
IMPLICIT_SUBTREE_JSON: "subtreeJson",
/**
* Contents can reference another tileset.json to use
* as an external tileset. This is a JSON-based format.
*
* @type {string}
* @constant
* @private
*/
EXTERNAL_TILESET: "externalTileset",
/**
* Multiple contents are handled separately from the other content types
* due to differences in request scheduling.
*
* @type {string}
* @constant
* @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.
*/
MULTIPLE_CONTENT: "multipleContent",
/**
* GeoJSON content for MAXAR_content_geojson
extension.
*
* @type {string}
* @constant
* @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.
*/
GEOJSON: "geoJson",
/**
* Binary voxel content for 3DTILES_content_voxels
extension.
*
* @type {string}
* @constant
* @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.
*/
VOXEL_BINARY: "voxl",
/**
* Binary voxel content for 3DTILES_content_voxels
extension.
*
* @type {string}
* @constant
* @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.
*/
VOXEL_JSON: "voxelJson"
};
Cesium3DTileContentType.isBinaryFormat = function(contentType) {
switch (contentType) {
case Cesium3DTileContentType.BATCHED_3D_MODEL:
case Cesium3DTileContentType.INSTANCED_3D_MODEL:
case Cesium3DTileContentType.COMPOSITE:
case Cesium3DTileContentType.POINT_CLOUD:
case Cesium3DTileContentType.VECTOR:
case Cesium3DTileContentType.GEOMETRY:
case Cesium3DTileContentType.IMPLICIT_SUBTREE:
case Cesium3DTileContentType.VOXEL_BINARY:
case Cesium3DTileContentType.GLTF_BINARY:
return true;
default:
return false;
}
};
var Cesium3DTileContentType_default = Object.freeze(Cesium3DTileContentType);
// packages/engine/Source/Scene/Cesium3DTileOptimizationHint.js
var Cesium3DTileOptimizationHint = {
NOT_COMPUTED: -1,
USE_OPTIMIZATION: 1,
SKIP_OPTIMIZATION: 0
};
var Cesium3DTileOptimizationHint_default = Object.freeze(Cesium3DTileOptimizationHint);
// packages/engine/Source/Scene/Cesium3DTilePass.js
var Cesium3DTilePass = {
RENDER: 0,
PICK: 1,
SHADOW: 2,
PRELOAD: 3,
PRELOAD_FLIGHT: 4,
REQUEST_RENDER_MODE_DEFER_CHECK: 5,
MOST_DETAILED_PRELOAD: 6,
MOST_DETAILED_PICK: 7,
NUMBER_OF_PASSES: 8
};
var passOptions = new Array(Cesium3DTilePass.NUMBER_OF_PASSES);
passOptions[Cesium3DTilePass.RENDER] = Object.freeze({
pass: Cesium3DTilePass.RENDER,
isRender: true,
requestTiles: true,
ignoreCommands: false
});
passOptions[Cesium3DTilePass.PICK] = Object.freeze({
pass: Cesium3DTilePass.PICK,
isRender: false,
requestTiles: false,
ignoreCommands: false
});
passOptions[Cesium3DTilePass.SHADOW] = Object.freeze({
pass: Cesium3DTilePass.SHADOW,
isRender: false,
requestTiles: true,
ignoreCommands: false
});
passOptions[Cesium3DTilePass.PRELOAD] = Object.freeze({
pass: Cesium3DTilePass.SHADOW,
isRender: false,
requestTiles: true,
ignoreCommands: true
});
passOptions[Cesium3DTilePass.PRELOAD_FLIGHT] = Object.freeze({
pass: Cesium3DTilePass.PRELOAD_FLIGHT,
isRender: false,
requestTiles: true,
ignoreCommands: true
});
passOptions[Cesium3DTilePass.REQUEST_RENDER_MODE_DEFER_CHECK] = Object.freeze({
pass: Cesium3DTilePass.REQUEST_RENDER_MODE_DEFER_CHECK,
isRender: false,
requestTiles: true,
ignoreCommands: true
});
passOptions[Cesium3DTilePass.MOST_DETAILED_PRELOAD] = Object.freeze({
pass: Cesium3DTilePass.MOST_DETAILED_PRELOAD,
isRender: false,
requestTiles: true,
ignoreCommands: true
});
passOptions[Cesium3DTilePass.MOST_DETAILED_PICK] = Object.freeze({
pass: Cesium3DTilePass.MOST_DETAILED_PICK,
isRender: false,
requestTiles: false,
ignoreCommands: false
});
Cesium3DTilePass.getPassOptions = function(pass) {
return passOptions[pass];
};
var Cesium3DTilePass_default = Object.freeze(Cesium3DTilePass);
// packages/engine/Source/Scene/Empty3DTileContent.js
function Empty3DTileContent(tileset, tile) {
this._tileset = tileset;
this._tile = tile;
this.featurePropertiesDirty = false;
}
Object.defineProperties(Empty3DTileContent.prototype, {
featuresLength: {
get: function() {
return 0;
}
},
pointsLength: {
get: function() {
return 0;
}
},
trianglesLength: {
get: function() {
return 0;
}
},
geometryByteLength: {
get: function() {
return 0;
}
},
texturesByteLength: {
get: function() {
return 0;
}
},
batchTableByteLength: {
get: function() {
return 0;
}
},
innerContents: {
get: function() {
return void 0;
}
},
/**
* Returns true when the tile's content is ready to render; otherwise false
*
* @memberof Empty3DTileContent.prototype
*
* @type {boolean}
* @readonly
* @private
*/
ready: {
get: function() {
return true;
}
},
/**
* Gets the promise that will be resolved when the tile's content is ready to render.
*
* @memberof Empty3DTileContent.prototype
*
* @type {PromiseMultiple3DTileContent
checks if any of the inner contents have dirty featurePropertiesDirty.
* @memberof Multiple3DTileContent.prototype
*
* @type {boolean}
*
* @private
*/
featurePropertiesDirty: {
get: function() {
const contents = this._contents;
const length3 = contents.length;
for (let i = 0; i < length3; ++i) {
if (contents[i].featurePropertiesDirty) {
return true;
}
}
return false;
},
set: function(value) {
const contents = this._contents;
const length3 = contents.length;
for (let i = 0; i < length3; ++i) {
contents[i].featurePropertiesDirty = value;
}
}
},
/**
* Part of the {@link Cesium3DTileContent} interface. Multiple3DTileContent
* always returns 0
. Instead call featuresLength
for a specific inner content.
*
* @memberof Multiple3DTileContent.prototype
*
* @type {number}
* @readonly
*
* @private
*/
featuresLength: {
get: function() {
return 0;
}
},
/**
* Part of the {@link Cesium3DTileContent} interface. Multiple3DTileContent
* always returns 0
. Instead, call pointsLength
for a specific inner content.
*
* @memberof Multiple3DTileContent.prototype
*
* @type {number}
* @readonly
*
* @private
*/
pointsLength: {
get: function() {
return 0;
}
},
/**
* Part of the {@link Cesium3DTileContent} interface. Multiple3DTileContent
* always returns 0
. Instead call trianglesLength
for a specific inner content.
*
* @memberof Multiple3DTileContent.prototype
*
* @type {number}
* @readonly
*
* @private
*/
trianglesLength: {
get: function() {
return 0;
}
},
/**
* Part of the {@link Cesium3DTileContent} interface. Multiple3DTileContent
* always returns 0
. Instead call geometryByteLength
for a specific inner content.
*
* @memberof Multiple3DTileContent.prototype
*
* @type {number}
* @readonly
*
* @private
*/
geometryByteLength: {
get: function() {
return 0;
}
},
/**
* Part of the {@link Cesium3DTileContent} interface. Multiple3DTileContent
* always returns 0
. Instead call texturesByteLength
for a specific inner content.
*
* @memberof Multiple3DTileContent.prototype
*
* @type {number}
* @readonly
*
* @private
*/
texturesByteLength: {
get: function() {
return 0;
}
},
/**
* Part of the {@link Cesium3DTileContent} interface. Multiple3DTileContent
* always returns 0
. Instead call batchTableByteLength
for a specific inner content.
*
* @memberof Multiple3DTileContent.prototype
*
* @type {number}
* @readonly
*
* @private
*/
batchTableByteLength: {
get: function() {
return 0;
}
},
innerContents: {
get: function() {
return this._contents;
}
},
/**
* Returns true when the tile's content is ready to render; otherwise false
*
* @memberof Multiple3DTileContent.prototype
*
* @type {boolean}
* @readonly
* @private
*/
ready: {
get: function() {
if (!this._contentsCreated) {
return false;
}
return this._ready;
}
},
/**
* Gets the promise that will be resolved when the tile's content is ready to render.
*
* @memberof Multiple3DTileContent.prototype
*
* @type {PromiseMultiple3DTileContent
does not
* have a single URL, so this returns undefined.
* @memberof Multiple3DTileContent.prototype
*
* @type {string}
* @readonly
* @private
*/
url: {
get: function() {
return void 0;
}
},
/**
* Part of the {@link Cesium3DTileContent} interface. Multiple3DTileContent
* always returns undefined
. Instead call metadata
for a specific inner content.
* @memberof Multiple3DTileContent.prototype
* @private
*/
metadata: {
get: function() {
return void 0;
},
set: function() {
throw new DeveloperError_default("Multiple3DTileContent cannot have metadata");
}
},
/**
* Part of the {@link Cesium3DTileContent} interface. Multiple3DTileContent
* always returns undefined
. Instead call batchTable
for a specific inner content.
* @memberof Multiple3DTileContent.prototype
* @private
*/
batchTable: {
get: function() {
return void 0;
}
},
/**
* Part of the {@link Cesium3DTileContent} interface. Multiple3DTileContent
* always returns undefined
. Instead call group
for a specific inner content.
* @memberof Multiple3DTileContent.prototype
* @private
*/
group: {
get: function() {
return void 0;
},
set: function() {
throw new DeveloperError_default(
"Multiple3DTileContent cannot have group metadata"
);
}
},
/**
* Get an array of the inner content URLs, regardless of whether they've
* been fetched or not. This is intended for use with
* {@link Cesium3DTileset#debugShowUrl}.
* @memberof Multiple3DTileContent.prototype
*
* @type {string[]}
* @readonly
* @private
*/
innerContentUrls: {
get: function() {
return this._innerContentHeaders.map(function(contentHeader) {
return contentHeader.uri;
});
}
}
});
function updatePendingRequests(multipleContents, deltaRequestCount) {
multipleContents._requestsInFlight += deltaRequestCount;
multipleContents.tileset.statistics.numberOfPendingRequests += deltaRequestCount;
}
function cancelPendingRequests(multipleContents, originalContentState) {
multipleContents._cancelCount++;
multipleContents._tile._contentState = originalContentState;
const statistics2 = multipleContents.tileset.statistics;
statistics2.numberOfPendingRequests -= multipleContents._requestsInFlight;
statistics2.numberOfAttemptedRequests += multipleContents._requestsInFlight;
multipleContents._requestsInFlight = 0;
const contentCount = multipleContents._innerContentHeaders.length;
multipleContents._arrayFetchPromises = new Array(contentCount);
}
Multiple3DTileContent.prototype.requestInnerContents = function() {
if (!canScheduleAllRequests(this._serverKeys)) {
this.tileset.statistics.numberOfAttemptedRequests += this._serverKeys.length;
return;
}
const contentHeaders = this._innerContentHeaders;
updatePendingRequests(this, contentHeaders.length);
const originalCancelCount = this._cancelCount;
for (let i = 0; i < contentHeaders.length; i++) {
this._arrayFetchPromises[i] = requestInnerContent(
this,
i,
originalCancelCount,
this._tile._contentState
);
}
return createInnerContents(this);
};
function canScheduleAllRequests(serverKeys) {
const requestCountsByServer = {};
for (let i = 0; i < serverKeys.length; i++) {
const serverKey = serverKeys[i];
if (defined_default(requestCountsByServer[serverKey])) {
requestCountsByServer[serverKey]++;
} else {
requestCountsByServer[serverKey] = 1;
}
}
for (const key in requestCountsByServer) {
if (requestCountsByServer.hasOwnProperty(key) && !RequestScheduler_default.serverHasOpenSlots(key, requestCountsByServer[key])) {
return false;
}
}
return RequestScheduler_default.heapHasOpenSlots(serverKeys.length);
}
function requestInnerContent(multipleContents, index, originalCancelCount, originalContentState) {
const contentResource = multipleContents._innerContentResources[index].clone();
const tile = multipleContents.tile;
const priorityFunction = function() {
return tile._priority;
};
const serverKey = multipleContents._serverKeys[index];
const request = new Request_default({
throttle: true,
throttleByServer: true,
type: RequestType_default.TILES3D,
priorityFunction,
serverKey
});
contentResource.request = request;
multipleContents._requests[index] = request;
const promise = contentResource.fetchArrayBuffer();
if (!defined_default(promise)) {
return;
}
return promise.then(function(arrayBuffer) {
if (originalCancelCount < multipleContents._cancelCount) {
return;
}
if (contentResource.request.cancelled || contentResource.request.state === RequestState_default.CANCELLED) {
cancelPendingRequests(multipleContents, originalContentState);
return;
}
updatePendingRequests(multipleContents, -1);
return arrayBuffer;
}).catch(function(error) {
if (originalCancelCount < multipleContents._cancelCount) {
return;
}
if (contentResource.request.cancelled || contentResource.request.state === RequestState_default.CANCELLED) {
cancelPendingRequests(multipleContents, originalContentState);
return;
}
updatePendingRequests(multipleContents, -1);
handleInnerContentFailed(multipleContents, index, error);
});
}
async function createInnerContents(multipleContents) {
const originalCancelCount = multipleContents._cancelCount;
const arrayBuffers = await Promise.all(multipleContents._arrayFetchPromises);
if (originalCancelCount < multipleContents._cancelCount) {
return;
}
const promises = arrayBuffers.map(
(arrayBuffer, i) => createInnerContent(multipleContents, arrayBuffer, i)
);
const contents = await Promise.all(promises);
multipleContents._contentsCreated = true;
multipleContents._contents = contents.filter(defined_default);
return contents;
}
async function createInnerContent(multipleContents, arrayBuffer, index) {
if (!defined_default(arrayBuffer)) {
return;
}
try {
const preprocessed = preprocess3DTileContent_default(arrayBuffer);
if (preprocessed.contentType === Cesium3DTileContentType_default.EXTERNAL_TILESET) {
throw new RuntimeError_default(
"External tilesets are disallowed inside multiple contents"
);
}
multipleContents._disableSkipLevelOfDetail = multipleContents._disableSkipLevelOfDetail || preprocessed.contentType === Cesium3DTileContentType_default.GEOMETRY || preprocessed.contentType === Cesium3DTileContentType_default.VECTOR;
const tileset = multipleContents._tileset;
const resource = multipleContents._innerContentResources[index];
const tile = multipleContents._tile;
let content;
const contentFactory = Cesium3DTileContentFactory_default[preprocessed.contentType];
if (defined_default(preprocessed.binaryPayload)) {
content = await Promise.resolve(
contentFactory(
tileset,
tile,
resource,
preprocessed.binaryPayload.buffer,
0
)
);
} else {
content = await Promise.resolve(
contentFactory(tileset, tile, resource, preprocessed.jsonPayload)
);
}
const contentHeader = multipleContents._innerContentHeaders[index];
if (tile.hasImplicitContentMetadata) {
const subtree = tile.implicitSubtree;
const coordinates = tile.implicitCoordinates;
content.metadata = subtree.getContentMetadataView(coordinates, index);
} else if (!tile.hasImplicitContent) {
content.metadata = findContentMetadata_default(tileset, contentHeader);
}
const groupMetadata = findGroupMetadata_default(tileset, contentHeader);
if (defined_default(groupMetadata)) {
content.group = new Cesium3DContentGroup_default({
metadata: groupMetadata
});
}
return content;
} catch (error) {
handleInnerContentFailed(multipleContents, index, error);
}
}
function handleInnerContentFailed(multipleContents, index, error) {
const tileset = multipleContents._tileset;
const url2 = multipleContents._innerContentResources[index].url;
const message = defined_default(error.message) ? error.message : error.toString();
if (tileset.tileFailed.numberOfListeners > 0) {
tileset.tileFailed.raiseEvent({
url: url2,
message
});
} else {
console.log(`A content failed to load: ${url2}`);
console.log(`Error: ${message}`);
}
}
Multiple3DTileContent.prototype.cancelRequests = function() {
for (let i = 0; i < this._requests.length; i++) {
const request = this._requests[i];
if (defined_default(request)) {
request.cancel();
}
}
};
Multiple3DTileContent.prototype.hasProperty = function(batchId, name) {
return false;
};
Multiple3DTileContent.prototype.getFeature = function(batchId) {
return void 0;
};
Multiple3DTileContent.prototype.applyDebugSettings = function(enabled, color) {
const contents = this._contents;
const length3 = contents.length;
for (let i = 0; i < length3; ++i) {
contents[i].applyDebugSettings(enabled, color);
}
};
Multiple3DTileContent.prototype.applyStyle = function(style) {
const contents = this._contents;
const length3 = contents.length;
for (let i = 0; i < length3; ++i) {
contents[i].applyStyle(style);
}
};
Multiple3DTileContent.prototype.update = function(tileset, frameState) {
const contents = this._contents;
const length3 = contents.length;
let ready = true;
for (let i = 0; i < length3; ++i) {
contents[i].update(tileset, frameState);
ready = ready && contents[i].ready;
}
if (!this._ready && ready) {
this._ready = true;
this._resolveContent(this);
}
};
Multiple3DTileContent.prototype.isDestroyed = function() {
return false;
};
Multiple3DTileContent.prototype.destroy = function() {
const contents = this._contents;
const length3 = contents.length;
for (let i = 0; i < length3; ++i) {
contents[i].destroy();
}
return destroyObject_default(this);
};
var Multiple3DTileContent_default = Multiple3DTileContent;
// packages/engine/Source/Core/PolygonPipeline.js
var import_earcut = __toESM(require_earcut(), 1);
var scaleToGeodeticHeightN = new Cartesian3_default();
var scaleToGeodeticHeightP = new Cartesian3_default();
var PolygonPipeline = {};
PolygonPipeline.computeArea2D = function(positions) {
Check_default.defined("positions", positions);
Check_default.typeOf.number.greaterThanOrEquals(
"positions.length",
positions.length,
3
);
const length3 = positions.length;
let area = 0;
for (let i0 = length3 - 1, i1 = 0; i1 < length3; i0 = i1++) {
const v02 = positions[i0];
const v13 = positions[i1];
area += v02.x * v13.y - v13.x * v02.y;
}
return area * 0.5;
};
PolygonPipeline.computeWindingOrder2D = function(positions) {
const area = PolygonPipeline.computeArea2D(positions);
return area > 0 ? WindingOrder_default.COUNTER_CLOCKWISE : WindingOrder_default.CLOCKWISE;
};
PolygonPipeline.triangulate = function(positions, holes) {
Check_default.defined("positions", positions);
const flattenedPositions = Cartesian2_default.packArray(positions);
return (0, import_earcut.default)(flattenedPositions, holes, 2);
};
var subdivisionV0Scratch = new Cartesian3_default();
var subdivisionV1Scratch = new Cartesian3_default();
var subdivisionV2Scratch = new Cartesian3_default();
var subdivisionS0Scratch = new Cartesian3_default();
var subdivisionS1Scratch = new Cartesian3_default();
var subdivisionS2Scratch = new Cartesian3_default();
var subdivisionMidScratch = new Cartesian3_default();
var subdivisionT0Scratch = new Cartesian2_default();
var subdivisionT1Scratch = new Cartesian2_default();
var subdivisionT2Scratch = new Cartesian2_default();
var subdivisionTexcoordMidScratch = new Cartesian2_default();
PolygonPipeline.computeSubdivision = function(ellipsoid, positions, indices2, texcoords, granularity) {
granularity = defaultValue_default(granularity, Math_default.RADIANS_PER_DEGREE);
const hasTexcoords = defined_default(texcoords);
Check_default.typeOf.object("ellipsoid", ellipsoid);
Check_default.defined("positions", positions);
Check_default.defined("indices", indices2);
Check_default.typeOf.number.greaterThanOrEquals("indices.length", indices2.length, 3);
Check_default.typeOf.number.equals("indices.length % 3", "0", indices2.length % 3, 0);
Check_default.typeOf.number.greaterThan("granularity", granularity, 0);
const triangles = indices2.slice(0);
let i;
const length3 = positions.length;
const subdividedPositions = new Array(length3 * 3);
const subdividedTexcoords = new Array(length3 * 2);
let q = 0;
let p = 0;
for (i = 0; i < length3; i++) {
const item = positions[i];
subdividedPositions[q++] = item.x;
subdividedPositions[q++] = item.y;
subdividedPositions[q++] = item.z;
if (hasTexcoords) {
const texcoordItem = texcoords[i];
subdividedTexcoords[p++] = texcoordItem.x;
subdividedTexcoords[p++] = texcoordItem.y;
}
}
const subdividedIndices = [];
const edges = {};
const radius = ellipsoid.maximumRadius;
const minDistance = Math_default.chordLength(granularity, radius);
const minDistanceSqrd = minDistance * minDistance;
while (triangles.length > 0) {
const i2 = triangles.pop();
const i1 = triangles.pop();
const i0 = triangles.pop();
const v02 = Cartesian3_default.fromArray(
subdividedPositions,
i0 * 3,
subdivisionV0Scratch
);
const v13 = Cartesian3_default.fromArray(
subdividedPositions,
i1 * 3,
subdivisionV1Scratch
);
const v23 = Cartesian3_default.fromArray(
subdividedPositions,
i2 * 3,
subdivisionV2Scratch
);
let t0, t1, t2;
if (hasTexcoords) {
t0 = Cartesian2_default.fromArray(
subdividedTexcoords,
i0 * 2,
subdivisionT0Scratch
);
t1 = Cartesian2_default.fromArray(
subdividedTexcoords,
i1 * 2,
subdivisionT1Scratch
);
t2 = Cartesian2_default.fromArray(
subdividedTexcoords,
i2 * 2,
subdivisionT2Scratch
);
}
const s0 = Cartesian3_default.multiplyByScalar(
Cartesian3_default.normalize(v02, subdivisionS0Scratch),
radius,
subdivisionS0Scratch
);
const s1 = Cartesian3_default.multiplyByScalar(
Cartesian3_default.normalize(v13, subdivisionS1Scratch),
radius,
subdivisionS1Scratch
);
const s2 = Cartesian3_default.multiplyByScalar(
Cartesian3_default.normalize(v23, subdivisionS2Scratch),
radius,
subdivisionS2Scratch
);
const g0 = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(s0, s1, subdivisionMidScratch)
);
const g1 = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(s1, s2, subdivisionMidScratch)
);
const g2 = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(s2, s0, subdivisionMidScratch)
);
const max3 = Math.max(g0, g1, g2);
let edge;
let mid;
let midTexcoord;
if (max3 > minDistanceSqrd) {
if (g0 === max3) {
edge = `${Math.min(i0, i1)} ${Math.max(i0, i1)}`;
i = edges[edge];
if (!defined_default(i)) {
mid = Cartesian3_default.add(v02, v13, subdivisionMidScratch);
Cartesian3_default.multiplyByScalar(mid, 0.5, mid);
subdividedPositions.push(mid.x, mid.y, mid.z);
i = subdividedPositions.length / 3 - 1;
edges[edge] = i;
if (hasTexcoords) {
midTexcoord = Cartesian2_default.add(t0, t1, subdivisionTexcoordMidScratch);
Cartesian2_default.multiplyByScalar(midTexcoord, 0.5, midTexcoord);
subdividedTexcoords.push(midTexcoord.x, midTexcoord.y);
}
}
triangles.push(i0, i, i2);
triangles.push(i, i1, i2);
} else if (g1 === max3) {
edge = `${Math.min(i1, i2)} ${Math.max(i1, i2)}`;
i = edges[edge];
if (!defined_default(i)) {
mid = Cartesian3_default.add(v13, v23, subdivisionMidScratch);
Cartesian3_default.multiplyByScalar(mid, 0.5, mid);
subdividedPositions.push(mid.x, mid.y, mid.z);
i = subdividedPositions.length / 3 - 1;
edges[edge] = i;
if (hasTexcoords) {
midTexcoord = Cartesian2_default.add(t1, t2, subdivisionTexcoordMidScratch);
Cartesian2_default.multiplyByScalar(midTexcoord, 0.5, midTexcoord);
subdividedTexcoords.push(midTexcoord.x, midTexcoord.y);
}
}
triangles.push(i1, i, i0);
triangles.push(i, i2, i0);
} else if (g2 === max3) {
edge = `${Math.min(i2, i0)} ${Math.max(i2, i0)}`;
i = edges[edge];
if (!defined_default(i)) {
mid = Cartesian3_default.add(v23, v02, subdivisionMidScratch);
Cartesian3_default.multiplyByScalar(mid, 0.5, mid);
subdividedPositions.push(mid.x, mid.y, mid.z);
i = subdividedPositions.length / 3 - 1;
edges[edge] = i;
if (hasTexcoords) {
midTexcoord = Cartesian2_default.add(t2, t0, subdivisionTexcoordMidScratch);
Cartesian2_default.multiplyByScalar(midTexcoord, 0.5, midTexcoord);
subdividedTexcoords.push(midTexcoord.x, midTexcoord.y);
}
}
triangles.push(i2, i, i1);
triangles.push(i, i0, i1);
}
} else {
subdividedIndices.push(i0);
subdividedIndices.push(i1);
subdividedIndices.push(i2);
}
}
const geometryOptions = {
attributes: {
position: new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: subdividedPositions
})
},
indices: subdividedIndices,
primitiveType: PrimitiveType_default.TRIANGLES
};
if (hasTexcoords) {
geometryOptions.attributes.st = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 2,
values: subdividedTexcoords
});
}
return new Geometry_default(geometryOptions);
};
var subdivisionC0Scratch = new Cartographic_default();
var subdivisionC1Scratch = new Cartographic_default();
var subdivisionC2Scratch = new Cartographic_default();
var subdivisionCartographicScratch = new Cartographic_default();
PolygonPipeline.computeRhumbLineSubdivision = function(ellipsoid, positions, indices2, texcoords, granularity) {
granularity = defaultValue_default(granularity, Math_default.RADIANS_PER_DEGREE);
const hasTexcoords = defined_default(texcoords);
Check_default.typeOf.object("ellipsoid", ellipsoid);
Check_default.defined("positions", positions);
Check_default.defined("indices", indices2);
Check_default.typeOf.number.greaterThanOrEquals("indices.length", indices2.length, 3);
Check_default.typeOf.number.equals("indices.length % 3", "0", indices2.length % 3, 0);
Check_default.typeOf.number.greaterThan("granularity", granularity, 0);
const triangles = indices2.slice(0);
let i;
const length3 = positions.length;
const subdividedPositions = new Array(length3 * 3);
const subdividedTexcoords = new Array(length3 * 2);
let q = 0;
let p = 0;
for (i = 0; i < length3; i++) {
const item = positions[i];
subdividedPositions[q++] = item.x;
subdividedPositions[q++] = item.y;
subdividedPositions[q++] = item.z;
if (hasTexcoords) {
const texcoordItem = texcoords[i];
subdividedTexcoords[p++] = texcoordItem.x;
subdividedTexcoords[p++] = texcoordItem.y;
}
}
const subdividedIndices = [];
const edges = {};
const radius = ellipsoid.maximumRadius;
const minDistance = Math_default.chordLength(granularity, radius);
const rhumb0 = new EllipsoidRhumbLine_default(void 0, void 0, ellipsoid);
const rhumb1 = new EllipsoidRhumbLine_default(void 0, void 0, ellipsoid);
const rhumb2 = new EllipsoidRhumbLine_default(void 0, void 0, ellipsoid);
while (triangles.length > 0) {
const i2 = triangles.pop();
const i1 = triangles.pop();
const i0 = triangles.pop();
const v02 = Cartesian3_default.fromArray(
subdividedPositions,
i0 * 3,
subdivisionV0Scratch
);
const v13 = Cartesian3_default.fromArray(
subdividedPositions,
i1 * 3,
subdivisionV1Scratch
);
const v23 = Cartesian3_default.fromArray(
subdividedPositions,
i2 * 3,
subdivisionV2Scratch
);
let t0, t1, t2;
if (hasTexcoords) {
t0 = Cartesian2_default.fromArray(
subdividedTexcoords,
i0 * 2,
subdivisionT0Scratch
);
t1 = Cartesian2_default.fromArray(
subdividedTexcoords,
i1 * 2,
subdivisionT1Scratch
);
t2 = Cartesian2_default.fromArray(
subdividedTexcoords,
i2 * 2,
subdivisionT2Scratch
);
}
const c0 = ellipsoid.cartesianToCartographic(v02, subdivisionC0Scratch);
const c14 = ellipsoid.cartesianToCartographic(v13, subdivisionC1Scratch);
const c22 = ellipsoid.cartesianToCartographic(v23, subdivisionC2Scratch);
rhumb0.setEndPoints(c0, c14);
const g0 = rhumb0.surfaceDistance;
rhumb1.setEndPoints(c14, c22);
const g1 = rhumb1.surfaceDistance;
rhumb2.setEndPoints(c22, c0);
const g2 = rhumb2.surfaceDistance;
const max3 = Math.max(g0, g1, g2);
let edge;
let mid;
let midHeight;
let midCartesian3;
let midTexcoord;
if (max3 > minDistance) {
if (g0 === max3) {
edge = `${Math.min(i0, i1)} ${Math.max(i0, i1)}`;
i = edges[edge];
if (!defined_default(i)) {
mid = rhumb0.interpolateUsingFraction(
0.5,
subdivisionCartographicScratch
);
midHeight = (c0.height + c14.height) * 0.5;
midCartesian3 = Cartesian3_default.fromRadians(
mid.longitude,
mid.latitude,
midHeight,
ellipsoid,
subdivisionMidScratch
);
subdividedPositions.push(
midCartesian3.x,
midCartesian3.y,
midCartesian3.z
);
i = subdividedPositions.length / 3 - 1;
edges[edge] = i;
if (hasTexcoords) {
midTexcoord = Cartesian2_default.add(t0, t1, subdivisionTexcoordMidScratch);
Cartesian2_default.multiplyByScalar(midTexcoord, 0.5, midTexcoord);
subdividedTexcoords.push(midTexcoord.x, midTexcoord.y);
}
}
triangles.push(i0, i, i2);
triangles.push(i, i1, i2);
} else if (g1 === max3) {
edge = `${Math.min(i1, i2)} ${Math.max(i1, i2)}`;
i = edges[edge];
if (!defined_default(i)) {
mid = rhumb1.interpolateUsingFraction(
0.5,
subdivisionCartographicScratch
);
midHeight = (c14.height + c22.height) * 0.5;
midCartesian3 = Cartesian3_default.fromRadians(
mid.longitude,
mid.latitude,
midHeight,
ellipsoid,
subdivisionMidScratch
);
subdividedPositions.push(
midCartesian3.x,
midCartesian3.y,
midCartesian3.z
);
i = subdividedPositions.length / 3 - 1;
edges[edge] = i;
if (hasTexcoords) {
midTexcoord = Cartesian2_default.add(t1, t2, subdivisionTexcoordMidScratch);
Cartesian2_default.multiplyByScalar(midTexcoord, 0.5, midTexcoord);
subdividedTexcoords.push(midTexcoord.x, midTexcoord.y);
}
}
triangles.push(i1, i, i0);
triangles.push(i, i2, i0);
} else if (g2 === max3) {
edge = `${Math.min(i2, i0)} ${Math.max(i2, i0)}`;
i = edges[edge];
if (!defined_default(i)) {
mid = rhumb2.interpolateUsingFraction(
0.5,
subdivisionCartographicScratch
);
midHeight = (c22.height + c0.height) * 0.5;
midCartesian3 = Cartesian3_default.fromRadians(
mid.longitude,
mid.latitude,
midHeight,
ellipsoid,
subdivisionMidScratch
);
subdividedPositions.push(
midCartesian3.x,
midCartesian3.y,
midCartesian3.z
);
i = subdividedPositions.length / 3 - 1;
edges[edge] = i;
if (hasTexcoords) {
midTexcoord = Cartesian2_default.add(t2, t0, subdivisionTexcoordMidScratch);
Cartesian2_default.multiplyByScalar(midTexcoord, 0.5, midTexcoord);
subdividedTexcoords.push(midTexcoord.x, midTexcoord.y);
}
}
triangles.push(i2, i, i1);
triangles.push(i, i0, i1);
}
} else {
subdividedIndices.push(i0);
subdividedIndices.push(i1);
subdividedIndices.push(i2);
}
}
const geometryOptions = {
attributes: {
position: new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: subdividedPositions
})
},
indices: subdividedIndices,
primitiveType: PrimitiveType_default.TRIANGLES
};
if (hasTexcoords) {
geometryOptions.attributes.st = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 2,
values: subdividedTexcoords
});
}
return new Geometry_default(geometryOptions);
};
PolygonPipeline.scaleToGeodeticHeight = function(positions, height, ellipsoid, scaleToSurface4) {
ellipsoid = defaultValue_default(ellipsoid, Ellipsoid_default.WGS84);
let n = scaleToGeodeticHeightN;
let p = scaleToGeodeticHeightP;
height = defaultValue_default(height, 0);
scaleToSurface4 = defaultValue_default(scaleToSurface4, true);
if (defined_default(positions)) {
const length3 = positions.length;
for (let i = 0; i < length3; i += 3) {
Cartesian3_default.fromArray(positions, i, p);
if (scaleToSurface4) {
p = ellipsoid.scaleToGeodeticSurface(p, p);
}
if (height !== 0) {
n = ellipsoid.geodeticSurfaceNormal(p, n);
Cartesian3_default.multiplyByScalar(n, height, n);
Cartesian3_default.add(p, n, p);
}
positions[i] = p.x;
positions[i + 1] = p.y;
positions[i + 2] = p.z;
}
}
return positions;
};
var PolygonPipeline_default = PolygonPipeline;
// packages/engine/Source/Core/RectangleGeometryLibrary.js
var cos = Math.cos;
var sin = Math.sin;
var sqrt = Math.sqrt;
var RectangleGeometryLibrary = {};
RectangleGeometryLibrary.computePosition = function(computedOptions, ellipsoid, computeST, row, col, position, st) {
const radiiSquared = ellipsoid.radiiSquared;
const nwCorner = computedOptions.nwCorner;
const rectangle = computedOptions.boundingRectangle;
let stLatitude = nwCorner.latitude - computedOptions.granYCos * row + col * computedOptions.granXSin;
const cosLatitude = cos(stLatitude);
const nZ = sin(stLatitude);
const kZ = radiiSquared.z * nZ;
let stLongitude = nwCorner.longitude + row * computedOptions.granYSin + col * computedOptions.granXCos;
const nX = cosLatitude * cos(stLongitude);
const nY = cosLatitude * sin(stLongitude);
const kX = radiiSquared.x * nX;
const kY = radiiSquared.y * nY;
const gamma = sqrt(kX * nX + kY * nY + kZ * nZ);
position.x = kX / gamma;
position.y = kY / gamma;
position.z = kZ / gamma;
if (computeST) {
const stNwCorner = computedOptions.stNwCorner;
if (defined_default(stNwCorner)) {
stLatitude = stNwCorner.latitude - computedOptions.stGranYCos * row + col * computedOptions.stGranXSin;
stLongitude = stNwCorner.longitude + row * computedOptions.stGranYSin + col * computedOptions.stGranXCos;
st.x = (stLongitude - computedOptions.stWest) * computedOptions.lonScalar;
st.y = (stLatitude - computedOptions.stSouth) * computedOptions.latScalar;
} else {
st.x = (stLongitude - rectangle.west) * computedOptions.lonScalar;
st.y = (stLatitude - rectangle.south) * computedOptions.latScalar;
}
}
};
var rotationMatrixScratch = new Matrix2_default();
var nwCartesian = new Cartesian3_default();
var centerScratch = new Cartographic_default();
var centerCartesian = new Cartesian3_default();
var proj = new GeographicProjection_default();
function getRotationOptions(nwCorner, rotation, granularityX, granularityY, center, width, height) {
const cosRotation = Math.cos(rotation);
const granYCos = granularityY * cosRotation;
const granXCos = granularityX * cosRotation;
const sinRotation = Math.sin(rotation);
const granYSin = granularityY * sinRotation;
const granXSin = granularityX * sinRotation;
nwCartesian = proj.project(nwCorner, nwCartesian);
nwCartesian = Cartesian3_default.subtract(nwCartesian, centerCartesian, nwCartesian);
const rotationMatrix = Matrix2_default.fromRotation(rotation, rotationMatrixScratch);
nwCartesian = Matrix2_default.multiplyByVector(
rotationMatrix,
nwCartesian,
nwCartesian
);
nwCartesian = Cartesian3_default.add(nwCartesian, centerCartesian, nwCartesian);
nwCorner = proj.unproject(nwCartesian, nwCorner);
width -= 1;
height -= 1;
const latitude = nwCorner.latitude;
const latitude0 = latitude + width * granXSin;
const latitude1 = latitude - granYCos * height;
const latitude2 = latitude - granYCos * height + width * granXSin;
const north = Math.max(latitude, latitude0, latitude1, latitude2);
const south = Math.min(latitude, latitude0, latitude1, latitude2);
const longitude = nwCorner.longitude;
const longitude0 = longitude + width * granXCos;
const longitude1 = longitude + height * granYSin;
const longitude2 = longitude + height * granYSin + width * granXCos;
const east = Math.max(longitude, longitude0, longitude1, longitude2);
const west = Math.min(longitude, longitude0, longitude1, longitude2);
return {
north,
south,
east,
west,
granYCos,
granYSin,
granXCos,
granXSin,
nwCorner
};
}
RectangleGeometryLibrary.computeOptions = function(rectangle, granularity, rotation, stRotation, boundingRectangleScratch2, nwCornerResult, stNwCornerResult) {
let east = rectangle.east;
let west = rectangle.west;
let north = rectangle.north;
let south = rectangle.south;
let northCap = false;
let southCap = false;
if (north === Math_default.PI_OVER_TWO) {
northCap = true;
}
if (south === -Math_default.PI_OVER_TWO) {
southCap = true;
}
let dx;
const dy = north - south;
if (west > east) {
dx = Math_default.TWO_PI - west + east;
} else {
dx = east - west;
}
const width = Math.ceil(dx / granularity) + 1;
const height = Math.ceil(dy / granularity) + 1;
const granularityX = dx / (width - 1);
const granularityY = dy / (height - 1);
const nwCorner = Rectangle_default.northwest(rectangle, nwCornerResult);
const center = Rectangle_default.center(rectangle, centerScratch);
if (rotation !== 0 || stRotation !== 0) {
if (center.longitude < nwCorner.longitude) {
center.longitude += Math_default.TWO_PI;
}
centerCartesian = proj.project(center, centerCartesian);
}
const granYCos = granularityY;
const granXCos = granularityX;
const granYSin = 0;
const granXSin = 0;
const boundingRectangle = Rectangle_default.clone(
rectangle,
boundingRectangleScratch2
);
const computedOptions = {
granYCos,
granYSin,
granXCos,
granXSin,
nwCorner,
boundingRectangle,
width,
height,
northCap,
southCap
};
if (rotation !== 0) {
const rotationOptions = getRotationOptions(
nwCorner,
rotation,
granularityX,
granularityY,
center,
width,
height
);
north = rotationOptions.north;
south = rotationOptions.south;
east = rotationOptions.east;
west = rotationOptions.west;
if (north < -Math_default.PI_OVER_TWO || north > Math_default.PI_OVER_TWO || south < -Math_default.PI_OVER_TWO || south > Math_default.PI_OVER_TWO) {
throw new DeveloperError_default(
"Rotated rectangle is invalid. It crosses over either the north or south pole."
);
}
computedOptions.granYCos = rotationOptions.granYCos;
computedOptions.granYSin = rotationOptions.granYSin;
computedOptions.granXCos = rotationOptions.granXCos;
computedOptions.granXSin = rotationOptions.granXSin;
boundingRectangle.north = north;
boundingRectangle.south = south;
boundingRectangle.east = east;
boundingRectangle.west = west;
}
if (stRotation !== 0) {
rotation = rotation - stRotation;
const stNwCorner = Rectangle_default.northwest(boundingRectangle, stNwCornerResult);
const stRotationOptions = getRotationOptions(
stNwCorner,
rotation,
granularityX,
granularityY,
center,
width,
height
);
computedOptions.stGranYCos = stRotationOptions.granYCos;
computedOptions.stGranXCos = stRotationOptions.granXCos;
computedOptions.stGranYSin = stRotationOptions.granYSin;
computedOptions.stGranXSin = stRotationOptions.granXSin;
computedOptions.stNwCorner = stNwCorner;
computedOptions.stWest = stRotationOptions.west;
computedOptions.stSouth = stRotationOptions.south;
}
return computedOptions;
};
var RectangleGeometryLibrary_default = RectangleGeometryLibrary;
// packages/engine/Source/Core/RectangleOutlineGeometry.js
var bottomBoundingSphere = new BoundingSphere_default();
var topBoundingSphere = new BoundingSphere_default();
var positionScratch6 = new Cartesian3_default();
var rectangleScratch = new Rectangle_default();
function constructRectangle(geometry, computedOptions) {
const ellipsoid = geometry._ellipsoid;
const height = computedOptions.height;
const width = computedOptions.width;
const northCap = computedOptions.northCap;
const southCap = computedOptions.southCap;
let rowHeight = height;
let widthMultiplier = 2;
let size = 0;
let corners2 = 4;
if (northCap) {
widthMultiplier -= 1;
rowHeight -= 1;
size += 1;
corners2 -= 2;
}
if (southCap) {
widthMultiplier -= 1;
rowHeight -= 1;
size += 1;
corners2 -= 2;
}
size += widthMultiplier * width + 2 * rowHeight - corners2;
const positions = new Float64Array(size * 3);
let posIndex = 0;
let row = 0;
let col;
const position = positionScratch6;
if (northCap) {
RectangleGeometryLibrary_default.computePosition(
computedOptions,
ellipsoid,
false,
row,
0,
position
);
positions[posIndex++] = position.x;
positions[posIndex++] = position.y;
positions[posIndex++] = position.z;
} else {
for (col = 0; col < width; col++) {
RectangleGeometryLibrary_default.computePosition(
computedOptions,
ellipsoid,
false,
row,
col,
position
);
positions[posIndex++] = position.x;
positions[posIndex++] = position.y;
positions[posIndex++] = position.z;
}
}
col = width - 1;
for (row = 1; row < height; row++) {
RectangleGeometryLibrary_default.computePosition(
computedOptions,
ellipsoid,
false,
row,
col,
position
);
positions[posIndex++] = position.x;
positions[posIndex++] = position.y;
positions[posIndex++] = position.z;
}
row = height - 1;
if (!southCap) {
for (col = width - 2; col >= 0; col--) {
RectangleGeometryLibrary_default.computePosition(
computedOptions,
ellipsoid,
false,
row,
col,
position
);
positions[posIndex++] = position.x;
positions[posIndex++] = position.y;
positions[posIndex++] = position.z;
}
}
col = 0;
for (row = height - 2; row > 0; row--) {
RectangleGeometryLibrary_default.computePosition(
computedOptions,
ellipsoid,
false,
row,
col,
position
);
positions[posIndex++] = position.x;
positions[posIndex++] = position.y;
positions[posIndex++] = position.z;
}
const indicesSize = positions.length / 3 * 2;
const indices2 = IndexDatatype_default.createTypedArray(
positions.length / 3,
indicesSize
);
let index = 0;
for (let i = 0; i < positions.length / 3 - 1; i++) {
indices2[index++] = i;
indices2[index++] = i + 1;
}
indices2[index++] = positions.length / 3 - 1;
indices2[index++] = 0;
const geo = new Geometry_default({
attributes: new GeometryAttributes_default(),
primitiveType: PrimitiveType_default.LINES
});
geo.attributes.position = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: positions
});
geo.indices = indices2;
return geo;
}
function constructExtrudedRectangle(rectangleGeometry, computedOptions) {
const surfaceHeight = rectangleGeometry._surfaceHeight;
const extrudedHeight = rectangleGeometry._extrudedHeight;
const ellipsoid = rectangleGeometry._ellipsoid;
const minHeight = extrudedHeight;
const maxHeight = surfaceHeight;
const geo = constructRectangle(rectangleGeometry, computedOptions);
const height = computedOptions.height;
const width = computedOptions.width;
const topPositions = PolygonPipeline_default.scaleToGeodeticHeight(
geo.attributes.position.values,
maxHeight,
ellipsoid,
false
);
let length3 = topPositions.length;
const positions = new Float64Array(length3 * 2);
positions.set(topPositions);
const bottomPositions = PolygonPipeline_default.scaleToGeodeticHeight(
geo.attributes.position.values,
minHeight,
ellipsoid
);
positions.set(bottomPositions, length3);
geo.attributes.position.values = positions;
const northCap = computedOptions.northCap;
const southCap = computedOptions.southCap;
let corners2 = 4;
if (northCap) {
corners2 -= 1;
}
if (southCap) {
corners2 -= 1;
}
const indicesSize = (positions.length / 3 + corners2) * 2;
const indices2 = IndexDatatype_default.createTypedArray(
positions.length / 3,
indicesSize
);
length3 = positions.length / 6;
let index = 0;
for (let i = 0; i < length3 - 1; i++) {
indices2[index++] = i;
indices2[index++] = i + 1;
indices2[index++] = i + length3;
indices2[index++] = i + length3 + 1;
}
indices2[index++] = length3 - 1;
indices2[index++] = 0;
indices2[index++] = length3 + length3 - 1;
indices2[index++] = length3;
indices2[index++] = 0;
indices2[index++] = length3;
let bottomCorner;
if (northCap) {
bottomCorner = height - 1;
} else {
const topRightCorner = width - 1;
indices2[index++] = topRightCorner;
indices2[index++] = topRightCorner + length3;
bottomCorner = width + height - 2;
}
indices2[index++] = bottomCorner;
indices2[index++] = bottomCorner + length3;
if (!southCap) {
const bottomLeftCorner = width + bottomCorner - 1;
indices2[index++] = bottomLeftCorner;
indices2[index] = bottomLeftCorner + length3;
}
geo.indices = indices2;
return geo;
}
function RectangleOutlineGeometry(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const rectangle = options.rectangle;
const granularity = defaultValue_default(
options.granularity,
Math_default.RADIANS_PER_DEGREE
);
const ellipsoid = defaultValue_default(options.ellipsoid, Ellipsoid_default.WGS84);
const rotation = defaultValue_default(options.rotation, 0);
if (!defined_default(rectangle)) {
throw new DeveloperError_default("rectangle is required.");
}
Rectangle_default.validate(rectangle);
if (rectangle.north < rectangle.south) {
throw new DeveloperError_default(
"options.rectangle.north must be greater than options.rectangle.south"
);
}
const height = defaultValue_default(options.height, 0);
const extrudedHeight = defaultValue_default(options.extrudedHeight, height);
this._rectangle = Rectangle_default.clone(rectangle);
this._granularity = granularity;
this._ellipsoid = ellipsoid;
this._surfaceHeight = Math.max(height, extrudedHeight);
this._rotation = rotation;
this._extrudedHeight = Math.min(height, extrudedHeight);
this._offsetAttribute = options.offsetAttribute;
this._workerName = "createRectangleOutlineGeometry";
}
RectangleOutlineGeometry.packedLength = Rectangle_default.packedLength + Ellipsoid_default.packedLength + 5;
RectangleOutlineGeometry.pack = function(value, array, startingIndex) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required");
}
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
Rectangle_default.pack(value._rectangle, array, startingIndex);
startingIndex += Rectangle_default.packedLength;
Ellipsoid_default.pack(value._ellipsoid, array, startingIndex);
startingIndex += Ellipsoid_default.packedLength;
array[startingIndex++] = value._granularity;
array[startingIndex++] = value._surfaceHeight;
array[startingIndex++] = value._rotation;
array[startingIndex++] = value._extrudedHeight;
array[startingIndex] = defaultValue_default(value._offsetAttribute, -1);
return array;
};
var scratchRectangle2 = new Rectangle_default();
var scratchEllipsoid = Ellipsoid_default.clone(Ellipsoid_default.UNIT_SPHERE);
var scratchOptions3 = {
rectangle: scratchRectangle2,
ellipsoid: scratchEllipsoid,
granularity: void 0,
height: void 0,
rotation: void 0,
extrudedHeight: void 0,
offsetAttribute: void 0
};
RectangleOutlineGeometry.unpack = function(array, startingIndex, result) {
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
const rectangle = Rectangle_default.unpack(array, startingIndex, scratchRectangle2);
startingIndex += Rectangle_default.packedLength;
const ellipsoid = Ellipsoid_default.unpack(array, startingIndex, scratchEllipsoid);
startingIndex += Ellipsoid_default.packedLength;
const granularity = array[startingIndex++];
const height = array[startingIndex++];
const rotation = array[startingIndex++];
const extrudedHeight = array[startingIndex++];
const offsetAttribute = array[startingIndex];
if (!defined_default(result)) {
scratchOptions3.granularity = granularity;
scratchOptions3.height = height;
scratchOptions3.rotation = rotation;
scratchOptions3.extrudedHeight = extrudedHeight;
scratchOptions3.offsetAttribute = offsetAttribute === -1 ? void 0 : offsetAttribute;
return new RectangleOutlineGeometry(scratchOptions3);
}
result._rectangle = Rectangle_default.clone(rectangle, result._rectangle);
result._ellipsoid = Ellipsoid_default.clone(ellipsoid, result._ellipsoid);
result._surfaceHeight = height;
result._rotation = rotation;
result._extrudedHeight = extrudedHeight;
result._offsetAttribute = offsetAttribute === -1 ? void 0 : offsetAttribute;
return result;
};
var nwScratch = new Cartographic_default();
RectangleOutlineGeometry.createGeometry = function(rectangleGeometry) {
const rectangle = rectangleGeometry._rectangle;
const ellipsoid = rectangleGeometry._ellipsoid;
const computedOptions = RectangleGeometryLibrary_default.computeOptions(
rectangle,
rectangleGeometry._granularity,
rectangleGeometry._rotation,
0,
rectangleScratch,
nwScratch
);
let geometry;
let boundingSphere;
if (Math_default.equalsEpsilon(
rectangle.north,
rectangle.south,
Math_default.EPSILON10
) || Math_default.equalsEpsilon(
rectangle.east,
rectangle.west,
Math_default.EPSILON10
)) {
return void 0;
}
const surfaceHeight = rectangleGeometry._surfaceHeight;
const extrudedHeight = rectangleGeometry._extrudedHeight;
const extrude = !Math_default.equalsEpsilon(
surfaceHeight,
extrudedHeight,
0,
Math_default.EPSILON2
);
let offsetValue;
if (extrude) {
geometry = constructExtrudedRectangle(rectangleGeometry, computedOptions);
if (defined_default(rectangleGeometry._offsetAttribute)) {
const size = geometry.attributes.position.values.length / 3;
let offsetAttribute = new Uint8Array(size);
if (rectangleGeometry._offsetAttribute === GeometryOffsetAttribute_default.TOP) {
offsetAttribute = offsetAttribute.fill(1, 0, size / 2);
} else {
offsetValue = rectangleGeometry._offsetAttribute === GeometryOffsetAttribute_default.NONE ? 0 : 1;
offsetAttribute = offsetAttribute.fill(offsetValue);
}
geometry.attributes.applyOffset = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentsPerAttribute: 1,
values: offsetAttribute
});
}
const topBS = BoundingSphere_default.fromRectangle3D(
rectangle,
ellipsoid,
surfaceHeight,
topBoundingSphere
);
const bottomBS = BoundingSphere_default.fromRectangle3D(
rectangle,
ellipsoid,
extrudedHeight,
bottomBoundingSphere
);
boundingSphere = BoundingSphere_default.union(topBS, bottomBS);
} else {
geometry = constructRectangle(rectangleGeometry, computedOptions);
geometry.attributes.position.values = PolygonPipeline_default.scaleToGeodeticHeight(
geometry.attributes.position.values,
surfaceHeight,
ellipsoid,
false
);
if (defined_default(rectangleGeometry._offsetAttribute)) {
const length3 = geometry.attributes.position.values.length;
offsetValue = rectangleGeometry._offsetAttribute === GeometryOffsetAttribute_default.NONE ? 0 : 1;
const applyOffset = new Uint8Array(length3 / 3).fill(offsetValue);
geometry.attributes.applyOffset = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentsPerAttribute: 1,
values: applyOffset
});
}
boundingSphere = BoundingSphere_default.fromRectangle3D(
rectangle,
ellipsoid,
surfaceHeight
);
}
return new Geometry_default({
attributes: geometry.attributes,
indices: geometry.indices,
primitiveType: PrimitiveType_default.LINES,
boundingSphere,
offsetAttribute: rectangleGeometry._offsetAttribute
});
};
var RectangleOutlineGeometry_default = RectangleOutlineGeometry;
// packages/engine/Source/Scene/TileBoundingRegion.js
function TileBoundingRegion(options) {
Check_default.typeOf.object("options", options);
Check_default.typeOf.object("options.rectangle", options.rectangle);
this.rectangle = Rectangle_default.clone(options.rectangle);
this.minimumHeight = defaultValue_default(options.minimumHeight, 0);
this.maximumHeight = defaultValue_default(options.maximumHeight, 0);
this.southwestCornerCartesian = new Cartesian3_default();
this.northeastCornerCartesian = new Cartesian3_default();
this.westNormal = new Cartesian3_default();
this.southNormal = new Cartesian3_default();
this.eastNormal = new Cartesian3_default();
this.northNormal = new Cartesian3_default();
const ellipsoid = defaultValue_default(options.ellipsoid, Ellipsoid_default.WGS84);
computeBox(this, options.rectangle, ellipsoid);
this._orientedBoundingBox = void 0;
this._boundingSphere = void 0;
if (defaultValue_default(options.computeBoundingVolumes, true)) {
this.computeBoundingVolumes(ellipsoid);
}
}
Object.defineProperties(TileBoundingRegion.prototype, {
/**
* The underlying bounding volume
*
* @memberof TileBoundingRegion.prototype
*
* @type {object}
* @readonly
*/
boundingVolume: {
get: function() {
return this._orientedBoundingBox;
}
},
/**
* The underlying bounding sphere
*
* @memberof TileBoundingRegion.prototype
*
* @type {BoundingSphere}
* @readonly
*/
boundingSphere: {
get: function() {
return this._boundingSphere;
}
}
});
TileBoundingRegion.prototype.computeBoundingVolumes = function(ellipsoid) {
this._orientedBoundingBox = OrientedBoundingBox_default.fromRectangle(
this.rectangle,
this.minimumHeight,
this.maximumHeight,
ellipsoid
);
this._boundingSphere = BoundingSphere_default.fromOrientedBoundingBox(
this._orientedBoundingBox
);
};
var cartesian3Scratch = new Cartesian3_default();
var cartesian3Scratch22 = new Cartesian3_default();
var cartesian3Scratch32 = new Cartesian3_default();
var westNormalScratch = new Cartesian3_default();
var eastWestNormalScratch = new Cartesian3_default();
var westernMidpointScratch = new Cartesian3_default();
var easternMidpointScratch = new Cartesian3_default();
var cartographicScratch2 = new Cartographic_default();
var planeScratch = new Plane_default(Cartesian3_default.UNIT_X, 0);
var rayScratch = new Ray_default();
function computeBox(tileBB, rectangle, ellipsoid) {
ellipsoid.cartographicToCartesian(
Rectangle_default.southwest(rectangle),
tileBB.southwestCornerCartesian
);
ellipsoid.cartographicToCartesian(
Rectangle_default.northeast(rectangle),
tileBB.northeastCornerCartesian
);
cartographicScratch2.longitude = rectangle.west;
cartographicScratch2.latitude = (rectangle.south + rectangle.north) * 0.5;
cartographicScratch2.height = 0;
const westernMidpointCartesian = ellipsoid.cartographicToCartesian(
cartographicScratch2,
westernMidpointScratch
);
const westNormal = Cartesian3_default.cross(
westernMidpointCartesian,
Cartesian3_default.UNIT_Z,
westNormalScratch
);
Cartesian3_default.normalize(westNormal, tileBB.westNormal);
cartographicScratch2.longitude = rectangle.east;
const easternMidpointCartesian = ellipsoid.cartographicToCartesian(
cartographicScratch2,
easternMidpointScratch
);
const eastNormal = Cartesian3_default.cross(
Cartesian3_default.UNIT_Z,
easternMidpointCartesian,
cartesian3Scratch
);
Cartesian3_default.normalize(eastNormal, tileBB.eastNormal);
let westVector = Cartesian3_default.subtract(
westernMidpointCartesian,
easternMidpointCartesian,
cartesian3Scratch
);
if (Cartesian3_default.magnitude(westVector) === 0) {
westVector = Cartesian3_default.clone(westNormal, westVector);
}
const eastWestNormal = Cartesian3_default.normalize(
westVector,
eastWestNormalScratch
);
const south = rectangle.south;
let southSurfaceNormal;
if (south > 0) {
cartographicScratch2.longitude = (rectangle.west + rectangle.east) * 0.5;
cartographicScratch2.latitude = south;
const southCenterCartesian = ellipsoid.cartographicToCartesian(
cartographicScratch2,
rayScratch.origin
);
Cartesian3_default.clone(eastWestNormal, rayScratch.direction);
const westPlane = Plane_default.fromPointNormal(
tileBB.southwestCornerCartesian,
tileBB.westNormal,
planeScratch
);
IntersectionTests_default.rayPlane(
rayScratch,
westPlane,
tileBB.southwestCornerCartesian
);
southSurfaceNormal = ellipsoid.geodeticSurfaceNormal(
southCenterCartesian,
cartesian3Scratch22
);
} else {
southSurfaceNormal = ellipsoid.geodeticSurfaceNormalCartographic(
Rectangle_default.southeast(rectangle),
cartesian3Scratch22
);
}
const southNormal = Cartesian3_default.cross(
southSurfaceNormal,
westVector,
cartesian3Scratch32
);
Cartesian3_default.normalize(southNormal, tileBB.southNormal);
const north = rectangle.north;
let northSurfaceNormal;
if (north < 0) {
cartographicScratch2.longitude = (rectangle.west + rectangle.east) * 0.5;
cartographicScratch2.latitude = north;
const northCenterCartesian = ellipsoid.cartographicToCartesian(
cartographicScratch2,
rayScratch.origin
);
Cartesian3_default.negate(eastWestNormal, rayScratch.direction);
const eastPlane = Plane_default.fromPointNormal(
tileBB.northeastCornerCartesian,
tileBB.eastNormal,
planeScratch
);
IntersectionTests_default.rayPlane(
rayScratch,
eastPlane,
tileBB.northeastCornerCartesian
);
northSurfaceNormal = ellipsoid.geodeticSurfaceNormal(
northCenterCartesian,
cartesian3Scratch22
);
} else {
northSurfaceNormal = ellipsoid.geodeticSurfaceNormalCartographic(
Rectangle_default.northwest(rectangle),
cartesian3Scratch22
);
}
const northNormal = Cartesian3_default.cross(
westVector,
northSurfaceNormal,
cartesian3Scratch32
);
Cartesian3_default.normalize(northNormal, tileBB.northNormal);
}
var southwestCornerScratch = new Cartesian3_default();
var northeastCornerScratch = new Cartesian3_default();
var negativeUnitY = new Cartesian3_default(0, -1, 0);
var negativeUnitZ = new Cartesian3_default(0, 0, -1);
var vectorScratch = new Cartesian3_default();
function distanceToCameraRegion(tileBB, frameState) {
const camera = frameState.camera;
const cameraCartesianPosition = camera.positionWC;
const cameraCartographicPosition = camera.positionCartographic;
let result = 0;
if (!Rectangle_default.contains(tileBB.rectangle, cameraCartographicPosition)) {
let southwestCornerCartesian = tileBB.southwestCornerCartesian;
let northeastCornerCartesian = tileBB.northeastCornerCartesian;
let westNormal = tileBB.westNormal;
let southNormal = tileBB.southNormal;
let eastNormal = tileBB.eastNormal;
let northNormal = tileBB.northNormal;
if (frameState.mode !== SceneMode_default.SCENE3D) {
southwestCornerCartesian = frameState.mapProjection.project(
Rectangle_default.southwest(tileBB.rectangle),
southwestCornerScratch
);
southwestCornerCartesian.z = southwestCornerCartesian.y;
southwestCornerCartesian.y = southwestCornerCartesian.x;
southwestCornerCartesian.x = 0;
northeastCornerCartesian = frameState.mapProjection.project(
Rectangle_default.northeast(tileBB.rectangle),
northeastCornerScratch
);
northeastCornerCartesian.z = northeastCornerCartesian.y;
northeastCornerCartesian.y = northeastCornerCartesian.x;
northeastCornerCartesian.x = 0;
westNormal = negativeUnitY;
eastNormal = Cartesian3_default.UNIT_Y;
southNormal = negativeUnitZ;
northNormal = Cartesian3_default.UNIT_Z;
}
const vectorFromSouthwestCorner = Cartesian3_default.subtract(
cameraCartesianPosition,
southwestCornerCartesian,
vectorScratch
);
const distanceToWestPlane = Cartesian3_default.dot(
vectorFromSouthwestCorner,
westNormal
);
const distanceToSouthPlane = Cartesian3_default.dot(
vectorFromSouthwestCorner,
southNormal
);
const vectorFromNortheastCorner = Cartesian3_default.subtract(
cameraCartesianPosition,
northeastCornerCartesian,
vectorScratch
);
const distanceToEastPlane = Cartesian3_default.dot(
vectorFromNortheastCorner,
eastNormal
);
const distanceToNorthPlane = Cartesian3_default.dot(
vectorFromNortheastCorner,
northNormal
);
if (distanceToWestPlane > 0) {
result += distanceToWestPlane * distanceToWestPlane;
} else if (distanceToEastPlane > 0) {
result += distanceToEastPlane * distanceToEastPlane;
}
if (distanceToSouthPlane > 0) {
result += distanceToSouthPlane * distanceToSouthPlane;
} else if (distanceToNorthPlane > 0) {
result += distanceToNorthPlane * distanceToNorthPlane;
}
}
let cameraHeight;
let minimumHeight;
let maximumHeight;
if (frameState.mode === SceneMode_default.SCENE3D) {
cameraHeight = cameraCartographicPosition.height;
minimumHeight = tileBB.minimumHeight;
maximumHeight = tileBB.maximumHeight;
} else {
cameraHeight = cameraCartesianPosition.x;
minimumHeight = 0;
maximumHeight = 0;
}
if (cameraHeight > maximumHeight) {
const distanceAboveTop = cameraHeight - maximumHeight;
result += distanceAboveTop * distanceAboveTop;
} else if (cameraHeight < minimumHeight) {
const distanceBelowBottom = minimumHeight - cameraHeight;
result += distanceBelowBottom * distanceBelowBottom;
}
return Math.sqrt(result);
}
TileBoundingRegion.prototype.distanceToCamera = function(frameState) {
Check_default.defined("frameState", frameState);
const regionResult = distanceToCameraRegion(this, frameState);
if (frameState.mode === SceneMode_default.SCENE3D && defined_default(this._orientedBoundingBox)) {
const obbResult = Math.sqrt(
this._orientedBoundingBox.distanceSquaredTo(frameState.camera.positionWC)
);
return Math.max(regionResult, obbResult);
}
return regionResult;
};
TileBoundingRegion.prototype.intersectPlane = function(plane) {
Check_default.defined("plane", plane);
return this._orientedBoundingBox.intersectPlane(plane);
};
TileBoundingRegion.prototype.createDebugVolume = function(color) {
Check_default.defined("color", color);
const modelMatrix = new Matrix4_default.clone(Matrix4_default.IDENTITY);
const geometry = new RectangleOutlineGeometry_default({
rectangle: this.rectangle,
height: this.minimumHeight,
extrudedHeight: this.maximumHeight
});
const instance = new GeometryInstance_default({
geometry,
id: "outline",
modelMatrix,
attributes: {
color: ColorGeometryInstanceAttribute_default.fromColor(color)
}
});
return new Primitive_default({
geometryInstances: instance,
appearance: new PerInstanceColorAppearance_default({
translucent: false,
flat: true
}),
asynchronous: false
});
};
var TileBoundingRegion_default = TileBoundingRegion;
// packages/engine/Source/Core/CoplanarPolygonGeometryLibrary.js
var CoplanarPolygonGeometryLibrary = {};
var scratchIntersectionPoint = new Cartesian3_default();
var scratchXAxis2 = new Cartesian3_default();
var scratchYAxis2 = new Cartesian3_default();
var scratchZAxis2 = new Cartesian3_default();
var obbScratch = new OrientedBoundingBox_default();
CoplanarPolygonGeometryLibrary.validOutline = function(positions) {
Check_default.defined("positions", positions);
const orientedBoundingBox = OrientedBoundingBox_default.fromPoints(
positions,
obbScratch
);
const halfAxes = orientedBoundingBox.halfAxes;
const xAxis = Matrix3_default.getColumn(halfAxes, 0, scratchXAxis2);
const yAxis = Matrix3_default.getColumn(halfAxes, 1, scratchYAxis2);
const zAxis = Matrix3_default.getColumn(halfAxes, 2, scratchZAxis2);
const xMag = Cartesian3_default.magnitude(xAxis);
const yMag = Cartesian3_default.magnitude(yAxis);
const zMag = Cartesian3_default.magnitude(zAxis);
return !(xMag === 0 && (yMag === 0 || zMag === 0) || yMag === 0 && zMag === 0);
};
CoplanarPolygonGeometryLibrary.computeProjectTo2DArguments = function(positions, centerResult, planeAxis1Result, planeAxis2Result) {
Check_default.defined("positions", positions);
Check_default.defined("centerResult", centerResult);
Check_default.defined("planeAxis1Result", planeAxis1Result);
Check_default.defined("planeAxis2Result", planeAxis2Result);
const orientedBoundingBox = OrientedBoundingBox_default.fromPoints(
positions,
obbScratch
);
const halfAxes = orientedBoundingBox.halfAxes;
const xAxis = Matrix3_default.getColumn(halfAxes, 0, scratchXAxis2);
const yAxis = Matrix3_default.getColumn(halfAxes, 1, scratchYAxis2);
const zAxis = Matrix3_default.getColumn(halfAxes, 2, scratchZAxis2);
const xMag = Cartesian3_default.magnitude(xAxis);
const yMag = Cartesian3_default.magnitude(yAxis);
const zMag = Cartesian3_default.magnitude(zAxis);
const min3 = Math.min(xMag, yMag, zMag);
if (xMag === 0 && (yMag === 0 || zMag === 0) || yMag === 0 && zMag === 0) {
return false;
}
let planeAxis1;
let planeAxis2;
if (min3 === yMag || min3 === zMag) {
planeAxis1 = xAxis;
}
if (min3 === xMag) {
planeAxis1 = yAxis;
} else if (min3 === zMag) {
planeAxis2 = yAxis;
}
if (min3 === xMag || min3 === yMag) {
planeAxis2 = zAxis;
}
Cartesian3_default.normalize(planeAxis1, planeAxis1Result);
Cartesian3_default.normalize(planeAxis2, planeAxis2Result);
Cartesian3_default.clone(orientedBoundingBox.center, centerResult);
return true;
};
function projectTo2D(position, center, axis1, axis2, result) {
const v7 = Cartesian3_default.subtract(position, center, scratchIntersectionPoint);
const x = Cartesian3_default.dot(axis1, v7);
const y = Cartesian3_default.dot(axis2, v7);
return Cartesian2_default.fromElements(x, y, result);
}
CoplanarPolygonGeometryLibrary.createProjectPointsTo2DFunction = function(center, axis1, axis2) {
return function(positions) {
const positionResults = new Array(positions.length);
for (let i = 0; i < positions.length; i++) {
positionResults[i] = projectTo2D(positions[i], center, axis1, axis2);
}
return positionResults;
};
};
CoplanarPolygonGeometryLibrary.createProjectPointTo2DFunction = function(center, axis1, axis2) {
return function(position, result) {
return projectTo2D(position, center, axis1, axis2, result);
};
};
var CoplanarPolygonGeometryLibrary_default = CoplanarPolygonGeometryLibrary;
// packages/engine/Source/Core/Queue.js
function Queue() {
this._array = [];
this._offset = 0;
this._length = 0;
}
Object.defineProperties(Queue.prototype, {
/**
* The length of the queue.
*
* @memberof Queue.prototype
*
* @type {number}
* @readonly
*/
length: {
get: function() {
return this._length;
}
}
});
Queue.prototype.enqueue = function(item) {
this._array.push(item);
this._length++;
};
Queue.prototype.dequeue = function() {
if (this._length === 0) {
return void 0;
}
const array = this._array;
let offset2 = this._offset;
const item = array[offset2];
array[offset2] = void 0;
offset2++;
if (offset2 > 10 && offset2 * 2 > array.length) {
this._array = array.slice(offset2);
offset2 = 0;
}
this._offset = offset2;
this._length--;
return item;
};
Queue.prototype.peek = function() {
if (this._length === 0) {
return void 0;
}
return this._array[this._offset];
};
Queue.prototype.contains = function(item) {
return this._array.indexOf(item) !== -1;
};
Queue.prototype.clear = function() {
this._array.length = this._offset = this._length = 0;
};
Queue.prototype.sort = function(compareFunction) {
if (this._offset > 0) {
this._array = this._array.slice(this._offset);
this._offset = 0;
}
this._array.sort(compareFunction);
};
var Queue_default = Queue;
// packages/engine/Source/Core/PolygonGeometryLibrary.js
var PolygonGeometryLibrary = {};
PolygonGeometryLibrary.computeHierarchyPackedLength = function(polygonHierarchy, CartesianX) {
let numComponents = 0;
const stack = [polygonHierarchy];
while (stack.length > 0) {
const hierarchy = stack.pop();
if (!defined_default(hierarchy)) {
continue;
}
numComponents += 2;
const positions = hierarchy.positions;
const holes = hierarchy.holes;
if (defined_default(positions) && positions.length > 0) {
numComponents += positions.length * CartesianX.packedLength;
}
if (defined_default(holes)) {
const length3 = holes.length;
for (let i = 0; i < length3; ++i) {
stack.push(holes[i]);
}
}
}
return numComponents;
};
PolygonGeometryLibrary.packPolygonHierarchy = function(polygonHierarchy, array, startingIndex, CartesianX) {
const stack = [polygonHierarchy];
while (stack.length > 0) {
const hierarchy = stack.pop();
if (!defined_default(hierarchy)) {
continue;
}
const positions = hierarchy.positions;
const holes = hierarchy.holes;
array[startingIndex++] = defined_default(positions) ? positions.length : 0;
array[startingIndex++] = defined_default(holes) ? holes.length : 0;
if (defined_default(positions)) {
const positionsLength = positions.length;
for (let i = 0; i < positionsLength; ++i, startingIndex += CartesianX.packedLength) {
CartesianX.pack(positions[i], array, startingIndex);
}
}
if (defined_default(holes)) {
const holesLength = holes.length;
for (let j = 0; j < holesLength; ++j) {
stack.push(holes[j]);
}
}
}
return startingIndex;
};
PolygonGeometryLibrary.unpackPolygonHierarchy = function(array, startingIndex, CartesianX) {
const positionsLength = array[startingIndex++];
const holesLength = array[startingIndex++];
const positions = new Array(positionsLength);
const holes = holesLength > 0 ? new Array(holesLength) : void 0;
for (let i = 0; i < positionsLength; ++i, startingIndex += CartesianX.packedLength) {
positions[i] = CartesianX.unpack(array, startingIndex);
}
for (let j = 0; j < holesLength; ++j) {
holes[j] = PolygonGeometryLibrary.unpackPolygonHierarchy(
array,
startingIndex,
CartesianX
);
startingIndex = holes[j].startingIndex;
delete holes[j].startingIndex;
}
return {
positions,
holes,
startingIndex
};
};
var distance2DScratch = new Cartesian2_default();
function getPointAtDistance2D(p0, p1, distance2, length3) {
Cartesian2_default.subtract(p1, p0, distance2DScratch);
Cartesian2_default.multiplyByScalar(
distance2DScratch,
distance2 / length3,
distance2DScratch
);
Cartesian2_default.add(p0, distance2DScratch, distance2DScratch);
return [distance2DScratch.x, distance2DScratch.y];
}
var distanceScratch4 = new Cartesian3_default();
function getPointAtDistance(p0, p1, distance2, length3) {
Cartesian3_default.subtract(p1, p0, distanceScratch4);
Cartesian3_default.multiplyByScalar(
distanceScratch4,
distance2 / length3,
distanceScratch4
);
Cartesian3_default.add(p0, distanceScratch4, distanceScratch4);
return [distanceScratch4.x, distanceScratch4.y, distanceScratch4.z];
}
PolygonGeometryLibrary.subdivideLineCount = function(p0, p1, minDistance) {
const distance2 = Cartesian3_default.distance(p0, p1);
const n = distance2 / minDistance;
const countDivide = Math.max(0, Math.ceil(Math_default.log2(n)));
return Math.pow(2, countDivide);
};
var scratchCartographic02 = new Cartographic_default();
var scratchCartographic12 = new Cartographic_default();
var scratchCartographic22 = new Cartographic_default();
var scratchCartesian0 = new Cartesian3_default();
var scratchRhumbLine = new EllipsoidRhumbLine_default();
PolygonGeometryLibrary.subdivideRhumbLineCount = function(ellipsoid, p0, p1, minDistance) {
const c0 = ellipsoid.cartesianToCartographic(p0, scratchCartographic02);
const c14 = ellipsoid.cartesianToCartographic(p1, scratchCartographic12);
const rhumb = new EllipsoidRhumbLine_default(c0, c14, ellipsoid);
const n = rhumb.surfaceDistance / minDistance;
const countDivide = Math.max(0, Math.ceil(Math_default.log2(n)));
return Math.pow(2, countDivide);
};
PolygonGeometryLibrary.subdivideTexcoordLine = function(t0, t1, p0, p1, minDistance, result) {
const subdivisions = PolygonGeometryLibrary.subdivideLineCount(
p0,
p1,
minDistance
);
const length2D = Cartesian2_default.distance(t0, t1);
const distanceBetweenCoords = length2D / subdivisions;
const texcoords = result;
texcoords.length = subdivisions * 2;
let index = 0;
for (let i = 0; i < subdivisions; i++) {
const t = getPointAtDistance2D(t0, t1, i * distanceBetweenCoords, length2D);
texcoords[index++] = t[0];
texcoords[index++] = t[1];
}
return texcoords;
};
PolygonGeometryLibrary.subdivideLine = function(p0, p1, minDistance, result) {
const numVertices = PolygonGeometryLibrary.subdivideLineCount(
p0,
p1,
minDistance
);
const length3 = Cartesian3_default.distance(p0, p1);
const distanceBetweenVertices = length3 / numVertices;
if (!defined_default(result)) {
result = [];
}
const positions = result;
positions.length = numVertices * 3;
let index = 0;
for (let i = 0; i < numVertices; i++) {
const p = getPointAtDistance(p0, p1, i * distanceBetweenVertices, length3);
positions[index++] = p[0];
positions[index++] = p[1];
positions[index++] = p[2];
}
return positions;
};
PolygonGeometryLibrary.subdivideTexcoordRhumbLine = function(t0, t1, ellipsoid, p0, p1, minDistance, result) {
const c0 = ellipsoid.cartesianToCartographic(p0, scratchCartographic02);
const c14 = ellipsoid.cartesianToCartographic(p1, scratchCartographic12);
scratchRhumbLine.setEndPoints(c0, c14);
const n = scratchRhumbLine.surfaceDistance / minDistance;
const countDivide = Math.max(0, Math.ceil(Math_default.log2(n)));
const subdivisions = Math.pow(2, countDivide);
const length2D = Cartesian2_default.distance(t0, t1);
const distanceBetweenCoords = length2D / subdivisions;
const texcoords = result;
texcoords.length = subdivisions * 2;
let index = 0;
for (let i = 0; i < subdivisions; i++) {
const t = getPointAtDistance2D(t0, t1, i * distanceBetweenCoords, length2D);
texcoords[index++] = t[0];
texcoords[index++] = t[1];
}
return texcoords;
};
PolygonGeometryLibrary.subdivideRhumbLine = function(ellipsoid, p0, p1, minDistance, result) {
const c0 = ellipsoid.cartesianToCartographic(p0, scratchCartographic02);
const c14 = ellipsoid.cartesianToCartographic(p1, scratchCartographic12);
const rhumb = new EllipsoidRhumbLine_default(c0, c14, ellipsoid);
const n = rhumb.surfaceDistance / minDistance;
const countDivide = Math.max(0, Math.ceil(Math_default.log2(n)));
const numVertices = Math.pow(2, countDivide);
const distanceBetweenVertices = rhumb.surfaceDistance / numVertices;
if (!defined_default(result)) {
result = [];
}
const positions = result;
positions.length = numVertices * 3;
let index = 0;
for (let i = 0; i < numVertices; i++) {
const c = rhumb.interpolateUsingSurfaceDistance(
i * distanceBetweenVertices,
scratchCartographic22
);
const p = ellipsoid.cartographicToCartesian(c, scratchCartesian0);
positions[index++] = p.x;
positions[index++] = p.y;
positions[index++] = p.z;
}
return positions;
};
var scaleToGeodeticHeightN1 = new Cartesian3_default();
var scaleToGeodeticHeightN2 = new Cartesian3_default();
var scaleToGeodeticHeightP1 = new Cartesian3_default();
var scaleToGeodeticHeightP2 = new Cartesian3_default();
PolygonGeometryLibrary.scaleToGeodeticHeightExtruded = function(geometry, maxHeight, minHeight, ellipsoid, perPositionHeight) {
ellipsoid = defaultValue_default(ellipsoid, Ellipsoid_default.WGS84);
const n1 = scaleToGeodeticHeightN1;
let n2 = scaleToGeodeticHeightN2;
const p = scaleToGeodeticHeightP1;
let p2 = scaleToGeodeticHeightP2;
if (defined_default(geometry) && defined_default(geometry.attributes) && defined_default(geometry.attributes.position)) {
const positions = geometry.attributes.position.values;
const length3 = positions.length / 2;
for (let i = 0; i < length3; i += 3) {
Cartesian3_default.fromArray(positions, i, p);
ellipsoid.geodeticSurfaceNormal(p, n1);
p2 = ellipsoid.scaleToGeodeticSurface(p, p2);
n2 = Cartesian3_default.multiplyByScalar(n1, minHeight, n2);
n2 = Cartesian3_default.add(p2, n2, n2);
positions[i + length3] = n2.x;
positions[i + 1 + length3] = n2.y;
positions[i + 2 + length3] = n2.z;
if (perPositionHeight) {
p2 = Cartesian3_default.clone(p, p2);
}
n2 = Cartesian3_default.multiplyByScalar(n1, maxHeight, n2);
n2 = Cartesian3_default.add(p2, n2, n2);
positions[i] = n2.x;
positions[i + 1] = n2.y;
positions[i + 2] = n2.z;
}
}
return geometry;
};
PolygonGeometryLibrary.polygonOutlinesFromHierarchy = function(polygonHierarchy, scaleToEllipsoidSurface, ellipsoid) {
const polygons = [];
const queue = new Queue_default();
queue.enqueue(polygonHierarchy);
let i;
let j;
let length3;
while (queue.length !== 0) {
const outerNode = queue.dequeue();
let outerRing = outerNode.positions;
if (scaleToEllipsoidSurface) {
length3 = outerRing.length;
for (i = 0; i < length3; i++) {
ellipsoid.scaleToGeodeticSurface(outerRing[i], outerRing[i]);
}
}
outerRing = arrayRemoveDuplicates_default(
outerRing,
Cartesian3_default.equalsEpsilon,
true
);
if (outerRing.length < 3) {
continue;
}
const numChildren = outerNode.holes ? outerNode.holes.length : 0;
for (i = 0; i < numChildren; i++) {
const hole = outerNode.holes[i];
let holePositions = hole.positions;
if (scaleToEllipsoidSurface) {
length3 = holePositions.length;
for (j = 0; j < length3; ++j) {
ellipsoid.scaleToGeodeticSurface(holePositions[j], holePositions[j]);
}
}
holePositions = arrayRemoveDuplicates_default(
holePositions,
Cartesian3_default.equalsEpsilon,
true
);
if (holePositions.length < 3) {
continue;
}
polygons.push(holePositions);
let numGrandchildren = 0;
if (defined_default(hole.holes)) {
numGrandchildren = hole.holes.length;
}
for (j = 0; j < numGrandchildren; j++) {
queue.enqueue(hole.holes[j]);
}
}
polygons.push(outerRing);
}
return polygons;
};
PolygonGeometryLibrary.polygonsFromHierarchy = function(polygonHierarchy, keepDuplicates, projectPointsTo2D, scaleToEllipsoidSurface, ellipsoid) {
const hierarchy = [];
const polygons = [];
const queue = new Queue_default();
queue.enqueue(polygonHierarchy);
while (queue.length !== 0) {
const outerNode = queue.dequeue();
let outerRing = outerNode.positions;
const holes = outerNode.holes;
let i;
let length3;
if (scaleToEllipsoidSurface) {
length3 = outerRing.length;
for (i = 0; i < length3; i++) {
ellipsoid.scaleToGeodeticSurface(outerRing[i], outerRing[i]);
}
}
if (!keepDuplicates) {
outerRing = arrayRemoveDuplicates_default(
outerRing,
Cartesian3_default.equalsEpsilon,
true
);
}
if (outerRing.length < 3) {
continue;
}
let positions2D = projectPointsTo2D(outerRing);
if (!defined_default(positions2D)) {
continue;
}
const holeIndices = [];
let originalWindingOrder = PolygonPipeline_default.computeWindingOrder2D(
positions2D
);
if (originalWindingOrder === WindingOrder_default.CLOCKWISE) {
positions2D.reverse();
outerRing = outerRing.slice().reverse();
}
let positions = outerRing.slice();
const numChildren = defined_default(holes) ? holes.length : 0;
const polygonHoles = [];
let j;
for (i = 0; i < numChildren; i++) {
const hole = holes[i];
let holePositions = hole.positions;
if (scaleToEllipsoidSurface) {
length3 = holePositions.length;
for (j = 0; j < length3; ++j) {
ellipsoid.scaleToGeodeticSurface(holePositions[j], holePositions[j]);
}
}
if (!keepDuplicates) {
holePositions = arrayRemoveDuplicates_default(
holePositions,
Cartesian3_default.equalsEpsilon,
true
);
}
if (holePositions.length < 3) {
continue;
}
const holePositions2D = projectPointsTo2D(holePositions);
if (!defined_default(holePositions2D)) {
continue;
}
originalWindingOrder = PolygonPipeline_default.computeWindingOrder2D(
holePositions2D
);
if (originalWindingOrder === WindingOrder_default.CLOCKWISE) {
holePositions2D.reverse();
holePositions = holePositions.slice().reverse();
}
polygonHoles.push(holePositions);
holeIndices.push(positions.length);
positions = positions.concat(holePositions);
positions2D = positions2D.concat(holePositions2D);
let numGrandchildren = 0;
if (defined_default(hole.holes)) {
numGrandchildren = hole.holes.length;
}
for (j = 0; j < numGrandchildren; j++) {
queue.enqueue(hole.holes[j]);
}
}
hierarchy.push({
outerRing,
holes: polygonHoles
});
polygons.push({
positions,
positions2D,
holes: holeIndices
});
}
return {
hierarchy,
polygons
};
};
var computeBoundingRectangleCartesian2 = new Cartesian2_default();
var computeBoundingRectangleCartesian3 = new Cartesian3_default();
var computeBoundingRectangleQuaternion = new Quaternion_default();
var computeBoundingRectangleMatrix3 = new Matrix3_default();
PolygonGeometryLibrary.computeBoundingRectangle = function(planeNormal, projectPointTo2D, positions, angle, result) {
const rotation = Quaternion_default.fromAxisAngle(
planeNormal,
angle,
computeBoundingRectangleQuaternion
);
const textureMatrix = Matrix3_default.fromQuaternion(
rotation,
computeBoundingRectangleMatrix3
);
let minX = Number.POSITIVE_INFINITY;
let maxX = Number.NEGATIVE_INFINITY;
let minY = Number.POSITIVE_INFINITY;
let maxY = Number.NEGATIVE_INFINITY;
const length3 = positions.length;
for (let i = 0; i < length3; ++i) {
const p = Cartesian3_default.clone(
positions[i],
computeBoundingRectangleCartesian3
);
Matrix3_default.multiplyByVector(textureMatrix, p, p);
const st = projectPointTo2D(p, computeBoundingRectangleCartesian2);
if (defined_default(st)) {
minX = Math.min(minX, st.x);
maxX = Math.max(maxX, st.x);
minY = Math.min(minY, st.y);
maxY = Math.max(maxY, st.y);
}
}
result.x = minX;
result.y = minY;
result.width = maxX - minX;
result.height = maxY - minY;
return result;
};
PolygonGeometryLibrary.createGeometryFromPositions = function(ellipsoid, polygon, textureCoordinates, granularity, perPositionHeight, vertexFormat, arcType) {
let indices2 = PolygonPipeline_default.triangulate(polygon.positions2D, polygon.holes);
if (indices2.length < 3) {
indices2 = [0, 1, 2];
}
const positions = polygon.positions;
const hasTexcoords = defined_default(textureCoordinates);
const texcoords = hasTexcoords ? textureCoordinates.positions : void 0;
if (perPositionHeight) {
const length3 = positions.length;
const flattenedPositions = new Array(length3 * 3);
let index = 0;
for (let i = 0; i < length3; i++) {
const p = positions[i];
flattenedPositions[index++] = p.x;
flattenedPositions[index++] = p.y;
flattenedPositions[index++] = p.z;
}
const geometryOptions = {
attributes: {
position: new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: flattenedPositions
})
},
indices: indices2,
primitiveType: PrimitiveType_default.TRIANGLES
};
if (hasTexcoords) {
geometryOptions.attributes.st = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 2,
values: Cartesian2_default.packArray(texcoords)
});
}
const geometry = new Geometry_default(geometryOptions);
if (vertexFormat.normal) {
return GeometryPipeline_default.computeNormal(geometry);
}
return geometry;
}
if (arcType === ArcType_default.GEODESIC) {
return PolygonPipeline_default.computeSubdivision(
ellipsoid,
positions,
indices2,
texcoords,
granularity
);
} else if (arcType === ArcType_default.RHUMB) {
return PolygonPipeline_default.computeRhumbLineSubdivision(
ellipsoid,
positions,
indices2,
texcoords,
granularity
);
}
};
var computeWallTexcoordsSubdivided = [];
var computeWallIndicesSubdivided = [];
var p1Scratch2 = new Cartesian3_default();
var p2Scratch2 = new Cartesian3_default();
PolygonGeometryLibrary.computeWallGeometry = function(positions, textureCoordinates, ellipsoid, granularity, perPositionHeight, arcType) {
let edgePositions;
let topEdgeLength;
let i;
let p1;
let p2;
let t1;
let t2;
let edgeTexcoords;
let topEdgeTexcoordLength;
let length3 = positions.length;
let index = 0;
let textureIndex = 0;
const hasTexcoords = defined_default(textureCoordinates);
const texcoords = hasTexcoords ? textureCoordinates.positions : void 0;
if (!perPositionHeight) {
const minDistance = Math_default.chordLength(
granularity,
ellipsoid.maximumRadius
);
let numVertices = 0;
if (arcType === ArcType_default.GEODESIC) {
for (i = 0; i < length3; i++) {
numVertices += PolygonGeometryLibrary.subdivideLineCount(
positions[i],
positions[(i + 1) % length3],
minDistance
);
}
} else if (arcType === ArcType_default.RHUMB) {
for (i = 0; i < length3; i++) {
numVertices += PolygonGeometryLibrary.subdivideRhumbLineCount(
ellipsoid,
positions[i],
positions[(i + 1) % length3],
minDistance
);
}
}
topEdgeLength = (numVertices + length3) * 3;
edgePositions = new Array(topEdgeLength * 2);
if (hasTexcoords) {
topEdgeTexcoordLength = (numVertices + length3) * 2;
edgeTexcoords = new Array(topEdgeTexcoordLength * 2);
}
for (i = 0; i < length3; i++) {
p1 = positions[i];
p2 = positions[(i + 1) % length3];
let tempPositions;
let tempTexcoords;
if (hasTexcoords) {
t1 = texcoords[i];
t2 = texcoords[(i + 1) % length3];
}
if (arcType === ArcType_default.GEODESIC) {
tempPositions = PolygonGeometryLibrary.subdivideLine(
p1,
p2,
minDistance,
computeWallIndicesSubdivided
);
if (hasTexcoords) {
tempTexcoords = PolygonGeometryLibrary.subdivideTexcoordLine(
t1,
t2,
p1,
p2,
minDistance,
computeWallTexcoordsSubdivided
);
}
} else if (arcType === ArcType_default.RHUMB) {
tempPositions = PolygonGeometryLibrary.subdivideRhumbLine(
ellipsoid,
p1,
p2,
minDistance,
computeWallIndicesSubdivided
);
if (hasTexcoords) {
tempTexcoords = PolygonGeometryLibrary.subdivideTexcoordRhumbLine(
t1,
t2,
ellipsoid,
p1,
p2,
minDistance,
computeWallTexcoordsSubdivided
);
}
}
const tempPositionsLength = tempPositions.length;
for (let j = 0; j < tempPositionsLength; ++j, ++index) {
edgePositions[index] = tempPositions[j];
edgePositions[index + topEdgeLength] = tempPositions[j];
}
edgePositions[index] = p2.x;
edgePositions[index + topEdgeLength] = p2.x;
++index;
edgePositions[index] = p2.y;
edgePositions[index + topEdgeLength] = p2.y;
++index;
edgePositions[index] = p2.z;
edgePositions[index + topEdgeLength] = p2.z;
++index;
if (hasTexcoords) {
const tempTexcoordsLength = tempTexcoords.length;
for (let k = 0; k < tempTexcoordsLength; ++k, ++textureIndex) {
edgeTexcoords[textureIndex] = tempTexcoords[k];
edgeTexcoords[textureIndex + topEdgeTexcoordLength] = tempTexcoords[k];
}
edgeTexcoords[textureIndex] = t2.x;
edgeTexcoords[textureIndex + topEdgeTexcoordLength] = t2.x;
++textureIndex;
edgeTexcoords[textureIndex] = t2.y;
edgeTexcoords[textureIndex + topEdgeTexcoordLength] = t2.y;
++textureIndex;
}
}
} else {
topEdgeLength = length3 * 3 * 2;
edgePositions = new Array(topEdgeLength * 2);
if (hasTexcoords) {
topEdgeTexcoordLength = length3 * 2 * 2;
edgeTexcoords = new Array(topEdgeTexcoordLength * 2);
}
for (i = 0; i < length3; i++) {
p1 = positions[i];
p2 = positions[(i + 1) % length3];
edgePositions[index] = edgePositions[index + topEdgeLength] = p1.x;
++index;
edgePositions[index] = edgePositions[index + topEdgeLength] = p1.y;
++index;
edgePositions[index] = edgePositions[index + topEdgeLength] = p1.z;
++index;
edgePositions[index] = edgePositions[index + topEdgeLength] = p2.x;
++index;
edgePositions[index] = edgePositions[index + topEdgeLength] = p2.y;
++index;
edgePositions[index] = edgePositions[index + topEdgeLength] = p2.z;
++index;
if (hasTexcoords) {
t1 = texcoords[i];
t2 = texcoords[(i + 1) % length3];
edgeTexcoords[textureIndex] = edgeTexcoords[textureIndex + topEdgeTexcoordLength] = t1.x;
++textureIndex;
edgeTexcoords[textureIndex] = edgeTexcoords[textureIndex + topEdgeTexcoordLength] = t1.y;
++textureIndex;
edgeTexcoords[textureIndex] = edgeTexcoords[textureIndex + topEdgeTexcoordLength] = t2.x;
++textureIndex;
edgeTexcoords[textureIndex] = edgeTexcoords[textureIndex + topEdgeTexcoordLength] = t2.y;
++textureIndex;
}
}
}
length3 = edgePositions.length;
const indices2 = IndexDatatype_default.createTypedArray(
length3 / 3,
length3 - positions.length * 6
);
let edgeIndex = 0;
length3 /= 6;
for (i = 0; i < length3; i++) {
const UL = i;
const UR = UL + 1;
const LL = UL + length3;
const LR = LL + 1;
p1 = Cartesian3_default.fromArray(edgePositions, UL * 3, p1Scratch2);
p2 = Cartesian3_default.fromArray(edgePositions, UR * 3, p2Scratch2);
if (Cartesian3_default.equalsEpsilon(
p1,
p2,
Math_default.EPSILON10,
Math_default.EPSILON10
)) {
continue;
}
indices2[edgeIndex++] = UL;
indices2[edgeIndex++] = LL;
indices2[edgeIndex++] = UR;
indices2[edgeIndex++] = UR;
indices2[edgeIndex++] = LL;
indices2[edgeIndex++] = LR;
}
const geometryOptions = {
attributes: new GeometryAttributes_default({
position: new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: edgePositions
})
}),
indices: indices2,
primitiveType: PrimitiveType_default.TRIANGLES
};
if (hasTexcoords) {
geometryOptions.attributes.st = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 2,
values: edgeTexcoords
});
}
const geometry = new Geometry_default(geometryOptions);
return geometry;
};
var PolygonGeometryLibrary_default = PolygonGeometryLibrary;
// packages/engine/Source/Core/CoplanarPolygonOutlineGeometry.js
function createGeometryFromPositions(positions) {
const length3 = positions.length;
const flatPositions2 = new Float64Array(length3 * 3);
const indices2 = IndexDatatype_default.createTypedArray(length3, length3 * 2);
let positionIndex = 0;
let index = 0;
for (let i = 0; i < length3; i++) {
const position = positions[i];
flatPositions2[positionIndex++] = position.x;
flatPositions2[positionIndex++] = position.y;
flatPositions2[positionIndex++] = position.z;
indices2[index++] = i;
indices2[index++] = (i + 1) % length3;
}
const attributes = new GeometryAttributes_default({
position: new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: flatPositions2
})
});
return new Geometry_default({
attributes,
indices: indices2,
primitiveType: PrimitiveType_default.LINES
});
}
function CoplanarPolygonOutlineGeometry(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const polygonHierarchy = options.polygonHierarchy;
Check_default.defined("options.polygonHierarchy", polygonHierarchy);
this._polygonHierarchy = polygonHierarchy;
this._workerName = "createCoplanarPolygonOutlineGeometry";
this.packedLength = PolygonGeometryLibrary_default.computeHierarchyPackedLength(
polygonHierarchy,
Cartesian3_default
) + 1;
}
CoplanarPolygonOutlineGeometry.fromPositions = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
Check_default.defined("options.positions", options.positions);
const newOptions2 = {
polygonHierarchy: {
positions: options.positions
}
};
return new CoplanarPolygonOutlineGeometry(newOptions2);
};
CoplanarPolygonOutlineGeometry.pack = function(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
startingIndex = PolygonGeometryLibrary_default.packPolygonHierarchy(
value._polygonHierarchy,
array,
startingIndex,
Cartesian3_default
);
array[startingIndex] = value.packedLength;
return array;
};
var scratchOptions4 = {
polygonHierarchy: {}
};
CoplanarPolygonOutlineGeometry.unpack = function(array, startingIndex, result) {
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
const polygonHierarchy = PolygonGeometryLibrary_default.unpackPolygonHierarchy(
array,
startingIndex,
Cartesian3_default
);
startingIndex = polygonHierarchy.startingIndex;
delete polygonHierarchy.startingIndex;
const packedLength = array[startingIndex];
if (!defined_default(result)) {
result = new CoplanarPolygonOutlineGeometry(scratchOptions4);
}
result._polygonHierarchy = polygonHierarchy;
result.packedLength = packedLength;
return result;
};
CoplanarPolygonOutlineGeometry.createGeometry = function(polygonGeometry) {
const polygonHierarchy = polygonGeometry._polygonHierarchy;
let outerPositions = polygonHierarchy.positions;
outerPositions = arrayRemoveDuplicates_default(
outerPositions,
Cartesian3_default.equalsEpsilon,
true
);
if (outerPositions.length < 3) {
return;
}
const isValid = CoplanarPolygonGeometryLibrary_default.validOutline(outerPositions);
if (!isValid) {
return void 0;
}
const polygons = PolygonGeometryLibrary_default.polygonOutlinesFromHierarchy(
polygonHierarchy,
false
);
if (polygons.length === 0) {
return void 0;
}
const geometries = [];
for (let i = 0; i < polygons.length; i++) {
const geometryInstance = new GeometryInstance_default({
geometry: createGeometryFromPositions(polygons[i])
});
geometries.push(geometryInstance);
}
const geometry = GeometryPipeline_default.combineInstances(geometries)[0];
const boundingSphere = BoundingSphere_default.fromPoints(polygonHierarchy.positions);
return new Geometry_default({
attributes: geometry.attributes,
indices: geometry.indices,
primitiveType: geometry.primitiveType,
boundingSphere
});
};
var CoplanarPolygonOutlineGeometry_default = CoplanarPolygonOutlineGeometry;
// packages/engine/Source/Scene/TileBoundingS2Cell.js
var centerCartographicScratch = new Cartographic_default();
function TileBoundingS2Cell(options) {
Check_default.typeOf.object("options", options);
Check_default.typeOf.string("options.token", options.token);
const s2Cell = S2Cell_default.fromToken(options.token);
const minimumHeight = defaultValue_default(options.minimumHeight, 0);
const maximumHeight = defaultValue_default(options.maximumHeight, 0);
const ellipsoid = defaultValue_default(options.ellipsoid, Ellipsoid_default.WGS84);
this.s2Cell = s2Cell;
this.minimumHeight = minimumHeight;
this.maximumHeight = maximumHeight;
this.ellipsoid = ellipsoid;
const boundingPlanes = computeBoundingPlanes(
s2Cell,
minimumHeight,
maximumHeight,
ellipsoid
);
this._boundingPlanes = boundingPlanes;
const vertices = computeVertices(boundingPlanes);
this._vertices = vertices;
this._edgeNormals = new Array(6);
this._edgeNormals[0] = computeEdgeNormals(
boundingPlanes[0],
vertices.slice(0, 4)
);
let i;
for (i = 0; i < 4; i++) {
this._edgeNormals[0][i] = Cartesian3_default.negate(
this._edgeNormals[0][i],
this._edgeNormals[0][i]
);
}
this._edgeNormals[1] = computeEdgeNormals(
boundingPlanes[1],
vertices.slice(4, 8)
);
for (i = 0; i < 4; i++) {
this._edgeNormals[2 + i] = computeEdgeNormals(boundingPlanes[2 + i], [
vertices[i % 4],
vertices[(i + 1) % 4],
vertices[4 + (i + 1) % 4],
vertices[4 + i]
]);
}
this._planeVertices = [
this._vertices.slice(0, 4),
this._vertices.slice(4, 8)
];
for (i = 0; i < 4; i++) {
this._planeVertices.push([
this._vertices[i % 4],
this._vertices[(i + 1) % 4],
this._vertices[4 + (i + 1) % 4],
this._vertices[4 + i]
]);
}
const center = s2Cell.getCenter();
centerCartographicScratch = ellipsoid.cartesianToCartographic(
center,
centerCartographicScratch
);
centerCartographicScratch.height = (maximumHeight + minimumHeight) / 2;
this.center = ellipsoid.cartographicToCartesian(
centerCartographicScratch,
center
);
this._boundingSphere = BoundingSphere_default.fromPoints(vertices);
}
var centerGeodeticNormalScratch = new Cartesian3_default();
var topCartographicScratch = new Cartographic_default();
var topScratch = new Cartesian3_default();
var vertexCartographicScratch = new Cartographic_default();
var vertexScratch = new Cartesian3_default();
var vertexGeodeticNormalScratch = new Cartesian3_default();
var sideNormalScratch = new Cartesian3_default();
var sideScratch = new Cartesian3_default();
function computeBoundingPlanes(s2Cell, minimumHeight, maximumHeight, ellipsoid) {
const planes = new Array(6);
const centerPoint = s2Cell.getCenter();
const centerSurfaceNormal = ellipsoid.geodeticSurfaceNormal(
centerPoint,
centerGeodeticNormalScratch
);
const topCartographic = ellipsoid.cartesianToCartographic(
centerPoint,
topCartographicScratch
);
topCartographic.height = maximumHeight;
const top = ellipsoid.cartographicToCartesian(topCartographic, topScratch);
const topPlane = Plane_default.fromPointNormal(top, centerSurfaceNormal);
planes[0] = topPlane;
let maxDistance = 0;
let i;
const vertices = [];
let vertex, vertexCartographic;
for (i = 0; i < 4; i++) {
vertex = s2Cell.getVertex(i);
vertices[i] = vertex;
vertexCartographic = ellipsoid.cartesianToCartographic(
vertex,
vertexCartographicScratch
);
vertexCartographic.height = minimumHeight;
const distance2 = Plane_default.getPointDistance(
topPlane,
ellipsoid.cartographicToCartesian(vertexCartographic, vertexScratch)
);
if (distance2 < maxDistance) {
maxDistance = distance2;
}
}
const bottomPlane = Plane_default.clone(topPlane);
bottomPlane.normal = Cartesian3_default.negate(
bottomPlane.normal,
bottomPlane.normal
);
bottomPlane.distance = bottomPlane.distance * -1 + maxDistance;
planes[1] = bottomPlane;
for (i = 0; i < 4; i++) {
vertex = vertices[i];
const adjacentVertex = vertices[(i + 1) % 4];
const geodeticNormal = ellipsoid.geodeticSurfaceNormal(
vertex,
vertexGeodeticNormalScratch
);
const side = Cartesian3_default.subtract(adjacentVertex, vertex, sideScratch);
let sideNormal = Cartesian3_default.cross(side, geodeticNormal, sideNormalScratch);
sideNormal = Cartesian3_default.normalize(sideNormal, sideNormal);
planes[2 + i] = Plane_default.fromPointNormal(vertex, sideNormal);
}
return planes;
}
var n0Scratch = new Cartesian3_default();
var n1Scratch = new Cartesian3_default();
var n2Scratch = new Cartesian3_default();
var x0Scratch = new Cartesian3_default();
var x1Scratch = new Cartesian3_default();
var x2Scratch = new Cartesian3_default();
var t0Scratch = new Cartesian3_default();
var t1Scratch = new Cartesian3_default();
var t2Scratch = new Cartesian3_default();
var f0Scratch = new Cartesian3_default();
var f1Scratch = new Cartesian3_default();
var f2Scratch = new Cartesian3_default();
var sScratch2 = new Cartesian3_default();
var matrixScratch = new Matrix3_default();
function computeIntersection(p0, p1, p2) {
n0Scratch = p0.normal;
n1Scratch = p1.normal;
n2Scratch = p2.normal;
x0Scratch = Cartesian3_default.multiplyByScalar(p0.normal, -p0.distance, x0Scratch);
x1Scratch = Cartesian3_default.multiplyByScalar(p1.normal, -p1.distance, x1Scratch);
x2Scratch = Cartesian3_default.multiplyByScalar(p2.normal, -p2.distance, x2Scratch);
f0Scratch = Cartesian3_default.multiplyByScalar(
Cartesian3_default.cross(n1Scratch, n2Scratch, t0Scratch),
Cartesian3_default.dot(x0Scratch, n0Scratch),
f0Scratch
);
f1Scratch = Cartesian3_default.multiplyByScalar(
Cartesian3_default.cross(n2Scratch, n0Scratch, t1Scratch),
Cartesian3_default.dot(x1Scratch, n1Scratch),
f1Scratch
);
f2Scratch = Cartesian3_default.multiplyByScalar(
Cartesian3_default.cross(n0Scratch, n1Scratch, t2Scratch),
Cartesian3_default.dot(x2Scratch, n2Scratch),
f2Scratch
);
matrixScratch[0] = n0Scratch.x;
matrixScratch[1] = n1Scratch.x;
matrixScratch[2] = n2Scratch.x;
matrixScratch[3] = n0Scratch.y;
matrixScratch[4] = n1Scratch.y;
matrixScratch[5] = n2Scratch.y;
matrixScratch[6] = n0Scratch.z;
matrixScratch[7] = n1Scratch.z;
matrixScratch[8] = n2Scratch.z;
const determinant = Matrix3_default.determinant(matrixScratch);
sScratch2 = Cartesian3_default.add(f0Scratch, f1Scratch, sScratch2);
sScratch2 = Cartesian3_default.add(sScratch2, f2Scratch, sScratch2);
return new Cartesian3_default(
sScratch2.x / determinant,
sScratch2.y / determinant,
sScratch2.z / determinant
);
}
function computeVertices(boundingPlanes) {
const vertices = new Array(8);
for (let i = 0; i < 4; i++) {
vertices[i] = computeIntersection(
boundingPlanes[0],
boundingPlanes[2 + (i + 3) % 4],
boundingPlanes[2 + i % 4]
);
vertices[i + 4] = computeIntersection(
boundingPlanes[1],
boundingPlanes[2 + (i + 3) % 4],
boundingPlanes[2 + i % 4]
);
}
return vertices;
}
var edgeScratch = new Cartesian3_default();
var edgeNormalScratch = new Cartesian3_default();
function computeEdgeNormals(plane, vertices) {
const edgeNormals = [];
for (let i = 0; i < 4; i++) {
edgeScratch = Cartesian3_default.subtract(
vertices[(i + 1) % 4],
vertices[i],
edgeScratch
);
edgeNormalScratch = Cartesian3_default.cross(
plane.normal,
edgeScratch,
edgeNormalScratch
);
edgeNormalScratch = Cartesian3_default.normalize(
edgeNormalScratch,
edgeNormalScratch
);
edgeNormals[i] = Cartesian3_default.clone(edgeNormalScratch);
}
return edgeNormals;
}
Object.defineProperties(TileBoundingS2Cell.prototype, {
/**
* The underlying bounding volume.
*
* @memberof TileOrientedBoundingBox.prototype
*
* @type {object}
* @readonly
*/
boundingVolume: {
get: function() {
return this;
}
},
/**
* The underlying bounding sphere.
*
* @memberof TileOrientedBoundingBox.prototype
*
* @type {BoundingSphere}
* @readonly
*/
boundingSphere: {
get: function() {
return this._boundingSphere;
}
}
});
var facePointScratch = new Cartesian3_default();
TileBoundingS2Cell.prototype.distanceToCamera = function(frameState) {
Check_default.defined("frameState", frameState);
const point = frameState.camera.positionWC;
const selectedPlaneIndices = [];
const vertices = [];
let edgeNormals;
if (Plane_default.getPointDistance(this._boundingPlanes[0], point) > 0) {
selectedPlaneIndices.push(0);
vertices.push(this._planeVertices[0]);
edgeNormals = this._edgeNormals[0];
} else if (Plane_default.getPointDistance(this._boundingPlanes[1], point) > 0) {
selectedPlaneIndices.push(1);
vertices.push(this._planeVertices[1]);
edgeNormals = this._edgeNormals[1];
}
let i;
let sidePlaneIndex;
for (i = 0; i < 4; i++) {
sidePlaneIndex = 2 + i;
if (Plane_default.getPointDistance(this._boundingPlanes[sidePlaneIndex], point) > 0) {
selectedPlaneIndices.push(sidePlaneIndex);
vertices.push(this._planeVertices[sidePlaneIndex]);
edgeNormals = this._edgeNormals[sidePlaneIndex];
}
}
if (selectedPlaneIndices.length === 0) {
return 0;
}
let facePoint;
let selectedPlane;
if (selectedPlaneIndices.length === 1) {
selectedPlane = this._boundingPlanes[selectedPlaneIndices[0]];
facePoint = closestPointPolygon(
Plane_default.projectPointOntoPlane(selectedPlane, point, facePointScratch),
vertices[0],
selectedPlane,
edgeNormals
);
return Cartesian3_default.distance(facePoint, point);
} else if (selectedPlaneIndices.length === 2) {
if (selectedPlaneIndices[0] === 0) {
const edge = [
this._vertices[4 * selectedPlaneIndices[0] + (selectedPlaneIndices[1] - 2)],
this._vertices[4 * selectedPlaneIndices[0] + (selectedPlaneIndices[1] - 2 + 1) % 4]
];
facePoint = closestPointLineSegment(point, edge[0], edge[1]);
return Cartesian3_default.distance(facePoint, point);
}
let minimumDistance = Number.MAX_VALUE;
let distance2;
for (i = 0; i < 2; i++) {
selectedPlane = this._boundingPlanes[selectedPlaneIndices[i]];
facePoint = closestPointPolygon(
Plane_default.projectPointOntoPlane(selectedPlane, point, facePointScratch),
vertices[i],
selectedPlane,
this._edgeNormals[selectedPlaneIndices[i]]
);
distance2 = Cartesian3_default.distanceSquared(facePoint, point);
if (distance2 < minimumDistance) {
minimumDistance = distance2;
}
}
return Math.sqrt(minimumDistance);
} else if (selectedPlaneIndices.length > 3) {
facePoint = closestPointPolygon(
Plane_default.projectPointOntoPlane(
this._boundingPlanes[1],
point,
facePointScratch
),
this._planeVertices[1],
this._boundingPlanes[1],
this._edgeNormals[1]
);
return Cartesian3_default.distance(facePoint, point);
}
const skip = selectedPlaneIndices[1] === 2 && selectedPlaneIndices[2] === 5 ? 0 : 1;
if (selectedPlaneIndices[0] === 0) {
return Cartesian3_default.distance(
point,
this._vertices[(selectedPlaneIndices[1] - 2 + skip) % 4]
);
}
return Cartesian3_default.distance(
point,
this._vertices[4 + (selectedPlaneIndices[1] - 2 + skip) % 4]
);
};
var dScratch2 = new Cartesian3_default();
var pL0Scratch = new Cartesian3_default();
function closestPointLineSegment(p, l0, l1) {
const d = Cartesian3_default.subtract(l1, l0, dScratch2);
const pL0 = Cartesian3_default.subtract(p, l0, pL0Scratch);
let t = Cartesian3_default.dot(d, pL0);
if (t <= 0) {
return l0;
}
const dMag = Cartesian3_default.dot(d, d);
if (t >= dMag) {
return l1;
}
t = t / dMag;
return new Cartesian3_default(
(1 - t) * l0.x + t * l1.x,
(1 - t) * l0.y + t * l1.y,
(1 - t) * l0.z + t * l1.z
);
}
var edgePlaneScratch = new Plane_default(Cartesian3_default.UNIT_X, 0);
function closestPointPolygon(p, vertices, plane, edgeNormals) {
let minDistance = Number.MAX_VALUE;
let distance2;
let closestPoint;
let closestPointOnEdge;
for (let i = 0; i < vertices.length; i++) {
const edgePlane = Plane_default.fromPointNormal(
vertices[i],
edgeNormals[i],
edgePlaneScratch
);
const edgePlaneDistance = Plane_default.getPointDistance(edgePlane, p);
if (edgePlaneDistance < 0) {
continue;
}
closestPointOnEdge = closestPointLineSegment(
p,
vertices[i],
vertices[(i + 1) % 4]
);
distance2 = Cartesian3_default.distance(p, closestPointOnEdge);
if (distance2 < minDistance) {
minDistance = distance2;
closestPoint = closestPointOnEdge;
}
}
if (!defined_default(closestPoint)) {
return p;
}
return closestPoint;
}
TileBoundingS2Cell.prototype.intersectPlane = function(plane) {
Check_default.defined("plane", plane);
let plusCount = 0;
let negCount = 0;
for (let i = 0; i < this._vertices.length; i++) {
const distanceToPlane = Cartesian3_default.dot(plane.normal, this._vertices[i]) + plane.distance;
if (distanceToPlane < 0) {
negCount++;
} else {
plusCount++;
}
}
if (plusCount === this._vertices.length) {
return Intersect_default.INSIDE;
} else if (negCount === this._vertices.length) {
return Intersect_default.OUTSIDE;
}
return Intersect_default.INTERSECTING;
};
TileBoundingS2Cell.prototype.createDebugVolume = function(color) {
Check_default.defined("color", color);
const modelMatrix = new Matrix4_default.clone(Matrix4_default.IDENTITY);
const topPlanePolygon = new CoplanarPolygonOutlineGeometry_default({
polygonHierarchy: {
positions: this._planeVertices[0]
}
});
const topPlaneGeometry = CoplanarPolygonOutlineGeometry_default.createGeometry(
topPlanePolygon
);
const topPlaneInstance = new GeometryInstance_default({
geometry: topPlaneGeometry,
id: "outline",
modelMatrix,
attributes: {
color: ColorGeometryInstanceAttribute_default.fromColor(color)
}
});
const bottomPlanePolygon = new CoplanarPolygonOutlineGeometry_default({
polygonHierarchy: {
positions: this._planeVertices[1]
}
});
const bottomPlaneGeometry = CoplanarPolygonOutlineGeometry_default.createGeometry(
bottomPlanePolygon
);
const bottomPlaneInstance = new GeometryInstance_default({
geometry: bottomPlaneGeometry,
id: "outline",
modelMatrix,
attributes: {
color: ColorGeometryInstanceAttribute_default.fromColor(color)
}
});
const sideInstances = [];
for (let i = 0; i < 4; i++) {
const sidePlanePolygon = new CoplanarPolygonOutlineGeometry_default({
polygonHierarchy: {
positions: this._planeVertices[2 + i]
}
});
const sidePlaneGeometry = CoplanarPolygonOutlineGeometry_default.createGeometry(
sidePlanePolygon
);
sideInstances[i] = new GeometryInstance_default({
geometry: sidePlaneGeometry,
id: "outline",
modelMatrix,
attributes: {
color: ColorGeometryInstanceAttribute_default.fromColor(color)
}
});
}
return new Primitive_default({
geometryInstances: [
sideInstances[0],
sideInstances[1],
sideInstances[2],
sideInstances[3],
bottomPlaneInstance,
topPlaneInstance
],
appearance: new PerInstanceColorAppearance_default({
translucent: false,
flat: true
}),
asynchronous: false
});
};
var TileBoundingS2Cell_default = TileBoundingS2Cell;
// packages/engine/Source/Core/EllipsoidOutlineGeometry.js
var defaultRadii = new Cartesian3_default(1, 1, 1);
var cos2 = Math.cos;
var sin2 = Math.sin;
function EllipsoidOutlineGeometry(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const radii = defaultValue_default(options.radii, defaultRadii);
const innerRadii = defaultValue_default(options.innerRadii, radii);
const minimumClock = defaultValue_default(options.minimumClock, 0);
const maximumClock = defaultValue_default(options.maximumClock, Math_default.TWO_PI);
const minimumCone = defaultValue_default(options.minimumCone, 0);
const maximumCone = defaultValue_default(options.maximumCone, Math_default.PI);
const stackPartitions = Math.round(defaultValue_default(options.stackPartitions, 10));
const slicePartitions = Math.round(defaultValue_default(options.slicePartitions, 8));
const subdivisions = Math.round(defaultValue_default(options.subdivisions, 128));
if (stackPartitions < 1) {
throw new DeveloperError_default("options.stackPartitions cannot be less than 1");
}
if (slicePartitions < 0) {
throw new DeveloperError_default("options.slicePartitions cannot be less than 0");
}
if (subdivisions < 0) {
throw new DeveloperError_default(
"options.subdivisions must be greater than or equal to zero."
);
}
if (defined_default(options.offsetAttribute) && options.offsetAttribute === GeometryOffsetAttribute_default.TOP) {
throw new DeveloperError_default(
"GeometryOffsetAttribute.TOP is not a supported options.offsetAttribute for this geometry."
);
}
this._radii = Cartesian3_default.clone(radii);
this._innerRadii = Cartesian3_default.clone(innerRadii);
this._minimumClock = minimumClock;
this._maximumClock = maximumClock;
this._minimumCone = minimumCone;
this._maximumCone = maximumCone;
this._stackPartitions = stackPartitions;
this._slicePartitions = slicePartitions;
this._subdivisions = subdivisions;
this._offsetAttribute = options.offsetAttribute;
this._workerName = "createEllipsoidOutlineGeometry";
}
EllipsoidOutlineGeometry.packedLength = 2 * Cartesian3_default.packedLength + 8;
EllipsoidOutlineGeometry.pack = function(value, array, startingIndex) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required");
}
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
Cartesian3_default.pack(value._radii, array, startingIndex);
startingIndex += Cartesian3_default.packedLength;
Cartesian3_default.pack(value._innerRadii, array, startingIndex);
startingIndex += Cartesian3_default.packedLength;
array[startingIndex++] = value._minimumClock;
array[startingIndex++] = value._maximumClock;
array[startingIndex++] = value._minimumCone;
array[startingIndex++] = value._maximumCone;
array[startingIndex++] = value._stackPartitions;
array[startingIndex++] = value._slicePartitions;
array[startingIndex++] = value._subdivisions;
array[startingIndex] = defaultValue_default(value._offsetAttribute, -1);
return array;
};
var scratchRadii = new Cartesian3_default();
var scratchInnerRadii = new Cartesian3_default();
var scratchOptions5 = {
radii: scratchRadii,
innerRadii: scratchInnerRadii,
minimumClock: void 0,
maximumClock: void 0,
minimumCone: void 0,
maximumCone: void 0,
stackPartitions: void 0,
slicePartitions: void 0,
subdivisions: void 0,
offsetAttribute: void 0
};
EllipsoidOutlineGeometry.unpack = function(array, startingIndex, result) {
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
const radii = Cartesian3_default.unpack(array, startingIndex, scratchRadii);
startingIndex += Cartesian3_default.packedLength;
const innerRadii = Cartesian3_default.unpack(array, startingIndex, scratchInnerRadii);
startingIndex += Cartesian3_default.packedLength;
const minimumClock = array[startingIndex++];
const maximumClock = array[startingIndex++];
const minimumCone = array[startingIndex++];
const maximumCone = array[startingIndex++];
const stackPartitions = array[startingIndex++];
const slicePartitions = array[startingIndex++];
const subdivisions = array[startingIndex++];
const offsetAttribute = array[startingIndex];
if (!defined_default(result)) {
scratchOptions5.minimumClock = minimumClock;
scratchOptions5.maximumClock = maximumClock;
scratchOptions5.minimumCone = minimumCone;
scratchOptions5.maximumCone = maximumCone;
scratchOptions5.stackPartitions = stackPartitions;
scratchOptions5.slicePartitions = slicePartitions;
scratchOptions5.subdivisions = subdivisions;
scratchOptions5.offsetAttribute = offsetAttribute === -1 ? void 0 : offsetAttribute;
return new EllipsoidOutlineGeometry(scratchOptions5);
}
result._radii = Cartesian3_default.clone(radii, result._radii);
result._innerRadii = Cartesian3_default.clone(innerRadii, result._innerRadii);
result._minimumClock = minimumClock;
result._maximumClock = maximumClock;
result._minimumCone = minimumCone;
result._maximumCone = maximumCone;
result._stackPartitions = stackPartitions;
result._slicePartitions = slicePartitions;
result._subdivisions = subdivisions;
result._offsetAttribute = offsetAttribute === -1 ? void 0 : offsetAttribute;
return result;
};
EllipsoidOutlineGeometry.createGeometry = function(ellipsoidGeometry) {
const radii = ellipsoidGeometry._radii;
if (radii.x <= 0 || radii.y <= 0 || radii.z <= 0) {
return;
}
const innerRadii = ellipsoidGeometry._innerRadii;
if (innerRadii.x <= 0 || innerRadii.y <= 0 || innerRadii.z <= 0) {
return;
}
const minimumClock = ellipsoidGeometry._minimumClock;
const maximumClock = ellipsoidGeometry._maximumClock;
const minimumCone = ellipsoidGeometry._minimumCone;
const maximumCone = ellipsoidGeometry._maximumCone;
const subdivisions = ellipsoidGeometry._subdivisions;
const ellipsoid = Ellipsoid_default.fromCartesian3(radii);
let slicePartitions = ellipsoidGeometry._slicePartitions + 1;
let stackPartitions = ellipsoidGeometry._stackPartitions + 1;
slicePartitions = Math.round(
slicePartitions * Math.abs(maximumClock - minimumClock) / Math_default.TWO_PI
);
stackPartitions = Math.round(
stackPartitions * Math.abs(maximumCone - minimumCone) / Math_default.PI
);
if (slicePartitions < 2) {
slicePartitions = 2;
}
if (stackPartitions < 2) {
stackPartitions = 2;
}
let extraIndices = 0;
let vertexMultiplier = 1;
const hasInnerSurface = innerRadii.x !== radii.x || innerRadii.y !== radii.y || innerRadii.z !== radii.z;
let isTopOpen = false;
let isBotOpen = false;
if (hasInnerSurface) {
vertexMultiplier = 2;
if (minimumCone > 0) {
isTopOpen = true;
extraIndices += slicePartitions;
}
if (maximumCone < Math.PI) {
isBotOpen = true;
extraIndices += slicePartitions;
}
}
const vertexCount = subdivisions * vertexMultiplier * (stackPartitions + slicePartitions);
const positions = new Float64Array(vertexCount * 3);
const numIndices = 2 * (vertexCount + extraIndices - (slicePartitions + stackPartitions) * vertexMultiplier);
const indices2 = IndexDatatype_default.createTypedArray(vertexCount, numIndices);
let i;
let j;
let theta;
let phi;
let index = 0;
const sinPhi = new Array(stackPartitions);
const cosPhi = new Array(stackPartitions);
for (i = 0; i < stackPartitions; i++) {
phi = minimumCone + i * (maximumCone - minimumCone) / (stackPartitions - 1);
sinPhi[i] = sin2(phi);
cosPhi[i] = cos2(phi);
}
const sinTheta = new Array(subdivisions);
const cosTheta = new Array(subdivisions);
for (i = 0; i < subdivisions; i++) {
theta = minimumClock + i * (maximumClock - minimumClock) / (subdivisions - 1);
sinTheta[i] = sin2(theta);
cosTheta[i] = cos2(theta);
}
for (i = 0; i < stackPartitions; i++) {
for (j = 0; j < subdivisions; j++) {
positions[index++] = radii.x * sinPhi[i] * cosTheta[j];
positions[index++] = radii.y * sinPhi[i] * sinTheta[j];
positions[index++] = radii.z * cosPhi[i];
}
}
if (hasInnerSurface) {
for (i = 0; i < stackPartitions; i++) {
for (j = 0; j < subdivisions; j++) {
positions[index++] = innerRadii.x * sinPhi[i] * cosTheta[j];
positions[index++] = innerRadii.y * sinPhi[i] * sinTheta[j];
positions[index++] = innerRadii.z * cosPhi[i];
}
}
}
sinPhi.length = subdivisions;
cosPhi.length = subdivisions;
for (i = 0; i < subdivisions; i++) {
phi = minimumCone + i * (maximumCone - minimumCone) / (subdivisions - 1);
sinPhi[i] = sin2(phi);
cosPhi[i] = cos2(phi);
}
sinTheta.length = slicePartitions;
cosTheta.length = slicePartitions;
for (i = 0; i < slicePartitions; i++) {
theta = minimumClock + i * (maximumClock - minimumClock) / (slicePartitions - 1);
sinTheta[i] = sin2(theta);
cosTheta[i] = cos2(theta);
}
for (i = 0; i < subdivisions; i++) {
for (j = 0; j < slicePartitions; j++) {
positions[index++] = radii.x * sinPhi[i] * cosTheta[j];
positions[index++] = radii.y * sinPhi[i] * sinTheta[j];
positions[index++] = radii.z * cosPhi[i];
}
}
if (hasInnerSurface) {
for (i = 0; i < subdivisions; i++) {
for (j = 0; j < slicePartitions; j++) {
positions[index++] = innerRadii.x * sinPhi[i] * cosTheta[j];
positions[index++] = innerRadii.y * sinPhi[i] * sinTheta[j];
positions[index++] = innerRadii.z * cosPhi[i];
}
}
}
index = 0;
for (i = 0; i < stackPartitions * vertexMultiplier; i++) {
const topOffset = i * subdivisions;
for (j = 0; j < subdivisions - 1; j++) {
indices2[index++] = topOffset + j;
indices2[index++] = topOffset + j + 1;
}
}
let offset2 = stackPartitions * subdivisions * vertexMultiplier;
for (i = 0; i < slicePartitions; i++) {
for (j = 0; j < subdivisions - 1; j++) {
indices2[index++] = offset2 + i + j * slicePartitions;
indices2[index++] = offset2 + i + (j + 1) * slicePartitions;
}
}
if (hasInnerSurface) {
offset2 = stackPartitions * subdivisions * vertexMultiplier + slicePartitions * subdivisions;
for (i = 0; i < slicePartitions; i++) {
for (j = 0; j < subdivisions - 1; j++) {
indices2[index++] = offset2 + i + j * slicePartitions;
indices2[index++] = offset2 + i + (j + 1) * slicePartitions;
}
}
}
if (hasInnerSurface) {
let outerOffset = stackPartitions * subdivisions * vertexMultiplier;
let innerOffset = outerOffset + subdivisions * slicePartitions;
if (isTopOpen) {
for (i = 0; i < slicePartitions; i++) {
indices2[index++] = outerOffset + i;
indices2[index++] = innerOffset + i;
}
}
if (isBotOpen) {
outerOffset += subdivisions * slicePartitions - slicePartitions;
innerOffset += subdivisions * slicePartitions - slicePartitions;
for (i = 0; i < slicePartitions; i++) {
indices2[index++] = outerOffset + i;
indices2[index++] = innerOffset + i;
}
}
}
const attributes = new GeometryAttributes_default({
position: new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: positions
})
});
if (defined_default(ellipsoidGeometry._offsetAttribute)) {
const length3 = positions.length;
const offsetValue = ellipsoidGeometry._offsetAttribute === GeometryOffsetAttribute_default.NONE ? 0 : 1;
const applyOffset = new Uint8Array(length3 / 3).fill(offsetValue);
attributes.applyOffset = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentsPerAttribute: 1,
values: applyOffset
});
}
return new Geometry_default({
attributes,
indices: indices2,
primitiveType: PrimitiveType_default.LINES,
boundingSphere: BoundingSphere_default.fromEllipsoid(ellipsoid),
offsetAttribute: ellipsoidGeometry._offsetAttribute
});
};
var EllipsoidOutlineGeometry_default = EllipsoidOutlineGeometry;
// packages/engine/Source/Core/SphereOutlineGeometry.js
function SphereOutlineGeometry(options) {
const radius = defaultValue_default(options.radius, 1);
const radii = new Cartesian3_default(radius, radius, radius);
const ellipsoidOptions = {
radii,
stackPartitions: options.stackPartitions,
slicePartitions: options.slicePartitions,
subdivisions: options.subdivisions
};
this._ellipsoidGeometry = new EllipsoidOutlineGeometry_default(ellipsoidOptions);
this._workerName = "createSphereOutlineGeometry";
}
SphereOutlineGeometry.packedLength = EllipsoidOutlineGeometry_default.packedLength;
SphereOutlineGeometry.pack = function(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
return EllipsoidOutlineGeometry_default.pack(
value._ellipsoidGeometry,
array,
startingIndex
);
};
var scratchEllipsoidGeometry = new EllipsoidOutlineGeometry_default();
var scratchOptions6 = {
radius: void 0,
radii: new Cartesian3_default(),
stackPartitions: void 0,
slicePartitions: void 0,
subdivisions: void 0
};
SphereOutlineGeometry.unpack = function(array, startingIndex, result) {
const ellipsoidGeometry = EllipsoidOutlineGeometry_default.unpack(
array,
startingIndex,
scratchEllipsoidGeometry
);
scratchOptions6.stackPartitions = ellipsoidGeometry._stackPartitions;
scratchOptions6.slicePartitions = ellipsoidGeometry._slicePartitions;
scratchOptions6.subdivisions = ellipsoidGeometry._subdivisions;
if (!defined_default(result)) {
scratchOptions6.radius = ellipsoidGeometry._radii.x;
return new SphereOutlineGeometry(scratchOptions6);
}
Cartesian3_default.clone(ellipsoidGeometry._radii, scratchOptions6.radii);
result._ellipsoidGeometry = new EllipsoidOutlineGeometry_default(scratchOptions6);
return result;
};
SphereOutlineGeometry.createGeometry = function(sphereGeometry) {
return EllipsoidOutlineGeometry_default.createGeometry(
sphereGeometry._ellipsoidGeometry
);
};
var SphereOutlineGeometry_default = SphereOutlineGeometry;
// packages/engine/Source/Scene/TileBoundingSphere.js
function TileBoundingSphere(center, radius) {
if (radius === 0) {
radius = Math_default.EPSILON7;
}
this._boundingSphere = new BoundingSphere_default(center, radius);
}
Object.defineProperties(TileBoundingSphere.prototype, {
/**
* The center of the bounding sphere
*
* @memberof TileBoundingSphere.prototype
*
* @type {Cartesian3}
* @readonly
*/
center: {
get: function() {
return this._boundingSphere.center;
}
},
/**
* The radius of the bounding sphere
*
* @memberof TileBoundingSphere.prototype
*
* @type {number}
* @readonly
*/
radius: {
get: function() {
return this._boundingSphere.radius;
}
},
/**
* The underlying bounding volume
*
* @memberof TileBoundingSphere.prototype
*
* @type {object}
* @readonly
*/
boundingVolume: {
get: function() {
return this._boundingSphere;
}
},
/**
* The underlying bounding sphere
*
* @memberof TileBoundingSphere.prototype
*
* @type {BoundingSphere}
* @readonly
*/
boundingSphere: {
get: function() {
return this._boundingSphere;
}
}
});
TileBoundingSphere.prototype.distanceToCamera = function(frameState) {
Check_default.defined("frameState", frameState);
const boundingSphere = this._boundingSphere;
return Math.max(
0,
Cartesian3_default.distance(boundingSphere.center, frameState.camera.positionWC) - boundingSphere.radius
);
};
TileBoundingSphere.prototype.intersectPlane = function(plane) {
Check_default.defined("plane", plane);
return BoundingSphere_default.intersectPlane(this._boundingSphere, plane);
};
TileBoundingSphere.prototype.update = function(center, radius) {
Cartesian3_default.clone(center, this._boundingSphere.center);
this._boundingSphere.radius = radius;
};
TileBoundingSphere.prototype.createDebugVolume = function(color) {
Check_default.defined("color", color);
const geometry = new SphereOutlineGeometry_default({
radius: this.radius
});
const modelMatrix = Matrix4_default.fromTranslation(
this.center,
new Matrix4_default.clone(Matrix4_default.IDENTITY)
);
const instance = new GeometryInstance_default({
geometry,
id: "outline",
modelMatrix,
attributes: {
color: ColorGeometryInstanceAttribute_default.fromColor(color)
}
});
return new Primitive_default({
geometryInstances: instance,
appearance: new PerInstanceColorAppearance_default({
translucent: false,
flat: true
}),
asynchronous: false
});
};
var TileBoundingSphere_default = TileBoundingSphere;
// packages/engine/Source/Scene/TileOrientedBoundingBox.js
var scratchU = new Cartesian3_default();
var scratchV = new Cartesian3_default();
var scratchW2 = new Cartesian3_default();
var scratchCartesian8 = new Cartesian3_default();
function computeMissingVector(a3, b, result) {
result = Cartesian3_default.cross(a3, b, result);
const magnitude = Cartesian3_default.magnitude(result);
return Cartesian3_default.multiplyByScalar(
result,
Math_default.EPSILON7 / magnitude,
result
);
}
function findOrthogonalVector(a3, result) {
const temp = Cartesian3_default.normalize(a3, scratchCartesian8);
const b = Cartesian3_default.equalsEpsilon(
temp,
Cartesian3_default.UNIT_X,
Math_default.EPSILON6
) ? Cartesian3_default.UNIT_Y : Cartesian3_default.UNIT_X;
return computeMissingVector(a3, b, result);
}
function checkHalfAxes(halfAxes) {
let u3 = Matrix3_default.getColumn(halfAxes, 0, scratchU);
let v7 = Matrix3_default.getColumn(halfAxes, 1, scratchV);
let w = Matrix3_default.getColumn(halfAxes, 2, scratchW2);
const uZero = Cartesian3_default.equals(u3, Cartesian3_default.ZERO);
const vZero = Cartesian3_default.equals(v7, Cartesian3_default.ZERO);
const wZero = Cartesian3_default.equals(w, Cartesian3_default.ZERO);
if (!uZero && !vZero && !wZero) {
return halfAxes;
}
if (uZero && vZero && wZero) {
halfAxes[0] = Math_default.EPSILON7;
halfAxes[4] = Math_default.EPSILON7;
halfAxes[8] = Math_default.EPSILON7;
return halfAxes;
}
if (uZero && !vZero && !wZero) {
u3 = computeMissingVector(v7, w, u3);
} else if (!uZero && vZero && !wZero) {
v7 = computeMissingVector(u3, w, v7);
} else if (!uZero && !vZero && wZero) {
w = computeMissingVector(v7, u3, w);
} else if (!uZero) {
v7 = findOrthogonalVector(u3, v7);
w = computeMissingVector(v7, u3, w);
} else if (!vZero) {
u3 = findOrthogonalVector(v7, u3);
w = computeMissingVector(v7, u3, w);
} else if (!wZero) {
u3 = findOrthogonalVector(w, u3);
v7 = computeMissingVector(w, u3, v7);
}
Matrix3_default.setColumn(halfAxes, 0, u3, halfAxes);
Matrix3_default.setColumn(halfAxes, 1, v7, halfAxes);
Matrix3_default.setColumn(halfAxes, 2, w, halfAxes);
return halfAxes;
}
function TileOrientedBoundingBox(center, halfAxes) {
halfAxes = checkHalfAxes(halfAxes);
this._orientedBoundingBox = new OrientedBoundingBox_default(center, halfAxes);
this._boundingSphere = BoundingSphere_default.fromOrientedBoundingBox(
this._orientedBoundingBox
);
}
Object.defineProperties(TileOrientedBoundingBox.prototype, {
/**
* The underlying bounding volume.
*
* @memberof TileOrientedBoundingBox.prototype
*
* @type {object}
* @readonly
*/
boundingVolume: {
get: function() {
return this._orientedBoundingBox;
}
},
/**
* The underlying bounding sphere.
*
* @memberof TileOrientedBoundingBox.prototype
*
* @type {BoundingSphere}
* @readonly
*/
boundingSphere: {
get: function() {
return this._boundingSphere;
}
}
});
TileOrientedBoundingBox.prototype.distanceToCamera = function(frameState) {
Check_default.defined("frameState", frameState);
return Math.sqrt(
this._orientedBoundingBox.distanceSquaredTo(frameState.camera.positionWC)
);
};
TileOrientedBoundingBox.prototype.intersectPlane = function(plane) {
Check_default.defined("plane", plane);
return this._orientedBoundingBox.intersectPlane(plane);
};
TileOrientedBoundingBox.prototype.update = function(center, halfAxes) {
Cartesian3_default.clone(center, this._orientedBoundingBox.center);
halfAxes = checkHalfAxes(halfAxes);
Matrix3_default.clone(halfAxes, this._orientedBoundingBox.halfAxes);
BoundingSphere_default.fromOrientedBoundingBox(
this._orientedBoundingBox,
this._boundingSphere
);
};
TileOrientedBoundingBox.prototype.createDebugVolume = function(color) {
Check_default.defined("color", color);
const geometry = new BoxOutlineGeometry_default({
// Make a 2x2x2 cube
minimum: new Cartesian3_default(-1, -1, -1),
maximum: new Cartesian3_default(1, 1, 1)
});
const modelMatrix = Matrix4_default.fromRotationTranslation(
this.boundingVolume.halfAxes,
this.boundingVolume.center
);
const instance = new GeometryInstance_default({
geometry,
id: "outline",
modelMatrix,
attributes: {
color: ColorGeometryInstanceAttribute_default.fromColor(color)
}
});
return new Primitive_default({
geometryInstances: instance,
appearance: new PerInstanceColorAppearance_default({
translucent: false,
flat: true
}),
asynchronous: false
});
};
var TileOrientedBoundingBox_default = TileOrientedBoundingBox;
// packages/engine/Source/Scene/Cesium3DTile.js
function Cesium3DTile(tileset, baseResource2, header, parent) {
this._tileset = tileset;
this._header = header;
const hasContentsArray = defined_default(header.contents);
const hasMultipleContents = hasContentsArray && header.contents.length > 1 || hasExtension_default(header, "3DTILES_multiple_contents");
const contentHeader = hasContentsArray && !hasMultipleContents ? header.contents[0] : header.content;
this._contentHeader = contentHeader;
this.transform = defined_default(header.transform) ? Matrix4_default.unpack(header.transform) : Matrix4_default.clone(Matrix4_default.IDENTITY);
const parentTransform = defined_default(parent) ? parent.computedTransform : tileset.modelMatrix;
const computedTransform = Matrix4_default.multiply(
parentTransform,
this.transform,
new Matrix4_default()
);
const parentInitialTransform = defined_default(parent) ? parent._initialTransform : Matrix4_default.IDENTITY;
this._initialTransform = Matrix4_default.multiply(
parentInitialTransform,
this.transform,
new Matrix4_default()
);
this.computedTransform = computedTransform;
this._boundingVolume = this.createBoundingVolume(
header.boundingVolume,
computedTransform
);
this._boundingVolume2D = void 0;
let contentBoundingVolume;
if (defined_default(contentHeader) && defined_default(contentHeader.boundingVolume)) {
contentBoundingVolume = this.createBoundingVolume(
contentHeader.boundingVolume,
computedTransform
);
}
this._contentBoundingVolume = contentBoundingVolume;
this._contentBoundingVolume2D = void 0;
let viewerRequestVolume;
if (defined_default(header.viewerRequestVolume)) {
viewerRequestVolume = this.createBoundingVolume(
header.viewerRequestVolume,
computedTransform
);
}
this._viewerRequestVolume = viewerRequestVolume;
this.geometricError = header.geometricError;
this._geometricError = header.geometricError;
if (!defined_default(this._geometricError)) {
this._geometricError = defined_default(parent) ? parent._geometricError : tileset._geometricError;
Cesium3DTile._deprecationWarning(
"geometricErrorUndefined",
"Required property geometricError is undefined for this tile. Using parent's geometric error instead."
);
}
this.updateGeometricErrorScale();
let refine;
if (defined_default(header.refine)) {
if (header.refine === "replace" || header.refine === "add") {
Cesium3DTile._deprecationWarning(
"lowercase-refine",
`This tile uses a lowercase refine "${header.refine}". Instead use "${header.refine.toUpperCase()}".`
);
}
refine = header.refine.toUpperCase() === "REPLACE" ? Cesium3DTileRefine_default.REPLACE : Cesium3DTileRefine_default.ADD;
} else if (defined_default(parent)) {
refine = parent.refine;
} else {
refine = Cesium3DTileRefine_default.REPLACE;
}
this.refine = refine;
this.children = [];
this.parent = parent;
let content;
let hasEmptyContent = false;
let contentState;
let contentResource;
let serverKey;
baseResource2 = Resource_default.createIfNeeded(baseResource2);
if (hasMultipleContents) {
contentState = Cesium3DTileContentState_default.UNLOADED;
contentResource = baseResource2.clone();
} else if (defined_default(contentHeader)) {
let contentHeaderUri = contentHeader.uri;
if (defined_default(contentHeader.url)) {
Cesium3DTile._deprecationWarning(
"contentUrl",
'This tileset JSON uses the "content.url" property which has been deprecated. Use "content.uri" instead.'
);
contentHeaderUri = contentHeader.url;
}
if (contentHeaderUri === "") {
Cesium3DTile._deprecationWarning(
"contentUriEmpty",
"content.uri property is an empty string, which creates a circular dependency, making this tileset invalid. Omit the content property instead"
);
content = new Empty3DTileContent_default(tileset, this);
hasEmptyContent = true;
contentState = Cesium3DTileContentState_default.READY;
} else {
contentState = Cesium3DTileContentState_default.UNLOADED;
contentResource = baseResource2.getDerivedResource({
url: contentHeaderUri
});
serverKey = RequestScheduler_default.getServerKey(
contentResource.getUrlComponent()
);
}
} else {
content = new Empty3DTileContent_default(tileset, this);
hasEmptyContent = true;
contentState = Cesium3DTileContentState_default.READY;
}
this._content = content;
this._contentResource = contentResource;
this._contentState = contentState;
this._expiredContent = void 0;
this._serverKey = serverKey;
this.hasEmptyContent = hasEmptyContent;
this.hasTilesetContent = false;
this.hasImplicitContent = false;
this.hasImplicitContentMetadata = false;
this.hasMultipleContents = hasMultipleContents;
this.metadata = findTileMetadata_default(tileset, header);
this.cacheNode = void 0;
const expire = header.expire;
let expireDuration;
let expireDate;
if (defined_default(expire)) {
expireDuration = expire.duration;
if (defined_default(expire.date)) {
expireDate = JulianDate_default.fromIso8601(expire.date);
}
}
this.expireDuration = expireDuration;
this.expireDate = expireDate;
this.lastStyleTime = 0;
this._optimChildrenWithinParent = Cesium3DTileOptimizationHint_default.NOT_COMPUTED;
this.clippingPlanesDirty = false;
this.priorityDeferred = false;
this.implicitTileset = void 0;
this.implicitCoordinates = void 0;
this.implicitSubtree = void 0;
this._distanceToCamera = 0;
this._centerZDepth = 0;
this._screenSpaceError = 0;
this._screenSpaceErrorProgressiveResolution = 0;
this._visibilityPlaneMask = 0;
this._visible = false;
this._inRequestVolume = false;
this._finalResolution = true;
this._depth = 0;
this._stackLength = 0;
this._selectionDepth = 0;
this._updatedVisibilityFrame = 0;
this._touchedFrame = 0;
this._visitedFrame = 0;
this._selectedFrame = 0;
this._requestedFrame = 0;
this._ancestorWithContent = void 0;
this._ancestorWithContentAvailable = void 0;
this._refines = false;
this._shouldSelect = false;
this._isClipped = true;
this._clippingPlanesState = 0;
this._debugBoundingVolume = void 0;
this._debugContentBoundingVolume = void 0;
this._debugViewerRequestVolume = void 0;
this._debugColor = Color_default.fromRandom({ alpha: 1 });
this._debugColorizeTiles = false;
this._priority = 0;
this._priorityHolder = this;
this._priorityProgressiveResolution = false;
this._priorityProgressiveResolutionScreenSpaceErrorLeaf = false;
this._priorityReverseScreenSpaceError = 0;
this._foveatedFactor = 0;
this._wasMinPriorityChild = false;
this._loadTimestamp = new JulianDate_default();
this._commandsLength = 0;
this._color = void 0;
this._colorDirty = false;
this._request = void 0;
}
Cesium3DTile._deprecationWarning = deprecationWarning_default;
Object.defineProperties(Cesium3DTile.prototype, {
/**
* The tileset containing this tile.
*
* @memberof Cesium3DTile.prototype
*
* @type {Cesium3DTileset}
* @readonly
*/
tileset: {
get: function() {
return this._tileset;
}
},
/**
* The tile's content. This represents the actual tile's payload,
* not the content's metadata in the tileset JSON file.
*
* @memberof Cesium3DTile.prototype
*
* @type {Cesium3DTileContent}
* @readonly
*/
content: {
get: function() {
return this._content;
}
},
/**
* Get the tile's bounding volume.
*
* @memberof Cesium3DTile.prototype
*
* @type {TileBoundingVolume}
* @readonly
* @private
*/
boundingVolume: {
get: function() {
return this._boundingVolume;
}
},
/**
* Get the bounding volume of the tile's contents. This defaults to the
* tile's bounding volume when the content's bounding volume is
* undefined
.
*
* @memberof Cesium3DTile.prototype
*
* @type {TileBoundingVolume}
* @readonly
* @private
*/
contentBoundingVolume: {
get: function() {
return defaultValue_default(this._contentBoundingVolume, this._boundingVolume);
}
},
/**
* Get the bounding sphere derived from the tile's bounding volume.
*
* @memberof Cesium3DTile.prototype
*
* @type {BoundingSphere}
* @readonly
*/
boundingSphere: {
get: function() {
return this._boundingVolume.boundingSphere;
}
},
/**
* Determines if the tile is visible within the current field of view
*
* @memberof Cesium3DTile.prototype
*
* @type {boolean}
* @readonly
*
* @private
*/
isVisible: {
get: function() {
return this._visible && this._inRequestVolume;
}
},
/**
* Returns the extras
property in the tileset JSON for this tile, which contains application specific metadata.
* Returns undefined
if extras
does not exist.
*
* @memberof Cesium3DTile.prototype
*
* @type {object}
* @readonly
* @see {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification#specifying-extensions-and-application-specific-extras|Extras in the 3D Tiles specification.}
*/
extras: {
get: function() {
return this._header.extras;
}
},
/**
* Gets or sets the tile's highlight color.
*
* @memberof Cesium3DTile.prototype
*
* @type {Color}
*
* @default {@link Color.WHITE}
*
* @private
*/
color: {
get: function() {
if (!defined_default(this._color)) {
this._color = new Color_default();
}
return Color_default.clone(this._color);
},
set: function(value) {
this._color = Color_default.clone(value, this._color);
this._colorDirty = true;
}
},
/**
* Determines if the tile's content is renderable. false
if the
* tile has empty content or if it points to an external tileset or implicit content
*
* @memberof Cesium3DTile.prototype
*
* @type {boolean}
* @readonly
*
* @private
*/
hasRenderableContent: {
get: function() {
return !this.hasEmptyContent && !this.hasTilesetContent && !this.hasImplicitContent;
}
},
/**
* Determines if the tile has available content to render. true
if the tile's
* content is ready or if it has expired content that renders while new content loads; otherwise,
* false
.
*
* @memberof Cesium3DTile.prototype
*
* @type {boolean}
* @readonly
*
* @private
*/
contentAvailable: {
get: function() {
return this.contentReady && this.hasRenderableContent || defined_default(this._expiredContent) && !this.contentFailed;
}
},
/**
* Determines if the tile's content is ready. This is automatically true
for
* tile's with empty content.
*
* @memberof Cesium3DTile.prototype
*
* @type {boolean}
* @readonly
*
* @private
*/
contentReady: {
get: function() {
return this._contentState === Cesium3DTileContentState_default.READY;
}
},
/**
* Determines if the tile's content has not be requested. true
if tile's
* content has not be requested; otherwise, false
.
*
* @memberof Cesium3DTile.prototype
*
* @type {boolean}
* @readonly
*
* @private
*/
contentUnloaded: {
get: function() {
return this._contentState === Cesium3DTileContentState_default.UNLOADED;
}
},
/**
* Determines if the tile has renderable content which is unloaded
*
* @memberof Cesium3DTile.prototype
*
* @type {boolean}
* @readonly
*
* @private
*/
hasUnloadedRenderableContent: {
get: function() {
return this.hasRenderableContent && this.contentUnloaded;
}
},
/**
* Determines if the tile's content is expired. true
if tile's
* content is expired; otherwise, false
.
*
* @memberof Cesium3DTile.prototype
*
* @type {boolean}
* @readonly
*
* @private
*/
contentExpired: {
get: function() {
return this._contentState === Cesium3DTileContentState_default.EXPIRED;
}
},
/**
* Determines if the tile's content failed to load. true
if the tile's
* content failed to load; otherwise, false
.
*
* @memberof Cesium3DTile.prototype
*
* @type {boolean}
* @readonly
*
* @private
*/
contentFailed: {
get: function() {
return this._contentState === Cesium3DTileContentState_default.FAILED;
}
},
/**
* Returns the number of draw commands used by this tile.
*
* @readonly
*
* @private
*/
commandsLength: {
get: function() {
return this._commandsLength;
}
}
});
var scratchCartesian9 = new Cartesian3_default();
function isPriorityDeferred(tile, frameState) {
const { tileset, boundingSphere } = tile;
const { radius, center } = boundingSphere;
const { camera } = frameState;
const scaledCameraDirection = Cartesian3_default.multiplyByScalar(
camera.directionWC,
tile._centerZDepth,
scratchCartesian9
);
const closestPointOnLine = Cartesian3_default.add(
camera.positionWC,
scaledCameraDirection,
scratchCartesian9
);
const toLine = Cartesian3_default.subtract(
closestPointOnLine,
center,
scratchCartesian9
);
const distanceToCenterLine = Cartesian3_default.magnitude(toLine);
const notTouchingSphere = distanceToCenterLine > radius;
if (notTouchingSphere) {
const toLineNormalized = Cartesian3_default.normalize(toLine, scratchCartesian9);
const scaledToLine = Cartesian3_default.multiplyByScalar(
toLineNormalized,
radius,
scratchCartesian9
);
const closestOnSphere = Cartesian3_default.add(
center,
scaledToLine,
scratchCartesian9
);
const toClosestOnSphere = Cartesian3_default.subtract(
closestOnSphere,
camera.positionWC,
scratchCartesian9
);
const toClosestOnSphereNormalize = Cartesian3_default.normalize(
toClosestOnSphere,
scratchCartesian9
);
tile._foveatedFactor = 1 - Math.abs(Cartesian3_default.dot(camera.directionWC, toClosestOnSphereNormalize));
} else {
tile._foveatedFactor = 0;
}
const replace = tile.refine === Cesium3DTileRefine_default.REPLACE;
const skipLevelOfDetail = tileset.isSkippingLevelOfDetail;
if (replace && !skipLevelOfDetail || !tileset.foveatedScreenSpaceError || tileset.foveatedConeSize === 1 || tile._priorityProgressiveResolution && replace && skipLevelOfDetail || tileset._pass === Cesium3DTilePass_default.PRELOAD_FLIGHT || tileset._pass === Cesium3DTilePass_default.PRELOAD) {
return false;
}
const maximumFovatedFactor = 1 - Math.cos(camera.frustum.fov * 0.5);
const foveatedConeFactor = tileset.foveatedConeSize * maximumFovatedFactor;
if (tile._foveatedFactor <= foveatedConeFactor) {
return false;
}
const range = maximumFovatedFactor - foveatedConeFactor;
const normalizedFoveatedFactor = Math_default.clamp(
(tile._foveatedFactor - foveatedConeFactor) / range,
0,
1
);
const sseRelaxation = tileset.foveatedInterpolationCallback(
tileset.foveatedMinimumScreenSpaceErrorRelaxation,
tileset.maximumScreenSpaceError,
normalizedFoveatedFactor
);
const sse = tile._screenSpaceError === 0 && defined_default(tile.parent) ? tile.parent._screenSpaceError * 0.5 : tile._screenSpaceError;
return tileset.maximumScreenSpaceError - sseRelaxation <= sse;
}
var scratchJulianDate = new JulianDate_default();
Cesium3DTile.prototype.getScreenSpaceError = function(frameState, useParentGeometricError, progressiveResolutionHeightFraction) {
const tileset = this._tileset;
const heightFraction = defaultValue_default(progressiveResolutionHeightFraction, 1);
const parentGeometricError = defined_default(this.parent) ? this.parent.geometricError : tileset._scaledGeometricError;
const geometricError = useParentGeometricError ? parentGeometricError : this.geometricError;
if (geometricError === 0) {
return 0;
}
const { camera, context } = frameState;
let frustum = camera.frustum;
const width = context.drawingBufferWidth;
const height = context.drawingBufferHeight * heightFraction;
let error;
if (frameState.mode === SceneMode_default.SCENE2D || frustum instanceof OrthographicFrustum_default) {
const offCenterFrustum = frustum.offCenterFrustum;
if (defined_default(offCenterFrustum)) {
frustum = offCenterFrustum;
}
const pixelSize = Math.max(frustum.top - frustum.bottom, frustum.right - frustum.left) / Math.max(width, height);
error = geometricError / pixelSize;
} else {
const distance2 = Math.max(this._distanceToCamera, Math_default.EPSILON7);
const sseDenominator = frustum.sseDenominator;
error = geometricError * height / (distance2 * sseDenominator);
if (tileset.dynamicScreenSpaceError) {
const density = tileset._dynamicScreenSpaceErrorComputedDensity;
const factor2 = tileset.dynamicScreenSpaceErrorFactor;
const dynamicError = Math_default.fog(distance2, density) * factor2;
error -= dynamicError;
}
}
error /= frameState.pixelRatio;
return error;
};
function isPriorityProgressiveResolution(tileset, tile) {
if (tileset.progressiveResolutionHeightFraction <= 0 || tileset.progressiveResolutionHeightFraction > 0.5) {
return false;
}
let isProgressiveResolutionTile = tile._screenSpaceErrorProgressiveResolution > tileset._maximumScreenSpaceError;
tile._priorityProgressiveResolutionScreenSpaceErrorLeaf = false;
const parent = tile.parent;
const maximumScreenSpaceError = tileset._maximumScreenSpaceError;
const tilePasses = tile._screenSpaceErrorProgressiveResolution <= maximumScreenSpaceError;
const parentFails = defined_default(parent) && parent._screenSpaceErrorProgressiveResolution > maximumScreenSpaceError;
if (tilePasses && parentFails) {
tile._priorityProgressiveResolutionScreenSpaceErrorLeaf = true;
isProgressiveResolutionTile = true;
}
return isProgressiveResolutionTile;
}
function getPriorityReverseScreenSpaceError(tileset, tile) {
const parent = tile.parent;
const useParentScreenSpaceError = defined_default(parent) && (!tileset.isSkippingLevelOfDetail || tile._screenSpaceError === 0 || parent.hasTilesetContent || parent.hasImplicitContent);
const screenSpaceError2 = useParentScreenSpaceError ? parent._screenSpaceError : tile._screenSpaceError;
return tileset.root._screenSpaceError - screenSpaceError2;
}
Cesium3DTile.prototype.updateVisibility = function(frameState) {
const { parent, tileset } = this;
if (this._updatedVisibilityFrame === tileset._updatedVisibilityFrame) {
return;
}
const parentTransform = defined_default(parent) ? parent.computedTransform : tileset.modelMatrix;
const parentVisibilityPlaneMask = defined_default(parent) ? parent._visibilityPlaneMask : CullingVolume_default.MASK_INDETERMINATE;
this.updateTransform(parentTransform);
this._distanceToCamera = this.distanceToTile(frameState);
this._centerZDepth = this.distanceToTileCenter(frameState);
this._screenSpaceError = this.getScreenSpaceError(frameState, false);
this._screenSpaceErrorProgressiveResolution = this.getScreenSpaceError(
frameState,
false,
tileset.progressiveResolutionHeightFraction
);
this._visibilityPlaneMask = this.visibility(
frameState,
parentVisibilityPlaneMask
);
this._visible = this._visibilityPlaneMask !== CullingVolume_default.MASK_OUTSIDE;
this._inRequestVolume = this.insideViewerRequestVolume(frameState);
this._priorityReverseScreenSpaceError = getPriorityReverseScreenSpaceError(
tileset,
this
);
this._priorityProgressiveResolution = isPriorityProgressiveResolution(
tileset,
this
);
this.priorityDeferred = isPriorityDeferred(this, frameState);
this._updatedVisibilityFrame = tileset._updatedVisibilityFrame;
};
Cesium3DTile.prototype.updateExpiration = function() {
if (defined_default(this.expireDate) && this.contentReady && !this.hasEmptyContent && !this.hasMultipleContents) {
const now2 = JulianDate_default.now(scratchJulianDate);
if (JulianDate_default.lessThan(this.expireDate, now2)) {
this._contentState = Cesium3DTileContentState_default.EXPIRED;
this._expiredContent = this._content;
}
}
};
function updateExpireDate(tile) {
if (!defined_default(tile.expireDuration)) {
return;
}
const expireDurationDate = JulianDate_default.now(scratchJulianDate);
JulianDate_default.addSeconds(
expireDurationDate,
tile.expireDuration,
expireDurationDate
);
if (defined_default(tile.expireDate)) {
if (JulianDate_default.lessThan(tile.expireDate, expireDurationDate)) {
JulianDate_default.clone(expireDurationDate, tile.expireDate);
}
} else {
tile.expireDate = JulianDate_default.clone(expireDurationDate);
}
}
function createPriorityFunction(tile) {
return function() {
return tile._priority;
};
}
Cesium3DTile.prototype.requestContent = function() {
if (this.hasEmptyContent) {
return;
}
if (this.hasMultipleContents) {
return requestMultipleContents(this);
}
return requestSingleContent(this);
};
function requestMultipleContents(tile) {
let multipleContents = tile._content;
const tileset = tile._tileset;
if (!defined_default(multipleContents)) {
const contentsJson = hasExtension_default(tile._header, "3DTILES_multiple_contents") ? tile._header.extensions["3DTILES_multiple_contents"] : tile._header;
multipleContents = new Multiple3DTileContent_default(
tileset,
tile,
tile._contentResource.clone(),
contentsJson
);
tile._content = multipleContents;
}
const promise = multipleContents.requestInnerContents();
if (!defined_default(promise)) {
return;
}
tile._contentState = Cesium3DTileContentState_default.LOADING;
return promise.then((content) => {
if (tile.isDestroyed()) {
return;
}
if (!defined_default(content)) {
return;
}
tile._contentState = Cesium3DTileContentState_default.PROCESSING;
return multipleContents;
}).catch((error) => {
if (tile.isDestroyed()) {
return;
}
tile._contentState = Cesium3DTileContentState_default.FAILED;
throw error;
});
}
async function processArrayBuffer(tile, tileset, request, expired, requestPromise) {
const previousState = tile._contentState;
tile._contentState = Cesium3DTileContentState_default.LOADING;
++tileset.statistics.numberOfPendingRequests;
let arrayBuffer;
try {
arrayBuffer = await requestPromise;
} catch (error) {
--tileset.statistics.numberOfPendingRequests;
if (tile.isDestroyed()) {
return;
}
if (request.cancelled || request.state === RequestState_default.CANCELLED) {
tile._contentState = previousState;
++tileset.statistics.numberOfAttemptedRequests;
return;
}
tile._contentState = Cesium3DTileContentState_default.FAILED;
throw error;
}
if (tile.isDestroyed()) {
--tileset.statistics.numberOfPendingRequests;
return;
}
if (request.cancelled || request.state === RequestState_default.CANCELLED) {
tile._contentState = previousState;
--tileset.statistics.numberOfPendingRequests;
++tileset.statistics.numberOfAttemptedRequests;
return;
}
try {
const content = await makeContent(tile, arrayBuffer);
--tileset.statistics.numberOfPendingRequests;
if (tile.isDestroyed()) {
return;
}
if (expired) {
tile.expireDate = void 0;
}
tile._content = content;
tile._contentState = Cesium3DTileContentState_default.PROCESSING;
return content;
} catch (error) {
--tileset.statistics.numberOfPendingRequests;
if (tile.isDestroyed()) {
return;
}
tile._contentState = Cesium3DTileContentState_default.FAILED;
throw error;
}
}
function requestSingleContent(tile) {
const resource = tile._contentResource.clone();
const expired = tile.contentExpired;
if (expired) {
resource.setQueryParameters({
expired: tile.expireDate.toString()
});
}
const request = new Request_default({
throttle: true,
throttleByServer: true,
type: RequestType_default.TILES3D,
priorityFunction: createPriorityFunction(tile),
serverKey: tile._serverKey
});
tile._request = request;
resource.request = request;
const tileset = tile._tileset;
const promise = resource.fetchArrayBuffer();
if (!defined_default(promise)) {
++tileset.statistics.numberOfAttemptedRequests;
return;
}
return processArrayBuffer(tile, tileset, request, expired, promise);
}
async function makeContent(tile, arrayBuffer) {
const preprocessed = preprocess3DTileContent_default(arrayBuffer);
const tileset = tile._tileset;
tileset._disableSkipLevelOfDetail = tileset._disableSkipLevelOfDetail || preprocessed.contentType === Cesium3DTileContentType_default.GEOMETRY || preprocessed.contentType === Cesium3DTileContentType_default.VECTOR;
if (preprocessed.contentType === Cesium3DTileContentType_default.IMPLICIT_SUBTREE || preprocessed.contentType === Cesium3DTileContentType_default.IMPLICIT_SUBTREE_JSON) {
tile.hasImplicitContent = true;
}
if (preprocessed.contentType === Cesium3DTileContentType_default.EXTERNAL_TILESET) {
tile.hasTilesetContent = true;
}
let content;
const contentFactory = Cesium3DTileContentFactory_default[preprocessed.contentType];
if (tile.isDestroyed()) {
return;
}
if (defined_default(preprocessed.binaryPayload)) {
content = await Promise.resolve(
contentFactory(
tileset,
tile,
tile._contentResource,
preprocessed.binaryPayload.buffer,
0
)
);
} else {
content = await Promise.resolve(
contentFactory(
tileset,
tile,
tile._contentResource,
preprocessed.jsonPayload
)
);
}
const contentHeader = tile._contentHeader;
if (tile.hasImplicitContentMetadata) {
const subtree = tile.implicitSubtree;
const coordinates = tile.implicitCoordinates;
content.metadata = subtree.getContentMetadataView(coordinates, 0);
} else if (!tile.hasImplicitContent) {
content.metadata = findContentMetadata_default(tileset, contentHeader);
}
const groupMetadata = findGroupMetadata_default(tileset, contentHeader);
if (defined_default(groupMetadata)) {
content.group = new Cesium3DContentGroup_default({
metadata: groupMetadata
});
}
return content;
}
Cesium3DTile.prototype.cancelRequests = function() {
if (this.hasMultipleContents) {
this._content.cancelRequests();
} else {
this._request.cancel();
}
};
Cesium3DTile.prototype.unloadContent = function() {
if (!this.hasRenderableContent) {
return;
}
this._content = this._content && this._content.destroy();
this._contentState = Cesium3DTileContentState_default.UNLOADED;
this.lastStyleTime = 0;
this.clippingPlanesDirty = this._clippingPlanesState === 0;
this._clippingPlanesState = 0;
this._debugColorizeTiles = false;
this._debugBoundingVolume = this._debugBoundingVolume && this._debugBoundingVolume.destroy();
this._debugContentBoundingVolume = this._debugContentBoundingVolume && this._debugContentBoundingVolume.destroy();
this._debugViewerRequestVolume = this._debugViewerRequestVolume && this._debugViewerRequestVolume.destroy();
};
var scratchProjectedBoundingSphere = new BoundingSphere_default();
function getBoundingVolume(tile, frameState) {
if (frameState.mode !== SceneMode_default.SCENE3D && !defined_default(tile._boundingVolume2D)) {
const boundingSphere = tile._boundingVolume.boundingSphere;
const sphere = BoundingSphere_default.projectTo2D(
boundingSphere,
frameState.mapProjection,
scratchProjectedBoundingSphere
);
tile._boundingVolume2D = new TileBoundingSphere_default(
sphere.center,
sphere.radius
);
}
return frameState.mode !== SceneMode_default.SCENE3D ? tile._boundingVolume2D : tile._boundingVolume;
}
function getContentBoundingVolume2(tile, frameState) {
if (frameState.mode !== SceneMode_default.SCENE3D && !defined_default(tile._contentBoundingVolume2D)) {
const boundingSphere = tile._contentBoundingVolume.boundingSphere;
const sphere = BoundingSphere_default.projectTo2D(
boundingSphere,
frameState.mapProjection,
scratchProjectedBoundingSphere
);
tile._contentBoundingVolume2D = new TileBoundingSphere_default(
sphere.center,
sphere.radius
);
}
return frameState.mode !== SceneMode_default.SCENE3D ? tile._contentBoundingVolume2D : tile._contentBoundingVolume;
}
Cesium3DTile.prototype.visibility = function(frameState, parentVisibilityPlaneMask) {
const cullingVolume = frameState.cullingVolume;
const boundingVolume = getBoundingVolume(this, frameState);
const tileset = this._tileset;
const clippingPlanes = tileset.clippingPlanes;
if (defined_default(clippingPlanes) && clippingPlanes.enabled) {
const intersection = clippingPlanes.computeIntersectionWithBoundingVolume(
boundingVolume,
tileset.clippingPlanesOriginMatrix
);
this._isClipped = intersection !== Intersect_default.INSIDE;
if (intersection === Intersect_default.OUTSIDE) {
return CullingVolume_default.MASK_OUTSIDE;
}
}
return cullingVolume.computeVisibilityWithPlaneMask(
boundingVolume,
parentVisibilityPlaneMask
);
};
Cesium3DTile.prototype.contentVisibility = function(frameState) {
if (!defined_default(this._contentBoundingVolume)) {
return Intersect_default.INSIDE;
}
if (this._visibilityPlaneMask === CullingVolume_default.MASK_INSIDE) {
return Intersect_default.INSIDE;
}
const cullingVolume = frameState.cullingVolume;
const boundingVolume = getContentBoundingVolume2(this, frameState);
const tileset = this._tileset;
const clippingPlanes = tileset.clippingPlanes;
if (defined_default(clippingPlanes) && clippingPlanes.enabled) {
const intersection = clippingPlanes.computeIntersectionWithBoundingVolume(
boundingVolume,
tileset.clippingPlanesOriginMatrix
);
this._isClipped = intersection !== Intersect_default.INSIDE;
if (intersection === Intersect_default.OUTSIDE) {
return Intersect_default.OUTSIDE;
}
}
return cullingVolume.computeVisibility(boundingVolume);
};
Cesium3DTile.prototype.distanceToTile = function(frameState) {
const boundingVolume = getBoundingVolume(this, frameState);
return boundingVolume.distanceToCamera(frameState);
};
var scratchToTileCenter = new Cartesian3_default();
Cesium3DTile.prototype.distanceToTileCenter = function(frameState) {
const tileBoundingVolume = getBoundingVolume(this, frameState);
const boundingVolume = tileBoundingVolume.boundingVolume;
const toCenter = Cartesian3_default.subtract(
boundingVolume.center,
frameState.camera.positionWC,
scratchToTileCenter
);
return Cartesian3_default.dot(frameState.camera.directionWC, toCenter);
};
Cesium3DTile.prototype.insideViewerRequestVolume = function(frameState) {
const viewerRequestVolume = this._viewerRequestVolume;
return !defined_default(viewerRequestVolume) || viewerRequestVolume.distanceToCamera(frameState) === 0;
};
var scratchMatrix2 = new Matrix3_default();
var scratchScale3 = new Cartesian3_default();
var scratchHalfAxes2 = new Matrix3_default();
var scratchCenter4 = new Cartesian3_default();
var scratchRectangle3 = new Rectangle_default();
var scratchOrientedBoundingBox = new OrientedBoundingBox_default();
var scratchTransform = new Matrix4_default();
function createBox(box, transform3, result) {
let center = Cartesian3_default.fromElements(box[0], box[1], box[2], scratchCenter4);
let halfAxes = Matrix3_default.fromArray(box, 3, scratchHalfAxes2);
center = Matrix4_default.multiplyByPoint(transform3, center, center);
const rotationScale = Matrix4_default.getMatrix3(transform3, scratchMatrix2);
halfAxes = Matrix3_default.multiply(rotationScale, halfAxes, halfAxes);
if (defined_default(result)) {
result.update(center, halfAxes);
return result;
}
return new TileOrientedBoundingBox_default(center, halfAxes);
}
function createBoxFromTransformedRegion(region, transform3, initialTransform, result) {
const rectangle = Rectangle_default.unpack(region, 0, scratchRectangle3);
const minimumHeight = region[4];
const maximumHeight = region[5];
const orientedBoundingBox = OrientedBoundingBox_default.fromRectangle(
rectangle,
minimumHeight,
maximumHeight,
Ellipsoid_default.WGS84,
scratchOrientedBoundingBox
);
let center = orientedBoundingBox.center;
let halfAxes = orientedBoundingBox.halfAxes;
transform3 = Matrix4_default.multiplyTransformation(
transform3,
Matrix4_default.inverseTransformation(initialTransform, scratchTransform),
scratchTransform
);
center = Matrix4_default.multiplyByPoint(transform3, center, center);
const rotationScale = Matrix4_default.getMatrix3(transform3, scratchMatrix2);
halfAxes = Matrix3_default.multiply(rotationScale, halfAxes, halfAxes);
if (defined_default(result) && result instanceof TileOrientedBoundingBox_default) {
result.update(center, halfAxes);
return result;
}
return new TileOrientedBoundingBox_default(center, halfAxes);
}
function createRegion(region, transform3, initialTransform, result) {
if (!Matrix4_default.equalsEpsilon(transform3, initialTransform, Math_default.EPSILON8)) {
return createBoxFromTransformedRegion(
region,
transform3,
initialTransform,
result
);
}
if (defined_default(result)) {
return result;
}
const rectangleRegion = Rectangle_default.unpack(region, 0, scratchRectangle3);
return new TileBoundingRegion_default({
rectangle: rectangleRegion,
minimumHeight: region[4],
maximumHeight: region[5]
});
}
function createSphere(sphere, transform3, result) {
let center = Cartesian3_default.fromElements(
sphere[0],
sphere[1],
sphere[2],
scratchCenter4
);
let radius = sphere[3];
center = Matrix4_default.multiplyByPoint(transform3, center, center);
const scale = Matrix4_default.getScale(transform3, scratchScale3);
const uniformScale = Cartesian3_default.maximumComponent(scale);
radius *= uniformScale;
if (defined_default(result)) {
result.update(center, radius);
return result;
}
return new TileBoundingSphere_default(center, radius);
}
Cesium3DTile.prototype.createBoundingVolume = function(boundingVolumeHeader, transform3, result) {
if (!defined_default(boundingVolumeHeader)) {
throw new RuntimeError_default("boundingVolume must be defined");
}
if (hasExtension_default(boundingVolumeHeader, "3DTILES_bounding_volume_S2")) {
return new TileBoundingS2Cell_default(
boundingVolumeHeader.extensions["3DTILES_bounding_volume_S2"]
);
}
const { box, region, sphere } = boundingVolumeHeader;
if (defined_default(box)) {
return createBox(box, transform3, result);
}
if (defined_default(region)) {
return createRegion(region, transform3, this._initialTransform, result);
}
if (defined_default(sphere)) {
return createSphere(sphere, transform3, result);
}
throw new RuntimeError_default(
"boundingVolume must contain a sphere, region, or box"
);
};
Cesium3DTile.prototype.updateTransform = function(parentTransform) {
parentTransform = defaultValue_default(parentTransform, Matrix4_default.IDENTITY);
const computedTransform = Matrix4_default.multiplyTransformation(
parentTransform,
this.transform,
scratchTransform
);
const transformChanged = !Matrix4_default.equals(
computedTransform,
this.computedTransform
);
if (!transformChanged) {
return;
}
Matrix4_default.clone(computedTransform, this.computedTransform);
const header = this._header;
const contentHeader = this._contentHeader;
this._boundingVolume = this.createBoundingVolume(
header.boundingVolume,
this.computedTransform,
this._boundingVolume
);
if (defined_default(this._contentBoundingVolume)) {
this._contentBoundingVolume = this.createBoundingVolume(
contentHeader.boundingVolume,
this.computedTransform,
this._contentBoundingVolume
);
}
if (defined_default(this._viewerRequestVolume)) {
this._viewerRequestVolume = this.createBoundingVolume(
header.viewerRequestVolume,
this.computedTransform,
this._viewerRequestVolume
);
}
this.updateGeometricErrorScale();
this._debugBoundingVolume = this._debugBoundingVolume && this._debugBoundingVolume.destroy();
this._debugContentBoundingVolume = this._debugContentBoundingVolume && this._debugContentBoundingVolume.destroy();
this._debugViewerRequestVolume = this._debugViewerRequestVolume && this._debugViewerRequestVolume.destroy();
};
Cesium3DTile.prototype.updateGeometricErrorScale = function() {
const scale = Matrix4_default.getScale(this.computedTransform, scratchScale3);
const uniformScale = Cartesian3_default.maximumComponent(scale);
this.geometricError = this._geometricError * uniformScale;
if (!defined_default(this.parent)) {
const tileset = this._tileset;
tileset._scaledGeometricError = tileset._geometricError * uniformScale;
}
};
function applyDebugSettings(tile, tileset, frameState, passOptions2) {
if (!passOptions2.isRender) {
return;
}
const hasContentBoundingVolume = defined_default(tile._contentHeader) && defined_default(tile._contentHeader.boundingVolume);
const showVolume = tileset.debugShowBoundingVolume || tileset.debugShowContentBoundingVolume && !hasContentBoundingVolume;
if (showVolume) {
let color;
if (!tile._finalResolution) {
color = Color_default.YELLOW;
} else if (!tile.hasRenderableContent) {
color = Color_default.DARKGRAY;
} else {
color = Color_default.WHITE;
}
if (!defined_default(tile._debugBoundingVolume)) {
tile._debugBoundingVolume = tile._boundingVolume.createDebugVolume(color);
}
tile._debugBoundingVolume.update(frameState);
const attributes = tile._debugBoundingVolume.getGeometryInstanceAttributes(
"outline"
);
attributes.color = ColorGeometryInstanceAttribute_default.toValue(
color,
attributes.color
);
} else if (!showVolume && defined_default(tile._debugBoundingVolume)) {
tile._debugBoundingVolume = tile._debugBoundingVolume.destroy();
}
if (tileset.debugShowContentBoundingVolume && hasContentBoundingVolume) {
if (!defined_default(tile._debugContentBoundingVolume)) {
tile._debugContentBoundingVolume = tile._contentBoundingVolume.createDebugVolume(
Color_default.BLUE
);
}
tile._debugContentBoundingVolume.update(frameState);
} else if (!tileset.debugShowContentBoundingVolume && defined_default(tile._debugContentBoundingVolume)) {
tile._debugContentBoundingVolume = tile._debugContentBoundingVolume.destroy();
}
if (tileset.debugShowViewerRequestVolume && defined_default(tile._viewerRequestVolume)) {
if (!defined_default(tile._debugViewerRequestVolume)) {
tile._debugViewerRequestVolume = tile._viewerRequestVolume.createDebugVolume(
Color_default.YELLOW
);
}
tile._debugViewerRequestVolume.update(frameState);
} else if (!tileset.debugShowViewerRequestVolume && defined_default(tile._debugViewerRequestVolume)) {
tile._debugViewerRequestVolume = tile._debugViewerRequestVolume.destroy();
}
const debugColorizeTilesOn = tileset.debugColorizeTiles && !tile._debugColorizeTiles || defined_default(tileset._heatmap.tilePropertyName);
const debugColorizeTilesOff = !tileset.debugColorizeTiles && tile._debugColorizeTiles;
if (debugColorizeTilesOn) {
tileset._heatmap.colorize(tile, frameState);
tile._debugColorizeTiles = true;
tile.color = tile._debugColor;
} else if (debugColorizeTilesOff) {
tile._debugColorizeTiles = false;
tile.color = Color_default.WHITE;
}
if (tile._colorDirty) {
tile._colorDirty = false;
tile._content.applyDebugSettings(true, tile._color);
}
if (debugColorizeTilesOff) {
tileset.makeStyleDirty();
}
}
function updateContent(tile, tileset, frameState) {
const expiredContent = tile._expiredContent;
if (!tile.hasMultipleContents && defined_default(expiredContent)) {
if (!tile.contentReady) {
try {
expiredContent.update(tileset, frameState);
} catch (error) {
}
return;
}
tile._expiredContent.destroy();
tile._expiredContent = void 0;
}
if (!defined_default(tile.content)) {
return;
}
try {
tile.content.update(tileset, frameState);
} catch (error) {
tile._contentState = Cesium3DTileContentState_default.FAILED;
throw error;
}
}
function updateClippingPlanes2(tile, tileset) {
const clippingPlanes = tileset.clippingPlanes;
let currentClippingPlanesState = 0;
if (defined_default(clippingPlanes) && tile._isClipped && clippingPlanes.enabled) {
currentClippingPlanesState = clippingPlanes.clippingPlanesState;
}
if (currentClippingPlanesState !== tile._clippingPlanesState) {
tile._clippingPlanesState = currentClippingPlanesState;
tile.clippingPlanesDirty = true;
}
}
Cesium3DTile.prototype.update = function(tileset, frameState, passOptions2) {
const { commandList } = frameState;
const commandStart = commandList.length;
updateClippingPlanes2(this, tileset);
applyDebugSettings(this, tileset, frameState, passOptions2);
updateContent(this, tileset, frameState);
const commandEnd = commandList.length;
this._commandsLength = commandEnd - commandStart;
for (let i = commandStart; i < commandEnd; ++i) {
const command = commandList[i];
const translucent = command.pass === Pass_default.TRANSLUCENT;
command.depthForTranslucentClassification = translucent;
}
this.clippingPlanesDirty = false;
};
var scratchCommandList = [];
Cesium3DTile.prototype.process = function(tileset, frameState) {
if (!this.contentExpired && !this.contentReady && this._content.ready) {
updateExpireDate(this);
this._selectedFrame = 0;
this.lastStyleTime = 0;
JulianDate_default.now(this._loadTimestamp);
this._contentState = Cesium3DTileContentState_default.READY;
if (!this.hasTilesetContent && !this.hasImplicitContent) {
tileset._statistics.incrementLoadCounts(this.content);
++tileset._statistics.numberOfTilesWithContentReady;
++tileset._statistics.numberOfLoadedTilesTotal;
tileset._cache.add(this);
}
}
const savedCommandList = frameState.commandList;
frameState.commandList = scratchCommandList;
try {
this._content.update(tileset, frameState);
} catch (error) {
this._contentState = Cesium3DTileContentState_default.FAILED;
throw error;
}
scratchCommandList.length = 0;
frameState.commandList = savedCommandList;
};
function isolateDigits(normalizedValue, numberOfDigits, leftShift) {
const scaled = normalizedValue * Math.pow(10, numberOfDigits);
const integer = parseInt(scaled);
return integer * Math.pow(10, leftShift);
}
function priorityNormalizeAndClamp(value, minimum, maximum) {
return Math.max(
Math_default.normalize(value, minimum, maximum) - Math_default.EPSILON7,
0
);
}
Cesium3DTile.prototype.updatePriority = function() {
const tileset = this.tileset;
const preferLeaves = tileset.preferLeaves;
const minimumPriority = tileset._minimumPriority;
const maximumPriority = tileset._maximumPriority;
const digitsForANumber = 4;
const digitsForABoolean = 1;
const preferredSortingLeftShift = 0;
const preferredSortingDigitsCount = digitsForANumber;
const foveatedLeftShift = preferredSortingLeftShift + preferredSortingDigitsCount;
const foveatedDigitsCount = digitsForANumber;
const preloadProgressiveResolutionLeftShift = foveatedLeftShift + foveatedDigitsCount;
const preloadProgressiveResolutionDigitsCount = digitsForABoolean;
const preloadProgressiveResolutionScale = Math.pow(
10,
preloadProgressiveResolutionLeftShift
);
const foveatedDeferLeftShift = preloadProgressiveResolutionLeftShift + preloadProgressiveResolutionDigitsCount;
const foveatedDeferDigitsCount = digitsForABoolean;
const foveatedDeferScale = Math.pow(10, foveatedDeferLeftShift);
const preloadFlightLeftShift = foveatedDeferLeftShift + foveatedDeferDigitsCount;
const preloadFlightScale = Math.pow(10, preloadFlightLeftShift);
let depthDigits = priorityNormalizeAndClamp(
this._depth,
minimumPriority.depth,
maximumPriority.depth
);
depthDigits = preferLeaves ? 1 - depthDigits : depthDigits;
const useDistance = !tileset.isSkippingLevelOfDetail && this.refine === Cesium3DTileRefine_default.REPLACE;
const normalizedPreferredSorting = useDistance ? priorityNormalizeAndClamp(
this._priorityHolder._distanceToCamera,
minimumPriority.distance,
maximumPriority.distance
) : priorityNormalizeAndClamp(
this._priorityReverseScreenSpaceError,
minimumPriority.reverseScreenSpaceError,
maximumPriority.reverseScreenSpaceError
);
const preferredSortingDigits = isolateDigits(
normalizedPreferredSorting,
preferredSortingDigitsCount,
preferredSortingLeftShift
);
const preloadProgressiveResolutionDigits = this._priorityProgressiveResolution ? 0 : preloadProgressiveResolutionScale;
const normalizedFoveatedFactor = priorityNormalizeAndClamp(
this._priorityHolder._foveatedFactor,
minimumPriority.foveatedFactor,
maximumPriority.foveatedFactor
);
const foveatedDigits = isolateDigits(
normalizedFoveatedFactor,
foveatedDigitsCount,
foveatedLeftShift
);
const foveatedDeferDigits = this.priorityDeferred ? foveatedDeferScale : 0;
const preloadFlightDigits = tileset._pass === Cesium3DTilePass_default.PRELOAD_FLIGHT ? 0 : preloadFlightScale;
this._priority = depthDigits + preferredSortingDigits + preloadProgressiveResolutionDigits + foveatedDigits + foveatedDeferDigits + preloadFlightDigits;
};
Cesium3DTile.prototype.isDestroyed = function() {
return false;
};
Cesium3DTile.prototype.destroy = function() {
this._content = this._content && this._content.destroy();
this._expiredContent = this._expiredContent && !this._expiredContent.isDestroyed() && this._expiredContent.destroy();
this._debugBoundingVolume = this._debugBoundingVolume && this._debugBoundingVolume.destroy();
this._debugContentBoundingVolume = this._debugContentBoundingVolume && this._debugContentBoundingVolume.destroy();
this._debugViewerRequestVolume = this._debugViewerRequestVolume && this._debugViewerRequestVolume.destroy();
return destroyObject_default(this);
};
var Cesium3DTile_default = Cesium3DTile;
// packages/engine/Source/Scene/GroupMetadata.js
function GroupMetadata(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const id = options.id;
const group = options.group;
const metadataClass = options.class;
Check_default.typeOf.object("options.group", group);
Check_default.typeOf.object("options.class", metadataClass);
const properties = defined_default(group.properties) ? group.properties : {};
this._class = metadataClass;
this._properties = properties;
this._id = id;
this._extras = group.extras;
this._extensions = group.extensions;
}
Object.defineProperties(GroupMetadata.prototype, {
/**
* The class that properties conform to.
*
* @memberof GroupMetadata.prototype
* @type {MetadataClass}
* @readonly
* @private
*/
class: {
get: function() {
return this._class;
}
},
/**
* The ID of the group.
*
* @memberof GroupMetadata.prototype
* @type {string}
* @readonly
* @private
*/
id: {
get: function() {
return this._id;
}
},
/**
* Extra user-defined properties.
*
* @memberof GroupMetadata.prototype
* @type {*}
* @readonly
* @private
*/
extras: {
get: function() {
return this._extras;
}
},
/**
* An object containing extensions.
*
* @memberof GroupMetadata.prototype
* @type {object}
* @readonly
* @private
*/
extensions: {
get: function() {
return this._extensions;
}
}
});
GroupMetadata.prototype.hasProperty = function(propertyId) {
return MetadataEntity_default.hasProperty(propertyId, this._properties, this._class);
};
GroupMetadata.prototype.hasPropertyBySemantic = function(semantic) {
return MetadataEntity_default.hasPropertyBySemantic(
semantic,
this._properties,
this._class
);
};
GroupMetadata.prototype.getPropertyIds = function(results) {
return MetadataEntity_default.getPropertyIds(this._properties, this._class, results);
};
GroupMetadata.prototype.getProperty = function(propertyId) {
return MetadataEntity_default.getProperty(propertyId, this._properties, this._class);
};
GroupMetadata.prototype.setProperty = function(propertyId, value) {
return MetadataEntity_default.setProperty(
propertyId,
value,
this._properties,
this._class
);
};
GroupMetadata.prototype.getPropertyBySemantic = function(semantic) {
return MetadataEntity_default.getPropertyBySemantic(
semantic,
this._properties,
this._class
);
};
GroupMetadata.prototype.setPropertyBySemantic = function(semantic, value) {
return MetadataEntity_default.setPropertyBySemantic(
semantic,
value,
this._properties,
this._class
);
};
var GroupMetadata_default = GroupMetadata;
// packages/engine/Source/Scene/TilesetMetadata.js
function TilesetMetadata(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const tileset = options.tileset;
const metadataClass = options.class;
Check_default.typeOf.object("options.tileset", tileset);
Check_default.typeOf.object("options.class", metadataClass);
const properties = defined_default(tileset.properties) ? tileset.properties : {};
this._class = metadataClass;
this._properties = properties;
this._extras = tileset.extras;
this._extensions = tileset.extensions;
}
Object.defineProperties(TilesetMetadata.prototype, {
/**
* The class that properties conform to.
*
* @memberof TilesetMetadata.prototype
* @type {MetadataClass}
* @readonly
* @private
*/
class: {
get: function() {
return this._class;
}
},
/**
* Extra user-defined properties.
*
* @memberof TilesetMetadata.prototype
* @type {*}
* @readonly
* @private
*/
extras: {
get: function() {
return this._extras;
}
},
/**
* An object containing extensions.
*
* @memberof TilesetMetadata.prototype
* @type {object}
* @readonly
* @private
*/
extensions: {
get: function() {
return this._extensions;
}
}
});
TilesetMetadata.prototype.hasProperty = function(propertyId) {
return MetadataEntity_default.hasProperty(propertyId, this._properties, this._class);
};
TilesetMetadata.prototype.hasPropertyBySemantic = function(semantic) {
return MetadataEntity_default.hasPropertyBySemantic(
semantic,
this._properties,
this._class
);
};
TilesetMetadata.prototype.getPropertyIds = function(results) {
return MetadataEntity_default.getPropertyIds(this._properties, this._class, results);
};
TilesetMetadata.prototype.getProperty = function(propertyId) {
return MetadataEntity_default.getProperty(propertyId, this._properties, this._class);
};
TilesetMetadata.prototype.setProperty = function(propertyId, value) {
return MetadataEntity_default.setProperty(
propertyId,
value,
this._properties,
this._class
);
};
TilesetMetadata.prototype.getPropertyBySemantic = function(semantic) {
return MetadataEntity_default.getPropertyBySemantic(
semantic,
this._properties,
this._class
);
};
TilesetMetadata.prototype.setPropertyBySemantic = function(semantic, value) {
return MetadataEntity_default.setPropertyBySemantic(
semantic,
value,
this._properties,
this._class
);
};
var TilesetMetadata_default = TilesetMetadata;
// packages/engine/Source/Scene/Cesium3DTilesetMetadata.js
function Cesium3DTilesetMetadata(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const metadataJson = options.metadataJson;
const schema = options.schema;
Check_default.typeOf.object("options.metadataJson", metadataJson);
Check_default.typeOf.object("options.schema", schema);
const metadata = defaultValue_default(metadataJson.metadata, metadataJson.tileset);
let tileset;
if (defined_default(metadata)) {
tileset = new TilesetMetadata_default({
tileset: metadata,
class: schema.classes[metadata.class]
});
}
let groupIds = [];
const groups = [];
const groupsJson = metadataJson.groups;
if (Array.isArray(groupsJson)) {
const length3 = groupsJson.length;
for (let i = 0; i < length3; i++) {
const group = groupsJson[i];
groups.push(
new GroupMetadata_default({
group,
class: schema.classes[group.class]
})
);
}
} else if (defined_default(groupsJson)) {
groupIds = Object.keys(groupsJson).sort();
const length3 = groupIds.length;
for (let i = 0; i < length3; i++) {
const groupId = groupIds[i];
if (groupsJson.hasOwnProperty(groupId)) {
const group = groupsJson[groupId];
groups.push(
new GroupMetadata_default({
id: groupId,
group: groupsJson[groupId],
class: schema.classes[group.class]
})
);
}
}
}
this._schema = schema;
this._groups = groups;
this._groupIds = groupIds;
this._tileset = tileset;
this._statistics = metadataJson.statistics;
this._extras = metadataJson.extras;
this._extensions = metadataJson.extensions;
}
Object.defineProperties(Cesium3DTilesetMetadata.prototype, {
/**
* Schema containing classes and enums.
*
* @memberof Cesium3DTilesetMetadata.prototype
* @type {MetadataSchema}
* @readonly
* @private
*/
schema: {
get: function() {
return this._schema;
}
},
/**
* Metadata about groups of content.
*
* @memberof Cesium3DTilesetMetadata.prototype
* @type {GroupMetadata[]}
* @readonly
* @private
*/
groups: {
get: function() {
return this._groups;
}
},
/**
* The IDs of the group metadata in the corresponding groups dictionary.
* Only populated if using the legacy schema.
*
* @memberof Cesium3DTilesetMetadata.prototype
* @type {}
* @readonly
* @private
*/
groupIds: {
get: function() {
return this._groupIds;
}
},
/**
* Metadata about the tileset as a whole.
*
* @memberof Cesium3DTilesetMetadata.prototype
* @type {TilesetMetadata}
* @readonly
* @private
*/
tileset: {
get: function() {
return this._tileset;
}
},
/**
* Statistics about the metadata.
* * See the {@link https://github.com/CesiumGS/3d-tiles/blob/main/extensions/3DTILES_metadata/schema/statistics.schema.json|statistics schema reference} * in the 3D Tiles spec for the full set of properties. *
* * @memberof Cesium3DTilesetMetadata.prototype * @type {object} * @readonly * @private */ statistics: { get: function() { return this._statistics; } }, /** * Extra user-defined properties. * * @memberof Cesium3DTilesetMetadata.prototype * @type {*} * @readonly * @private */ extras: { get: function() { return this._extras; } }, /** * An object containing extensions. * * @memberof Cesium3DTilesetMetadata.prototype * @type {object} * @readonly * @private */ extensions: { get: function() { return this._extensions; } } }); var Cesium3DTilesetMetadata_default = Cesium3DTilesetMetadata; // packages/engine/Source/Scene/Cesium3DTileOptimizations.js var Cesium3DTileOptimizations = {}; var scratchAxis = new Cartesian3_default(); Cesium3DTileOptimizations.checkChildrenWithinParent = function(tile) { Check_default.typeOf.object("tile", tile); const children = tile.children; const length3 = children.length; const boundingVolume = tile.boundingVolume; if (boundingVolume instanceof TileOrientedBoundingBox_default || boundingVolume instanceof TileBoundingRegion_default) { const orientedBoundingBox = boundingVolume._orientedBoundingBox; tile._optimChildrenWithinParent = Cesium3DTileOptimizationHint_default.USE_OPTIMIZATION; for (let i = 0; i < length3; ++i) { const child = children[i]; const childBoundingVolume = child.boundingVolume; if (!(childBoundingVolume instanceof TileOrientedBoundingBox_default || childBoundingVolume instanceof TileBoundingRegion_default)) { tile._optimChildrenWithinParent = Cesium3DTileOptimizationHint_default.SKIP_OPTIMIZATION; break; } const childOrientedBoundingBox = childBoundingVolume._orientedBoundingBox; const axis = Cartesian3_default.subtract( childOrientedBoundingBox.center, orientedBoundingBox.center, scratchAxis ); const axisLength = Cartesian3_default.magnitude(axis); Cartesian3_default.divideByScalar(axis, axisLength, axis); const proj1 = Math.abs(orientedBoundingBox.halfAxes[0] * axis.x) + Math.abs(orientedBoundingBox.halfAxes[1] * axis.y) + Math.abs(orientedBoundingBox.halfAxes[2] * axis.z) + Math.abs(orientedBoundingBox.halfAxes[3] * axis.x) + Math.abs(orientedBoundingBox.halfAxes[4] * axis.y) + Math.abs(orientedBoundingBox.halfAxes[5] * axis.z) + Math.abs(orientedBoundingBox.halfAxes[6] * axis.x) + Math.abs(orientedBoundingBox.halfAxes[7] * axis.y) + Math.abs(orientedBoundingBox.halfAxes[8] * axis.z); const proj2 = Math.abs(childOrientedBoundingBox.halfAxes[0] * axis.x) + Math.abs(childOrientedBoundingBox.halfAxes[1] * axis.y) + Math.abs(childOrientedBoundingBox.halfAxes[2] * axis.z) + Math.abs(childOrientedBoundingBox.halfAxes[3] * axis.x) + Math.abs(childOrientedBoundingBox.halfAxes[4] * axis.y) + Math.abs(childOrientedBoundingBox.halfAxes[5] * axis.z) + Math.abs(childOrientedBoundingBox.halfAxes[6] * axis.x) + Math.abs(childOrientedBoundingBox.halfAxes[7] * axis.y) + Math.abs(childOrientedBoundingBox.halfAxes[8] * axis.z); if (proj1 <= proj2 + axisLength) { tile._optimChildrenWithinParent = Cesium3DTileOptimizationHint_default.SKIP_OPTIMIZATION; break; } } } return tile._optimChildrenWithinParent === Cesium3DTileOptimizationHint_default.USE_OPTIMIZATION; }; var Cesium3DTileOptimizations_default = Cesium3DTileOptimizations; // packages/engine/Source/Core/DoublyLinkedList.js function DoublyLinkedList() { this.head = void 0; this.tail = void 0; this._length = 0; } Object.defineProperties(DoublyLinkedList.prototype, { length: { get: function() { return this._length; } } }); function DoublyLinkedListNode(item, previous, next) { this.item = item; this.previous = previous; this.next = next; } DoublyLinkedList.prototype.add = function(item) { const node = new DoublyLinkedListNode(item, this.tail, void 0); if (defined_default(this.tail)) { this.tail.next = node; this.tail = node; } else { this.head = node; this.tail = node; } ++this._length; return node; }; function remove(list, node) { if (defined_default(node.previous) && defined_default(node.next)) { node.previous.next = node.next; node.next.previous = node.previous; } else if (defined_default(node.previous)) { node.previous.next = void 0; list.tail = node.previous; } else if (defined_default(node.next)) { node.next.previous = void 0; list.head = node.next; } else { list.head = void 0; list.tail = void 0; } node.next = void 0; node.previous = void 0; } DoublyLinkedList.prototype.remove = function(node) { if (!defined_default(node)) { return; } remove(this, node); --this._length; }; DoublyLinkedList.prototype.splice = function(node, nextNode) { if (node === nextNode) { return; } remove(this, nextNode); const oldNodeNext = node.next; node.next = nextNode; if (this.tail === node) { this.tail = nextNode; } else { oldNodeNext.previous = nextNode; } nextNode.next = oldNodeNext; nextNode.previous = node; }; var DoublyLinkedList_default = DoublyLinkedList; // packages/engine/Source/Scene/Cesium3DTilesetCache.js function Cesium3DTilesetCache() { this._list = new DoublyLinkedList_default(); this._sentinel = this._list.add(); this._trimTiles = false; } Cesium3DTilesetCache.prototype.reset = function() { this._list.splice(this._list.tail, this._sentinel); }; Cesium3DTilesetCache.prototype.touch = function(tile) { const node = tile.cacheNode; if (defined_default(node)) { this._list.splice(this._sentinel, node); } }; Cesium3DTilesetCache.prototype.add = function(tile) { if (!defined_default(tile.cacheNode)) { tile.cacheNode = this._list.add(tile); } }; Cesium3DTilesetCache.prototype.unloadTile = function(tileset, tile, unloadCallback) { const node = tile.cacheNode; if (!defined_default(node)) { return; } this._list.remove(node); tile.cacheNode = void 0; unloadCallback(tileset, tile); }; Cesium3DTilesetCache.prototype.unloadTiles = function(tileset, unloadCallback) { const trimTiles = this._trimTiles; this._trimTiles = false; const list = this._list; const maximumMemoryUsageInBytes = tileset.maximumMemoryUsage * 1024 * 1024; const sentinel = this._sentinel; let node = list.head; while (node !== sentinel && (tileset.totalMemoryUsageInBytes > maximumMemoryUsageInBytes || trimTiles)) { const tile = node.item; node = node.next; this.unloadTile(tileset, tile, unloadCallback); } }; Cesium3DTilesetCache.prototype.trim = function() { this._trimTiles = true; }; var Cesium3DTilesetCache_default = Cesium3DTilesetCache; // packages/engine/Source/Scene/Cesium3DTilesetHeatmap.js function Cesium3DTilesetHeatmap(tilePropertyName) { this.tilePropertyName = tilePropertyName; this._minimum = Number.MAX_VALUE; this._maximum = -Number.MAX_VALUE; this._previousMinimum = Number.MAX_VALUE; this._previousMaximum = -Number.MAX_VALUE; this._referenceMinimum = {}; this._referenceMaximum = {}; } function getHeatmapValue(tileValue, tilePropertyName) { let value; if (tilePropertyName === "_loadTimestamp") { value = JulianDate_default.toDate(tileValue).getTime(); } else { value = tileValue; } return value; } Cesium3DTilesetHeatmap.prototype.setReferenceMinimumMaximum = function(minimum, maximum, tilePropertyName) { this._referenceMinimum[tilePropertyName] = getHeatmapValue( minimum, tilePropertyName ); this._referenceMaximum[tilePropertyName] = getHeatmapValue( maximum, tilePropertyName ); }; function getHeatmapValueAndUpdateMinimumMaximum(heatmap, tile) { const tilePropertyName = heatmap.tilePropertyName; if (defined_default(tilePropertyName)) { const heatmapValue = getHeatmapValue( tile[tilePropertyName], tilePropertyName ); if (!defined_default(heatmapValue)) { heatmap.tilePropertyName = void 0; return heatmapValue; } heatmap._maximum = Math.max(heatmapValue, heatmap._maximum); heatmap._minimum = Math.min(heatmapValue, heatmap._minimum); return heatmapValue; } } var heatmapColors = [ new Color_default(0.1, 0.1, 0.1, 1), // Dark Gray new Color_default(0.153, 0.278, 0.878, 1), // Blue new Color_default(0.827, 0.231, 0.49, 1), // Pink new Color_default(0.827, 0.188, 0.22, 1), // Red new Color_default(1, 0.592, 0.259, 1), // Orange new Color_default(1, 0.843, 0, 1) ]; Cesium3DTilesetHeatmap.prototype.colorize = function(tile, frameState) { const tilePropertyName = this.tilePropertyName; if (!defined_default(tilePropertyName) || !tile.contentAvailable || tile._selectedFrame !== frameState.frameNumber) { return; } const heatmapValue = getHeatmapValueAndUpdateMinimumMaximum(this, tile); const minimum = this._previousMinimum; const maximum = this._previousMaximum; if (minimum === Number.MAX_VALUE || maximum === -Number.MAX_VALUE) { return; } const shiftedMax = maximum - minimum + Math_default.EPSILON7; const shiftedValue = Math_default.clamp( heatmapValue - minimum, 0, shiftedMax ); const zeroToOne = shiftedValue / shiftedMax; const lastIndex = heatmapColors.length - 1; const colorPosition = zeroToOne * lastIndex; const colorPositionFloor = Math.floor(colorPosition); const colorPositionCeil = Math.ceil(colorPosition); const t = colorPosition - colorPositionFloor; const colorZero = heatmapColors[colorPositionFloor]; const colorOne = heatmapColors[colorPositionCeil]; const finalColor = Color_default.clone(Color_default.WHITE); finalColor.red = Math_default.lerp(colorZero.red, colorOne.red, t); finalColor.green = Math_default.lerp(colorZero.green, colorOne.green, t); finalColor.blue = Math_default.lerp(colorZero.blue, colorOne.blue, t); tile._debugColor = finalColor; }; Cesium3DTilesetHeatmap.prototype.resetMinimumMaximum = function() { const tilePropertyName = this.tilePropertyName; if (defined_default(tilePropertyName)) { const referenceMinimum = this._referenceMinimum[tilePropertyName]; const referenceMaximum = this._referenceMaximum[tilePropertyName]; const useReference = defined_default(referenceMinimum) && defined_default(referenceMaximum); this._previousMinimum = useReference ? referenceMinimum : this._minimum; this._previousMaximum = useReference ? referenceMaximum : this._maximum; this._minimum = Number.MAX_VALUE; this._maximum = -Number.MAX_VALUE; } }; var Cesium3DTilesetHeatmap_default = Cesium3DTilesetHeatmap; // packages/engine/Source/Scene/Cesium3DTilesetStatistics.js function Cesium3DTilesetStatistics() { this.selected = 0; this.visited = 0; this.numberOfCommands = 0; this.numberOfAttemptedRequests = 0; this.numberOfPendingRequests = 0; this.numberOfTilesProcessing = 0; this.numberOfTilesWithContentReady = 0; this.numberOfTilesTotal = 0; this.numberOfLoadedTilesTotal = 0; this.numberOfFeaturesSelected = 0; this.numberOfFeaturesLoaded = 0; this.numberOfPointsSelected = 0; this.numberOfPointsLoaded = 0; this.numberOfTrianglesSelected = 0; this.numberOfTilesStyled = 0; this.numberOfFeaturesStyled = 0; this.numberOfTilesCulledWithChildrenUnion = 0; this.geometryByteLength = 0; this.texturesByteLength = 0; this.batchTableByteLength = 0; } Cesium3DTilesetStatistics.prototype.clear = function() { this.selected = 0; this.visited = 0; this.numberOfCommands = 0; this.numberOfAttemptedRequests = 0; this.numberOfFeaturesSelected = 0; this.numberOfPointsSelected = 0; this.numberOfTrianglesSelected = 0; this.numberOfTilesStyled = 0; this.numberOfFeaturesStyled = 0; this.numberOfTilesCulledWithChildrenUnion = 0; }; function updatePointAndFeatureCounts(statistics2, content, decrement, load5) { const contents = content.innerContents; const pointsLength = content.pointsLength; const trianglesLength = content.trianglesLength; const featuresLength = content.featuresLength; const geometryByteLength = content.geometryByteLength; const texturesByteLength = content.texturesByteLength; const batchTableByteLength = content.batchTableByteLength; if (load5) { statistics2.numberOfFeaturesLoaded += decrement ? -featuresLength : featuresLength; statistics2.numberOfPointsLoaded += decrement ? -pointsLength : pointsLength; statistics2.geometryByteLength += decrement ? -geometryByteLength : geometryByteLength; statistics2.texturesByteLength += decrement ? -texturesByteLength : texturesByteLength; statistics2.batchTableByteLength += decrement ? -batchTableByteLength : batchTableByteLength; } else { statistics2.numberOfFeaturesSelected += decrement ? -featuresLength : featuresLength; statistics2.numberOfPointsSelected += decrement ? -pointsLength : pointsLength; statistics2.numberOfTrianglesSelected += decrement ? -trianglesLength : trianglesLength; } if (defined_default(contents)) { const length3 = contents.length; for (let i = 0; i < length3; ++i) { updatePointAndFeatureCounts(statistics2, contents[i], decrement, load5); } } } Cesium3DTilesetStatistics.prototype.incrementSelectionCounts = function(content) { updatePointAndFeatureCounts(this, content, false, false); }; Cesium3DTilesetStatistics.prototype.incrementLoadCounts = function(content) { updatePointAndFeatureCounts(this, content, false, true); }; Cesium3DTilesetStatistics.prototype.decrementLoadCounts = function(content) { updatePointAndFeatureCounts(this, content, true, true); }; Cesium3DTilesetStatistics.clone = function(statistics2, result) { result.selected = statistics2.selected; result.visited = statistics2.visited; result.numberOfCommands = statistics2.numberOfCommands; result.selected = statistics2.selected; result.numberOfAttemptedRequests = statistics2.numberOfAttemptedRequests; result.numberOfPendingRequests = statistics2.numberOfPendingRequests; result.numberOfTilesProcessing = statistics2.numberOfTilesProcessing; result.numberOfTilesWithContentReady = statistics2.numberOfTilesWithContentReady; result.numberOfTilesTotal = statistics2.numberOfTilesTotal; result.numberOfFeaturesSelected = statistics2.numberOfFeaturesSelected; result.numberOfFeaturesLoaded = statistics2.numberOfFeaturesLoaded; result.numberOfPointsSelected = statistics2.numberOfPointsSelected; result.numberOfPointsLoaded = statistics2.numberOfPointsLoaded; result.numberOfTrianglesSelected = statistics2.numberOfTrianglesSelected; result.numberOfTilesStyled = statistics2.numberOfTilesStyled; result.numberOfFeaturesStyled = statistics2.numberOfFeaturesStyled; result.numberOfTilesCulledWithChildrenUnion = statistics2.numberOfTilesCulledWithChildrenUnion; result.geometryByteLength = statistics2.geometryByteLength; result.texturesByteLength = statistics2.texturesByteLength; result.batchTableByteLength = statistics2.batchTableByteLength; }; var Cesium3DTilesetStatistics_default = Cesium3DTilesetStatistics; // packages/engine/Source/Scene/Cesium3DTileStyleEngine.js function Cesium3DTileStyleEngine() { this._style = void 0; this._styleDirty = false; this._lastStyleTime = 0; } Object.defineProperties(Cesium3DTileStyleEngine.prototype, { style: { get: function() { return this._style; }, set: function(value) { if (value === this._style) { return; } this._style = value; this._styleDirty = true; } } }); Cesium3DTileStyleEngine.prototype.makeDirty = function() { this._styleDirty = true; }; Cesium3DTileStyleEngine.prototype.resetDirty = function() { this._styleDirty = false; }; Cesium3DTileStyleEngine.prototype.applyStyle = function(tileset) { if (!defined_default(tileset.root)) { return; } if (defined_default(this._style) && !this._style._ready) { return; } const styleDirty = this._styleDirty; if (styleDirty) { ++this._lastStyleTime; } const lastStyleTime = this._lastStyleTime; const statistics2 = tileset._statistics; const tiles = styleDirty ? tileset._selectedTiles : tileset._selectedTilesToStyle; const length3 = tiles.length; for (let i = 0; i < length3; ++i) { const tile = tiles[i]; if (tile.lastStyleTime !== lastStyleTime) { const content = tile.content; tile.lastStyleTime = lastStyleTime; content.applyStyle(this._style); statistics2.numberOfFeaturesStyled += content.featuresLength; ++statistics2.numberOfTilesStyled; } } }; var Cesium3DTileStyleEngine_default = Cesium3DTileStyleEngine; // packages/engine/Source/Scene/ImplicitTileset.js function ImplicitTileset(baseResource2, tileJson, metadataSchema) { const implicitTiling = hasExtension_default(tileJson, "3DTILES_implicit_tiling") ? tileJson.extensions["3DTILES_implicit_tiling"] : tileJson.implicitTiling; Check_default.typeOf.object("implicitTiling", implicitTiling); this.baseResource = baseResource2; this.geometricError = tileJson.geometricError; this.metadataSchema = metadataSchema; const boundingVolume = tileJson.boundingVolume; if (!defined_default(boundingVolume.box) && !defined_default(boundingVolume.region) && !hasExtension_default(boundingVolume, "3DTILES_bounding_volume_S2") && !hasExtension_default(boundingVolume, "3DTILES_bounding_volume_cylinder")) { throw new RuntimeError_default( "Only box, region, 3DTILES_bounding_volume_S2, and 3DTILES_bounding_volume_cylinder are supported for implicit tiling" ); } this.boundingVolume = boundingVolume; this.refine = tileJson.refine; this.subtreeUriTemplate = new Resource_default({ url: implicitTiling.subtrees.uri }); this.contentUriTemplates = []; this.contentHeaders = []; const contentHeaders = gatherContentHeaders(tileJson); for (let i = 0; i < contentHeaders.length; i++) { const contentHeader = contentHeaders[i]; this.contentHeaders.push(clone_default(contentHeader, true)); const contentResource = new Resource_default({ url: contentHeader.uri }); this.contentUriTemplates.push(contentResource); } this.contentCount = this.contentHeaders.length; this.tileHeader = makeTileHeaderTemplate(tileJson); this.subdivisionScheme = ImplicitSubdivisionScheme_default[implicitTiling.subdivisionScheme]; this.branchingFactor = ImplicitSubdivisionScheme_default.getBranchingFactor( this.subdivisionScheme ); this.subtreeLevels = implicitTiling.subtreeLevels; if (defined_default(implicitTiling.availableLevels)) { this.availableLevels = implicitTiling.availableLevels; } else { this.availableLevels = implicitTiling.maximumLevel + 1; } } function gatherContentHeaders(tileJson) { if (hasExtension_default(tileJson, "3DTILES_multiple_contents")) { const extension = tileJson.extensions["3DTILES_multiple_contents"]; return defined_default(extension.contents) ? extension.contents : extension.content; } if (defined_default(tileJson.contents)) { return tileJson.contents; } if (defined_default(tileJson.content)) { return [tileJson.content]; } return []; } function makeTileHeaderTemplate(tileJson) { const template = clone_default(tileJson, true); if (defined_default(template.extensions)) { delete template.extensions["3DTILES_implicit_tiling"]; delete template.extensions["3DTILES_multiple_contents"]; if (Object.keys(template.extensions).length === 0) { delete template.extensions; } } delete template.implicitTiling; delete template.contents; delete template.content; return template; } var ImplicitTileset_default = ImplicitTileset; // packages/engine/Source/Core/MortonOrder.js var MortonOrder = {}; function insertOneSpacing(v7) { v7 = (v7 ^ v7 << 8) & 16711935; v7 = (v7 ^ v7 << 4) & 252645135; v7 = (v7 ^ v7 << 2) & 858993459; v7 = (v7 ^ v7 << 1) & 1431655765; return v7; } function insertTwoSpacing(v7) { v7 = (v7 ^ v7 << 16) & 50331903; v7 = (v7 ^ v7 << 8) & 50393103; v7 = (v7 ^ v7 << 4) & 51130563; v7 = (v7 ^ v7 << 2) & 153391689; return v7; } function removeOneSpacing(v7) { v7 &= 1431655765; v7 = (v7 ^ v7 >> 1) & 858993459; v7 = (v7 ^ v7 >> 2) & 252645135; v7 = (v7 ^ v7 >> 4) & 16711935; v7 = (v7 ^ v7 >> 8) & 65535; return v7; } function removeTwoSpacing(v7) { v7 &= 153391689; v7 = (v7 ^ v7 >> 2) & 51130563; v7 = (v7 ^ v7 >> 4) & 50393103; v7 = (v7 ^ v7 >> 8) & 4278190335; v7 = (v7 ^ v7 >> 16) & 1023; return v7; } MortonOrder.encode2D = function(x, y) { Check_default.typeOf.number("x", x); Check_default.typeOf.number("y", y); if (x < 0 || x > 65535 || y < 0 || y > 65535) { throw new DeveloperError_default("inputs must be 16-bit unsigned integers"); } return (insertOneSpacing(x) | insertOneSpacing(y) << 1) >>> 0; }; MortonOrder.decode2D = function(mortonIndex, result) { Check_default.typeOf.number("mortonIndex", mortonIndex); if (mortonIndex < 0 || mortonIndex > 4294967295) { throw new DeveloperError_default("input must be a 32-bit unsigned integer"); } if (!defined_default(result)) { result = new Array(2); } result[0] = removeOneSpacing(mortonIndex); result[1] = removeOneSpacing(mortonIndex >> 1); return result; }; MortonOrder.encode3D = function(x, y, z) { Check_default.typeOf.number("x", x); Check_default.typeOf.number("y", y); Check_default.typeOf.number("z", z); if (x < 0 || x > 1023 || y < 0 || y > 1023 || z < 0 || z > 1023) { throw new DeveloperError_default("inputs must be 10-bit unsigned integers"); } return insertTwoSpacing(x) | insertTwoSpacing(y) << 1 | insertTwoSpacing(z) << 2; }; MortonOrder.decode3D = function(mortonIndex, result) { Check_default.typeOf.number("mortonIndex", mortonIndex); if (mortonIndex < 0 || mortonIndex > 1073741823) { throw new DeveloperError_default("input must be a 30-bit unsigned integer"); } if (!defined_default(result)) { result = new Array(3); } result[0] = removeTwoSpacing(mortonIndex); result[1] = removeTwoSpacing(mortonIndex >> 1); result[2] = removeTwoSpacing(mortonIndex >> 2); return result; }; var MortonOrder_default = MortonOrder; // packages/engine/Source/Scene/ImplicitTileCoordinates.js function ImplicitTileCoordinates(options) { Check_default.typeOf.string("options.subdivisionScheme", options.subdivisionScheme); Check_default.typeOf.number("options.subtreeLevels", options.subtreeLevels); Check_default.typeOf.number("options.level", options.level); Check_default.typeOf.number("options.x", options.x); Check_default.typeOf.number("options.y", options.y); if (options.subdivisionScheme === ImplicitSubdivisionScheme_default.OCTREE) { Check_default.typeOf.number("options.z", options.z); } if (options.level < 0) { throw new DeveloperError_default("level must be non-negative"); } if (options.x < 0) { throw new DeveloperError_default("x must be non-negative"); } if (options.y < 0) { throw new DeveloperError_default("y must be non-negative"); } if (options.subdivisionScheme === ImplicitSubdivisionScheme_default.OCTREE) { if (options.z < 0) { throw new DeveloperError_default("z must be non-negative"); } } const dimensionAtLevel = 1 << options.level; if (options.x >= dimensionAtLevel) { throw new DeveloperError_default("x is out of range"); } if (options.y >= dimensionAtLevel) { throw new DeveloperError_default("y is out of range"); } if (options.subdivisionScheme === ImplicitSubdivisionScheme_default.OCTREE) { if (options.z >= dimensionAtLevel) { throw new DeveloperError_default("z is out of range"); } } this.subdivisionScheme = options.subdivisionScheme; this.subtreeLevels = options.subtreeLevels; this.level = options.level; this.x = options.x; this.y = options.y; this.z = void 0; if (options.subdivisionScheme === ImplicitSubdivisionScheme_default.OCTREE) { this.z = options.z; } } Object.defineProperties(ImplicitTileCoordinates.prototype, { /** * An index in the range of [0, branchingFactor) that indicates * which child of the parent cell these coordinates correspond to. * This can be viewed as a morton index within the parent tile. ** This is the last 3 bits of the morton index of the tile, but it can * be computed more directly by concatenating the bits [z0] y0 x0 *
* * @type {number} * @readonly * @private */ childIndex: { get: function() { let childIndex = 0; childIndex |= this.x & 1; childIndex |= (this.y & 1) << 1; if (this.subdivisionScheme === ImplicitSubdivisionScheme_default.OCTREE) { childIndex |= (this.z & 1) << 2; } return childIndex; } }, /** * Get the Morton index for this tile within the current level by interleaving * the bits of the x, y and z coordinates. * * @type {number} * @readonly * @private */ mortonIndex: { get: function() { if (this.subdivisionScheme === ImplicitSubdivisionScheme_default.OCTREE) { return MortonOrder_default.encode3D(this.x, this.y, this.z); } return MortonOrder_default.encode2D(this.x, this.y); } }, /** * Get the tile index by adding the Morton index to the level offset * * @type {number} * @readonly * @private */ tileIndex: { get: function() { const levelOffset = this.subdivisionScheme === ImplicitSubdivisionScheme_default.OCTREE ? ( // (8^N - 1) / (8-1) ((1 << 3 * this.level) - 1) / 7 ) : ( // (4^N - 1) / (4-1) ((1 << 2 * this.level) - 1) / 3 ); const mortonIndex = this.mortonIndex; return levelOffset + mortonIndex; } } }); function checkMatchingSubtreeShape(a3, b) { if (a3.subdivisionScheme !== b.subdivisionScheme) { throw new DeveloperError_default("coordinates must have same subdivisionScheme"); } if (a3.subtreeLevels !== b.subtreeLevels) { throw new DeveloperError_default("coordinates must have same subtreeLevels"); } } ImplicitTileCoordinates.prototype.getDescendantCoordinates = function(offsetCoordinates) { Check_default.typeOf.object("offsetCoordinates", offsetCoordinates); checkMatchingSubtreeShape(this, offsetCoordinates); const descendantLevel = this.level + offsetCoordinates.level; const descendantX = (this.x << offsetCoordinates.level) + offsetCoordinates.x; const descendantY = (this.y << offsetCoordinates.level) + offsetCoordinates.y; if (this.subdivisionScheme === ImplicitSubdivisionScheme_default.OCTREE) { const descendantZ = (this.z << offsetCoordinates.level) + offsetCoordinates.z; return new ImplicitTileCoordinates({ subdivisionScheme: this.subdivisionScheme, subtreeLevels: this.subtreeLevels, level: descendantLevel, x: descendantX, y: descendantY, z: descendantZ }); } return new ImplicitTileCoordinates({ subdivisionScheme: this.subdivisionScheme, subtreeLevels: this.subtreeLevels, level: descendantLevel, x: descendantX, y: descendantY }); }; ImplicitTileCoordinates.prototype.getAncestorCoordinates = function(offsetLevels) { Check_default.typeOf.number("offsetLevels", offsetLevels); if (offsetLevels < 0) { throw new DeveloperError_default("offsetLevels must be non-negative"); } if (offsetLevels > this.level) { throw new DeveloperError_default("ancestor cannot be above the tileset root"); } const divisor = 1 << offsetLevels; const ancestorLevel = this.level - offsetLevels; const ancestorX = Math.floor(this.x / divisor); const ancestorY = Math.floor(this.y / divisor); if (this.subdivisionScheme === ImplicitSubdivisionScheme_default.OCTREE) { const ancestorZ = Math.floor(this.z / divisor); return new ImplicitTileCoordinates({ subdivisionScheme: this.subdivisionScheme, subtreeLevels: this.subtreeLevels, level: ancestorLevel, x: ancestorX, y: ancestorY, z: ancestorZ }); } return new ImplicitTileCoordinates({ subdivisionScheme: this.subdivisionScheme, subtreeLevels: this.subtreeLevels, level: ancestorLevel, x: ancestorX, y: ancestorY }); }; ImplicitTileCoordinates.prototype.getOffsetCoordinates = function(descendantCoordinates) { Check_default.typeOf.object("descendantCoordinates", descendantCoordinates); if (!this.isEqual(descendantCoordinates) && !this.isAncestor(descendantCoordinates)) { throw new DeveloperError_default("this is not an ancestor of descendant"); } checkMatchingSubtreeShape(this, descendantCoordinates); const offsetLevel = descendantCoordinates.level - this.level; const dimensionAtOffsetLevel = 1 << offsetLevel; const offsetX = descendantCoordinates.x % dimensionAtOffsetLevel; const offsetY = descendantCoordinates.y % dimensionAtOffsetLevel; if (this.subdivisionScheme === ImplicitSubdivisionScheme_default.OCTREE) { const offsetZ = descendantCoordinates.z % dimensionAtOffsetLevel; return new ImplicitTileCoordinates({ subdivisionScheme: this.subdivisionScheme, subtreeLevels: this.subtreeLevels, level: offsetLevel, x: offsetX, y: offsetY, z: offsetZ }); } return new ImplicitTileCoordinates({ subdivisionScheme: this.subdivisionScheme, subtreeLevels: this.subtreeLevels, level: offsetLevel, x: offsetX, y: offsetY }); }; ImplicitTileCoordinates.prototype.getChildCoordinates = function(childIndex) { Check_default.typeOf.number("childIndex", childIndex); const branchingFactor = ImplicitSubdivisionScheme_default.getBranchingFactor( this.subdivisionScheme ); if (childIndex < 0 || branchingFactor <= childIndex) { throw new DeveloperError_default( `childIndex must be at least 0 and less than ${branchingFactor}` ); } const level = this.level + 1; const x = 2 * this.x + childIndex % 2; const y = 2 * this.y + Math.floor(childIndex / 2) % 2; if (this.subdivisionScheme === ImplicitSubdivisionScheme_default.OCTREE) { const z = 2 * this.z + Math.floor(childIndex / 4) % 2; return new ImplicitTileCoordinates({ subdivisionScheme: this.subdivisionScheme, subtreeLevels: this.subtreeLevels, level, x, y, z }); } return new ImplicitTileCoordinates({ subdivisionScheme: this.subdivisionScheme, subtreeLevels: this.subtreeLevels, level, x, y }); }; ImplicitTileCoordinates.prototype.getSubtreeCoordinates = function() { return this.getAncestorCoordinates(this.level % this.subtreeLevels); }; ImplicitTileCoordinates.prototype.getParentSubtreeCoordinates = function() { return this.getAncestorCoordinates( this.level % this.subtreeLevels + this.subtreeLevels ); }; ImplicitTileCoordinates.prototype.isAncestor = function(descendantCoordinates) { Check_default.typeOf.object("descendantCoordinates", descendantCoordinates); checkMatchingSubtreeShape(this, descendantCoordinates); const levelDifference = descendantCoordinates.level - this.level; if (levelDifference <= 0) { return false; } const ancestorX = descendantCoordinates.x >> levelDifference; const ancestorY = descendantCoordinates.y >> levelDifference; const isAncestorX = this.x === ancestorX; const isAncestorY = this.y === ancestorY; if (this.subdivisionScheme === ImplicitSubdivisionScheme_default.OCTREE) { const ancestorZ = descendantCoordinates.z >> levelDifference; const isAncestorZ = this.z === ancestorZ; return isAncestorX && isAncestorY && isAncestorZ; } return isAncestorX && isAncestorY; }; ImplicitTileCoordinates.prototype.isEqual = function(otherCoordinates) { Check_default.typeOf.object("otherCoordinates", otherCoordinates); return this.subdivisionScheme === otherCoordinates.subdivisionScheme && this.subtreeLevels === otherCoordinates.subtreeLevels && this.level === otherCoordinates.level && this.x === otherCoordinates.x && this.y === otherCoordinates.y && (this.subdivisionScheme === ImplicitSubdivisionScheme_default.OCTREE ? this.z === otherCoordinates.z : true); }; ImplicitTileCoordinates.prototype.isImplicitTilesetRoot = function() { return this.level === 0; }; ImplicitTileCoordinates.prototype.isSubtreeRoot = function() { return this.level % this.subtreeLevels === 0; }; ImplicitTileCoordinates.prototype.isBottomOfSubtree = function() { return this.level % this.subtreeLevels === this.subtreeLevels - 1; }; ImplicitTileCoordinates.prototype.getTemplateValues = function() { const values = { level: this.level, x: this.x, y: this.y }; if (this.subdivisionScheme === ImplicitSubdivisionScheme_default.OCTREE) { values.z = this.z; } return values; }; var scratchCoordinatesArray = [0, 0, 0]; ImplicitTileCoordinates.fromMortonIndex = function(subdivisionScheme, subtreeLevels, level, mortonIndex) { let coordinatesArray; if (subdivisionScheme === ImplicitSubdivisionScheme_default.OCTREE) { coordinatesArray = MortonOrder_default.decode3D( mortonIndex, scratchCoordinatesArray ); return new ImplicitTileCoordinates({ subdivisionScheme, subtreeLevels, level, x: coordinatesArray[0], y: coordinatesArray[1], z: coordinatesArray[2] }); } coordinatesArray = MortonOrder_default.decode2D(mortonIndex, scratchCoordinatesArray); return new ImplicitTileCoordinates({ subdivisionScheme, subtreeLevels, level, x: coordinatesArray[0], y: coordinatesArray[1] }); }; ImplicitTileCoordinates.fromTileIndex = function(subdivisionScheme, subtreeLevels, tileIndex) { let level; let levelOffset; let mortonIndex; if (subdivisionScheme === ImplicitSubdivisionScheme_default.OCTREE) { level = Math.floor(Math_default.log2(7 * tileIndex + 1) / 3); levelOffset = ((1 << 3 * level) - 1) / 7; mortonIndex = tileIndex - levelOffset; } else { level = Math.floor(Math_default.log2(3 * tileIndex + 1) / 2); levelOffset = ((1 << 2 * level) - 1) / 3; mortonIndex = tileIndex - levelOffset; } return ImplicitTileCoordinates.fromMortonIndex( subdivisionScheme, subtreeLevels, level, mortonIndex ); }; var ImplicitTileCoordinates_default = ImplicitTileCoordinates; // packages/engine/Source/Scene/Cesium3DTilesetTraversal.js function Cesium3DTilesetTraversal() { } Cesium3DTilesetTraversal.selectTiles = function(tileset, frameState) { DeveloperError_default.throwInstantiationError(); }; Cesium3DTilesetTraversal.sortChildrenByDistanceToCamera = function(a3, b) { if (b._distanceToCamera === 0 && a3._distanceToCamera === 0) { return b._centerZDepth - a3._centerZDepth; } return b._distanceToCamera - a3._distanceToCamera; }; Cesium3DTilesetTraversal.canTraverse = function(tile) { if (tile.children.length === 0) { return false; } if (tile.hasTilesetContent || tile.hasImplicitContent) { return !tile.contentExpired; } return tile._screenSpaceError > tile.tileset._maximumScreenSpaceError; }; Cesium3DTilesetTraversal.selectTile = function(tile, frameState) { if (tile.contentVisibility(frameState) === Intersect_default.OUTSIDE) { return; } const { content, tileset } = tile; if (content.featurePropertiesDirty) { content.featurePropertiesDirty = false; tile.lastStyleTime = 0; tileset._selectedTilesToStyle.push(tile); } else if (tile._selectedFrame < frameState.frameNumber - 1) { tileset._selectedTilesToStyle.push(tile); } tile._selectedFrame = frameState.frameNumber; tileset._selectedTiles.push(tile); }; Cesium3DTilesetTraversal.visitTile = function(tile, frameState) { ++tile.tileset._statistics.visited; tile._visitedFrame = frameState.frameNumber; }; Cesium3DTilesetTraversal.touchTile = function(tile, frameState) { if (tile._touchedFrame === frameState.frameNumber) { return; } tile.tileset._cache.touch(tile); tile._touchedFrame = frameState.frameNumber; }; Cesium3DTilesetTraversal.loadTile = function(tile, frameState) { const { tileset } = tile; if (tile._requestedFrame === frameState.frameNumber || !tile.hasUnloadedRenderableContent && !tile.contentExpired) { return; } if (!isOnScreenLongEnough(tile, frameState)) { return; } const cameraHasNotStoppedMovingLongEnough = frameState.camera.timeSinceMoved < tileset.foveatedTimeDelay; if (tile.priorityDeferred && cameraHasNotStoppedMovingLongEnough) { return; } tile._requestedFrame = frameState.frameNumber; tileset._requestedTiles.push(tile); }; function isOnScreenLongEnough(tile, frameState) { const { tileset } = tile; if (!tileset._cullRequestsWhileMoving) { return true; } const { positionWCDeltaMagnitude, positionWCDeltaMagnitudeLastFrame } = frameState.camera; const deltaMagnitude = positionWCDeltaMagnitude !== 0 ? positionWCDeltaMagnitude : positionWCDeltaMagnitudeLastFrame; const diameter = Math.max(tile.boundingSphere.radius * 2, 1); const movementRatio = tileset.cullRequestsWhileMovingMultiplier * deltaMagnitude / diameter; return movementRatio < 1; } Cesium3DTilesetTraversal.updateTile = function(tile, frameState) { updateTileVisibility(tile, frameState); tile.updateExpiration(); tile._wasMinPriorityChild = false; tile._priorityHolder = tile; updateMinimumMaximumPriority(tile); tile._shouldSelect = false; tile._finalResolution = true; }; function updateTileVisibility(tile, frameState) { tile.updateVisibility(frameState); if (!tile.isVisible) { return; } const hasChildren = tile.children.length > 0; if ((tile.hasTilesetContent || tile.hasImplicitContent) && hasChildren) { const child = tile.children[0]; updateTileVisibility(child, frameState); tile._visible = child._visible; return; } if (meetsScreenSpaceErrorEarly(tile, frameState)) { tile._visible = false; return; } const replace = tile.refine === Cesium3DTileRefine_default.REPLACE; const useOptimization = tile._optimChildrenWithinParent === Cesium3DTileOptimizationHint_default.USE_OPTIMIZATION; if (replace && useOptimization && hasChildren) { if (!anyChildrenVisible(tile, frameState)) { ++tile.tileset._statistics.numberOfTilesCulledWithChildrenUnion; tile._visible = false; return; } } } function meetsScreenSpaceErrorEarly(tile, frameState) { const { parent, tileset } = tile; if (!defined_default(parent) || parent.hasTilesetContent || parent.hasImplicitContent || parent.refine !== Cesium3DTileRefine_default.ADD) { return false; } return tile.getScreenSpaceError(frameState, true) <= tileset._maximumScreenSpaceError; } function anyChildrenVisible(tile, frameState) { let anyVisible = false; const children = tile.children; for (let i = 0; i < children.length; ++i) { const child = children[i]; child.updateVisibility(frameState); anyVisible = anyVisible || child.isVisible; } return anyVisible; } function updateMinimumMaximumPriority(tile) { const minimumPriority = tile.tileset._minimumPriority; const maximumPriority = tile.tileset._maximumPriority; const priorityHolder = tile._priorityHolder; maximumPriority.distance = Math.max( priorityHolder._distanceToCamera, maximumPriority.distance ); minimumPriority.distance = Math.min( priorityHolder._distanceToCamera, minimumPriority.distance ); maximumPriority.depth = Math.max(tile._depth, maximumPriority.depth); minimumPriority.depth = Math.min(tile._depth, minimumPriority.depth); maximumPriority.foveatedFactor = Math.max( priorityHolder._foveatedFactor, maximumPriority.foveatedFactor ); minimumPriority.foveatedFactor = Math.min( priorityHolder._foveatedFactor, minimumPriority.foveatedFactor ); maximumPriority.reverseScreenSpaceError = Math.max( tile._priorityReverseScreenSpaceError, maximumPriority.reverseScreenSpaceError ); minimumPriority.reverseScreenSpaceError = Math.min( tile._priorityReverseScreenSpaceError, minimumPriority.reverseScreenSpaceError ); } var Cesium3DTilesetTraversal_default = Cesium3DTilesetTraversal; // packages/engine/Source/Scene/Cesium3DTilesetMostDetailedTraversal.js function Cesium3DTilesetMostDetailedTraversal() { } var traversal = { stack: new ManagedArray_default(), stackMaximumLength: 0 }; Cesium3DTilesetMostDetailedTraversal.selectTiles = function(tileset, frameState) { tileset._selectedTiles.length = 0; tileset._requestedTiles.length = 0; tileset.hasMixedContent = false; let ready = true; const root = tileset.root; root.updateVisibility(frameState); if (!root.isVisible) { return ready; } const { touchTile, visitTile: visitTile3 } = Cesium3DTilesetTraversal_default; const stack = traversal.stack; stack.push(root); while (stack.length > 0) { traversal.stackMaximumLength = Math.max( traversal.stackMaximumLength, stack.length ); const tile = stack.pop(); const add2 = tile.refine === Cesium3DTileRefine_default.ADD; const replace = tile.refine === Cesium3DTileRefine_default.REPLACE; const traverse = canTraverse(tile); if (traverse) { updateAndPushChildren(tile, stack, frameState); } if (add2 || replace && !traverse) { loadTile(tileset, tile); touchTile(tile, frameState); selectDesiredTile(tile, frameState); if (tile.hasRenderableContent && !tile.contentAvailable) { ready = false; } } visitTile3(tile, frameState); } traversal.stack.trim(traversal.stackMaximumLength); return ready; }; function canTraverse(tile) { if (tile.children.length === 0) { return false; } if (tile.hasTilesetContent || tile.hasImplicitContent) { return !tile.contentExpired; } if (tile.hasEmptyContent) { return true; } return true; } function updateAndPushChildren(tile, stack, frameState) { const { children } = tile; for (let i = 0; i < children.length; ++i) { const child = children[i]; child.updateVisibility(frameState); if (child.isVisible) { stack.push(child); } } } function loadTile(tileset, tile) { if (tile.hasUnloadedRenderableContent || tile.contentExpired) { tile._priority = 0; tileset._requestedTiles.push(tile); } } function selectDesiredTile(tile, frameState) { if (tile.contentAvailable && tile.contentVisibility(frameState) !== Intersect_default.OUTSIDE) { tile.tileset._selectedTiles.push(tile); } } var Cesium3DTilesetMostDetailedTraversal_default = Cesium3DTilesetMostDetailedTraversal; // packages/engine/Source/Scene/Cesium3DTilesetBaseTraversal.js function Cesium3DTilesetBaseTraversal() { } var traversal2 = { stack: new ManagedArray_default(), stackMaximumLength: 0 }; var emptyTraversal = { stack: new ManagedArray_default(), stackMaximumLength: 0 }; Cesium3DTilesetBaseTraversal.selectTiles = function(tileset, frameState) { tileset._requestedTiles.length = 0; if (tileset.debugFreezeFrame) { return; } tileset._selectedTiles.length = 0; tileset._selectedTilesToStyle.length = 0; tileset._emptyTiles.length = 0; tileset.hasMixedContent = false; const root = tileset.root; Cesium3DTilesetTraversal_default.updateTile(root, frameState); if (!root.isVisible) { return; } if (root.getScreenSpaceError(frameState, true) <= tileset._maximumScreenSpaceError) { return; } executeTraversal(root, frameState); traversal2.stack.trim(traversal2.stackMaximumLength); emptyTraversal.stack.trim(emptyTraversal.stackMaximumLength); const requestedTiles = tileset._requestedTiles; for (let i = 0; i < requestedTiles.length; ++i) { requestedTiles[i].updatePriority(); } }; function selectDesiredTile2(tile, frameState) { if (tile.contentAvailable) { Cesium3DTilesetTraversal_default.selectTile(tile, frameState); } } function updateAndPushChildren2(tile, stack, frameState) { const replace = tile.refine === Cesium3DTileRefine_default.REPLACE; const { tileset, children } = tile; const { updateTile, loadTile: loadTile2, touchTile } = Cesium3DTilesetTraversal_default; for (let i = 0; i < children.length; ++i) { updateTile(children[i], frameState); } children.sort(Cesium3DTilesetTraversal_default.sortChildrenByDistanceToCamera); const checkRefines = replace && tile.hasRenderableContent; let refines = true; let anyChildrenVisible2 = false; let minIndex = -1; let minimumPriority = Number.MAX_VALUE; for (let i = 0; i < children.length; ++i) { const child = children[i]; if (child.isVisible) { stack.push(child); if (child._foveatedFactor < minimumPriority) { minIndex = i; minimumPriority = child._foveatedFactor; } anyChildrenVisible2 = true; } else if (checkRefines || tileset.loadSiblings) { if (child._foveatedFactor < minimumPriority) { minIndex = i; minimumPriority = child._foveatedFactor; } loadTile2(child, frameState); touchTile(child, frameState); } if (checkRefines) { let childRefines; if (!child._inRequestVolume) { childRefines = false; } else if (!child.hasRenderableContent) { childRefines = executeEmptyTraversal(child, frameState); } else { childRefines = child.contentAvailable; } refines = refines && childRefines; } } if (!anyChildrenVisible2) { refines = false; } if (minIndex !== -1 && replace) { const minPriorityChild = children[minIndex]; minPriorityChild._wasMinPriorityChild = true; const priorityHolder = (tile._wasMinPriorityChild || tile === tileset.root) && minimumPriority <= tile._priorityHolder._foveatedFactor ? tile._priorityHolder : tile; priorityHolder._foveatedFactor = Math.min( minPriorityChild._foveatedFactor, priorityHolder._foveatedFactor ); priorityHolder._distanceToCamera = Math.min( minPriorityChild._distanceToCamera, priorityHolder._distanceToCamera ); for (let i = 0; i < children.length; ++i) { children[i]._priorityHolder = priorityHolder; } } return refines; } function executeTraversal(root, frameState) { const { tileset } = root; const { canTraverse: canTraverse2, loadTile: loadTile2, visitTile: visitTile3, touchTile } = Cesium3DTilesetTraversal_default; const stack = traversal2.stack; stack.push(root); while (stack.length > 0) { traversal2.stackMaximumLength = Math.max( traversal2.stackMaximumLength, stack.length ); const tile = stack.pop(); const parent = tile.parent; const parentRefines = !defined_default(parent) || parent._refines; tile._refines = canTraverse2(tile) ? updateAndPushChildren2(tile, stack, frameState) && parentRefines : false; const stoppedRefining = !tile._refines && parentRefines; if (!tile.hasRenderableContent) { tileset._emptyTiles.push(tile); loadTile2(tile, frameState); if (stoppedRefining) { selectDesiredTile2(tile, frameState); } } else if (tile.refine === Cesium3DTileRefine_default.ADD) { selectDesiredTile2(tile, frameState); loadTile2(tile, frameState); } else if (tile.refine === Cesium3DTileRefine_default.REPLACE) { loadTile2(tile, frameState); if (stoppedRefining) { selectDesiredTile2(tile, frameState); } } visitTile3(tile, frameState); touchTile(tile, frameState); } } function executeEmptyTraversal(root, frameState) { const { canTraverse: canTraverse2, updateTile, loadTile: loadTile2, touchTile } = Cesium3DTilesetTraversal_default; let allDescendantsLoaded = true; const stack = emptyTraversal.stack; stack.push(root); while (stack.length > 0) { emptyTraversal.stackMaximumLength = Math.max( emptyTraversal.stackMaximumLength, stack.length ); const tile = stack.pop(); const children = tile.children; const childrenLength = children.length; const traverse = !tile.hasRenderableContent && canTraverse2(tile); const emptyLeaf = !tile.hasRenderableContent && tile.children.length === 0; if (!traverse && !tile.contentAvailable && !emptyLeaf) { allDescendantsLoaded = false; } updateTile(tile, frameState); if (!tile.isVisible) { loadTile2(tile, frameState); touchTile(tile, frameState); } if (traverse) { for (let i = 0; i < childrenLength; ++i) { const child = children[i]; stack.push(child); } } } return allDescendantsLoaded; } var Cesium3DTilesetBaseTraversal_default = Cesium3DTilesetBaseTraversal; // packages/engine/Source/Scene/Cesium3DTilesetSkipTraversal.js function Cesium3DTilesetSkipTraversal() { } var traversal3 = { stack: new ManagedArray_default(), stackMaximumLength: 0 }; var descendantTraversal = { stack: new ManagedArray_default(), stackMaximumLength: 0 }; var selectionTraversal = { stack: new ManagedArray_default(), stackMaximumLength: 0, ancestorStack: new ManagedArray_default(), ancestorStackMaximumLength: 0 }; var descendantSelectionDepth = 2; Cesium3DTilesetSkipTraversal.selectTiles = function(tileset, frameState) { tileset._requestedTiles.length = 0; if (tileset.debugFreezeFrame) { return; } tileset._selectedTiles.length = 0; tileset._selectedTilesToStyle.length = 0; tileset._emptyTiles.length = 0; tileset.hasMixedContent = false; const root = tileset.root; Cesium3DTilesetTraversal_default.updateTile(root, frameState); if (!root.isVisible) { return; } if (root.getScreenSpaceError(frameState, true) <= tileset._maximumScreenSpaceError) { return; } executeTraversal2(root, frameState); traverseAndSelect(root, frameState); traversal3.stack.trim(traversal3.stackMaximumLength); descendantTraversal.stack.trim(descendantTraversal.stackMaximumLength); selectionTraversal.stack.trim(selectionTraversal.stackMaximumLength); selectionTraversal.ancestorStack.trim( selectionTraversal.ancestorStackMaximumLength ); const requestedTiles = tileset._requestedTiles; for (let i = 0; i < requestedTiles.length; ++i) { requestedTiles[i].updatePriority(); } }; function selectDescendants(root, frameState) { const { updateTile, touchTile, selectTile } = Cesium3DTilesetTraversal_default; const stack = descendantTraversal.stack; stack.push(root); while (stack.length > 0) { descendantTraversal.stackMaximumLength = Math.max( descendantTraversal.stackMaximumLength, stack.length ); const tile = stack.pop(); const children = tile.children; for (let i = 0; i < children.length; ++i) { const child = children[i]; if (child.isVisible) { if (child.contentAvailable) { updateTile(child, frameState); touchTile(child, frameState); selectTile(child, frameState); } else if (child._depth - root._depth < descendantSelectionDepth) { stack.push(child); } } } } } function selectDesiredTile3(tile, frameState) { const loadedTile = tile.contentAvailable ? tile : tile._ancestorWithContentAvailable; if (defined_default(loadedTile)) { loadedTile._shouldSelect = true; } else { selectDescendants(tile, frameState); } } function updateTileAncestorContentLinks(tile, frameState) { tile._ancestorWithContent = void 0; tile._ancestorWithContentAvailable = void 0; const { parent } = tile; if (!defined_default(parent)) { return; } const parentHasContent = !parent.hasUnloadedRenderableContent || parent._requestedFrame === frameState.frameNumber; tile._ancestorWithContent = parentHasContent ? parent : parent._ancestorWithContent; tile._ancestorWithContentAvailable = parent.contentAvailable ? parent : parent._ancestorWithContentAvailable; } function reachedSkippingThreshold(tileset, tile) { const ancestor = tile._ancestorWithContent; return !tileset.immediatelyLoadDesiredLevelOfDetail && (tile._priorityProgressiveResolutionScreenSpaceErrorLeaf || defined_default(ancestor) && tile._screenSpaceError < ancestor._screenSpaceError / tileset.skipScreenSpaceErrorFactor && tile._depth > ancestor._depth + tileset.skipLevels); } function updateAndPushChildren3(tile, stack, frameState) { const { tileset, children } = tile; const { updateTile, loadTile: loadTile2, touchTile } = Cesium3DTilesetTraversal_default; for (let i = 0; i < children.length; ++i) { updateTile(children[i], frameState); } children.sort(Cesium3DTilesetTraversal_default.sortChildrenByDistanceToCamera); let anyChildrenVisible2 = false; for (let i = 0; i < children.length; ++i) { const child = children[i]; if (child.isVisible) { stack.push(child); anyChildrenVisible2 = true; } else if (tileset.loadSiblings) { loadTile2(child, frameState); touchTile(child, frameState); } } return anyChildrenVisible2; } function inBaseTraversal(tile, baseScreenSpaceError) { const { tileset } = tile; if (tileset.immediatelyLoadDesiredLevelOfDetail) { return false; } if (!defined_default(tile._ancestorWithContent)) { return true; } if (tile._screenSpaceError === 0) { return tile.parent._screenSpaceError > baseScreenSpaceError; } return tile._screenSpaceError > baseScreenSpaceError; } function executeTraversal2(root, frameState) { const { tileset } = root; const baseScreenSpaceError = tileset.immediatelyLoadDesiredLevelOfDetail ? Number.MAX_VALUE : Math.max(tileset.baseScreenSpaceError, tileset.maximumScreenSpaceError); const { canTraverse: canTraverse2, loadTile: loadTile2, visitTile: visitTile3, touchTile } = Cesium3DTilesetTraversal_default; const stack = traversal3.stack; stack.push(root); while (stack.length > 0) { traversal3.stackMaximumLength = Math.max( traversal3.stackMaximumLength, stack.length ); const tile = stack.pop(); updateTileAncestorContentLinks(tile, frameState); const parent = tile.parent; const parentRefines = !defined_default(parent) || parent._refines; tile._refines = canTraverse2(tile) ? updateAndPushChildren3(tile, stack, frameState) && parentRefines : false; const stoppedRefining = !tile._refines && parentRefines; if (!tile.hasRenderableContent) { tileset._emptyTiles.push(tile); loadTile2(tile, frameState); if (stoppedRefining) { selectDesiredTile3(tile, frameState); } } else if (tile.refine === Cesium3DTileRefine_default.ADD) { selectDesiredTile3(tile, frameState); loadTile2(tile, frameState); } else if (tile.refine === Cesium3DTileRefine_default.REPLACE) { if (inBaseTraversal(tile, baseScreenSpaceError)) { loadTile2(tile, frameState); if (stoppedRefining) { selectDesiredTile3(tile, frameState); } } else if (stoppedRefining) { selectDesiredTile3(tile, frameState); loadTile2(tile, frameState); } else if (reachedSkippingThreshold(tileset, tile)) { loadTile2(tile, frameState); } } visitTile3(tile, frameState); touchTile(tile, frameState); } } function traverseAndSelect(root, frameState) { const { selectTile, canTraverse: canTraverse2 } = Cesium3DTilesetTraversal_default; const { stack, ancestorStack } = selectionTraversal; let lastAncestor; stack.push(root); while (stack.length > 0 || ancestorStack.length > 0) { selectionTraversal.stackMaximumLength = Math.max( selectionTraversal.stackMaximumLength, stack.length ); selectionTraversal.ancestorStackMaximumLength = Math.max( selectionTraversal.ancestorStackMaximumLength, ancestorStack.length ); if (ancestorStack.length > 0) { const waitingTile = ancestorStack.peek(); if (waitingTile._stackLength === stack.length) { ancestorStack.pop(); if (waitingTile !== lastAncestor) { waitingTile._finalResolution = false; } selectTile(waitingTile, frameState); continue; } } const tile = stack.pop(); if (!defined_default(tile)) { continue; } const traverse = canTraverse2(tile); if (tile._shouldSelect) { if (tile.refine === Cesium3DTileRefine_default.ADD) { selectTile(tile, frameState); } else { tile._selectionDepth = ancestorStack.length; if (tile._selectionDepth > 0) { tile.tileset.hasMixedContent = true; } lastAncestor = tile; if (!traverse) { selectTile(tile, frameState); continue; } ancestorStack.push(tile); tile._stackLength = stack.length; } } if (traverse) { const children = tile.children; for (let i = 0; i < children.length; ++i) { const child = children[i]; if (child.isVisible) { stack.push(child); } } } } } var Cesium3DTilesetSkipTraversal_default = Cesium3DTilesetSkipTraversal; // packages/engine/Source/Scene/Cesium3DTileset.js function Cesium3DTileset(options) { options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT); this._url = void 0; this._basePath = void 0; this._root = void 0; this._resource = void 0; this._asset = void 0; this._properties = void 0; this._geometricError = void 0; this._scaledGeometricError = void 0; this._extensionsUsed = void 0; this._extensions = void 0; this._modelUpAxis = void 0; this._modelForwardAxis = void 0; this._cache = new Cesium3DTilesetCache_default(); this._processingQueue = []; this._selectedTiles = []; this._emptyTiles = []; this._requestedTiles = []; this._selectedTilesToStyle = []; this._loadTimestamp = void 0; this._timeSinceLoad = 0; this._updatedVisibilityFrame = 0; this._updatedModelMatrixFrame = 0; this._modelMatrixChanged = false; this._previousModelMatrix = void 0; this._extras = void 0; this._credits = void 0; this._showCreditsOnScreen = defaultValue_default(options.showCreditsOnScreen, false); this._cullWithChildrenBounds = defaultValue_default( options.cullWithChildrenBounds, true ); this._allTilesAdditive = true; this._hasMixedContent = false; this._stencilClearCommand = void 0; this._backfaceCommands = new ManagedArray_default(); this._maximumScreenSpaceError = defaultValue_default( options.maximumScreenSpaceError, 16 ); this._maximumMemoryUsage = defaultValue_default(options.maximumMemoryUsage, 512); this._styleEngine = new Cesium3DTileStyleEngine_default(); this._styleApplied = false; this._modelMatrix = defined_default(options.modelMatrix) ? Matrix4_default.clone(options.modelMatrix) : Matrix4_default.clone(Matrix4_default.IDENTITY); this._statistics = new Cesium3DTilesetStatistics_default(); this._statisticsLast = new Cesium3DTilesetStatistics_default(); this._statisticsPerPass = new Array(Cesium3DTilePass_default.NUMBER_OF_PASSES); for (let i = 0; i < Cesium3DTilePass_default.NUMBER_OF_PASSES; ++i) { this._statisticsPerPass[i] = new Cesium3DTilesetStatistics_default(); } this._requestedTilesInFlight = []; this._maximumPriority = { foveatedFactor: -Number.MAX_VALUE, depth: -Number.MAX_VALUE, distance: -Number.MAX_VALUE, reverseScreenSpaceError: -Number.MAX_VALUE }; this._minimumPriority = { foveatedFactor: Number.MAX_VALUE, depth: Number.MAX_VALUE, distance: Number.MAX_VALUE, reverseScreenSpaceError: Number.MAX_VALUE }; this._heatmap = new Cesium3DTilesetHeatmap_default( options.debugHeatmapTilePropertyName ); this.cullRequestsWhileMoving = defaultValue_default( options.cullRequestsWhileMoving, true ); this._cullRequestsWhileMoving = false; this.cullRequestsWhileMovingMultiplier = defaultValue_default( options.cullRequestsWhileMovingMultiplier, 60 ); this.progressiveResolutionHeightFraction = Math_default.clamp( defaultValue_default(options.progressiveResolutionHeightFraction, 0.3), 0, 0.5 ); this.preferLeaves = defaultValue_default(options.preferLeaves, false); this._tilesLoaded = false; this._initialTilesLoaded = false; this._tileDebugLabels = void 0; this._classificationType = options.classificationType; this._ellipsoid = defaultValue_default(options.ellipsoid, Ellipsoid_default.WGS84); this._initialClippingPlanesOriginMatrix = Matrix4_default.IDENTITY; this._clippingPlanesOriginMatrix = void 0; this._clippingPlanesOriginMatrixDirty = true; this._vectorClassificationOnly = defaultValue_default( options.vectorClassificationOnly, false ); this._vectorKeepDecodedPositions = defaultValue_default( options.vectorKeepDecodedPositions, false ); this.preloadWhenHidden = defaultValue_default(options.preloadWhenHidden, false); this.preloadFlightDestinations = defaultValue_default( options.preloadFlightDestinations, true ); this._pass = void 0; this.dynamicScreenSpaceError = defaultValue_default( options.dynamicScreenSpaceError, false ); this.foveatedScreenSpaceError = defaultValue_default( options.foveatedScreenSpaceError, true ); this._foveatedConeSize = defaultValue_default(options.foveatedConeSize, 0.1); this._foveatedMinimumScreenSpaceErrorRelaxation = defaultValue_default( options.foveatedMinimumScreenSpaceErrorRelaxation, 0 ); this.foveatedInterpolationCallback = defaultValue_default( options.foveatedInterpolationCallback, Math_default.lerp ); this.foveatedTimeDelay = defaultValue_default(options.foveatedTimeDelay, 0.2); this.dynamicScreenSpaceErrorDensity = 278e-5; this.dynamicScreenSpaceErrorFactor = 4; this.dynamicScreenSpaceErrorHeightFalloff = 0.25; this._dynamicScreenSpaceErrorComputedDensity = 0; this.shadows = defaultValue_default(options.shadows, ShadowMode_default.ENABLED); this.show = defaultValue_default(options.show, true); this.colorBlendMode = Cesium3DTileColorBlendMode_default.HIGHLIGHT; this.colorBlendAmount = 0.5; this._pointCloudShading = new PointCloudShading_default(options.pointCloudShading); this._pointCloudEyeDomeLighting = new PointCloudEyeDomeLighting_default2(); this.loadProgress = new Event_default(); this.allTilesLoaded = new Event_default(); this.initialTilesLoaded = new Event_default(); this.tileLoad = new Event_default(); this.tileUnload = new Event_default(); this.tileFailed = new Event_default(); this.tileVisible = new Event_default(); this.skipLevelOfDetail = defaultValue_default(options.skipLevelOfDetail, false); this._disableSkipLevelOfDetail = false; this.baseScreenSpaceError = defaultValue_default(options.baseScreenSpaceError, 1024); this.skipScreenSpaceErrorFactor = defaultValue_default( options.skipScreenSpaceErrorFactor, 16 ); this.skipLevels = defaultValue_default(options.skipLevels, 1); this.immediatelyLoadDesiredLevelOfDetail = defaultValue_default( options.immediatelyLoadDesiredLevelOfDetail, false ); this.loadSiblings = defaultValue_default(options.loadSiblings, false); this._clippingPlanes = void 0; this.clippingPlanes = options.clippingPlanes; if (defined_default(options.imageBasedLighting)) { this._imageBasedLighting = options.imageBasedLighting; this._shouldDestroyImageBasedLighting = false; } else { this._imageBasedLighting = new ImageBasedLighting_default(); this._shouldDestroyImageBasedLighting = true; } this.lightColor = options.lightColor; this.backFaceCulling = defaultValue_default(options.backFaceCulling, true); this._enableShowOutline = defaultValue_default(options.enableShowOutline, true); this.showOutline = defaultValue_default(options.showOutline, true); this.outlineColor = defaultValue_default(options.outlineColor, Color_default.BLACK); this.splitDirection = defaultValue_default( options.splitDirection, SplitDirection_default.NONE ); this._projectTo2D = defaultValue_default(options.projectTo2D, false); this.debugFreezeFrame = defaultValue_default(options.debugFreezeFrame, false); this.debugColorizeTiles = defaultValue_default(options.debugColorizeTiles, false); this._enableDebugWireframe = defaultValue_default( options.enableDebugWireframe, false ); this.debugWireframe = defaultValue_default(options.debugWireframe, false); if (this.debugWireframe === true && this._enableDebugWireframe === false) { oneTimeWarning_default( "tileset-debug-wireframe-ignored", "enableDebugWireframe must be set to true in the Cesium3DTileset constructor, otherwise debugWireframe will be ignored." ); } this.debugShowBoundingVolume = defaultValue_default( options.debugShowBoundingVolume, false ); this.debugShowContentBoundingVolume = defaultValue_default( options.debugShowContentBoundingVolume, false ); this.debugShowViewerRequestVolume = defaultValue_default( options.debugShowViewerRequestVolume, false ); this._tileDebugLabels = void 0; this.debugPickedTileLabelOnly = false; this.debugPickedTile = void 0; this.debugPickPosition = void 0; this.debugShowGeometricError = defaultValue_default( options.debugShowGeometricError, false ); this.debugShowRenderingStatistics = defaultValue_default( options.debugShowRenderingStatistics, false ); this.debugShowMemoryUsage = defaultValue_default(options.debugShowMemoryUsage, false); this.debugShowUrl = defaultValue_default(options.debugShowUrl, false); this.examineVectorLinesFunction = void 0; this._metadataExtension = void 0; this._customShader = options.customShader; let featureIdLabel = defaultValue_default(options.featureIdLabel, "featureId_0"); if (typeof featureIdLabel === "number") { featureIdLabel = `featureId_${featureIdLabel}`; } this._featureIdLabel = featureIdLabel; let instanceFeatureIdLabel = defaultValue_default( options.instanceFeatureIdLabel, "instanceFeatureId_0" ); if (typeof instanceFeatureIdLabel === "number") { instanceFeatureIdLabel = `instanceFeatureId_${instanceFeatureIdLabel}`; } this._instanceFeatureIdLabel = instanceFeatureIdLabel; if (defined_default(options.url)) { deprecationWarning_default( "Cesium3DTileset options.url", "Cesium3DTileset constructor parameter options.url was deprecated in CesiumJS 1.104. It will be removed in 1.107. Use Cesium3DTileset.fromUrl instead." ); const that = this; let resource; this._readyPromise = Promise.resolve(options.url).then(function(url2) { let basePath; resource = Resource_default.createIfNeeded(url2); that._resource = resource; that._credits = resource.credits; if (resource.extension === "json") { basePath = resource.getBaseUri(true); } else if (resource.isDataUri) { basePath = ""; } that._url = resource.url; that._basePath = basePath; return Cesium3DTileset.loadJson(resource); }).then(function(tilesetJson) { if (that.isDestroyed()) { return; } return processMetadataExtension(resource, tilesetJson).then( (metadata) => { that._metadataExtension = metadata; return tilesetJson; } ); }).then(function(tilesetJson) { if (that.isDestroyed()) { return; } that._geometricError = tilesetJson.geometricError; that._scaledGeometricError = tilesetJson.geometricError; that._root = that.loadTileset(resource, tilesetJson); const gltfUpAxis = defined_default(tilesetJson.asset.gltfUpAxis) ? Axis_default.fromName(tilesetJson.asset.gltfUpAxis) : Axis_default.Y; const modelUpAxis = defaultValue_default(options.modelUpAxis, gltfUpAxis); const modelForwardAxis = defaultValue_default(options.modelForwardAxis, Axis_default.X); const asset = tilesetJson.asset; that._asset = asset; that._properties = tilesetJson.properties; that._extensionsUsed = tilesetJson.extensionsUsed; that._extensions = tilesetJson.extensions; that._modelUpAxis = modelUpAxis; that._modelForwardAxis = modelForwardAxis; that._extras = tilesetJson.extras; const extras = asset.extras; if (defined_default(extras) && defined_default(extras.cesium) && defined_default(extras.cesium.credits)) { const extraCredits = extras.cesium.credits; let credits = that._credits; if (!defined_default(credits)) { credits = []; that._credits = credits; } for (let i = 0; i < extraCredits.length; ++i) { const credit = extraCredits[i]; credits.push(new Credit_default(credit.html, that._showCreditsOnScreen)); } } const boundingVolume = that._root.createBoundingVolume( tilesetJson.root.boundingVolume, Matrix4_default.IDENTITY ); const clippingPlanesOrigin = boundingVolume.boundingSphere.center; const originCartographic = that._ellipsoid.cartesianToCartographic( clippingPlanesOrigin ); if (defined_default(originCartographic) && originCartographic.height > ApproximateTerrainHeights_default._defaultMinTerrainHeight) { that._initialClippingPlanesOriginMatrix = Transforms_default.eastNorthUpToFixedFrame( clippingPlanesOrigin ); } that._clippingPlanesOriginMatrix = Matrix4_default.clone( that._initialClippingPlanesOriginMatrix ); return that; }); } } Object.defineProperties(Cesium3DTileset.prototype, { /** * NOTE: This getter exists so that `Picking.js` can differentiate between * PrimitiveCollection and Cesium3DTileset objects without inflating * the size of the module via `instanceof Cesium3DTileset` * @private */ isCesium3DTileset: { get: function() { return true; } }, /** * Gets the tileset's asset object property, which contains metadata about the tileset. ** See the {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification#reference-asset|asset schema reference} * in the 3D Tiles spec for the full set of properties. *
* * @memberof Cesium3DTileset.prototype * * @type {object} * @readonly */ asset: { get: function() { return this._asset; } }, /** * Gets the tileset's extensions object property. * * @memberof Cesium3DTileset.prototype * * @type {object} * @readonly */ extensions: { get: function() { return this._extensions; } }, /** * The {@link ClippingPlaneCollection} used to selectively disable rendering the tileset. * * @memberof Cesium3DTileset.prototype * * @type {ClippingPlaneCollection} */ clippingPlanes: { get: function() { return this._clippingPlanes; }, set: function(value) { ClippingPlaneCollection_default.setOwner(value, this, "_clippingPlanes"); } }, /** * Gets the tileset's properties dictionary object, which contains metadata about per-feature properties. ** See the {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification#reference-properties|properties schema reference} * in the 3D Tiles spec for the full set of properties. *
* * @memberof Cesium3DTileset.prototype * * @type {object} * @readonly * * @example * console.log(`Maximum building height: ${tileset.properties.height.maximum}`); * console.log(`Minimum building height: ${tileset.properties.height.minimum}`); * * @see Cesium3DTileFeature#getProperty * @see Cesium3DTileFeature#setProperty */ properties: { get: function() { return this._properties; } }, /** * Whentrue
, the tileset's root tile is loaded and the tileset is ready to render.
*
* @memberof Cesium3DTileset.prototype
*
* @type {boolean}
* @readonly
*
* @default false
*/
ready: {
get: function() {
deprecationWarning_default(
"Cesium3DTileset.ready",
"Cesium3DTileset.ready was deprecated in CesiumJS 1.104. It will be removed in 1.107. Use Cesium3DTileset.fromUrl instead."
);
return defined_default(this._root);
}
},
/**
* Gets the promise that will be resolved when the tileset's root tile is loaded and the tileset is ready to render.
* * This promise is resolved at the end of the frame before the first frame the tileset is rendered in. *
* * @memberof Cesium3DTileset.prototype * * @type {Promisetrue
, all tiles that meet the screen space error this frame are loaded. The tileset is
* completely loaded for this view.
*
* @memberof Cesium3DTileset.prototype
*
* @type {boolean}
* @readonly
*
* @default false
*
* @see Cesium3DTileset#allTilesLoaded
*/
tilesLoaded: {
get: function() {
return this._tilesLoaded;
}
},
/**
* The resource used to fetch the tileset JSON file
*
* @memberof Cesium3DTileset.prototype
*
* @type {Resource}
* @readonly
*/
resource: {
get: function() {
return this._resource;
}
},
/**
* The base path that non-absolute paths in tileset JSON file are relative to.
*
* @memberof Cesium3DTileset.prototype
*
* @type {string}
* @readonly
* @deprecated
*/
basePath: {
get: function() {
deprecationWarning_default(
"Cesium3DTileset.basePath",
"Cesium3DTileset.basePath has been deprecated. All tiles are relative to the url of the tileset JSON file that contains them. Use the url property instead."
);
return this._basePath;
}
},
/**
* The style, defined using the
* {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification/Styling|3D Tiles Styling language},
* applied to each feature in the tileset.
*
* Assign undefined
to remove the style, which will restore the visual
* appearance of the tileset to its default when no style was applied.
*
* The style is applied to a tile before the {@link Cesium3DTileset#tileVisible}
* event is raised, so code in tileVisible
can manually set a feature's
* properties (e.g. color and show) after the style is applied. When
* a new style is assigned any manually set properties are overwritten.
*
* Use an always "true" condition to specify the Color for all objects that are not * overridden by pre-existing conditions. Otherwise, the default color Cesium.Color.White * will be used. Similarly, use an always "true" condition to specify the show property * for all objects that are not overridden by pre-existing conditions. Otherwise, the * default show value true will be used. *
* * @memberof Cesium3DTileset.prototype * * @type {Cesium3DTileStyle|undefined} * * @default undefined * * @example * tileset.style = new Cesium.Cesium3DTileStyle({ * color : { * conditions : [ * ['${Height} >= 100', 'color("purple", 0.5)'], * ['${Height} >= 50', 'color("red")'], * ['true', 'color("blue")'] * ] * }, * show : '${Height} > 0', * meta : { * description : '"Building id ${id} has height ${Height}."' * } * }); * * @see {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification/Styling|3D Tiles Styling language} */ style: { get: function() { return this._styleEngine.style; }, set: function(value) { this._styleEngine.style = value; } }, /** * A custom shader to apply to all tiles in the tileset. Only used for * contents that use {@link Model}. Using custom shaders with a * {@link Cesium3DTileStyle} may lead to undefined behavior. * * @memberof Cesium3DTileset.prototype * * @type {CustomShader|undefined} * * @default undefined * * @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. */ customShader: { get: function() { return this._customShader; }, set: function(value) { this._customShader = value; } }, /** * Whether the tileset is rendering different levels of detail in the same view. * Only relevant if {@link Cesium3DTileset.isSkippingLevelOfDetail} is true. * * @memberof Cesium3DTileset.prototype * * @type {boolean} * @private */ hasMixedContent: { get: function() { return this._hasMixedContent; }, set: function(value) { Check_default.typeOf.bool("value", value); this._hasMixedContent = value; } }, /** * Whether this tileset is actually skipping levels of detail. * The user option may have been disabled if all tiles are using additive refinement, * or if some tiles have a content type for which rendering does not support skipping * * @memberof Cesium3DTileset.prototype * * @type {boolean} * @private * @readonly */ isSkippingLevelOfDetail: { get: function() { return this.skipLevelOfDetail && !defined_default(this._classificationType) && !this._disableSkipLevelOfDetail && !this._allTilesAdditive; } }, /** * The tileset's schema, groups, tileset metadata and other details from the * 3DTILES_metadata extension or a 3D Tiles 1.1 tileset JSON. This getter is * for internal use by other classes. * * @memberof Cesium3DTileset.prototype * @type {Cesium3DTilesetMetadata} * @private * @readonly * * @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. */ metadataExtension: { get: function() { return this._metadataExtension; } }, /** * The metadata properties attached to the tileset as a whole. * * @memberof Cesium3DTileset.prototype * * @type {TilesetMetadata} * @private * @readonly * * @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. */ metadata: { get: function() { if (defined_default(this._metadataExtension)) { return this._metadataExtension.tileset; } return void 0; } }, /** * The metadata schema used in this tileset. Shorthand for *tileset.metadataExtension.schema
*
* @memberof Cesium3DTileset.prototype
*
* @type {MetadataSchema}
* @private
* @readonly
*
* @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.
*/
schema: {
get: function() {
if (defined_default(this._metadataExtension)) {
return this._metadataExtension.schema;
}
return void 0;
}
},
/**
* The maximum screen space error used to drive level of detail refinement. This value helps determine when a tile
* refines to its descendants, and therefore plays a major role in balancing performance with visual quality.
*
* A tile's screen space error is roughly equivalent to the number of pixels wide that would be drawn if a sphere with a
* radius equal to the tile's geometric error were rendered at the tile's position. If this value exceeds
* maximumScreenSpaceError
the tile refines to its descendants.
*
* Depending on the tileset, maximumScreenSpaceError
may need to be tweaked to achieve the right balance.
* Higher values provide better performance but lower visual quality.
*
maximumScreenSpaceError
must be greater than or equal to zero.
*/
maximumScreenSpaceError: {
get: function() {
return this._maximumScreenSpaceError;
},
set: function(value) {
Check_default.typeOf.number.greaterThanOrEquals(
"maximumScreenSpaceError",
value,
0
);
this._maximumScreenSpaceError = value;
}
},
/**
* The maximum amount of GPU memory (in MB) that may be used to cache tiles. This value is estimated from
* geometry, textures, and batch table textures of loaded tiles. For point clouds, this value also
* includes per-point metadata.
* * Tiles not in view are unloaded to enforce this. *
** If decreasing this value results in unloading tiles, the tiles are unloaded the next frame. *
*
* If tiles sized more than maximumMemoryUsage
are needed
* to meet the desired screen space error, determined by {@link Cesium3DTileset#maximumScreenSpaceError},
* for the current view, then the memory usage of the tiles loaded will exceed
* maximumMemoryUsage
. For example, if the maximum is 256 MB, but
* 300 MB of tiles are needed to meet the screen space error, then 300 MB of tiles may be loaded. When
* these tiles go out of view, they will be unloaded.
*
maximumMemoryUsage
must be greater than or equal to zero.
* @see Cesium3DTileset#totalMemoryUsageInBytes
*/
maximumMemoryUsage: {
get: function() {
return this._maximumMemoryUsage;
},
set: function(value) {
Check_default.typeOf.number.greaterThanOrEquals("value", value, 0);
this._maximumMemoryUsage = value;
}
},
/**
* Options for controlling point size based on geometric error and eye dome lighting.
*
* @memberof Cesium3DTileset.prototype
*
* @type {PointCloudShading}
*/
pointCloudShading: {
get: function() {
return this._pointCloudShading;
},
set: function(value) {
Check_default.defined("pointCloudShading", value);
this._pointCloudShading = value;
}
},
/**
* The root tile.
*
* @memberOf Cesium3DTileset.prototype
*
* @type {Cesium3DTile}
* @readonly
*/
root: {
get: function() {
return this._root;
}
},
/**
* The tileset's bounding sphere.
*
* @memberof Cesium3DTileset.prototype
*
* @type {BoundingSphere}
* @readonly
*
* @example
* const tileset = await Cesium.Cesium3DTileset.fromUrl("http://localhost:8002/tilesets/Seattle/tileset.json");
*
* viewer.scene.primitives.add(tileset);
*
* // Set the camera to view the newly added tileset
* viewer.camera.viewBoundingSphere(tileset.boundingSphere, new Cesium.HeadingPitchRange(0, -0.5, 0));
*/
boundingSphere: {
get: function() {
this._root.updateTransform(this._modelMatrix);
return this._root.boundingSphere;
}
},
/**
* A 4x4 transformation matrix that transforms the entire tileset.
*
* @memberof Cesium3DTileset.prototype
*
* @type {Matrix4}
* @default Matrix4.IDENTITY
*
* @example
* // Adjust a tileset's height from the globe's surface.
* const heightOffset = 20.0;
* const boundingSphere = tileset.boundingSphere;
* const cartographic = Cesium.Cartographic.fromCartesian(boundingSphere.center);
* const surface = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, 0.0);
* const offset = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, heightOffset);
* const translation = Cesium.Cartesian3.subtract(offset, surface, new Cesium.Cartesian3());
* tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
*/
modelMatrix: {
get: function() {
return this._modelMatrix;
},
set: function(value) {
this._modelMatrix = Matrix4_default.clone(value, this._modelMatrix);
}
},
/**
* Returns the time, in milliseconds, since the tileset was loaded and first updated.
*
* @memberof Cesium3DTileset.prototype
*
* @type {number}
* @readonly
*/
timeSinceLoad: {
get: function() {
return this._timeSinceLoad;
}
},
/**
* The total amount of GPU memory in bytes used by the tileset. This value is estimated from
* geometry, texture, batch table textures, and binary metadata of loaded tiles.
*
* @memberof Cesium3DTileset.prototype
*
* @type {number}
* @readonly
*
* @see Cesium3DTileset#maximumMemoryUsage
*/
totalMemoryUsageInBytes: {
get: function() {
const statistics2 = this._statistics;
return statistics2.texturesByteLength + statistics2.geometryByteLength + statistics2.batchTableByteLength;
}
},
/**
* @private
*/
clippingPlanesOriginMatrix: {
get: function() {
if (!defined_default(this._clippingPlanesOriginMatrix)) {
return Matrix4_default.IDENTITY;
}
if (this._clippingPlanesOriginMatrixDirty) {
Matrix4_default.multiply(
this.root.computedTransform,
this._initialClippingPlanesOriginMatrix,
this._clippingPlanesOriginMatrix
);
this._clippingPlanesOriginMatrixDirty = false;
}
return this._clippingPlanesOriginMatrix;
}
},
/**
* @private
*/
styleEngine: {
get: function() {
return this._styleEngine;
}
},
/**
* @private
*/
statistics: {
get: function() {
return this._statistics;
}
},
/**
* Determines whether terrain, 3D Tiles, or both will be classified by this tileset.
* * This option is only applied to tilesets containing batched 3D models, * glTF content, geometry data, or vector data. Even when undefined, vector * and geometry data must render as classifications and will default to * rendering on both terrain and other 3D Tiles tilesets. *
** When enabled for batched 3D model and glTF tilesets, there are a few * requirements/limitations on the glTF: *
EXT_mesh_gpu_instancing
extension.POSITION
semantic is required._BATCHID
s and an index buffer are both present, all indices with the same batch id must occupy contiguous sections of the index buffer._BATCHID
s are present with no index buffer, all positions with the same batch id must occupy contiguous sections of the position buffer.* Additionally, classification is not supported for points or instanced 3D * models. *
* * @memberof Cesium3DTileset.prototype * * @type {ClassificationType} * @default undefined * * @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. * @readonly */ classificationType: { get: function() { return this._classificationType; } }, /** * Gets an ellipsoid describing the shape of the globe. * * @memberof Cesium3DTileset.prototype * * @type {Ellipsoid} * @readonly */ ellipsoid: { get: function() { return this._ellipsoid; } }, /** * Optimization option. Used when {@link Cesium3DTileset#foveatedScreenSpaceError} is true to control the cone size that determines which tiles are deferred. * Tiles that are inside this cone are loaded immediately. Tiles outside the cone are potentially deferred based on how far outside the cone they are and {@link Cesium3DTileset#foveatedInterpolationCallback} and {@link Cesium3DTileset#foveatedMinimumScreenSpaceErrorRelaxation}. * Setting this to 0.0 means the cone will be the line formed by the camera position and its view direction. Setting this to 1.0 means the cone encompasses the entire field of view of the camera, essentially disabling the effect. * * @memberof Cesium3DTileset.prototype * * @type {number} * @default 0.3 */ foveatedConeSize: { get: function() { return this._foveatedConeSize; }, set: function(value) { Check_default.typeOf.number.greaterThanOrEquals("foveatedConeSize", value, 0); Check_default.typeOf.number.lessThanOrEquals("foveatedConeSize", value, 1); this._foveatedConeSize = value; } }, /** * Optimization option. Used when {@link Cesium3DTileset#foveatedScreenSpaceError} is true to control the starting screen space error relaxation for tiles outside the foveated cone. * The screen space error will be raised starting with this value up to {@link Cesium3DTileset#maximumScreenSpaceError} based on the provided {@link Cesium3DTileset#foveatedInterpolationCallback}. * * @memberof Cesium3DTileset.prototype * * @type {number} * @default 0.0 */ foveatedMinimumScreenSpaceErrorRelaxation: { get: function() { return this._foveatedMinimumScreenSpaceErrorRelaxation; }, set: function(value) { Check_default.typeOf.number.greaterThanOrEquals( "foveatedMinimumScreenSpaceErrorRelaxation", value, 0 ); Check_default.typeOf.number.lessThanOrEquals( "foveatedMinimumScreenSpaceErrorRelaxation", value, this.maximumScreenSpaceError ); this._foveatedMinimumScreenSpaceErrorRelaxation = value; } }, /** * Returns theextras
property at the top-level of the tileset JSON, which contains application specific metadata.
* Returns undefined
if extras
does not exist.
*
* @memberof Cesium3DTileset.prototype
*
* @type {*}
* @readonly
*
* @see {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification#specifying-extensions-and-application-specific-extras|Extras in the 3D Tiles specification.}
*/
extras: {
get: function() {
return this._extras;
}
},
/**
* The properties for managing image-based lighting on this tileset.
*
* @memberof Cesium3DTileset.prototype
*
* @type {ImageBasedLighting}
*/
imageBasedLighting: {
get: function() {
return this._imageBasedLighting;
},
set: function(value) {
Check_default.typeOf.object("imageBasedLighting", this._imageBasedLighting);
if (value !== this._imageBasedLighting) {
if (this._shouldDestroyImageBasedLighting && !this._imageBasedLighting.isDestroyed()) {
this._imageBasedLighting.destroy();
}
this._imageBasedLighting = value;
this._shouldDestroyImageBasedLighting = false;
}
}
},
/**
* Indicates that only the tileset's vector tiles should be used for classification.
*
* @memberof Cesium3DTileset.prototype
*
* @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.
*
* @type {boolean}
* @default false
*/
vectorClassificationOnly: {
get: function() {
return this._vectorClassificationOnly;
}
},
/**
* Whether vector tiles should keep decoded positions in memory.
* This is used with {@link Cesium3DTileFeature.getPolylinePositions}.
*
* @memberof Cesium3DTileset.prototype
*
* @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.
*
* @type {boolean}
* @default false
*/
vectorKeepDecodedPositions: {
get: function() {
return this._vectorKeepDecodedPositions;
}
},
/**
* Determines whether the credits of the tileset will be displayed on the screen
*
* @memberof Cesium3DTileset.prototype
*
* @type {boolean}
* @default false
*/
showCreditsOnScreen: {
get: function() {
return this._showCreditsOnScreen;
},
set: function(value) {
this._showCreditsOnScreen = value;
}
},
/**
* Label of the feature ID set to use for picking and styling.
* * For EXT_mesh_features, this is the feature ID's label property, or * "featureId_N" (where N is the index in the featureIds array) when not * specified. EXT_feature_metadata did not have a label field, so such * feature ID sets are always labeled "featureId_N" where N is the index in * the list of all feature Ids, where feature ID attributes are listed before * feature ID textures. *
** If featureIdLabel is set to an integer N, it is converted to * the string "featureId_N" automatically. If both per-primitive and * per-instance feature IDs are present, the instance feature IDs take * priority. *
* * @memberof Cesium3DTileset.prototype * * @type {string} * @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. */ featureIdLabel: { get: function() { return this._featureIdLabel; }, set: function(value) { if (typeof value === "number") { value = `featureId_${value}`; } Check_default.typeOf.string("value", value); this._featureIdLabel = value; } }, /** * Label of the instance feature ID set used for picking and styling. ** If instanceFeatureIdLabel is set to an integer N, it is converted to * the string "instanceFeatureId_N" automatically. * If both per-primitive and per-instance feature IDs are present, the * instance feature IDs take priority. *
* * @memberof Cesium3DTileset.prototype * * @type {string} * @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. */ instanceFeatureIdLabel: { get: function() { return this._instanceFeatureIdLabel; }, set: function(value) { if (typeof value === "number") { value = `instanceFeatureId_${value}`; } Check_default.typeOf.string("value", value); this._instanceFeatureIdLabel = value; } } }); Cesium3DTileset.fromIonAssetId = async function(assetId, options) { Check_default.defined("assetId", assetId); const resource = await IonResource_default.fromAssetId(assetId); return Cesium3DTileset.fromUrl(resource, options); }; Cesium3DTileset.fromUrl = async function(url2, options) { Check_default.defined("url", url2); options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT); const resource = Resource_default.createIfNeeded(url2); let basePath; if (resource.extension === "json") { basePath = resource.getBaseUri(true); } else if (resource.isDataUri) { basePath = ""; } const tilesetJson = await Cesium3DTileset.loadJson(resource); const metadataExtension = await processMetadataExtension( resource, tilesetJson ); const tileset = new Cesium3DTileset(options); tileset._resource = resource; tileset._url = resource.url; tileset._basePath = basePath; tileset._metadataExtension = metadataExtension; tileset._geometricError = tilesetJson.geometricError; tileset._scaledGeometricError = tilesetJson.geometricError; const asset = tilesetJson.asset; tileset._asset = asset; tileset._extras = tilesetJson.extras; let credits = resource.credits; if (!defined_default(credits)) { credits = []; } const assetExtras = asset.extras; if (defined_default(assetExtras) && defined_default(assetExtras.cesium) && defined_default(assetExtras.cesium.credits)) { const extraCredits = assetExtras.cesium.credits; for (let i = 0; i < extraCredits.length; ++i) { const credit = extraCredits[i]; credits.push(new Credit_default(credit.html, tileset._showCreditsOnScreen)); } } tileset._credits = credits; const gltfUpAxis = defined_default(tilesetJson.asset.gltfUpAxis) ? Axis_default.fromName(tilesetJson.asset.gltfUpAxis) : Axis_default.Y; const modelUpAxis = defaultValue_default(options.modelUpAxis, gltfUpAxis); const modelForwardAxis = defaultValue_default(options.modelForwardAxis, Axis_default.X); tileset._properties = tilesetJson.properties; tileset._extensionsUsed = tilesetJson.extensionsUsed; tileset._extensions = tilesetJson.extensions; tileset._modelUpAxis = modelUpAxis; tileset._modelForwardAxis = modelForwardAxis; tileset._root = tileset.loadTileset(resource, tilesetJson); const boundingVolume = tileset._root.createBoundingVolume( tilesetJson.root.boundingVolume, Matrix4_default.IDENTITY ); const clippingPlanesOrigin = boundingVolume.boundingSphere.center; const originCartographic = tileset._ellipsoid.cartesianToCartographic( clippingPlanesOrigin ); if (defined_default(originCartographic) && originCartographic.height > ApproximateTerrainHeights_default._defaultMinTerrainHeight) { tileset._initialClippingPlanesOriginMatrix = Transforms_default.eastNorthUpToFixedFrame( clippingPlanesOrigin ); } tileset._clippingPlanesOriginMatrix = Matrix4_default.clone( tileset._initialClippingPlanesOriginMatrix ); tileset._readyPromise = Promise.resolve(tileset); tileset._ready = true; return tileset; }; Cesium3DTileset.loadJson = function(tilesetUrl) { const resource = Resource_default.createIfNeeded(tilesetUrl); return resource.fetchJson(); }; Cesium3DTileset.prototype.makeStyleDirty = function() { this._styleEngine.makeDirty(); }; Cesium3DTileset.prototype.loadTileset = function(resource, tilesetJson, parentTile) { const asset = tilesetJson.asset; if (!defined_default(asset)) { throw new RuntimeError_default("Tileset must have an asset property."); } if (asset.version !== "0.0" && asset.version !== "1.0" && asset.version !== "1.1") { throw new RuntimeError_default( "The tileset must be 3D Tiles version 0.0, 1.0, or 1.1" ); } if (defined_default(tilesetJson.extensionsRequired)) { Cesium3DTileset.checkSupportedExtensions(tilesetJson.extensionsRequired); } const statistics2 = this._statistics; const tilesetVersion = asset.tilesetVersion; if (defined_default(tilesetVersion)) { this._basePath += `?v=${tilesetVersion}`; resource = resource.clone(); resource.setQueryParameters({ v: tilesetVersion }); } const rootTile = makeTile2(this, resource, tilesetJson.root, parentTile); if (defined_default(parentTile)) { parentTile.children.push(rootTile); rootTile._depth = parentTile._depth + 1; } const stack = []; stack.push(rootTile); while (stack.length > 0) { const tile = stack.pop(); ++statistics2.numberOfTilesTotal; this._allTilesAdditive = this._allTilesAdditive && tile.refine === Cesium3DTileRefine_default.ADD; const children = tile._header.children; if (defined_default(children)) { for (let i = 0; i < children.length; ++i) { const childHeader = children[i]; const childTile = makeTile2(this, resource, childHeader, tile); tile.children.push(childTile); childTile._depth = tile._depth + 1; stack.push(childTile); } } if (this._cullWithChildrenBounds) { Cesium3DTileOptimizations_default.checkChildrenWithinParent(tile); } } return rootTile; }; function makeTile2(tileset, baseResource2, tileHeader, parentTile) { const hasImplicitTiling = defined_default(tileHeader.implicitTiling) || hasExtension_default(tileHeader, "3DTILES_implicit_tiling"); if (!hasImplicitTiling) { return new Cesium3DTile_default(tileset, baseResource2, tileHeader, parentTile); } const metadataSchema = tileset.schema; const implicitTileset = new ImplicitTileset_default( baseResource2, tileHeader, metadataSchema ); const rootCoordinates = new ImplicitTileCoordinates_default({ subdivisionScheme: implicitTileset.subdivisionScheme, subtreeLevels: implicitTileset.subtreeLevels, level: 0, x: 0, y: 0, // The constructor will only use this for octrees. z: 0 }); const contentUri = implicitTileset.subtreeUriTemplate.getDerivedResource({ templateValues: rootCoordinates.getTemplateValues() }).url; const deepCopy = true; const tileJson = clone_default(tileHeader, deepCopy); tileJson.contents = [ { uri: contentUri } ]; delete tileJson.content; delete tileJson.extensions; const tile = new Cesium3DTile_default(tileset, baseResource2, tileJson, parentTile); tile.implicitTileset = implicitTileset; tile.implicitCoordinates = rootCoordinates; return tile; } async function processMetadataExtension(resource, tilesetJson) { const metadataJson = hasExtension_default(tilesetJson, "3DTILES_metadata") ? tilesetJson.extensions["3DTILES_metadata"] : tilesetJson; let schemaLoader; if (defined_default(metadataJson.schemaUri)) { resource = resource.getDerivedResource({ url: metadataJson.schemaUri }); schemaLoader = ResourceCache_default.getSchemaLoader({ resource }); } else if (defined_default(metadataJson.schema)) { schemaLoader = ResourceCache_default.getSchemaLoader({ schema: metadataJson.schema }); } else { return; } await schemaLoader.load(); const metadataExtension = new Cesium3DTilesetMetadata_default({ schema: schemaLoader.schema, metadataJson }); ResourceCache_default.unload(schemaLoader); return metadataExtension; } var scratchPositionNormal = new Cartesian3_default(); var scratchCartographic7 = new Cartographic_default(); var scratchMatrix4 = new Matrix4_default(); var scratchCenter5 = new Cartesian3_default(); var scratchPosition7 = new Cartesian3_default(); var scratchDirection = new Cartesian3_default(); function updateDynamicScreenSpaceError(tileset, frameState) { let up; let direction2; let height; let minimumHeight; let maximumHeight; const camera = frameState.camera; const root = tileset._root; const tileBoundingVolume = root.contentBoundingVolume; if (tileBoundingVolume instanceof TileBoundingRegion_default) { up = Cartesian3_default.normalize(camera.positionWC, scratchPositionNormal); direction2 = camera.directionWC; height = camera.positionCartographic.height; minimumHeight = tileBoundingVolume.minimumHeight; maximumHeight = tileBoundingVolume.maximumHeight; } else { const transformLocal = Matrix4_default.inverseTransformation( root.computedTransform, scratchMatrix4 ); const ellipsoid = frameState.mapProjection.ellipsoid; const boundingVolume = tileBoundingVolume.boundingVolume; const centerLocal = Matrix4_default.multiplyByPoint( transformLocal, boundingVolume.center, scratchCenter5 ); if (Cartesian3_default.magnitude(centerLocal) > ellipsoid.minimumRadius) { const centerCartographic = Cartographic_default.fromCartesian( centerLocal, ellipsoid, scratchCartographic7 ); up = Cartesian3_default.normalize(camera.positionWC, scratchPositionNormal); direction2 = camera.directionWC; height = camera.positionCartographic.height; minimumHeight = 0; maximumHeight = centerCartographic.height * 2; } else { const positionLocal = Matrix4_default.multiplyByPoint( transformLocal, camera.positionWC, scratchPosition7 ); up = Cartesian3_default.UNIT_Z; direction2 = Matrix4_default.multiplyByPointAsVector( transformLocal, camera.directionWC, scratchDirection ); direction2 = Cartesian3_default.normalize(direction2, direction2); height = positionLocal.z; if (tileBoundingVolume instanceof TileOrientedBoundingBox_default) { const boxHeight = root._header.boundingVolume.box[11]; minimumHeight = centerLocal.z - boxHeight; maximumHeight = centerLocal.z + boxHeight; } else if (tileBoundingVolume instanceof TileBoundingSphere_default) { const radius = boundingVolume.radius; minimumHeight = centerLocal.z - radius; maximumHeight = centerLocal.z + radius; } } } const heightFalloff = tileset.dynamicScreenSpaceErrorHeightFalloff; const heightClose = minimumHeight + (maximumHeight - minimumHeight) * heightFalloff; const heightFar = maximumHeight; const t = Math_default.clamp( (height - heightClose) / (heightFar - heightClose), 0, 1 ); let horizonFactor = 1 - Math.abs(Cartesian3_default.dot(direction2, up)); horizonFactor = horizonFactor * (1 - t); tileset._dynamicScreenSpaceErrorComputedDensity = tileset.dynamicScreenSpaceErrorDensity * horizonFactor; } function requestContent(tileset, tile) { if (tile.hasEmptyContent) { return; } const { statistics: statistics2 } = tileset; const contentExpired = tile.contentExpired; const promise = tile.requestContent(); if (!defined_default(promise)) { return; } promise.then((content) => { if (!defined_default(content) || tile.isDestroyed() || tileset.isDestroyed()) { return; } tileset._processingQueue.push(tile); ++statistics2.numberOfTilesProcessing; }).catch((error) => { handleTileFailure(error, tileset, tile); }); if (contentExpired) { if (tile.hasTilesetContent || tile.hasImplicitContent) { destroySubtree(tileset, tile); } else { statistics2.decrementLoadCounts(tile.content); --statistics2.numberOfTilesWithContentReady; } } tileset._requestedTilesInFlight.push(tile); } function sortRequestByPriority(a3, b) { return a3._priority - b._priority; } Cesium3DTileset.prototype.postPassesUpdate = function(frameState) { if (!defined_default(this._root)) { return; } cancelOutOfViewRequests(this, frameState); raiseLoadProgressEvent(this, frameState); this._cache.unloadTiles(this, unloadTile); if (this._styleApplied) { this._styleEngine.resetDirty(); } this._styleApplied = false; }; Cesium3DTileset.prototype.prePassesUpdate = function(frameState) { if (!defined_default(this._root)) { return; } processTiles(this, frameState); const clippingPlanes = this._clippingPlanes; this._clippingPlanesOriginMatrixDirty = true; if (defined_default(clippingPlanes) && clippingPlanes.enabled) { clippingPlanes.update(frameState); } if (!defined_default(this._loadTimestamp)) { this._loadTimestamp = JulianDate_default.clone(frameState.time); } this._timeSinceLoad = Math.max( JulianDate_default.secondsDifference(frameState.time, this._loadTimestamp) * 1e3, 0 ); if (this.dynamicScreenSpaceError) { updateDynamicScreenSpaceError(this, frameState); } if (frameState.newFrame) { this._cache.reset(); } }; function cancelOutOfViewRequests(tileset, frameState) { const requestedTilesInFlight = tileset._requestedTilesInFlight; let removeCount = 0; for (let i = 0; i < requestedTilesInFlight.length; ++i) { const tile = requestedTilesInFlight[i]; const outOfView = frameState.frameNumber - tile._touchedFrame >= 1; if (tile._contentState !== Cesium3DTileContentState_default.LOADING) { ++removeCount; continue; } else if (outOfView) { tile.cancelRequests(); ++removeCount; continue; } if (removeCount > 0) { requestedTilesInFlight[i - removeCount] = tile; } } requestedTilesInFlight.length -= removeCount; } function requestTiles(tileset) { const requestedTiles = tileset._requestedTiles; requestedTiles.sort(sortRequestByPriority); for (let i = 0; i < requestedTiles.length; ++i) { requestContent(tileset, requestedTiles[i]); } } function handleTileFailure(error, tileset, tile) { if (tileset.isDestroyed()) { return; } let url2; if (!tile.isDestroyed()) { url2 = tile._contentResource.url; } const message = defined_default(error.message) ? error.message : error.toString(); if (tileset.tileFailed.numberOfListeners > 0) { tileset.tileFailed.raiseEvent({ url: url2, message }); } else { console.log(`A 3D tile failed to load: ${url2}`); console.log(`Error: ${message}`); } } function filterProcessingQueue(tileset) { const tiles = tileset._processingQueue; let removeCount = 0; for (let i = 0; i < tiles.length; ++i) { const tile = tiles[i]; if (tile.isDestroyed() || tile._contentState !== Cesium3DTileContentState_default.PROCESSING) { ++removeCount; continue; } if (removeCount > 0) { tiles[i - removeCount] = tile; } } tiles.length -= removeCount; } function processTiles(tileset, frameState) { filterProcessingQueue(tileset); const tiles = tileset._processingQueue; const statistics2 = tileset._statistics; let tile; for (let i = 0; i < tiles.length; ++i) { tile = tiles[i]; try { tile.process(tileset, frameState); if (tile.contentReady) { --statistics2.numberOfTilesProcessing; tileset.tileLoad.raiseEvent(tile); } } catch (error) { --statistics2.numberOfTilesProcessing; handleTileFailure(error, tileset, tile); } } } var scratchCartesian10 = new Cartesian3_default(); var stringOptions = { maximumFractionDigits: 3 }; function formatMemoryString(memorySizeInBytes) { const memoryInMegabytes = memorySizeInBytes / 1048576; if (memoryInMegabytes < 1) { return memoryInMegabytes.toLocaleString(void 0, stringOptions); } return Math.round(memoryInMegabytes).toLocaleString(); } function computeTileLabelPosition(tile) { const { halfAxes, radius, center } = tile.boundingVolume.boundingVolume; let position = Cartesian3_default.clone(center, scratchCartesian10); if (defined_default(halfAxes)) { position.x += 0.75 * (halfAxes[0] + halfAxes[3] + halfAxes[6]); position.y += 0.75 * (halfAxes[1] + halfAxes[4] + halfAxes[7]); position.z += 0.75 * (halfAxes[2] + halfAxes[5] + halfAxes[8]); } else if (defined_default(radius)) { let normal2 = Cartesian3_default.normalize(center, scratchCartesian10); normal2 = Cartesian3_default.multiplyByScalar( normal2, 0.75 * radius, scratchCartesian10 ); position = Cartesian3_default.add(normal2, center, scratchCartesian10); } return position; } function addTileDebugLabel(tile, tileset, position) { let labelString = ""; let attributes = 0; if (tileset.debugShowGeometricError) { labelString += ` Geometric error: ${tile.geometricError}`; attributes++; } if (tileset.debugShowRenderingStatistics) { labelString += ` Commands: ${tile.commandsLength}`; attributes++; const numberOfPoints = tile.content.pointsLength; if (numberOfPoints > 0) { labelString += ` Points: ${tile.content.pointsLength}`; attributes++; } const numberOfTriangles = tile.content.trianglesLength; if (numberOfTriangles > 0) { labelString += ` Triangles: ${tile.content.trianglesLength}`; attributes++; } labelString += ` Features: ${tile.content.featuresLength}`; attributes++; } if (tileset.debugShowMemoryUsage) { labelString += ` Texture Memory: ${formatMemoryString( tile.content.texturesByteLength )}`; labelString += ` Geometry Memory: ${formatMemoryString( tile.content.geometryByteLength )}`; attributes += 2; } if (tileset.debugShowUrl) { if (tile.hasMultipleContents) { labelString += "\nUrls:"; const urls = tile.content.innerContentUrls; for (let i = 0; i < urls.length; i++) { labelString += ` - ${urls[i]}`; } attributes += urls.length; } else { labelString += ` Url: ${tile._contentHeader.uri}`; attributes++; } } const newLabel = { text: labelString.substring(1), position, font: `${19 - attributes}px sans-serif`, showBackground: true, disableDepthTestDistance: Number.POSITIVE_INFINITY }; return tileset._tileDebugLabels.add(newLabel); } function updateTileDebugLabels(tileset, frameState) { const selectedTiles = tileset._selectedTiles; const selectedLength = selectedTiles.length; const emptyTiles = tileset._emptyTiles; const emptyLength = emptyTiles.length; tileset._tileDebugLabels.removeAll(); if (tileset.debugPickedTileLabelOnly) { if (defined_default(tileset.debugPickedTile)) { const position = defined_default(tileset.debugPickPosition) ? tileset.debugPickPosition : computeTileLabelPosition(tileset.debugPickedTile); const label = addTileDebugLabel( tileset.debugPickedTile, tileset, position ); label.pixelOffset = new Cartesian2_default(15, -15); } } else { for (let i = 0; i < selectedLength; ++i) { const tile = selectedTiles[i]; addTileDebugLabel(tile, tileset, computeTileLabelPosition(tile)); } for (let i = 0; i < emptyLength; ++i) { const tile = emptyTiles[i]; if (tile.hasTilesetContent || tile.hasImplicitContent) { addTileDebugLabel(tile, tileset, computeTileLabelPosition(tile)); } } } tileset._tileDebugLabels.update(frameState); } function updateTiles(tileset, frameState, passOptions2) { tileset._styleEngine.applyStyle(tileset); tileset._styleApplied = true; const { commandList, context } = frameState; const numberOfInitialCommands = commandList.length; const selectedTiles = tileset._selectedTiles; const bivariateVisibilityTest = tileset.isSkippingLevelOfDetail && tileset._hasMixedContent && context.stencilBuffer && selectedTiles.length > 0; tileset._backfaceCommands.length = 0; if (bivariateVisibilityTest) { if (!defined_default(tileset._stencilClearCommand)) { tileset._stencilClearCommand = new ClearCommand_default({ stencil: 0, pass: Pass_default.CESIUM_3D_TILE, renderState: RenderState_default.fromCache({ stencilMask: StencilConstants_default.SKIP_LOD_MASK }) }); } commandList.push(tileset._stencilClearCommand); } const { statistics: statistics2, tileVisible } = tileset; const isRender = passOptions2.isRender; const lengthBeforeUpdate = commandList.length; for (let i = 0; i < selectedTiles.length; ++i) { const tile = selectedTiles[i]; if (isRender) { tileVisible.raiseEvent(tile); } tile.update(tileset, frameState, passOptions2); statistics2.incrementSelectionCounts(tile.content); ++statistics2.selected; } const emptyTiles = tileset._emptyTiles; for (let i = 0; i < emptyTiles.length; ++i) { const tile = emptyTiles[i]; tile.update(tileset, frameState, passOptions2); } let addedCommandsLength = commandList.length - lengthBeforeUpdate; tileset._backfaceCommands.trim(); if (bivariateVisibilityTest) { const backfaceCommands = tileset._backfaceCommands.values; const backfaceCommandsLength = backfaceCommands.length; commandList.length += backfaceCommandsLength; for (let i = addedCommandsLength - 1; i >= 0; --i) { commandList[lengthBeforeUpdate + backfaceCommandsLength + i] = commandList[lengthBeforeUpdate + i]; } for (let i = 0; i < backfaceCommandsLength; ++i) { commandList[lengthBeforeUpdate + i] = backfaceCommands[i]; } } addedCommandsLength = commandList.length - numberOfInitialCommands; statistics2.numberOfCommands = addedCommandsLength; if (!isRender) { return; } if (tileset.pointCloudShading.attenuation && tileset.pointCloudShading.eyeDomeLighting && addedCommandsLength > 0) { tileset._pointCloudEyeDomeLighting.update( frameState, numberOfInitialCommands, tileset.pointCloudShading, tileset.boundingSphere ); } if (tileset.debugShowGeometricError || tileset.debugShowRenderingStatistics || tileset.debugShowMemoryUsage || tileset.debugShowUrl) { if (!defined_default(tileset._tileDebugLabels)) { tileset._tileDebugLabels = new LabelCollection_default(); } updateTileDebugLabels(tileset, frameState); } else { tileset._tileDebugLabels = tileset._tileDebugLabels && tileset._tileDebugLabels.destroy(); } } var scratchStack2 = []; function destroySubtree(tileset, tile) { const root = tile; const stack = scratchStack2; stack.push(tile); while (stack.length > 0) { tile = stack.pop(); const children = tile.children; for (let i = 0; i < children.length; ++i) { stack.push(children[i]); } if (tile !== root) { destroyTile(tileset, tile); --tileset._statistics.numberOfTilesTotal; } } root.children = []; } function unloadTile(tileset, tile) { tileset.tileUnload.raiseEvent(tile); tileset._statistics.decrementLoadCounts(tile.content); --tileset._statistics.numberOfTilesWithContentReady; tile.unloadContent(); } function destroyTile(tileset, tile) { tileset._cache.unloadTile(tileset, tile, unloadTile); tile.destroy(); } Cesium3DTileset.prototype.trimLoadedTiles = function() { this._cache.trim(); }; function raiseLoadProgressEvent(tileset, frameState) { const statistics2 = tileset._statistics; const statisticsLast = tileset._statisticsLast; const numberOfPendingRequests = statistics2.numberOfPendingRequests; const numberOfTilesProcessing = statistics2.numberOfTilesProcessing; const lastNumberOfPendingRequest = statisticsLast.numberOfPendingRequests; const lastNumberOfTilesProcessing = statisticsLast.numberOfTilesProcessing; Cesium3DTilesetStatistics_default.clone(statistics2, statisticsLast); const progressChanged = numberOfPendingRequests !== lastNumberOfPendingRequest || numberOfTilesProcessing !== lastNumberOfTilesProcessing; if (progressChanged) { frameState.afterRender.push(function() { tileset.loadProgress.raiseEvent( numberOfPendingRequests, numberOfTilesProcessing ); return true; }); } tileset._tilesLoaded = statistics2.numberOfPendingRequests === 0 && statistics2.numberOfTilesProcessing === 0 && statistics2.numberOfAttemptedRequests === 0; if (progressChanged && tileset._tilesLoaded) { frameState.afterRender.push(function() { tileset.allTilesLoaded.raiseEvent(); return true; }); if (!tileset._initialTilesLoaded) { tileset._initialTilesLoaded = true; frameState.afterRender.push(function() { tileset.initialTilesLoaded.raiseEvent(); return true; }); } } } function resetMinimumMaximum(tileset) { tileset._heatmap.resetMinimumMaximum(); tileset._minimumPriority.depth = Number.MAX_VALUE; tileset._maximumPriority.depth = -Number.MAX_VALUE; tileset._minimumPriority.foveatedFactor = Number.MAX_VALUE; tileset._maximumPriority.foveatedFactor = -Number.MAX_VALUE; tileset._minimumPriority.distance = Number.MAX_VALUE; tileset._maximumPriority.distance = -Number.MAX_VALUE; tileset._minimumPriority.reverseScreenSpaceError = Number.MAX_VALUE; tileset._maximumPriority.reverseScreenSpaceError = -Number.MAX_VALUE; } function detectModelMatrixChanged(tileset, frameState) { if (frameState.frameNumber === tileset._updatedModelMatrixFrame && defined_default(tileset._previousModelMatrix)) { return; } tileset._updatedModelMatrixFrame = frameState.frameNumber; tileset._modelMatrixChanged = !Matrix4_default.equals( tileset.modelMatrix, tileset._previousModelMatrix ); if (tileset._modelMatrixChanged) { tileset._previousModelMatrix = Matrix4_default.clone( tileset.modelMatrix, tileset._previousModelMatrix ); } } function update3(tileset, frameState, passStatistics, passOptions2) { if (frameState.mode === SceneMode_default.MORPHING) { return false; } if (!defined_default(tileset._root)) { return false; } const statistics2 = tileset._statistics; statistics2.clear(); ++tileset._updatedVisibilityFrame; resetMinimumMaximum(tileset); detectModelMatrixChanged(tileset, frameState); tileset._cullRequestsWhileMoving = tileset.cullRequestsWhileMoving && !tileset._modelMatrixChanged; const ready = tileset.getTraversal(passOptions2).selectTiles(tileset, frameState); if (passOptions2.requestTiles) { requestTiles(tileset); } updateTiles(tileset, frameState, passOptions2); Cesium3DTilesetStatistics_default.clone(statistics2, passStatistics); if (passOptions2.isRender) { const credits = tileset._credits; if (defined_default(credits) && statistics2.selected !== 0) { for (let i = 0; i < credits.length; ++i) { const credit = credits[i]; credit.showOnScreen = tileset._showCreditsOnScreen; frameState.creditDisplay.addCreditToNextFrame(credit); } } } return ready; } Cesium3DTileset.prototype.getTraversal = function(passOptions2) { const { pass } = passOptions2; if (pass === Cesium3DTilePass_default.MOST_DETAILED_PRELOAD || pass === Cesium3DTilePass_default.MOST_DETAILED_PICK) { return Cesium3DTilesetMostDetailedTraversal_default; } return this.isSkippingLevelOfDetail ? Cesium3DTilesetSkipTraversal_default : Cesium3DTilesetBaseTraversal_default; }; Cesium3DTileset.prototype.update = function(frameState) { this.updateForPass(frameState, frameState.tilesetPassState); }; Cesium3DTileset.prototype.updateForPass = function(frameState, tilesetPassState) { Check_default.typeOf.object("frameState", frameState); Check_default.typeOf.object("tilesetPassState", tilesetPassState); const pass = tilesetPassState.pass; if (pass === Cesium3DTilePass_default.PRELOAD && (!this.preloadWhenHidden || this.show) || pass === Cesium3DTilePass_default.PRELOAD_FLIGHT && (!this.preloadFlightDestinations || !this.show && !this.preloadWhenHidden) || pass === Cesium3DTilePass_default.REQUEST_RENDER_MODE_DEFER_CHECK && (!this._cullRequestsWhileMoving && this.foveatedTimeDelay <= 0 || !this.show)) { return; } const originalCommandList = frameState.commandList; const originalCamera = frameState.camera; const originalCullingVolume = frameState.cullingVolume; tilesetPassState.ready = false; const passOptions2 = Cesium3DTilePass_default.getPassOptions(pass); const ignoreCommands = passOptions2.ignoreCommands; const commandList = defaultValue_default( tilesetPassState.commandList, originalCommandList ); const commandStart = commandList.length; frameState.commandList = commandList; frameState.camera = defaultValue_default(tilesetPassState.camera, originalCamera); frameState.cullingVolume = defaultValue_default( tilesetPassState.cullingVolume, originalCullingVolume ); const passStatistics = this._statisticsPerPass[pass]; if (this.show || ignoreCommands) { this._pass = pass; tilesetPassState.ready = update3( this, frameState, passStatistics, passOptions2 ); } if (ignoreCommands) { commandList.length = commandStart; } frameState.commandList = originalCommandList; frameState.camera = originalCamera; frameState.cullingVolume = originalCullingVolume; }; Cesium3DTileset.prototype.hasExtension = function(extensionName) { if (!defined_default(this._extensionsUsed)) { return false; } return this._extensionsUsed.indexOf(extensionName) > -1; }; Cesium3DTileset.prototype.isDestroyed = function() { return false; }; Cesium3DTileset.prototype.destroy = function() { this._tileDebugLabels = this._tileDebugLabels && this._tileDebugLabels.destroy(); this._clippingPlanes = this._clippingPlanes && this._clippingPlanes.destroy(); if (defined_default(this._root)) { const stack = scratchStack2; stack.push(this._root); while (stack.length > 0) { const tile = stack.pop(); tile.destroy(); const children = tile.children; for (let i = 0; i < children.length; ++i) { stack.push(children[i]); } } } this._root = void 0; if (this._shouldDestroyImageBasedLighting && !this._imageBasedLighting.isDestroyed()) { this._imageBasedLighting.destroy(); } this._imageBasedLighting = void 0; return destroyObject_default(this); }; Cesium3DTileset.supportedExtensions = { "3DTILES_metadata": true, "3DTILES_implicit_tiling": true, "3DTILES_content_gltf": true, "3DTILES_multiple_contents": true, "3DTILES_bounding_volume_S2": true, "3DTILES_batch_table_hierarchy": true, "3DTILES_draco_point_compression": true, MAXAR_content_geojson: true }; Cesium3DTileset.checkSupportedExtensions = function(extensionsRequired) { for (let i = 0; i < extensionsRequired.length; i++) { if (!Cesium3DTileset.supportedExtensions[extensionsRequired[i]]) { throw new RuntimeError_default( `Unsupported 3D Tiles Extension: ${extensionsRequired[i]}` ); } } }; var Cesium3DTileset_default = Cesium3DTileset; // packages/engine/Source/DataSources/Cesium3DTilesetVisualizer.js var modelMatrixScratch2 = new Matrix4_default(); function Cesium3DTilesetVisualizer(scene, entityCollection) { if (!defined_default(scene)) { throw new DeveloperError_default("scene is required."); } if (!defined_default(entityCollection)) { throw new DeveloperError_default("entityCollection is required."); } entityCollection.collectionChanged.addEventListener( Cesium3DTilesetVisualizer.prototype._onCollectionChanged, this ); this._scene = scene; this._primitives = scene.primitives; this._entityCollection = entityCollection; this._tilesetHash = {}; this._entitiesToVisualize = new AssociativeArray_default(); this._onCollectionChanged(entityCollection, entityCollection.values, [], []); } Cesium3DTilesetVisualizer.prototype.update = function(time) { if (!defined_default(time)) { throw new DeveloperError_default("time is required."); } const entities = this._entitiesToVisualize.values; const tilesetHash = this._tilesetHash; const primitives = this._primitives; for (let i = 0, len = entities.length; i < len; i++) { const entity = entities[i]; const tilesetGraphics = entity._tileset; let resource; const tilesetData = tilesetHash[entity.id]; const show = entity.isShowing && entity.isAvailable(time) && Property_default.getValueOrDefault(tilesetGraphics._show, time, true); let modelMatrix; if (show) { modelMatrix = entity.computeModelMatrix(time, modelMatrixScratch2); resource = Resource_default.createIfNeeded( Property_default.getValueOrUndefined(tilesetGraphics._uri, time) ); } if (!show) { if (defined_default(tilesetData)) { tilesetData.tilesetPrimitive.show = false; } continue; } const tileset = defined_default(tilesetData) ? tilesetData.tilesetPrimitive : void 0; if (!defined_default(tilesetData) || resource.url !== tilesetData.url) { if (defined_default(tileset)) { primitives.removeAndDestroy(tileset); } delete tilesetHash[entity.id]; createTileset(resource, tilesetHash, entity, primitives); } if (!defined_default(tileset)) { continue; } tileset.show = true; if (defined_default(modelMatrix)) { tileset.modelMatrix = modelMatrix; } tileset.maximumScreenSpaceError = Property_default.getValueOrDefault( tilesetGraphics.maximumScreenSpaceError, time, tileset.maximumScreenSpaceError ); } return true; }; Cesium3DTilesetVisualizer.prototype.isDestroyed = function() { return false; }; Cesium3DTilesetVisualizer.prototype.destroy = function() { this._entityCollection.collectionChanged.removeEventListener( Cesium3DTilesetVisualizer.prototype._onCollectionChanged, this ); const entities = this._entitiesToVisualize.values; const tilesetHash = this._tilesetHash; const primitives = this._primitives; for (let i = entities.length - 1; i > -1; i--) { removeTileset(this, entities[i], tilesetHash, primitives); } return destroyObject_default(this); }; Cesium3DTilesetVisualizer.prototype.getBoundingSphere = function(entity, result) { if (!defined_default(entity)) { throw new DeveloperError_default("entity is required."); } if (!defined_default(result)) { throw new DeveloperError_default("result is required."); } const tilesetData = this._tilesetHash[entity.id]; if (!defined_default(tilesetData) || tilesetData.loadFail) { return BoundingSphereState_default.FAILED; } const primitive = tilesetData.tilesetPrimitive; if (!defined_default(primitive)) { return BoundingSphereState_default.PENDING; } if (!primitive.show) { return BoundingSphereState_default.FAILED; } BoundingSphere_default.clone(primitive.boundingSphere, result); return BoundingSphereState_default.DONE; }; Cesium3DTilesetVisualizer.prototype._onCollectionChanged = function(entityCollection, added, removed, changed) { let i; let entity; const entities = this._entitiesToVisualize; const tilesetHash = this._tilesetHash; const primitives = this._primitives; for (i = added.length - 1; i > -1; i--) { entity = added[i]; if (defined_default(entity._tileset)) { entities.set(entity.id, entity); } } for (i = changed.length - 1; i > -1; i--) { entity = changed[i]; if (defined_default(entity._tileset)) { entities.set(entity.id, entity); } else { removeTileset(this, entity, tilesetHash, primitives); entities.remove(entity.id); } } for (i = removed.length - 1; i > -1; i--) { entity = removed[i]; removeTileset(this, entity, tilesetHash, primitives); entities.remove(entity.id); } }; function removeTileset(visualizer, entity, tilesetHash, primitives) { const tilesetData = tilesetHash[entity.id]; if (defined_default(tilesetData)) { if (defined_default(tilesetData.tilesetPrimitive)) { primitives.removeAndDestroy(tilesetData.tilesetPrimitive); } delete tilesetHash[entity.id]; } } async function createTileset(resource, tilesetHash, entity, primitives) { tilesetHash[entity.id] = { url: resource.url, loadFail: false }; try { const tileset = await Cesium3DTileset_default.fromUrl(resource); tileset.id = entity; primitives.add(tileset); if (!defined_default(tilesetHash[entity.id])) { return; } tilesetHash[entity.id].tilesetPrimitive = tileset; } catch (error) { console.error(error); tilesetHash[entity.id].loadFail = true; } } var Cesium3DTilesetVisualizer_default = Cesium3DTilesetVisualizer; // packages/engine/Source/DataSources/CheckerboardMaterialProperty.js var defaultEvenColor = Color_default.WHITE; var defaultOddColor = Color_default.BLACK; var defaultRepeat2 = new Cartesian2_default(2, 2); function CheckerboardMaterialProperty(options) { options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT); this._definitionChanged = new Event_default(); this._evenColor = void 0; this._evenColorSubscription = void 0; this._oddColor = void 0; this._oddColorSubscription = void 0; this._repeat = void 0; this._repeatSubscription = void 0; this.evenColor = options.evenColor; this.oddColor = options.oddColor; this.repeat = options.repeat; } Object.defineProperties(CheckerboardMaterialProperty.prototype, { /** * Gets a value indicating if this property is constant. A property is considered * constant if getValue always returns the same result for the current definition. * @memberof CheckerboardMaterialProperty.prototype * * @type {boolean} * @readonly */ isConstant: { get: function() { return Property_default.isConstant(this._evenColor) && // Property_default.isConstant(this._oddColor) && // Property_default.isConstant(this._repeat); } }, /** * Gets the event that is raised whenever the definition of this property changes. * The definition is considered to have changed if a call to getValue would return * a different result for the same time. * @memberof CheckerboardMaterialProperty.prototype * * @type {Event} * @readonly */ definitionChanged: { get: function() { return this._definitionChanged; } }, /** * Gets or sets the Property specifying the first {@link Color}. * @memberof CheckerboardMaterialProperty.prototype * @type {Property|undefined} * @default Color.WHITE */ evenColor: createPropertyDescriptor_default("evenColor"), /** * Gets or sets the Property specifying the second {@link Color}. * @memberof CheckerboardMaterialProperty.prototype * @type {Property|undefined} * @default Color.BLACK */ oddColor: createPropertyDescriptor_default("oddColor"), /** * Gets or sets the {@link Cartesian2} Property specifying how many times the tiles repeat in each direction. * @memberof CheckerboardMaterialProperty.prototype * @type {Property|undefined} * @default new Cartesian2(2.0, 2.0) */ repeat: createPropertyDescriptor_default("repeat") }); CheckerboardMaterialProperty.prototype.getType = function(time) { return "Checkerboard"; }; CheckerboardMaterialProperty.prototype.getValue = function(time, result) { if (!defined_default(result)) { result = {}; } result.lightColor = Property_default.getValueOrClonedDefault( this._evenColor, time, defaultEvenColor, result.lightColor ); result.darkColor = Property_default.getValueOrClonedDefault( this._oddColor, time, defaultOddColor, result.darkColor ); result.repeat = Property_default.getValueOrDefault(this._repeat, time, defaultRepeat2); return result; }; CheckerboardMaterialProperty.prototype.equals = function(other) { return this === other || // other instanceof CheckerboardMaterialProperty && // Property_default.equals(this._evenColor, other._evenColor) && // Property_default.equals(this._oddColor, other._oddColor) && // Property_default.equals(this._repeat, other._repeat); }; var CheckerboardMaterialProperty_default = CheckerboardMaterialProperty; // packages/engine/Source/DataSources/EntityCollection.js var entityOptionsScratch = { id: void 0 }; function fireChangedEvent(collection) { if (collection._firing) { collection._refire = true; return; } if (collection._suspendCount === 0) { const added = collection._addedEntities; const removed = collection._removedEntities; const changed = collection._changedEntities; if (changed.length !== 0 || added.length !== 0 || removed.length !== 0) { collection._firing = true; do { collection._refire = false; const addedArray = added.values.slice(0); const removedArray = removed.values.slice(0); const changedArray = changed.values.slice(0); added.removeAll(); removed.removeAll(); changed.removeAll(); collection._collectionChanged.raiseEvent( collection, addedArray, removedArray, changedArray ); } while (collection._refire); collection._firing = false; } } } function EntityCollection(owner) { this._owner = owner; this._entities = new AssociativeArray_default(); this._addedEntities = new AssociativeArray_default(); this._removedEntities = new AssociativeArray_default(); this._changedEntities = new AssociativeArray_default(); this._suspendCount = 0; this._collectionChanged = new Event_default(); this._id = createGuid_default(); this._show = true; this._firing = false; this._refire = false; } EntityCollection.prototype.suspendEvents = function() { this._suspendCount++; }; EntityCollection.prototype.resumeEvents = function() { if (this._suspendCount === 0) { throw new DeveloperError_default( "resumeEvents can not be called before suspendEvents." ); } this._suspendCount--; fireChangedEvent(this); }; Object.defineProperties(EntityCollection.prototype, { /** * Gets the event that is fired when entities are added or removed from the collection. * The generated event is a {@link EntityCollection.CollectionChangedEventCallback}. * @memberof EntityCollection.prototype * @readonly * @type {Eventvalue
's red
, green
,
* blue
, and alpha
properties as shown in Example 1. These components range from 0.0
* (no intensity) to 1.0
(full intensity).
* @memberof PointPrimitive.prototype
* @type {Color}
*
* @example
* // Example 1. Assign yellow.
* p.color = Cesium.Color.YELLOW;
*
* @example
* // Example 2. Make a pointPrimitive 50% translucent.
* p.color = new Cesium.Color(1.0, 1.0, 1.0, 0.5);
*/
color: {
get: function() {
return this._color;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
const color = this._color;
if (!Color_default.equals(color, value)) {
Color_default.clone(value, color);
makeDirty3(this, COLOR_INDEX3);
}
}
},
/**
* Gets or sets the outline color of the point.
* @memberof PointPrimitive.prototype
* @type {Color}
*/
outlineColor: {
get: function() {
return this._outlineColor;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
const outlineColor = this._outlineColor;
if (!Color_default.equals(outlineColor, value)) {
Color_default.clone(value, outlineColor);
makeDirty3(this, OUTLINE_COLOR_INDEX);
}
}
},
/**
* Gets or sets the outline width in pixels. This width adds to pixelSize,
* increasing the total size of the point.
* @memberof PointPrimitive.prototype
* @type {number}
*/
outlineWidth: {
get: function() {
return this._outlineWidth;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
if (this._outlineWidth !== value) {
this._outlineWidth = value;
makeDirty3(this, OUTLINE_WIDTH_INDEX);
}
}
},
/**
* Gets or sets the condition specifying at what distance from the camera that this point will be displayed.
* @memberof PointPrimitive.prototype
* @type {DistanceDisplayCondition}
* @default undefined
*/
distanceDisplayCondition: {
get: function() {
return this._distanceDisplayCondition;
},
set: function(value) {
if (defined_default(value) && value.far <= value.near) {
throw new DeveloperError_default("far must be greater than near");
}
if (!DistanceDisplayCondition_default.equals(this._distanceDisplayCondition, value)) {
this._distanceDisplayCondition = DistanceDisplayCondition_default.clone(
value,
this._distanceDisplayCondition
);
makeDirty3(this, DISTANCE_DISPLAY_CONDITION_INDEX2);
}
}
},
/**
* Gets or sets the distance from the camera at which to disable the depth test to, for example, prevent clipping against terrain.
* When set to zero, the depth test is always applied. When set to Number.POSITIVE_INFINITY, the depth test is never applied.
* @memberof PointPrimitive.prototype
* @type {number}
* @default 0.0
*/
disableDepthTestDistance: {
get: function() {
return this._disableDepthTestDistance;
},
set: function(value) {
if (this._disableDepthTestDistance !== value) {
if (!defined_default(value) || value < 0) {
throw new DeveloperError_default(
"disableDepthTestDistance must be greater than or equal to 0.0."
);
}
this._disableDepthTestDistance = value;
makeDirty3(this, DISABLE_DEPTH_DISTANCE_INDEX);
}
}
},
/**
* Gets or sets the user-defined value returned when the point is picked.
* @memberof PointPrimitive.prototype
* @type {*}
*/
id: {
get: function() {
return this._id;
},
set: function(value) {
this._id = value;
if (defined_default(this._pickId)) {
this._pickId.object.id = value;
}
}
},
/**
* @private
*/
pickId: {
get: function() {
return this._pickId;
}
},
/**
* Determines whether or not this point will be shown or hidden because it was clustered.
* @memberof PointPrimitive.prototype
* @type {boolean}
* @private
*/
clusterShow: {
get: function() {
return this._clusterShow;
},
set: function(value) {
if (this._clusterShow !== value) {
this._clusterShow = value;
makeDirty3(this, SHOW_INDEX5);
}
}
}
});
PointPrimitive.prototype.getPickId = function(context) {
if (!defined_default(this._pickId)) {
this._pickId = context.createPickId({
primitive: this,
collection: this._collection,
id: this._id
});
}
return this._pickId;
};
PointPrimitive.prototype._getActualPosition = function() {
return this._actualPosition;
};
PointPrimitive.prototype._setActualPosition = function(value) {
Cartesian3_default.clone(value, this._actualPosition);
makeDirty3(this, POSITION_INDEX5);
};
var tempCartesian32 = new Cartesian4_default();
PointPrimitive._computeActualPosition = function(position, frameState, modelMatrix) {
if (frameState.mode === SceneMode_default.SCENE3D) {
return position;
}
Matrix4_default.multiplyByPoint(modelMatrix, position, tempCartesian32);
return SceneTransforms_default.computeActualWgs84Position(frameState, tempCartesian32);
};
var scratchCartesian44 = new Cartesian4_default();
PointPrimitive._computeScreenSpacePosition = function(modelMatrix, position, scene, result) {
const positionWorld = Matrix4_default.multiplyByVector(
modelMatrix,
Cartesian4_default.fromElements(
position.x,
position.y,
position.z,
1,
scratchCartesian44
),
scratchCartesian44
);
const positionWC2 = SceneTransforms_default.wgs84ToWindowCoordinates(
scene,
positionWorld,
result
);
return positionWC2;
};
PointPrimitive.prototype.computeScreenSpacePosition = function(scene, result) {
const pointPrimitiveCollection = this._pointPrimitiveCollection;
if (!defined_default(result)) {
result = new Cartesian2_default();
}
if (!defined_default(pointPrimitiveCollection)) {
throw new DeveloperError_default("PointPrimitive must be in a collection.");
}
if (!defined_default(scene)) {
throw new DeveloperError_default("scene is required.");
}
const modelMatrix = pointPrimitiveCollection.modelMatrix;
const windowCoordinates = PointPrimitive._computeScreenSpacePosition(
modelMatrix,
this._actualPosition,
scene,
result
);
if (!defined_default(windowCoordinates)) {
return void 0;
}
windowCoordinates.y = scene.canvas.clientHeight - windowCoordinates.y;
return windowCoordinates;
};
PointPrimitive.getScreenSpaceBoundingBox = function(point, screenSpacePosition, result) {
const size = point.pixelSize;
const halfSize = size * 0.5;
const x = screenSpacePosition.x - halfSize;
const y = screenSpacePosition.y - halfSize;
const width = size;
const height = size;
if (!defined_default(result)) {
result = new BoundingRectangle_default();
}
result.x = x;
result.y = y;
result.width = width;
result.height = height;
return result;
};
PointPrimitive.prototype.equals = function(other) {
return this === other || defined_default(other) && this._id === other._id && Cartesian3_default.equals(this._position, other._position) && Color_default.equals(this._color, other._color) && this._pixelSize === other._pixelSize && this._outlineWidth === other._outlineWidth && this._show === other._show && Color_default.equals(this._outlineColor, other._outlineColor) && NearFarScalar_default.equals(this._scaleByDistance, other._scaleByDistance) && NearFarScalar_default.equals(
this._translucencyByDistance,
other._translucencyByDistance
) && DistanceDisplayCondition_default.equals(
this._distanceDisplayCondition,
other._distanceDisplayCondition
) && this._disableDepthTestDistance === other._disableDepthTestDistance;
};
PointPrimitive.prototype._destroy = function() {
this._pickId = this._pickId && this._pickId.destroy();
this._pointPrimitiveCollection = void 0;
};
var PointPrimitive_default = PointPrimitive;
// packages/engine/Source/Shaders/PointPrimitiveCollectionFS.js
var PointPrimitiveCollectionFS_default = "in vec4 v_color;\nin vec4 v_outlineColor;\nin float v_innerPercent;\nin float v_pixelDistance;\nin vec4 v_pickColor;\n\nvoid main()\n{\n // The distance in UV space from this fragment to the center of the point, at most 0.5.\n float distanceToCenter = length(gl_PointCoord - vec2(0.5));\n // The max distance stops one pixel shy of the edge to leave space for anti-aliasing.\n float maxDistance = max(0.0, 0.5 - v_pixelDistance);\n float wholeAlpha = 1.0 - smoothstep(maxDistance, 0.5, distanceToCenter);\n float innerAlpha = 1.0 - smoothstep(maxDistance * v_innerPercent, 0.5 * v_innerPercent, distanceToCenter);\n\n vec4 color = mix(v_outlineColor, v_color, innerAlpha);\n color.a *= wholeAlpha;\n\n// Fully transparent parts of the billboard are not pickable.\n#if !defined(OPAQUE) && !defined(TRANSLUCENT)\n if (color.a < 0.005) // matches 0/255 and 1/255\n {\n discard;\n }\n#else\n// The billboard is rendered twice. The opaque pass discards translucent fragments\n// and the translucent pass discards opaque fragments.\n#ifdef OPAQUE\n if (color.a < 0.995) // matches < 254/255\n {\n discard;\n }\n#else\n if (color.a >= 0.995) // matches 254/255 and 255/255\n {\n discard;\n }\n#endif\n#endif\n\n out_FragColor = czm_gammaCorrect(color);\n czm_writeLogDepth();\n}\n";
// packages/engine/Source/Shaders/PointPrimitiveCollectionVS.js
var PointPrimitiveCollectionVS_default = `uniform float u_maxTotalPointSize;
in vec4 positionHighAndSize;
in vec4 positionLowAndOutline;
in vec4 compressedAttribute0; // color, outlineColor, pick color
in vec4 compressedAttribute1; // show, translucency by distance, some free space
in vec4 scaleByDistance; // near, nearScale, far, farScale
in vec3 distanceDisplayConditionAndDisableDepth; // near, far, disableDepthTestDistance
out vec4 v_color;
out vec4 v_outlineColor;
out float v_innerPercent;
out float v_pixelDistance;
out vec4 v_pickColor;
const float SHIFT_LEFT8 = 256.0;
const float SHIFT_RIGHT8 = 1.0 / 256.0;
void main()
{
// Modifying this shader may also require modifications to PointPrimitive._computeScreenSpacePosition
// unpack attributes
vec3 positionHigh = positionHighAndSize.xyz;
vec3 positionLow = positionLowAndOutline.xyz;
float outlineWidthBothSides = 2.0 * positionLowAndOutline.w;
float totalSize = positionHighAndSize.w + outlineWidthBothSides;
float outlinePercent = outlineWidthBothSides / totalSize;
// Scale in response to browser-zoom.
totalSize *= czm_pixelRatio;
float temp = compressedAttribute1.x * SHIFT_RIGHT8;
float show = floor(temp);
#ifdef EYE_DISTANCE_TRANSLUCENCY
vec4 translucencyByDistance;
translucencyByDistance.x = compressedAttribute1.z;
translucencyByDistance.z = compressedAttribute1.w;
translucencyByDistance.y = ((temp - floor(temp)) * SHIFT_LEFT8) / 255.0;
temp = compressedAttribute1.y * SHIFT_RIGHT8;
translucencyByDistance.w = ((temp - floor(temp)) * SHIFT_LEFT8) / 255.0;
#endif
///////////////////////////////////////////////////////////////////////////
vec4 color;
vec4 outlineColor;
vec4 pickColor;
// compressedAttribute0.z => pickColor.rgb
temp = compressedAttribute0.z * SHIFT_RIGHT8;
pickColor.b = (temp - floor(temp)) * SHIFT_LEFT8;
temp = floor(temp) * SHIFT_RIGHT8;
pickColor.g = (temp - floor(temp)) * SHIFT_LEFT8;
pickColor.r = floor(temp);
// compressedAttribute0.x => color.rgb
temp = compressedAttribute0.x * SHIFT_RIGHT8;
color.b = (temp - floor(temp)) * SHIFT_LEFT8;
temp = floor(temp) * SHIFT_RIGHT8;
color.g = (temp - floor(temp)) * SHIFT_LEFT8;
color.r = floor(temp);
// compressedAttribute0.y => outlineColor.rgb
temp = compressedAttribute0.y * SHIFT_RIGHT8;
outlineColor.b = (temp - floor(temp)) * SHIFT_LEFT8;
temp = floor(temp) * SHIFT_RIGHT8;
outlineColor.g = (temp - floor(temp)) * SHIFT_LEFT8;
outlineColor.r = floor(temp);
// compressedAttribute0.w => color.a, outlineColor.a, pickColor.a
temp = compressedAttribute0.w * SHIFT_RIGHT8;
pickColor.a = (temp - floor(temp)) * SHIFT_LEFT8;
pickColor = pickColor / 255.0;
temp = floor(temp) * SHIFT_RIGHT8;
outlineColor.a = (temp - floor(temp)) * SHIFT_LEFT8;
outlineColor /= 255.0;
color.a = floor(temp);
color /= 255.0;
///////////////////////////////////////////////////////////////////////////
vec4 p = czm_translateRelativeToEye(positionHigh, positionLow);
vec4 positionEC = czm_modelViewRelativeToEye * p;
///////////////////////////////////////////////////////////////////////////
#if defined(EYE_DISTANCE_SCALING) || defined(EYE_DISTANCE_TRANSLUCENCY) || defined(DISTANCE_DISPLAY_CONDITION) || defined(DISABLE_DEPTH_DISTANCE)
float lengthSq;
if (czm_sceneMode == czm_sceneMode2D)
{
// 2D camera distance is a special case
// treat all billboards as flattened to the z=0.0 plane
lengthSq = czm_eyeHeight2D.y;
}
else
{
lengthSq = dot(positionEC.xyz, positionEC.xyz);
}
#endif
#ifdef EYE_DISTANCE_SCALING
totalSize *= czm_nearFarScalar(scaleByDistance, lengthSq);
#endif
if (totalSize > 0.0) {
// Add padding for anti-aliasing on both sides.
totalSize += 3.0;
}
// Clamp to max point size.
totalSize = min(totalSize, u_maxTotalPointSize);
// If size is too small, push vertex behind near plane for clipping.
// Note that context.minimumAliasedPointSize "will be at most 1.0".
if (totalSize < 1.0)
{
positionEC.xyz = vec3(0.0);
totalSize = 1.0;
}
float translucency = 1.0;
#ifdef EYE_DISTANCE_TRANSLUCENCY
translucency = czm_nearFarScalar(translucencyByDistance, lengthSq);
// push vertex behind near plane for clipping
if (translucency < 0.004)
{
positionEC.xyz = vec3(0.0);
}
#endif
#ifdef DISTANCE_DISPLAY_CONDITION
float nearSq = distanceDisplayConditionAndDisableDepth.x;
float farSq = distanceDisplayConditionAndDisableDepth.y;
if (lengthSq < nearSq || lengthSq > farSq) {
// push vertex behind camera to force it to be clipped
positionEC.xyz = vec3(0.0, 0.0, 1.0);
}
#endif
gl_Position = czm_projection * positionEC;
czm_vertexLogDepth();
#ifdef DISABLE_DEPTH_DISTANCE
float disableDepthTestDistance = distanceDisplayConditionAndDisableDepth.z;
if (disableDepthTestDistance == 0.0 && czm_minimumDisableDepthTestDistance != 0.0)
{
disableDepthTestDistance = czm_minimumDisableDepthTestDistance;
}
if (disableDepthTestDistance != 0.0)
{
// Don't try to "multiply both sides" by w. Greater/less-than comparisons won't work for negative values of w.
float zclip = gl_Position.z / gl_Position.w;
bool clipped = (zclip < -1.0 || zclip > 1.0);
if (!clipped && (disableDepthTestDistance < 0.0 || (lengthSq > 0.0 && lengthSq < disableDepthTestDistance)))
{
// Position z on the near plane.
gl_Position.z = -gl_Position.w;
#ifdef LOG_DEPTH
czm_vertexLogDepth(vec4(czm_currentFrustum.x));
#endif
}
}
#endif
v_color = color;
v_color.a *= translucency * show;
v_outlineColor = outlineColor;
v_outlineColor.a *= translucency * show;
v_innerPercent = 1.0 - outlinePercent;
v_pixelDistance = 2.0 / totalSize;
gl_PointSize = totalSize * show;
gl_Position *= show;
v_pickColor = pickColor;
}
`;
// packages/engine/Source/Scene/PointPrimitiveCollection.js
var SHOW_INDEX6 = PointPrimitive_default.SHOW_INDEX;
var POSITION_INDEX6 = PointPrimitive_default.POSITION_INDEX;
var COLOR_INDEX4 = PointPrimitive_default.COLOR_INDEX;
var OUTLINE_COLOR_INDEX2 = PointPrimitive_default.OUTLINE_COLOR_INDEX;
var OUTLINE_WIDTH_INDEX2 = PointPrimitive_default.OUTLINE_WIDTH_INDEX;
var PIXEL_SIZE_INDEX2 = PointPrimitive_default.PIXEL_SIZE_INDEX;
var SCALE_BY_DISTANCE_INDEX4 = PointPrimitive_default.SCALE_BY_DISTANCE_INDEX;
var TRANSLUCENCY_BY_DISTANCE_INDEX4 = PointPrimitive_default.TRANSLUCENCY_BY_DISTANCE_INDEX;
var DISTANCE_DISPLAY_CONDITION_INDEX3 = PointPrimitive_default.DISTANCE_DISPLAY_CONDITION_INDEX;
var DISABLE_DEPTH_DISTANCE_INDEX2 = PointPrimitive_default.DISABLE_DEPTH_DISTANCE_INDEX;
var NUMBER_OF_PROPERTIES4 = PointPrimitive_default.NUMBER_OF_PROPERTIES;
var attributeLocations5 = {
positionHighAndSize: 0,
positionLowAndOutline: 1,
compressedAttribute0: 2,
// color, outlineColor, pick color
compressedAttribute1: 3,
// show, translucency by distance, some free space
scaleByDistance: 4,
distanceDisplayConditionAndDisableDepth: 5
};
function PointPrimitiveCollection(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this._sp = void 0;
this._spTranslucent = void 0;
this._rsOpaque = void 0;
this._rsTranslucent = void 0;
this._vaf = void 0;
this._pointPrimitives = [];
this._pointPrimitivesToUpdate = [];
this._pointPrimitivesToUpdateIndex = 0;
this._pointPrimitivesRemoved = false;
this._createVertexArray = false;
this._shaderScaleByDistance = false;
this._compiledShaderScaleByDistance = false;
this._shaderTranslucencyByDistance = false;
this._compiledShaderTranslucencyByDistance = false;
this._shaderDistanceDisplayCondition = false;
this._compiledShaderDistanceDisplayCondition = false;
this._shaderDisableDepthDistance = false;
this._compiledShaderDisableDepthDistance = false;
this._propertiesChanged = new Uint32Array(NUMBER_OF_PROPERTIES4);
this._maxPixelSize = 1;
this._baseVolume = new BoundingSphere_default();
this._baseVolumeWC = new BoundingSphere_default();
this._baseVolume2D = new BoundingSphere_default();
this._boundingVolume = new BoundingSphere_default();
this._boundingVolumeDirty = false;
this._colorCommands = [];
this.show = defaultValue_default(options.show, true);
this.modelMatrix = Matrix4_default.clone(
defaultValue_default(options.modelMatrix, Matrix4_default.IDENTITY)
);
this._modelMatrix = Matrix4_default.clone(Matrix4_default.IDENTITY);
this.debugShowBoundingVolume = defaultValue_default(
options.debugShowBoundingVolume,
false
);
this.blendOption = defaultValue_default(
options.blendOption,
BlendOption_default.OPAQUE_AND_TRANSLUCENT
);
this._blendOption = void 0;
this._mode = SceneMode_default.SCENE3D;
this._maxTotalPointSize = 1;
this._buffersUsage = [
BufferUsage_default.STATIC_DRAW,
// SHOW_INDEX
BufferUsage_default.STATIC_DRAW,
// POSITION_INDEX
BufferUsage_default.STATIC_DRAW,
// COLOR_INDEX
BufferUsage_default.STATIC_DRAW,
// OUTLINE_COLOR_INDEX
BufferUsage_default.STATIC_DRAW,
// OUTLINE_WIDTH_INDEX
BufferUsage_default.STATIC_DRAW,
// PIXEL_SIZE_INDEX
BufferUsage_default.STATIC_DRAW,
// SCALE_BY_DISTANCE_INDEX
BufferUsage_default.STATIC_DRAW,
// TRANSLUCENCY_BY_DISTANCE_INDEX
BufferUsage_default.STATIC_DRAW
// DISTANCE_DISPLAY_CONDITION_INDEX
];
const that = this;
this._uniforms = {
u_maxTotalPointSize: function() {
return that._maxTotalPointSize;
}
};
}
Object.defineProperties(PointPrimitiveCollection.prototype, {
/**
* Returns the number of points in this collection. This is commonly used with
* {@link PointPrimitiveCollection#get} to iterate over all the points
* in the collection.
* @memberof PointPrimitiveCollection.prototype
* @type {number}
*/
length: {
get: function() {
removePointPrimitives(this);
return this._pointPrimitives.length;
}
}
});
function destroyPointPrimitives(pointPrimitives) {
const length3 = pointPrimitives.length;
for (let i = 0; i < length3; ++i) {
if (pointPrimitives[i]) {
pointPrimitives[i]._destroy();
}
}
}
PointPrimitiveCollection.prototype.add = function(options) {
const p = new PointPrimitive_default(options, this);
p._index = this._pointPrimitives.length;
this._pointPrimitives.push(p);
this._createVertexArray = true;
return p;
};
PointPrimitiveCollection.prototype.remove = function(pointPrimitive) {
if (this.contains(pointPrimitive)) {
this._pointPrimitives[pointPrimitive._index] = null;
this._pointPrimitivesRemoved = true;
this._createVertexArray = true;
pointPrimitive._destroy();
return true;
}
return false;
};
PointPrimitiveCollection.prototype.removeAll = function() {
destroyPointPrimitives(this._pointPrimitives);
this._pointPrimitives = [];
this._pointPrimitivesToUpdate = [];
this._pointPrimitivesToUpdateIndex = 0;
this._pointPrimitivesRemoved = false;
this._createVertexArray = true;
};
function removePointPrimitives(pointPrimitiveCollection) {
if (pointPrimitiveCollection._pointPrimitivesRemoved) {
pointPrimitiveCollection._pointPrimitivesRemoved = false;
const newPointPrimitives = [];
const pointPrimitives = pointPrimitiveCollection._pointPrimitives;
const length3 = pointPrimitives.length;
for (let i = 0, j = 0; i < length3; ++i) {
const pointPrimitive = pointPrimitives[i];
if (pointPrimitive) {
pointPrimitive._index = j++;
newPointPrimitives.push(pointPrimitive);
}
}
pointPrimitiveCollection._pointPrimitives = newPointPrimitives;
}
}
PointPrimitiveCollection.prototype._updatePointPrimitive = function(pointPrimitive, propertyChanged) {
if (!pointPrimitive._dirty) {
this._pointPrimitivesToUpdate[this._pointPrimitivesToUpdateIndex++] = pointPrimitive;
}
++this._propertiesChanged[propertyChanged];
};
PointPrimitiveCollection.prototype.contains = function(pointPrimitive) {
return defined_default(pointPrimitive) && pointPrimitive._pointPrimitiveCollection === this;
};
PointPrimitiveCollection.prototype.get = function(index) {
if (!defined_default(index)) {
throw new DeveloperError_default("index is required.");
}
removePointPrimitives(this);
return this._pointPrimitives[index];
};
PointPrimitiveCollection.prototype.computeNewBuffersUsage = function() {
const buffersUsage = this._buffersUsage;
let usageChanged = false;
const properties = this._propertiesChanged;
for (let k = 0; k < NUMBER_OF_PROPERTIES4; ++k) {
const newUsage = properties[k] === 0 ? BufferUsage_default.STATIC_DRAW : BufferUsage_default.STREAM_DRAW;
usageChanged = usageChanged || buffersUsage[k] !== newUsage;
buffersUsage[k] = newUsage;
}
return usageChanged;
};
function createVAF2(context, numberOfPointPrimitives, buffersUsage) {
return new VertexArrayFacade_default(
context,
[
{
index: attributeLocations5.positionHighAndSize,
componentsPerAttribute: 4,
componentDatatype: ComponentDatatype_default.FLOAT,
usage: buffersUsage[POSITION_INDEX6]
},
{
index: attributeLocations5.positionLowAndShow,
componentsPerAttribute: 4,
componentDatatype: ComponentDatatype_default.FLOAT,
usage: buffersUsage[POSITION_INDEX6]
},
{
index: attributeLocations5.compressedAttribute0,
componentsPerAttribute: 4,
componentDatatype: ComponentDatatype_default.FLOAT,
usage: buffersUsage[COLOR_INDEX4]
},
{
index: attributeLocations5.compressedAttribute1,
componentsPerAttribute: 4,
componentDatatype: ComponentDatatype_default.FLOAT,
usage: buffersUsage[TRANSLUCENCY_BY_DISTANCE_INDEX4]
},
{
index: attributeLocations5.scaleByDistance,
componentsPerAttribute: 4,
componentDatatype: ComponentDatatype_default.FLOAT,
usage: buffersUsage[SCALE_BY_DISTANCE_INDEX4]
},
{
index: attributeLocations5.distanceDisplayConditionAndDisableDepth,
componentsPerAttribute: 3,
componentDatatype: ComponentDatatype_default.FLOAT,
usage: buffersUsage[DISTANCE_DISPLAY_CONDITION_INDEX3]
}
],
numberOfPointPrimitives
);
}
var writePositionScratch2 = new EncodedCartesian3_default();
function writePositionSizeAndOutline(pointPrimitiveCollection, context, vafWriters, pointPrimitive) {
const i = pointPrimitive._index;
const position = pointPrimitive._getActualPosition();
if (pointPrimitiveCollection._mode === SceneMode_default.SCENE3D) {
BoundingSphere_default.expand(
pointPrimitiveCollection._baseVolume,
position,
pointPrimitiveCollection._baseVolume
);
pointPrimitiveCollection._boundingVolumeDirty = true;
}
EncodedCartesian3_default.fromCartesian(position, writePositionScratch2);
const pixelSize = pointPrimitive.pixelSize;
const outlineWidth = pointPrimitive.outlineWidth;
pointPrimitiveCollection._maxPixelSize = Math.max(
pointPrimitiveCollection._maxPixelSize,
pixelSize + outlineWidth
);
const positionHighWriter = vafWriters[attributeLocations5.positionHighAndSize];
const high = writePositionScratch2.high;
positionHighWriter(i, high.x, high.y, high.z, pixelSize);
const positionLowWriter = vafWriters[attributeLocations5.positionLowAndOutline];
const low = writePositionScratch2.low;
positionLowWriter(i, low.x, low.y, low.z, outlineWidth);
}
var LEFT_SHIFT162 = 65536;
var LEFT_SHIFT82 = 256;
function writeCompressedAttrib02(pointPrimitiveCollection, context, vafWriters, pointPrimitive) {
const i = pointPrimitive._index;
const color = pointPrimitive.color;
const pickColor = pointPrimitive.getPickId(context).color;
const outlineColor = pointPrimitive.outlineColor;
let red = Color_default.floatToByte(color.red);
let green = Color_default.floatToByte(color.green);
let blue = Color_default.floatToByte(color.blue);
const compressed0 = red * LEFT_SHIFT162 + green * LEFT_SHIFT82 + blue;
red = Color_default.floatToByte(outlineColor.red);
green = Color_default.floatToByte(outlineColor.green);
blue = Color_default.floatToByte(outlineColor.blue);
const compressed1 = red * LEFT_SHIFT162 + green * LEFT_SHIFT82 + blue;
red = Color_default.floatToByte(pickColor.red);
green = Color_default.floatToByte(pickColor.green);
blue = Color_default.floatToByte(pickColor.blue);
const compressed2 = red * LEFT_SHIFT162 + green * LEFT_SHIFT82 + blue;
const compressed3 = Color_default.floatToByte(color.alpha) * LEFT_SHIFT162 + Color_default.floatToByte(outlineColor.alpha) * LEFT_SHIFT82 + Color_default.floatToByte(pickColor.alpha);
const writer = vafWriters[attributeLocations5.compressedAttribute0];
writer(i, compressed0, compressed1, compressed2, compressed3);
}
function writeCompressedAttrib12(pointPrimitiveCollection, context, vafWriters, pointPrimitive) {
const i = pointPrimitive._index;
let near = 0;
let nearValue = 1;
let far = 1;
let farValue = 1;
const translucency = pointPrimitive.translucencyByDistance;
if (defined_default(translucency)) {
near = translucency.near;
nearValue = translucency.nearValue;
far = translucency.far;
farValue = translucency.farValue;
if (nearValue !== 1 || farValue !== 1) {
pointPrimitiveCollection._shaderTranslucencyByDistance = true;
}
}
let show = pointPrimitive.show && pointPrimitive.clusterShow;
if (pointPrimitive.color.alpha === 0 && pointPrimitive.outlineColor.alpha === 0) {
show = false;
}
nearValue = Math_default.clamp(nearValue, 0, 1);
nearValue = nearValue === 1 ? 255 : nearValue * 255 | 0;
const compressed0 = (show ? 1 : 0) * LEFT_SHIFT82 + nearValue;
farValue = Math_default.clamp(farValue, 0, 1);
farValue = farValue === 1 ? 255 : farValue * 255 | 0;
const compressed1 = farValue;
const writer = vafWriters[attributeLocations5.compressedAttribute1];
writer(i, compressed0, compressed1, near, far);
}
function writeScaleByDistance2(pointPrimitiveCollection, context, vafWriters, pointPrimitive) {
const i = pointPrimitive._index;
const writer = vafWriters[attributeLocations5.scaleByDistance];
let near = 0;
let nearValue = 1;
let far = 1;
let farValue = 1;
const scale = pointPrimitive.scaleByDistance;
if (defined_default(scale)) {
near = scale.near;
nearValue = scale.nearValue;
far = scale.far;
farValue = scale.farValue;
if (nearValue !== 1 || farValue !== 1) {
pointPrimitiveCollection._shaderScaleByDistance = true;
}
}
writer(i, near, nearValue, far, farValue);
}
function writeDistanceDisplayConditionAndDepthDisable(pointPrimitiveCollection, context, vafWriters, pointPrimitive) {
const i = pointPrimitive._index;
const writer = vafWriters[attributeLocations5.distanceDisplayConditionAndDisableDepth];
let near = 0;
let far = Number.MAX_VALUE;
const distanceDisplayCondition = pointPrimitive.distanceDisplayCondition;
if (defined_default(distanceDisplayCondition)) {
near = distanceDisplayCondition.near;
far = distanceDisplayCondition.far;
near *= near;
far *= far;
pointPrimitiveCollection._shaderDistanceDisplayCondition = true;
}
let disableDepthTestDistance = pointPrimitive.disableDepthTestDistance;
disableDepthTestDistance *= disableDepthTestDistance;
if (disableDepthTestDistance > 0) {
pointPrimitiveCollection._shaderDisableDepthDistance = true;
if (disableDepthTestDistance === Number.POSITIVE_INFINITY) {
disableDepthTestDistance = -1;
}
}
writer(i, near, far, disableDepthTestDistance);
}
function writePointPrimitive(pointPrimitiveCollection, context, vafWriters, pointPrimitive) {
writePositionSizeAndOutline(
pointPrimitiveCollection,
context,
vafWriters,
pointPrimitive
);
writeCompressedAttrib02(
pointPrimitiveCollection,
context,
vafWriters,
pointPrimitive
);
writeCompressedAttrib12(
pointPrimitiveCollection,
context,
vafWriters,
pointPrimitive
);
writeScaleByDistance2(
pointPrimitiveCollection,
context,
vafWriters,
pointPrimitive
);
writeDistanceDisplayConditionAndDepthDisable(
pointPrimitiveCollection,
context,
vafWriters,
pointPrimitive
);
}
function recomputeActualPositions2(pointPrimitiveCollection, pointPrimitives, length3, frameState, modelMatrix, recomputeBoundingVolume) {
let boundingVolume;
if (frameState.mode === SceneMode_default.SCENE3D) {
boundingVolume = pointPrimitiveCollection._baseVolume;
pointPrimitiveCollection._boundingVolumeDirty = true;
} else {
boundingVolume = pointPrimitiveCollection._baseVolume2D;
}
const positions = [];
for (let i = 0; i < length3; ++i) {
const pointPrimitive = pointPrimitives[i];
const position = pointPrimitive.position;
const actualPosition = PointPrimitive_default._computeActualPosition(
position,
frameState,
modelMatrix
);
if (defined_default(actualPosition)) {
pointPrimitive._setActualPosition(actualPosition);
if (recomputeBoundingVolume) {
positions.push(actualPosition);
} else {
BoundingSphere_default.expand(boundingVolume, actualPosition, boundingVolume);
}
}
}
if (recomputeBoundingVolume) {
BoundingSphere_default.fromPoints(positions, boundingVolume);
}
}
function updateMode3(pointPrimitiveCollection, frameState) {
const mode2 = frameState.mode;
const pointPrimitives = pointPrimitiveCollection._pointPrimitives;
const pointPrimitivesToUpdate = pointPrimitiveCollection._pointPrimitivesToUpdate;
const modelMatrix = pointPrimitiveCollection._modelMatrix;
if (pointPrimitiveCollection._createVertexArray || pointPrimitiveCollection._mode !== mode2 || mode2 !== SceneMode_default.SCENE3D && !Matrix4_default.equals(modelMatrix, pointPrimitiveCollection.modelMatrix)) {
pointPrimitiveCollection._mode = mode2;
Matrix4_default.clone(pointPrimitiveCollection.modelMatrix, modelMatrix);
pointPrimitiveCollection._createVertexArray = true;
if (mode2 === SceneMode_default.SCENE3D || mode2 === SceneMode_default.SCENE2D || mode2 === SceneMode_default.COLUMBUS_VIEW) {
recomputeActualPositions2(
pointPrimitiveCollection,
pointPrimitives,
pointPrimitives.length,
frameState,
modelMatrix,
true
);
}
} else if (mode2 === SceneMode_default.MORPHING) {
recomputeActualPositions2(
pointPrimitiveCollection,
pointPrimitives,
pointPrimitives.length,
frameState,
modelMatrix,
true
);
} else if (mode2 === SceneMode_default.SCENE2D || mode2 === SceneMode_default.COLUMBUS_VIEW) {
recomputeActualPositions2(
pointPrimitiveCollection,
pointPrimitivesToUpdate,
pointPrimitiveCollection._pointPrimitivesToUpdateIndex,
frameState,
modelMatrix,
false
);
}
}
function updateBoundingVolume2(collection, frameState, boundingVolume) {
const pixelSize = frameState.camera.getPixelSize(
boundingVolume,
frameState.context.drawingBufferWidth,
frameState.context.drawingBufferHeight
);
const size = pixelSize * collection._maxPixelSize;
boundingVolume.radius += size;
}
var scratchWriterArray2 = [];
PointPrimitiveCollection.prototype.update = function(frameState) {
removePointPrimitives(this);
if (!this.show) {
return;
}
this._maxTotalPointSize = ContextLimits_default.maximumAliasedPointSize;
updateMode3(this, frameState);
const pointPrimitives = this._pointPrimitives;
const pointPrimitivesLength = pointPrimitives.length;
const pointPrimitivesToUpdate = this._pointPrimitivesToUpdate;
const pointPrimitivesToUpdateLength = this._pointPrimitivesToUpdateIndex;
const properties = this._propertiesChanged;
const createVertexArray7 = this._createVertexArray;
let vafWriters;
const context = frameState.context;
const pass = frameState.passes;
const picking = pass.pick;
if (createVertexArray7 || !picking && this.computeNewBuffersUsage()) {
this._createVertexArray = false;
for (let k = 0; k < NUMBER_OF_PROPERTIES4; ++k) {
properties[k] = 0;
}
this._vaf = this._vaf && this._vaf.destroy();
if (pointPrimitivesLength > 0) {
this._vaf = createVAF2(context, pointPrimitivesLength, this._buffersUsage);
vafWriters = this._vaf.writers;
for (let i = 0; i < pointPrimitivesLength; ++i) {
const pointPrimitive = this._pointPrimitives[i];
pointPrimitive._dirty = false;
writePointPrimitive(this, context, vafWriters, pointPrimitive);
}
this._vaf.commit();
}
this._pointPrimitivesToUpdateIndex = 0;
} else if (pointPrimitivesToUpdateLength > 0) {
const writers = scratchWriterArray2;
writers.length = 0;
if (properties[POSITION_INDEX6] || properties[OUTLINE_WIDTH_INDEX2] || properties[PIXEL_SIZE_INDEX2]) {
writers.push(writePositionSizeAndOutline);
}
if (properties[COLOR_INDEX4] || properties[OUTLINE_COLOR_INDEX2]) {
writers.push(writeCompressedAttrib02);
}
if (properties[SHOW_INDEX6] || properties[TRANSLUCENCY_BY_DISTANCE_INDEX4]) {
writers.push(writeCompressedAttrib12);
}
if (properties[SCALE_BY_DISTANCE_INDEX4]) {
writers.push(writeScaleByDistance2);
}
if (properties[DISTANCE_DISPLAY_CONDITION_INDEX3] || properties[DISABLE_DEPTH_DISTANCE_INDEX2]) {
writers.push(writeDistanceDisplayConditionAndDepthDisable);
}
const numWriters = writers.length;
vafWriters = this._vaf.writers;
if (pointPrimitivesToUpdateLength / pointPrimitivesLength > 0.1) {
for (let m = 0; m < pointPrimitivesToUpdateLength; ++m) {
const b = pointPrimitivesToUpdate[m];
b._dirty = false;
for (let n = 0; n < numWriters; ++n) {
writers[n](this, context, vafWriters, b);
}
}
this._vaf.commit();
} else {
for (let h = 0; h < pointPrimitivesToUpdateLength; ++h) {
const bb = pointPrimitivesToUpdate[h];
bb._dirty = false;
for (let o = 0; o < numWriters; ++o) {
writers[o](this, context, vafWriters, bb);
}
this._vaf.subCommit(bb._index, 1);
}
this._vaf.endSubCommits();
}
this._pointPrimitivesToUpdateIndex = 0;
}
if (pointPrimitivesToUpdateLength > pointPrimitivesLength * 1.5) {
pointPrimitivesToUpdate.length = pointPrimitivesLength;
}
if (!defined_default(this._vaf) || !defined_default(this._vaf.va)) {
return;
}
if (this._boundingVolumeDirty) {
this._boundingVolumeDirty = false;
BoundingSphere_default.transform(
this._baseVolume,
this.modelMatrix,
this._baseVolumeWC
);
}
let boundingVolume;
let modelMatrix = Matrix4_default.IDENTITY;
if (frameState.mode === SceneMode_default.SCENE3D) {
modelMatrix = this.modelMatrix;
boundingVolume = BoundingSphere_default.clone(
this._baseVolumeWC,
this._boundingVolume
);
} else {
boundingVolume = BoundingSphere_default.clone(
this._baseVolume2D,
this._boundingVolume
);
}
updateBoundingVolume2(this, frameState, boundingVolume);
const blendOptionChanged = this._blendOption !== this.blendOption;
this._blendOption = this.blendOption;
if (blendOptionChanged) {
if (this._blendOption === BlendOption_default.OPAQUE || this._blendOption === BlendOption_default.OPAQUE_AND_TRANSLUCENT) {
this._rsOpaque = RenderState_default.fromCache({
depthTest: {
enabled: true,
func: WebGLConstants_default.LEQUAL
},
depthMask: true
});
} else {
this._rsOpaque = void 0;
}
if (this._blendOption === BlendOption_default.TRANSLUCENT || this._blendOption === BlendOption_default.OPAQUE_AND_TRANSLUCENT) {
this._rsTranslucent = RenderState_default.fromCache({
depthTest: {
enabled: true,
func: WebGLConstants_default.LEQUAL
},
depthMask: false,
blending: BlendingState_default.ALPHA_BLEND
});
} else {
this._rsTranslucent = void 0;
}
}
this._shaderDisableDepthDistance = this._shaderDisableDepthDistance || frameState.minimumDisableDepthTestDistance !== 0;
let vs;
let fs;
if (blendOptionChanged || this._shaderScaleByDistance && !this._compiledShaderScaleByDistance || this._shaderTranslucencyByDistance && !this._compiledShaderTranslucencyByDistance || this._shaderDistanceDisplayCondition && !this._compiledShaderDistanceDisplayCondition || this._shaderDisableDepthDistance !== this._compiledShaderDisableDepthDistance) {
vs = new ShaderSource_default({
sources: [PointPrimitiveCollectionVS_default]
});
if (this._shaderScaleByDistance) {
vs.defines.push("EYE_DISTANCE_SCALING");
}
if (this._shaderTranslucencyByDistance) {
vs.defines.push("EYE_DISTANCE_TRANSLUCENCY");
}
if (this._shaderDistanceDisplayCondition) {
vs.defines.push("DISTANCE_DISPLAY_CONDITION");
}
if (this._shaderDisableDepthDistance) {
vs.defines.push("DISABLE_DEPTH_DISTANCE");
}
if (this._blendOption === BlendOption_default.OPAQUE_AND_TRANSLUCENT) {
fs = new ShaderSource_default({
defines: ["OPAQUE"],
sources: [PointPrimitiveCollectionFS_default]
});
this._sp = ShaderProgram_default.replaceCache({
context,
shaderProgram: this._sp,
vertexShaderSource: vs,
fragmentShaderSource: fs,
attributeLocations: attributeLocations5
});
fs = new ShaderSource_default({
defines: ["TRANSLUCENT"],
sources: [PointPrimitiveCollectionFS_default]
});
this._spTranslucent = ShaderProgram_default.replaceCache({
context,
shaderProgram: this._spTranslucent,
vertexShaderSource: vs,
fragmentShaderSource: fs,
attributeLocations: attributeLocations5
});
}
if (this._blendOption === BlendOption_default.OPAQUE) {
fs = new ShaderSource_default({
sources: [PointPrimitiveCollectionFS_default]
});
this._sp = ShaderProgram_default.replaceCache({
context,
shaderProgram: this._sp,
vertexShaderSource: vs,
fragmentShaderSource: fs,
attributeLocations: attributeLocations5
});
}
if (this._blendOption === BlendOption_default.TRANSLUCENT) {
fs = new ShaderSource_default({
sources: [PointPrimitiveCollectionFS_default]
});
this._spTranslucent = ShaderProgram_default.replaceCache({
context,
shaderProgram: this._spTranslucent,
vertexShaderSource: vs,
fragmentShaderSource: fs,
attributeLocations: attributeLocations5
});
}
this._compiledShaderScaleByDistance = this._shaderScaleByDistance;
this._compiledShaderTranslucencyByDistance = this._shaderTranslucencyByDistance;
this._compiledShaderDistanceDisplayCondition = this._shaderDistanceDisplayCondition;
this._compiledShaderDisableDepthDistance = this._shaderDisableDepthDistance;
}
let va;
let vaLength;
let command;
let j;
const commandList = frameState.commandList;
if (pass.render || picking) {
const colorList = this._colorCommands;
const opaque = this._blendOption === BlendOption_default.OPAQUE;
const opaqueAndTranslucent = this._blendOption === BlendOption_default.OPAQUE_AND_TRANSLUCENT;
va = this._vaf.va;
vaLength = va.length;
colorList.length = vaLength;
const totalLength = opaqueAndTranslucent ? vaLength * 2 : vaLength;
for (j = 0; j < totalLength; ++j) {
const opaqueCommand = opaque || opaqueAndTranslucent && j % 2 === 0;
command = colorList[j];
if (!defined_default(command)) {
command = colorList[j] = new DrawCommand_default();
}
command.primitiveType = PrimitiveType_default.POINTS;
command.pass = opaqueCommand || !opaqueAndTranslucent ? Pass_default.OPAQUE : Pass_default.TRANSLUCENT;
command.owner = this;
const index = opaqueAndTranslucent ? Math.floor(j / 2) : j;
command.boundingVolume = boundingVolume;
command.modelMatrix = modelMatrix;
command.shaderProgram = opaqueCommand ? this._sp : this._spTranslucent;
command.uniformMap = this._uniforms;
command.vertexArray = va[index].va;
command.renderState = opaqueCommand ? this._rsOpaque : this._rsTranslucent;
command.debugShowBoundingVolume = this.debugShowBoundingVolume;
command.pickId = "v_pickColor";
commandList.push(command);
}
}
};
PointPrimitiveCollection.prototype.isDestroyed = function() {
return false;
};
PointPrimitiveCollection.prototype.destroy = function() {
this._sp = this._sp && this._sp.destroy();
this._spTranslucent = this._spTranslucent && this._spTranslucent.destroy();
this._spPick = this._spPick && this._spPick.destroy();
this._vaf = this._vaf && this._vaf.destroy();
destroyPointPrimitives(this._pointPrimitives);
return destroyObject_default(this);
};
var PointPrimitiveCollection_default = PointPrimitiveCollection;
// node_modules/kdbush/index.js
var ARRAY_TYPES = [
Int8Array,
Uint8Array,
Uint8ClampedArray,
Int16Array,
Uint16Array,
Int32Array,
Uint32Array,
Float32Array,
Float64Array
];
var VERSION = 1;
var HEADER_SIZE = 8;
var KDBush = class {
/**
* Creates an index from raw `ArrayBuffer` data.
* @param {ArrayBuffer} data
*/
static from(data) {
if (!(data instanceof ArrayBuffer)) {
throw new Error("Data must be an instance of ArrayBuffer.");
}
const [magic, versionAndType] = new Uint8Array(data, 0, 2);
if (magic !== 219) {
throw new Error("Data does not appear to be in a KDBush format.");
}
const version2 = versionAndType >> 4;
if (version2 !== VERSION) {
throw new Error(`Got v${version2} data when expected v${VERSION}.`);
}
const ArrayType = ARRAY_TYPES[versionAndType & 15];
if (!ArrayType) {
throw new Error("Unrecognized array type.");
}
const [nodeSize] = new Uint16Array(data, 2, 1);
const [numItems] = new Uint32Array(data, 4, 1);
return new KDBush(numItems, nodeSize, ArrayType, data);
}
/**
* Creates an index that will hold a given number of items.
* @param {number} numItems
* @param {number} [nodeSize=64] Size of the KD-tree node (64 by default).
* @param {TypedArrayConstructor} [ArrayType=Float64Array] The array type used for coordinates storage (`Float64Array` by default).
* @param {ArrayBuffer} [data] (For internal use only)
*/
constructor(numItems, nodeSize = 64, ArrayType = Float64Array, data) {
if (isNaN(numItems) || numItems < 0)
throw new Error(`Unpexpected numItems value: ${numItems}.`);
this.numItems = +numItems;
this.nodeSize = Math.min(Math.max(+nodeSize, 2), 65535);
this.ArrayType = ArrayType;
this.IndexArrayType = numItems < 65536 ? Uint16Array : Uint32Array;
const arrayTypeIndex = ARRAY_TYPES.indexOf(this.ArrayType);
const coordsByteSize = numItems * 2 * this.ArrayType.BYTES_PER_ELEMENT;
const idsByteSize = numItems * this.IndexArrayType.BYTES_PER_ELEMENT;
const padCoords = (8 - idsByteSize % 8) % 8;
if (arrayTypeIndex < 0) {
throw new Error(`Unexpected typed array class: ${ArrayType}.`);
}
if (data && data instanceof ArrayBuffer) {
this.data = data;
this.ids = new this.IndexArrayType(this.data, HEADER_SIZE, numItems);
this.coords = new this.ArrayType(this.data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2);
this._pos = numItems * 2;
this._finished = true;
} else {
this.data = new ArrayBuffer(HEADER_SIZE + coordsByteSize + idsByteSize + padCoords);
this.ids = new this.IndexArrayType(this.data, HEADER_SIZE, numItems);
this.coords = new this.ArrayType(this.data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2);
this._pos = 0;
this._finished = false;
new Uint8Array(this.data, 0, 2).set([219, (VERSION << 4) + arrayTypeIndex]);
new Uint16Array(this.data, 2, 1)[0] = nodeSize;
new Uint32Array(this.data, 4, 1)[0] = numItems;
}
}
/**
* Add a point to the index.
* @param {number} x
* @param {number} y
* @returns {number} An incremental index associated with the added item (starting from `0`).
*/
add(x, y) {
const index = this._pos >> 1;
this.ids[index] = index;
this.coords[this._pos++] = x;
this.coords[this._pos++] = y;
return index;
}
/**
* Perform indexing of the added points.
*/
finish() {
const numAdded = this._pos >> 1;
if (numAdded !== this.numItems) {
throw new Error(`Added ${numAdded} items when expected ${this.numItems}.`);
}
sort(this.ids, this.coords, this.nodeSize, 0, this.numItems - 1, 0);
this._finished = true;
return this;
}
/**
* Search the index for items within a given bounding box.
* @param {number} minX
* @param {number} minY
* @param {number} maxX
* @param {number} maxY
* @returns {number[]} An array of indices correponding to the found items.
*/
range(minX, minY, maxX, maxY) {
if (!this._finished)
throw new Error("Data not yet indexed - call index.finish().");
const { ids, coords, nodeSize } = this;
const stack = [0, ids.length - 1, 0];
const result = [];
while (stack.length) {
const axis = stack.pop() || 0;
const right = stack.pop() || 0;
const left = stack.pop() || 0;
if (right - left <= nodeSize) {
for (let i = left; i <= right; i++) {
const x2 = coords[2 * i];
const y2 = coords[2 * i + 1];
if (x2 >= minX && x2 <= maxX && y2 >= minY && y2 <= maxY)
result.push(ids[i]);
}
continue;
}
const m = left + right >> 1;
const x = coords[2 * m];
const y = coords[2 * m + 1];
if (x >= minX && x <= maxX && y >= minY && y <= maxY)
result.push(ids[m]);
if (axis === 0 ? minX <= x : minY <= y) {
stack.push(left);
stack.push(m - 1);
stack.push(1 - axis);
}
if (axis === 0 ? maxX >= x : maxY >= y) {
stack.push(m + 1);
stack.push(right);
stack.push(1 - axis);
}
}
return result;
}
/**
* Search the index for items within a given radius.
* @param {number} qx
* @param {number} qy
* @param {number} r Query radius.
* @returns {number[]} An array of indices correponding to the found items.
*/
within(qx, qy, r) {
if (!this._finished)
throw new Error("Data not yet indexed - call index.finish().");
const { ids, coords, nodeSize } = this;
const stack = [0, ids.length - 1, 0];
const result = [];
const r2 = r * r;
while (stack.length) {
const axis = stack.pop() || 0;
const right = stack.pop() || 0;
const left = stack.pop() || 0;
if (right - left <= nodeSize) {
for (let i = left; i <= right; i++) {
if (sqDist(coords[2 * i], coords[2 * i + 1], qx, qy) <= r2)
result.push(ids[i]);
}
continue;
}
const m = left + right >> 1;
const x = coords[2 * m];
const y = coords[2 * m + 1];
if (sqDist(x, y, qx, qy) <= r2)
result.push(ids[m]);
if (axis === 0 ? qx - r <= x : qy - r <= y) {
stack.push(left);
stack.push(m - 1);
stack.push(1 - axis);
}
if (axis === 0 ? qx + r >= x : qy + r >= y) {
stack.push(m + 1);
stack.push(right);
stack.push(1 - axis);
}
}
return result;
}
};
function sort(ids, coords, nodeSize, left, right, axis) {
if (right - left <= nodeSize)
return;
const m = left + right >> 1;
select(ids, coords, m, left, right, axis);
sort(ids, coords, nodeSize, left, m - 1, 1 - axis);
sort(ids, coords, nodeSize, m + 1, right, 1 - axis);
}
function select(ids, coords, k, left, right, axis) {
while (right > left) {
if (right - left > 600) {
const n = right - left + 1;
const m = k - left + 1;
const z = Math.log(n);
const s = 0.5 * Math.exp(2 * z / 3);
const sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
const newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
const newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
select(ids, coords, k, newLeft, newRight, axis);
}
const t = coords[2 * k + axis];
let i = left;
let j = right;
swapItem(ids, coords, left, k);
if (coords[2 * right + axis] > t)
swapItem(ids, coords, left, right);
while (i < j) {
swapItem(ids, coords, i, j);
i++;
j--;
while (coords[2 * i + axis] < t)
i++;
while (coords[2 * j + axis] > t)
j--;
}
if (coords[2 * left + axis] === t)
swapItem(ids, coords, left, j);
else {
j++;
swapItem(ids, coords, j, right);
}
if (j <= k)
left = j + 1;
if (k <= j)
right = j - 1;
}
}
function swapItem(ids, coords, i, j) {
swap2(ids, i, j);
swap2(coords, 2 * i, 2 * j);
swap2(coords, 2 * i + 1, 2 * j + 1);
}
function swap2(arr, i, j) {
const tmp2 = arr[i];
arr[i] = arr[j];
arr[j] = tmp2;
}
function sqDist(ax, ay, bx, by) {
const dx = ax - bx;
const dy = ay - by;
return dx * dx + dy * dy;
}
// packages/engine/Source/DataSources/EntityCluster.js
function EntityCluster(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this._enabled = defaultValue_default(options.enabled, false);
this._pixelRange = defaultValue_default(options.pixelRange, 80);
this._minimumClusterSize = defaultValue_default(options.minimumClusterSize, 2);
this._clusterBillboards = defaultValue_default(options.clusterBillboards, true);
this._clusterLabels = defaultValue_default(options.clusterLabels, true);
this._clusterPoints = defaultValue_default(options.clusterPoints, true);
this._labelCollection = void 0;
this._billboardCollection = void 0;
this._pointCollection = void 0;
this._clusterBillboardCollection = void 0;
this._clusterLabelCollection = void 0;
this._clusterPointCollection = void 0;
this._collectionIndicesByEntity = {};
this._unusedLabelIndices = [];
this._unusedBillboardIndices = [];
this._unusedPointIndices = [];
this._previousClusters = [];
this._previousHeight = void 0;
this._enabledDirty = false;
this._clusterDirty = false;
this._cluster = void 0;
this._removeEventListener = void 0;
this._clusterEvent = new Event_default();
this.show = defaultValue_default(options.show, true);
}
function expandBoundingBox(bbox, pixelRange) {
bbox.x -= pixelRange;
bbox.y -= pixelRange;
bbox.width += pixelRange * 2;
bbox.height += pixelRange * 2;
}
var labelBoundingBoxScratch = new BoundingRectangle_default();
function getBoundingBox(item, coord, pixelRange, entityCluster, result) {
if (defined_default(item._labelCollection) && entityCluster._clusterLabels) {
result = Label_default.getScreenSpaceBoundingBox(item, coord, result);
} else if (defined_default(item._billboardCollection) && entityCluster._clusterBillboards) {
result = Billboard_default.getScreenSpaceBoundingBox(item, coord, result);
} else if (defined_default(item._pointPrimitiveCollection) && entityCluster._clusterPoints) {
result = PointPrimitive_default.getScreenSpaceBoundingBox(item, coord, result);
}
expandBoundingBox(result, pixelRange);
if (entityCluster._clusterLabels && !defined_default(item._labelCollection) && defined_default(item.id) && hasLabelIndex(entityCluster, item.id.id) && defined_default(item.id._label)) {
const labelIndex = entityCluster._collectionIndicesByEntity[item.id.id].labelIndex;
const label = entityCluster._labelCollection.get(labelIndex);
const labelBBox = Label_default.getScreenSpaceBoundingBox(
label,
coord,
labelBoundingBoxScratch
);
expandBoundingBox(labelBBox, pixelRange);
result = BoundingRectangle_default.union(result, labelBBox, result);
}
return result;
}
function addNonClusteredItem(item, entityCluster) {
item.clusterShow = true;
if (!defined_default(item._labelCollection) && defined_default(item.id) && hasLabelIndex(entityCluster, item.id.id) && defined_default(item.id._label)) {
const labelIndex = entityCluster._collectionIndicesByEntity[item.id.id].labelIndex;
const label = entityCluster._labelCollection.get(labelIndex);
label.clusterShow = true;
}
}
function addCluster(position, numPoints, ids, entityCluster) {
const cluster = {
billboard: entityCluster._clusterBillboardCollection.add(),
label: entityCluster._clusterLabelCollection.add(),
point: entityCluster._clusterPointCollection.add()
};
cluster.billboard.show = false;
cluster.point.show = false;
cluster.label.show = true;
cluster.label.text = numPoints.toLocaleString();
cluster.label.id = ids;
cluster.billboard.position = cluster.label.position = cluster.point.position = position;
entityCluster._clusterEvent.raiseEvent(ids, cluster);
}
function hasLabelIndex(entityCluster, entityId) {
return defined_default(entityCluster) && defined_default(entityCluster._collectionIndicesByEntity[entityId]) && defined_default(entityCluster._collectionIndicesByEntity[entityId].labelIndex);
}
function getScreenSpacePositions(collection, points, scene, occluder, entityCluster) {
if (!defined_default(collection)) {
return;
}
const length3 = collection.length;
for (let i = 0; i < length3; ++i) {
const item = collection.get(i);
item.clusterShow = false;
if (!item.show || entityCluster._scene.mode === SceneMode_default.SCENE3D && !occluder.isPointVisible(item.position)) {
continue;
}
const canClusterLabels = entityCluster._clusterLabels && defined_default(item._labelCollection);
const canClusterBillboards = entityCluster._clusterBillboards && defined_default(item.id._billboard);
const canClusterPoints = entityCluster._clusterPoints && defined_default(item.id._point);
if (canClusterLabels && (canClusterPoints || canClusterBillboards)) {
continue;
}
const coord = item.computeScreenSpacePosition(scene);
if (!defined_default(coord)) {
continue;
}
points.push({
index: i,
collection,
clustered: false,
coord
});
}
}
var pointBoundinRectangleScratch = new BoundingRectangle_default();
var totalBoundingRectangleScratch = new BoundingRectangle_default();
var neighborBoundingRectangleScratch = new BoundingRectangle_default();
function createDeclutterCallback(entityCluster) {
return function(amount) {
if (defined_default(amount) && amount < 0.05 || !entityCluster.enabled) {
return;
}
const scene = entityCluster._scene;
const labelCollection = entityCluster._labelCollection;
const billboardCollection = entityCluster._billboardCollection;
const pointCollection = entityCluster._pointCollection;
if (!defined_default(labelCollection) && !defined_default(billboardCollection) && !defined_default(pointCollection) || !entityCluster._clusterBillboards && !entityCluster._clusterLabels && !entityCluster._clusterPoints) {
return;
}
let clusteredLabelCollection = entityCluster._clusterLabelCollection;
let clusteredBillboardCollection = entityCluster._clusterBillboardCollection;
let clusteredPointCollection = entityCluster._clusterPointCollection;
if (defined_default(clusteredLabelCollection)) {
clusteredLabelCollection.removeAll();
} else {
clusteredLabelCollection = entityCluster._clusterLabelCollection = new LabelCollection_default(
{
scene
}
);
}
if (defined_default(clusteredBillboardCollection)) {
clusteredBillboardCollection.removeAll();
} else {
clusteredBillboardCollection = entityCluster._clusterBillboardCollection = new BillboardCollection_default(
{
scene
}
);
}
if (defined_default(clusteredPointCollection)) {
clusteredPointCollection.removeAll();
} else {
clusteredPointCollection = entityCluster._clusterPointCollection = new PointPrimitiveCollection_default();
}
const pixelRange = entityCluster._pixelRange;
const minimumClusterSize = entityCluster._minimumClusterSize;
const clusters = entityCluster._previousClusters;
const newClusters = [];
const previousHeight = entityCluster._previousHeight;
const currentHeight = scene.camera.positionCartographic.height;
const ellipsoid = scene.mapProjection.ellipsoid;
const cameraPosition = scene.camera.positionWC;
const occluder = new EllipsoidalOccluder_default(ellipsoid, cameraPosition);
const points = [];
if (entityCluster._clusterLabels) {
getScreenSpacePositions(
labelCollection,
points,
scene,
occluder,
entityCluster
);
}
if (entityCluster._clusterBillboards) {
getScreenSpacePositions(
billboardCollection,
points,
scene,
occluder,
entityCluster
);
}
if (entityCluster._clusterPoints) {
getScreenSpacePositions(
pointCollection,
points,
scene,
occluder,
entityCluster
);
}
let i;
let j;
let length3;
let bbox;
let neighbors;
let neighborLength;
let neighborIndex;
let neighborPoint;
let ids;
let numPoints;
let collection;
let collectionIndex;
if (points.length > 0) {
const index = new KDBush(points.length, 64, Uint32Array);
for (let p = 0; p < points.length; ++p) {
index.add(points[p].coord.x, points[p].coord.y);
}
index.finish();
if (currentHeight < previousHeight) {
length3 = clusters.length;
for (i = 0; i < length3; ++i) {
const cluster = clusters[i];
if (!occluder.isPointVisible(cluster.position)) {
continue;
}
const coord = Billboard_default._computeScreenSpacePosition(
Matrix4_default.IDENTITY,
cluster.position,
Cartesian3_default.ZERO,
Cartesian2_default.ZERO,
scene
);
if (!defined_default(coord)) {
continue;
}
const factor2 = 1 - currentHeight / previousHeight;
let width = cluster.width = cluster.width * factor2;
let height = cluster.height = cluster.height * factor2;
width = Math.max(width, cluster.minimumWidth);
height = Math.max(height, cluster.minimumHeight);
const minX = coord.x - width * 0.5;
const minY = coord.y - height * 0.5;
const maxX = coord.x + width;
const maxY = coord.y + height;
neighbors = index.range(minX, minY, maxX, maxY);
neighborLength = neighbors.length;
numPoints = 0;
ids = [];
for (j = 0; j < neighborLength; ++j) {
neighborIndex = neighbors[j];
neighborPoint = points[neighborIndex];
if (!neighborPoint.clustered) {
++numPoints;
collection = neighborPoint.collection;
collectionIndex = neighborPoint.index;
ids.push(collection.get(collectionIndex).id);
}
}
if (numPoints >= minimumClusterSize) {
addCluster(cluster.position, numPoints, ids, entityCluster);
newClusters.push(cluster);
for (j = 0; j < neighborLength; ++j) {
points[neighbors[j]].clustered = true;
}
}
}
}
length3 = points.length;
for (i = 0; i < length3; ++i) {
const point = points[i];
if (point.clustered) {
continue;
}
point.clustered = true;
collection = point.collection;
collectionIndex = point.index;
const item = collection.get(collectionIndex);
bbox = getBoundingBox(
item,
point.coord,
pixelRange,
entityCluster,
pointBoundinRectangleScratch
);
const totalBBox = BoundingRectangle_default.clone(
bbox,
totalBoundingRectangleScratch
);
neighbors = index.range(
bbox.x,
bbox.y,
bbox.x + bbox.width,
bbox.y + bbox.height
);
neighborLength = neighbors.length;
const clusterPosition = Cartesian3_default.clone(item.position);
numPoints = 1;
ids = [item.id];
for (j = 0; j < neighborLength; ++j) {
neighborIndex = neighbors[j];
neighborPoint = points[neighborIndex];
if (!neighborPoint.clustered) {
const neighborItem = neighborPoint.collection.get(
neighborPoint.index
);
const neighborBBox = getBoundingBox(
neighborItem,
neighborPoint.coord,
pixelRange,
entityCluster,
neighborBoundingRectangleScratch
);
Cartesian3_default.add(
neighborItem.position,
clusterPosition,
clusterPosition
);
BoundingRectangle_default.union(totalBBox, neighborBBox, totalBBox);
++numPoints;
ids.push(neighborItem.id);
}
}
if (numPoints >= minimumClusterSize) {
const position = Cartesian3_default.multiplyByScalar(
clusterPosition,
1 / numPoints,
clusterPosition
);
addCluster(position, numPoints, ids, entityCluster);
newClusters.push({
position,
width: totalBBox.width,
height: totalBBox.height,
minimumWidth: bbox.width,
minimumHeight: bbox.height
});
for (j = 0; j < neighborLength; ++j) {
points[neighbors[j]].clustered = true;
}
} else {
addNonClusteredItem(item, entityCluster);
}
}
}
if (clusteredLabelCollection.length === 0) {
clusteredLabelCollection.destroy();
entityCluster._clusterLabelCollection = void 0;
}
if (clusteredBillboardCollection.length === 0) {
clusteredBillboardCollection.destroy();
entityCluster._clusterBillboardCollection = void 0;
}
if (clusteredPointCollection.length === 0) {
clusteredPointCollection.destroy();
entityCluster._clusterPointCollection = void 0;
}
entityCluster._previousClusters = newClusters;
entityCluster._previousHeight = currentHeight;
};
}
EntityCluster.prototype._initialize = function(scene) {
this._scene = scene;
const cluster = createDeclutterCallback(this);
this._cluster = cluster;
this._removeEventListener = scene.camera.changed.addEventListener(cluster);
};
Object.defineProperties(EntityCluster.prototype, {
/**
* Gets or sets whether clustering is enabled.
* @memberof EntityCluster.prototype
* @type {boolean}
*/
enabled: {
get: function() {
return this._enabled;
},
set: function(value) {
this._enabledDirty = value !== this._enabled;
this._enabled = value;
}
},
/**
* Gets or sets the pixel range to extend the screen space bounding box.
* @memberof EntityCluster.prototype
* @type {number}
*/
pixelRange: {
get: function() {
return this._pixelRange;
},
set: function(value) {
this._clusterDirty = this._clusterDirty || value !== this._pixelRange;
this._pixelRange = value;
}
},
/**
* Gets or sets the minimum number of screen space objects that can be clustered.
* @memberof EntityCluster.prototype
* @type {number}
*/
minimumClusterSize: {
get: function() {
return this._minimumClusterSize;
},
set: function(value) {
this._clusterDirty = this._clusterDirty || value !== this._minimumClusterSize;
this._minimumClusterSize = value;
}
},
/**
* Gets the event that will be raised when a new cluster will be displayed. The signature of the event listener is {@link EntityCluster.newClusterCallback}.
* @memberof EntityCluster.prototype
* @type {EventsetInterpolationOptions
to set this.
* @memberof SampledPositionProperty.prototype
*
* @type {number}
* @default 1
* @readonly
*/
interpolationDegree: {
get: function() {
return this._property.interpolationDegree;
}
},
/**
* Gets the interpolation algorithm to use when retrieving a value. Call setInterpolationOptions
to set this.
* @memberof SampledPositionProperty.prototype
*
* @type {InterpolationAlgorithm}
* @default LinearApproximation
* @readonly
*/
interpolationAlgorithm: {
get: function() {
return this._property.interpolationAlgorithm;
}
},
/**
* The number of derivatives contained by this property; i.e. 0 for just position, 1 for velocity, etc.
* @memberof SampledPositionProperty.prototype
*
* @type {number}
* @default 0
*/
numberOfDerivatives: {
get: function() {
return this._numberOfDerivatives;
}
},
/**
* Gets or sets the type of extrapolation to perform when a value
* is requested at a time after any available samples.
* @memberof SampledPositionProperty.prototype
* @type {ExtrapolationType}
* @default ExtrapolationType.NONE
*/
forwardExtrapolationType: {
get: function() {
return this._property.forwardExtrapolationType;
},
set: function(value) {
this._property.forwardExtrapolationType = value;
}
},
/**
* Gets or sets the amount of time to extrapolate forward before
* the property becomes undefined. A value of 0 will extrapolate forever.
* @memberof SampledPositionProperty.prototype
* @type {number}
* @default 0
*/
forwardExtrapolationDuration: {
get: function() {
return this._property.forwardExtrapolationDuration;
},
set: function(value) {
this._property.forwardExtrapolationDuration = value;
}
},
/**
* Gets or sets the type of extrapolation to perform when a value
* is requested at a time before any available samples.
* @memberof SampledPositionProperty.prototype
* @type {ExtrapolationType}
* @default ExtrapolationType.NONE
*/
backwardExtrapolationType: {
get: function() {
return this._property.backwardExtrapolationType;
},
set: function(value) {
this._property.backwardExtrapolationType = value;
}
},
/**
* Gets or sets the amount of time to extrapolate backward
* before the property becomes undefined. A value of 0 will extrapolate forever.
* @memberof SampledPositionProperty.prototype
* @type {number}
* @default 0
*/
backwardExtrapolationDuration: {
get: function() {
return this._property.backwardExtrapolationDuration;
},
set: function(value) {
this._property.backwardExtrapolationDuration = value;
}
}
});
SampledPositionProperty.prototype.getValue = function(time, result) {
return this.getValueInReferenceFrame(time, ReferenceFrame_default.FIXED, result);
};
SampledPositionProperty.prototype.getValueInReferenceFrame = function(time, referenceFrame, result) {
Check_default.defined("time", time);
Check_default.defined("referenceFrame", referenceFrame);
result = this._property.getValue(time, result);
if (defined_default(result)) {
return PositionProperty_default.convertToReferenceFrame(
time,
result,
this._referenceFrame,
referenceFrame,
result
);
}
return void 0;
};
SampledPositionProperty.prototype.setInterpolationOptions = function(options) {
this._property.setInterpolationOptions(options);
};
SampledPositionProperty.prototype.addSample = function(time, position, derivatives) {
const numberOfDerivatives = this._numberOfDerivatives;
if (numberOfDerivatives > 0 && (!defined_default(derivatives) || derivatives.length !== numberOfDerivatives)) {
throw new DeveloperError_default(
"derivatives length must be equal to the number of derivatives."
);
}
this._property.addSample(time, position, derivatives);
};
SampledPositionProperty.prototype.addSamples = function(times, positions, derivatives) {
this._property.addSamples(times, positions, derivatives);
};
SampledPositionProperty.prototype.addSamplesPackedArray = function(packedSamples, epoch2) {
this._property.addSamplesPackedArray(packedSamples, epoch2);
};
SampledPositionProperty.prototype.removeSample = function(time) {
return this._property.removeSample(time);
};
SampledPositionProperty.prototype.removeSamples = function(timeInterval) {
this._property.removeSamples(timeInterval);
};
SampledPositionProperty.prototype.equals = function(other) {
return this === other || //
other instanceof SampledPositionProperty && Property_default.equals(this._property, other._property) && //
this._referenceFrame === other._referenceFrame;
};
var SampledPositionProperty_default = SampledPositionProperty;
// packages/engine/Source/DataSources/StripeOrientation.js
var StripeOrientation = {
/**
* Horizontal orientation.
* @type {number}
*/
HORIZONTAL: 0,
/**
* Vertical orientation.
* @type {number}
*/
VERTICAL: 1
};
var StripeOrientation_default = Object.freeze(StripeOrientation);
// packages/engine/Source/DataSources/StripeMaterialProperty.js
var defaultOrientation = StripeOrientation_default.HORIZONTAL;
var defaultEvenColor2 = Color_default.WHITE;
var defaultOddColor2 = Color_default.BLACK;
var defaultOffset4 = 0;
var defaultRepeat3 = 1;
function StripeMaterialProperty(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this._definitionChanged = new Event_default();
this._orientation = void 0;
this._orientationSubscription = void 0;
this._evenColor = void 0;
this._evenColorSubscription = void 0;
this._oddColor = void 0;
this._oddColorSubscription = void 0;
this._offset = void 0;
this._offsetSubscription = void 0;
this._repeat = void 0;
this._repeatSubscription = void 0;
this.orientation = options.orientation;
this.evenColor = options.evenColor;
this.oddColor = options.oddColor;
this.offset = options.offset;
this.repeat = options.repeat;
}
Object.defineProperties(StripeMaterialProperty.prototype, {
/**
* Gets a value indicating if this property is constant. A property is considered
* constant if getValue always returns the same result for the current definition.
* @memberof StripeMaterialProperty.prototype
*
* @type {boolean}
* @readonly
*/
isConstant: {
get: function() {
return Property_default.isConstant(this._orientation) && //
Property_default.isConstant(this._evenColor) && //
Property_default.isConstant(this._oddColor) && //
Property_default.isConstant(this._offset) && //
Property_default.isConstant(this._repeat);
}
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* The definition is considered to have changed if a call to getValue would return
* a different result for the same time.
* @memberof StripeMaterialProperty.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
/**
* Gets or sets the Property specifying the {@link StripeOrientation}/
* @memberof StripeMaterialProperty.prototype
* @type {Property|undefined}
* @default StripeOrientation.HORIZONTAL
*/
orientation: createPropertyDescriptor_default("orientation"),
/**
* Gets or sets the Property specifying the first {@link Color}.
* @memberof StripeMaterialProperty.prototype
* @type {Property|undefined}
* @default Color.WHITE
*/
evenColor: createPropertyDescriptor_default("evenColor"),
/**
* Gets or sets the Property specifying the second {@link Color}.
* @memberof StripeMaterialProperty.prototype
* @type {Property|undefined}
* @default Color.BLACK
*/
oddColor: createPropertyDescriptor_default("oddColor"),
/**
* Gets or sets the numeric Property specifying the point into the pattern
* to begin drawing; with 0.0 being the beginning of the even color, 1.0 the beginning
* of the odd color, 2.0 being the even color again, and any multiple or fractional values
* being in between.
* @memberof StripeMaterialProperty.prototype
* @type {Property|undefined}
* @default 0.0
*/
offset: createPropertyDescriptor_default("offset"),
/**
* Gets or sets the numeric Property specifying how many times the stripes repeat.
* @memberof StripeMaterialProperty.prototype
* @type {Property|undefined}
* @default 1.0
*/
repeat: createPropertyDescriptor_default("repeat")
});
StripeMaterialProperty.prototype.getType = function(time) {
return "Stripe";
};
StripeMaterialProperty.prototype.getValue = function(time, result) {
if (!defined_default(result)) {
result = {};
}
result.horizontal = Property_default.getValueOrDefault(this._orientation, time, defaultOrientation) === StripeOrientation_default.HORIZONTAL;
result.evenColor = Property_default.getValueOrClonedDefault(
this._evenColor,
time,
defaultEvenColor2,
result.evenColor
);
result.oddColor = Property_default.getValueOrClonedDefault(
this._oddColor,
time,
defaultOddColor2,
result.oddColor
);
result.offset = Property_default.getValueOrDefault(this._offset, time, defaultOffset4);
result.repeat = Property_default.getValueOrDefault(this._repeat, time, defaultRepeat3);
return result;
};
StripeMaterialProperty.prototype.equals = function(other) {
return this === other || //
other instanceof StripeMaterialProperty && //
Property_default.equals(this._orientation, other._orientation) && //
Property_default.equals(this._evenColor, other._evenColor) && //
Property_default.equals(this._oddColor, other._oddColor) && //
Property_default.equals(this._offset, other._offset) && //
Property_default.equals(this._repeat, other._repeat);
};
var StripeMaterialProperty_default = StripeMaterialProperty;
// packages/engine/Source/DataSources/TimeIntervalCollectionPositionProperty.js
function TimeIntervalCollectionPositionProperty(referenceFrame) {
this._definitionChanged = new Event_default();
this._intervals = new TimeIntervalCollection_default();
this._intervals.changedEvent.addEventListener(
TimeIntervalCollectionPositionProperty.prototype._intervalsChanged,
this
);
this._referenceFrame = defaultValue_default(referenceFrame, ReferenceFrame_default.FIXED);
}
Object.defineProperties(TimeIntervalCollectionPositionProperty.prototype, {
/**
* Gets a value indicating if this property is constant. A property is considered
* constant if getValue always returns the same result for the current definition.
* @memberof TimeIntervalCollectionPositionProperty.prototype
*
* @type {boolean}
* @readonly
*/
isConstant: {
get: function() {
return this._intervals.isEmpty;
}
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* The definition is considered to have changed if a call to getValue would return
* a different result for the same time.
* @memberof TimeIntervalCollectionPositionProperty.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
/**
* Gets the interval collection.
* @memberof TimeIntervalCollectionPositionProperty.prototype
* @type {TimeIntervalCollection}
* @readonly
*/
intervals: {
get: function() {
return this._intervals;
}
},
/**
* Gets the reference frame in which the position is defined.
* @memberof TimeIntervalCollectionPositionProperty.prototype
* @type {ReferenceFrame}
* @readonly
* @default ReferenceFrame.FIXED;
*/
referenceFrame: {
get: function() {
return this._referenceFrame;
}
}
});
TimeIntervalCollectionPositionProperty.prototype.getValue = function(time, result) {
return this.getValueInReferenceFrame(time, ReferenceFrame_default.FIXED, result);
};
TimeIntervalCollectionPositionProperty.prototype.getValueInReferenceFrame = function(time, referenceFrame, result) {
if (!defined_default(time)) {
throw new DeveloperError_default("time is required.");
}
if (!defined_default(referenceFrame)) {
throw new DeveloperError_default("referenceFrame is required.");
}
const position = this._intervals.findDataForIntervalContainingDate(time);
if (defined_default(position)) {
return PositionProperty_default.convertToReferenceFrame(
time,
position,
this._referenceFrame,
referenceFrame,
result
);
}
return void 0;
};
TimeIntervalCollectionPositionProperty.prototype.equals = function(other) {
return this === other || //
other instanceof TimeIntervalCollectionPositionProperty && //
this._intervals.equals(other._intervals, Property_default.equals) && //
this._referenceFrame === other._referenceFrame;
};
TimeIntervalCollectionPositionProperty.prototype._intervalsChanged = function() {
this._definitionChanged.raiseEvent(this);
};
var TimeIntervalCollectionPositionProperty_default = TimeIntervalCollectionPositionProperty;
// packages/engine/Source/DataSources/TimeIntervalCollectionProperty.js
function TimeIntervalCollectionProperty() {
this._definitionChanged = new Event_default();
this._intervals = new TimeIntervalCollection_default();
this._intervals.changedEvent.addEventListener(
TimeIntervalCollectionProperty.prototype._intervalsChanged,
this
);
}
Object.defineProperties(TimeIntervalCollectionProperty.prototype, {
/**
* Gets a value indicating if this property is constant. A property is considered
* constant if getValue always returns the same result for the current definition.
* @memberof TimeIntervalCollectionProperty.prototype
*
* @type {boolean}
* @readonly
*/
isConstant: {
get: function() {
return this._intervals.isEmpty;
}
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* The definition is changed whenever setValue is called with data different
* than the current value.
* @memberof TimeIntervalCollectionProperty.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
/**
* Gets the interval collection.
* @memberof TimeIntervalCollectionProperty.prototype
*
* @type {TimeIntervalCollection}
* @readonly
*/
intervals: {
get: function() {
return this._intervals;
}
}
});
TimeIntervalCollectionProperty.prototype.getValue = function(time, result) {
if (!defined_default(time)) {
throw new DeveloperError_default("time is required");
}
const value = this._intervals.findDataForIntervalContainingDate(time);
if (defined_default(value) && typeof value.clone === "function") {
return value.clone(result);
}
return value;
};
TimeIntervalCollectionProperty.prototype.equals = function(other) {
return this === other || //
other instanceof TimeIntervalCollectionProperty && //
this._intervals.equals(other._intervals, Property_default.equals);
};
TimeIntervalCollectionProperty.prototype._intervalsChanged = function() {
this._definitionChanged.raiseEvent(this);
};
var TimeIntervalCollectionProperty_default = TimeIntervalCollectionProperty;
// packages/engine/Source/DataSources/VelocityVectorProperty.js
function VelocityVectorProperty(position, normalize2) {
this._position = void 0;
this._subscription = void 0;
this._definitionChanged = new Event_default();
this._normalize = defaultValue_default(normalize2, true);
this.position = position;
}
Object.defineProperties(VelocityVectorProperty.prototype, {
/**
* Gets a value indicating if this property is constant.
* @memberof VelocityVectorProperty.prototype
*
* @type {boolean}
* @readonly
*/
isConstant: {
get: function() {
return Property_default.isConstant(this._position);
}
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* @memberof VelocityVectorProperty.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
/**
* Gets or sets the position property used to compute the velocity vector.
* @memberof VelocityVectorProperty.prototype
*
* @type {Property|undefined}
*/
position: {
get: function() {
return this._position;
},
set: function(value) {
const oldValue2 = this._position;
if (oldValue2 !== value) {
if (defined_default(oldValue2)) {
this._subscription();
}
this._position = value;
if (defined_default(value)) {
this._subscription = value._definitionChanged.addEventListener(
function() {
this._definitionChanged.raiseEvent(this);
},
this
);
}
this._definitionChanged.raiseEvent(this);
}
}
},
/**
* Gets or sets whether the vector produced by this property
* will be normalized or not.
* @memberof VelocityVectorProperty.prototype
*
* @type {boolean}
*/
normalize: {
get: function() {
return this._normalize;
},
set: function(value) {
if (this._normalize === value) {
return;
}
this._normalize = value;
this._definitionChanged.raiseEvent(this);
}
}
});
var position1Scratch = new Cartesian3_default();
var position2Scratch = new Cartesian3_default();
var timeScratch = new JulianDate_default();
var step = 1 / 60;
VelocityVectorProperty.prototype.getValue = function(time, result) {
return this._getValue(time, result);
};
VelocityVectorProperty.prototype._getValue = function(time, velocityResult, positionResult) {
if (!defined_default(time)) {
throw new DeveloperError_default("time is required");
}
if (!defined_default(velocityResult)) {
velocityResult = new Cartesian3_default();
}
const property = this._position;
if (Property_default.isConstant(property)) {
return this._normalize ? void 0 : Cartesian3_default.clone(Cartesian3_default.ZERO, velocityResult);
}
let position1 = property.getValue(time, position1Scratch);
let position2 = property.getValue(
JulianDate_default.addSeconds(time, step, timeScratch),
position2Scratch
);
if (!defined_default(position1)) {
return void 0;
}
if (!defined_default(position2)) {
position2 = position1;
position1 = property.getValue(
JulianDate_default.addSeconds(time, -step, timeScratch),
position2Scratch
);
if (!defined_default(position1)) {
return void 0;
}
}
if (Cartesian3_default.equals(position1, position2)) {
return this._normalize ? void 0 : Cartesian3_default.clone(Cartesian3_default.ZERO, velocityResult);
}
if (defined_default(positionResult)) {
position1.clone(positionResult);
}
const velocity = Cartesian3_default.subtract(position2, position1, velocityResult);
if (this._normalize) {
return Cartesian3_default.normalize(velocity, velocityResult);
}
return Cartesian3_default.divideByScalar(velocity, step, velocityResult);
};
VelocityVectorProperty.prototype.equals = function(other) {
return this === other || //
other instanceof VelocityVectorProperty && Property_default.equals(this._position, other._position);
};
var VelocityVectorProperty_default = VelocityVectorProperty;
// packages/engine/Source/DataSources/VelocityOrientationProperty.js
function VelocityOrientationProperty(position, ellipsoid) {
this._velocityVectorProperty = new VelocityVectorProperty_default(position, true);
this._subscription = void 0;
this._ellipsoid = void 0;
this._definitionChanged = new Event_default();
this.ellipsoid = defaultValue_default(ellipsoid, Ellipsoid_default.WGS84);
const that = this;
this._velocityVectorProperty.definitionChanged.addEventListener(function() {
that._definitionChanged.raiseEvent(that);
});
}
Object.defineProperties(VelocityOrientationProperty.prototype, {
/**
* Gets a value indicating if this property is constant.
* @memberof VelocityOrientationProperty.prototype
*
* @type {boolean}
* @readonly
*/
isConstant: {
get: function() {
return Property_default.isConstant(this._velocityVectorProperty);
}
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* @memberof VelocityOrientationProperty.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
/**
* Gets or sets the position property used to compute orientation.
* @memberof VelocityOrientationProperty.prototype
*
* @type {Property|undefined}
*/
position: {
get: function() {
return this._velocityVectorProperty.position;
},
set: function(value) {
this._velocityVectorProperty.position = value;
}
},
/**
* Gets or sets the ellipsoid used to determine which way is up.
* @memberof VelocityOrientationProperty.prototype
*
* @type {Property|undefined}
*/
ellipsoid: {
get: function() {
return this._ellipsoid;
},
set: function(value) {
const oldValue2 = this._ellipsoid;
if (oldValue2 !== value) {
this._ellipsoid = value;
this._definitionChanged.raiseEvent(this);
}
}
}
});
var positionScratch10 = new Cartesian3_default();
var velocityScratch = new Cartesian3_default();
var rotationScratch2 = new Matrix3_default();
VelocityOrientationProperty.prototype.getValue = function(time, result) {
const velocity = this._velocityVectorProperty._getValue(
time,
velocityScratch,
positionScratch10
);
if (!defined_default(velocity)) {
return void 0;
}
Transforms_default.rotationMatrixFromPositionVelocity(
positionScratch10,
velocity,
this._ellipsoid,
rotationScratch2
);
return Quaternion_default.fromRotationMatrix(rotationScratch2, result);
};
VelocityOrientationProperty.prototype.equals = function(other) {
return this === other || //
other instanceof VelocityOrientationProperty && Property_default.equals(
this._velocityVectorProperty,
other._velocityVectorProperty
) && (this._ellipsoid === other._ellipsoid || this._ellipsoid.equals(other._ellipsoid));
};
var VelocityOrientationProperty_default = VelocityOrientationProperty;
// packages/engine/Source/DataSources/CzmlDataSource.js
function UnitCartesian3() {
}
UnitCartesian3.packedLength = Cartesian3_default.packedLength;
UnitCartesian3.unpack = Cartesian3_default.unpack;
UnitCartesian3.pack = Cartesian3_default.pack;
var currentId;
function createReferenceProperty(entityCollection, referenceString) {
if (referenceString[0] === "#") {
referenceString = currentId + referenceString;
}
return ReferenceProperty_default.fromString(entityCollection, referenceString);
}
function createSpecializedProperty(type, entityCollection, packetData) {
if (defined_default(packetData.reference)) {
return createReferenceProperty(entityCollection, packetData.reference);
}
if (defined_default(packetData.velocityReference)) {
const referenceProperty = createReferenceProperty(
entityCollection,
packetData.velocityReference
);
switch (type) {
case Cartesian3_default:
case UnitCartesian3:
return new VelocityVectorProperty_default(
referenceProperty,
type === UnitCartesian3
);
case Quaternion_default:
return new VelocityOrientationProperty_default(referenceProperty);
}
}
throw new RuntimeError_default(`${JSON.stringify(packetData)} is not valid CZML.`);
}
function createAdapterProperty(property, adapterFunction) {
return new CallbackProperty_default(function(time, result) {
return adapterFunction(property.getValue(time, result));
}, property.isConstant);
}
var scratchCartesian15 = new Cartesian3_default();
var scratchSpherical = new Spherical_default();
var scratchCartographic9 = new Cartographic_default();
var scratchTimeInterval = new TimeInterval_default();
var scratchQuaternion = new Quaternion_default();
function unwrapColorInterval(czmlInterval) {
let rgbaf = czmlInterval.rgbaf;
if (defined_default(rgbaf)) {
return rgbaf;
}
const rgba = czmlInterval.rgba;
if (!defined_default(rgba)) {
return void 0;
}
const length3 = rgba.length;
if (length3 === Color_default.packedLength) {
return [
Color_default.byteToFloat(rgba[0]),
Color_default.byteToFloat(rgba[1]),
Color_default.byteToFloat(rgba[2]),
Color_default.byteToFloat(rgba[3])
];
}
rgbaf = new Array(length3);
for (let i = 0; i < length3; i += 5) {
rgbaf[i] = rgba[i];
rgbaf[i + 1] = Color_default.byteToFloat(rgba[i + 1]);
rgbaf[i + 2] = Color_default.byteToFloat(rgba[i + 2]);
rgbaf[i + 3] = Color_default.byteToFloat(rgba[i + 3]);
rgbaf[i + 4] = Color_default.byteToFloat(rgba[i + 4]);
}
return rgbaf;
}
function unwrapUriInterval(czmlInterval, sourceUri) {
const uri = defaultValue_default(czmlInterval.uri, czmlInterval);
if (defined_default(sourceUri)) {
return sourceUri.getDerivedResource({
url: uri
});
}
return Resource_default.createIfNeeded(uri);
}
function unwrapRectangleInterval(czmlInterval) {
let wsen = czmlInterval.wsen;
if (defined_default(wsen)) {
return wsen;
}
const wsenDegrees = czmlInterval.wsenDegrees;
if (!defined_default(wsenDegrees)) {
return void 0;
}
const length3 = wsenDegrees.length;
if (length3 === Rectangle_default.packedLength) {
return [
Math_default.toRadians(wsenDegrees[0]),
Math_default.toRadians(wsenDegrees[1]),
Math_default.toRadians(wsenDegrees[2]),
Math_default.toRadians(wsenDegrees[3])
];
}
wsen = new Array(length3);
for (let i = 0; i < length3; i += 5) {
wsen[i] = wsenDegrees[i];
wsen[i + 1] = Math_default.toRadians(wsenDegrees[i + 1]);
wsen[i + 2] = Math_default.toRadians(wsenDegrees[i + 2]);
wsen[i + 3] = Math_default.toRadians(wsenDegrees[i + 3]);
wsen[i + 4] = Math_default.toRadians(wsenDegrees[i + 4]);
}
return wsen;
}
function convertUnitSphericalToCartesian(unitSpherical) {
const length3 = unitSpherical.length;
scratchSpherical.magnitude = 1;
if (length3 === 2) {
scratchSpherical.clock = unitSpherical[0];
scratchSpherical.cone = unitSpherical[1];
Cartesian3_default.fromSpherical(scratchSpherical, scratchCartesian15);
return [scratchCartesian15.x, scratchCartesian15.y, scratchCartesian15.z];
}
const result = new Array(length3 / 3 * 4);
for (let i = 0, j = 0; i < length3; i += 3, j += 4) {
result[j] = unitSpherical[i];
scratchSpherical.clock = unitSpherical[i + 1];
scratchSpherical.cone = unitSpherical[i + 2];
Cartesian3_default.fromSpherical(scratchSpherical, scratchCartesian15);
result[j + 1] = scratchCartesian15.x;
result[j + 2] = scratchCartesian15.y;
result[j + 3] = scratchCartesian15.z;
}
return result;
}
function convertSphericalToCartesian(spherical) {
const length3 = spherical.length;
if (length3 === 3) {
scratchSpherical.clock = spherical[0];
scratchSpherical.cone = spherical[1];
scratchSpherical.magnitude = spherical[2];
Cartesian3_default.fromSpherical(scratchSpherical, scratchCartesian15);
return [scratchCartesian15.x, scratchCartesian15.y, scratchCartesian15.z];
}
const result = new Array(length3);
for (let i = 0; i < length3; i += 4) {
result[i] = spherical[i];
scratchSpherical.clock = spherical[i + 1];
scratchSpherical.cone = spherical[i + 2];
scratchSpherical.magnitude = spherical[i + 3];
Cartesian3_default.fromSpherical(scratchSpherical, scratchCartesian15);
result[i + 1] = scratchCartesian15.x;
result[i + 2] = scratchCartesian15.y;
result[i + 3] = scratchCartesian15.z;
}
return result;
}
function convertCartographicRadiansToCartesian(cartographicRadians) {
const length3 = cartographicRadians.length;
if (length3 === 3) {
scratchCartographic9.longitude = cartographicRadians[0];
scratchCartographic9.latitude = cartographicRadians[1];
scratchCartographic9.height = cartographicRadians[2];
Ellipsoid_default.WGS84.cartographicToCartesian(
scratchCartographic9,
scratchCartesian15
);
return [scratchCartesian15.x, scratchCartesian15.y, scratchCartesian15.z];
}
const result = new Array(length3);
for (let i = 0; i < length3; i += 4) {
result[i] = cartographicRadians[i];
scratchCartographic9.longitude = cartographicRadians[i + 1];
scratchCartographic9.latitude = cartographicRadians[i + 2];
scratchCartographic9.height = cartographicRadians[i + 3];
Ellipsoid_default.WGS84.cartographicToCartesian(
scratchCartographic9,
scratchCartesian15
);
result[i + 1] = scratchCartesian15.x;
result[i + 2] = scratchCartesian15.y;
result[i + 3] = scratchCartesian15.z;
}
return result;
}
function convertCartographicDegreesToCartesian(cartographicDegrees) {
const length3 = cartographicDegrees.length;
if (length3 === 3) {
scratchCartographic9.longitude = Math_default.toRadians(
cartographicDegrees[0]
);
scratchCartographic9.latitude = Math_default.toRadians(cartographicDegrees[1]);
scratchCartographic9.height = cartographicDegrees[2];
Ellipsoid_default.WGS84.cartographicToCartesian(
scratchCartographic9,
scratchCartesian15
);
return [scratchCartesian15.x, scratchCartesian15.y, scratchCartesian15.z];
}
const result = new Array(length3);
for (let i = 0; i < length3; i += 4) {
result[i] = cartographicDegrees[i];
scratchCartographic9.longitude = Math_default.toRadians(
cartographicDegrees[i + 1]
);
scratchCartographic9.latitude = Math_default.toRadians(
cartographicDegrees[i + 2]
);
scratchCartographic9.height = cartographicDegrees[i + 3];
Ellipsoid_default.WGS84.cartographicToCartesian(
scratchCartographic9,
scratchCartesian15
);
result[i + 1] = scratchCartesian15.x;
result[i + 2] = scratchCartesian15.y;
result[i + 3] = scratchCartesian15.z;
}
return result;
}
function unwrapCartesianInterval(czmlInterval) {
const cartesian11 = czmlInterval.cartesian;
if (defined_default(cartesian11)) {
return cartesian11;
}
const cartesianVelocity = czmlInterval.cartesianVelocity;
if (defined_default(cartesianVelocity)) {
return cartesianVelocity;
}
const unitCartesian = czmlInterval.unitCartesian;
if (defined_default(unitCartesian)) {
return unitCartesian;
}
const unitSpherical = czmlInterval.unitSpherical;
if (defined_default(unitSpherical)) {
return convertUnitSphericalToCartesian(unitSpherical);
}
const spherical = czmlInterval.spherical;
if (defined_default(spherical)) {
return convertSphericalToCartesian(spherical);
}
const cartographicRadians = czmlInterval.cartographicRadians;
if (defined_default(cartographicRadians)) {
return convertCartographicRadiansToCartesian(cartographicRadians);
}
const cartographicDegrees = czmlInterval.cartographicDegrees;
if (defined_default(cartographicDegrees)) {
return convertCartographicDegreesToCartesian(cartographicDegrees);
}
throw new RuntimeError_default(
`${JSON.stringify(czmlInterval)} is not a valid CZML interval.`
);
}
function normalizePackedCartesianArray(array, startingIndex) {
Cartesian3_default.unpack(array, startingIndex, scratchCartesian15);
Cartesian3_default.normalize(scratchCartesian15, scratchCartesian15);
Cartesian3_default.pack(scratchCartesian15, array, startingIndex);
}
function unwrapUnitCartesianInterval(czmlInterval) {
const cartesian11 = unwrapCartesianInterval(czmlInterval);
if (cartesian11.length === 3) {
normalizePackedCartesianArray(cartesian11, 0);
return cartesian11;
}
for (let i = 1; i < cartesian11.length; i += 4) {
normalizePackedCartesianArray(cartesian11, i);
}
return cartesian11;
}
function normalizePackedQuaternionArray(array, startingIndex) {
Quaternion_default.unpack(array, startingIndex, scratchQuaternion);
Quaternion_default.normalize(scratchQuaternion, scratchQuaternion);
Quaternion_default.pack(scratchQuaternion, array, startingIndex);
}
function unwrapQuaternionInterval(czmlInterval) {
const unitQuaternion = czmlInterval.unitQuaternion;
if (defined_default(unitQuaternion)) {
if (unitQuaternion.length === 4) {
normalizePackedQuaternionArray(unitQuaternion, 0);
return unitQuaternion;
}
for (let i = 1; i < unitQuaternion.length; i += 5) {
normalizePackedQuaternionArray(unitQuaternion, i);
}
}
return unitQuaternion;
}
function getPropertyType(czmlInterval) {
if (typeof czmlInterval === "boolean") {
return Boolean;
} else if (typeof czmlInterval === "number") {
return Number;
} else if (typeof czmlInterval === "string") {
return String;
} else if (czmlInterval.hasOwnProperty("array")) {
return Array;
} else if (czmlInterval.hasOwnProperty("boolean")) {
return Boolean;
} else if (czmlInterval.hasOwnProperty("boundingRectangle")) {
return BoundingRectangle_default;
} else if (czmlInterval.hasOwnProperty("cartesian2")) {
return Cartesian2_default;
} else if (czmlInterval.hasOwnProperty("cartesian") || czmlInterval.hasOwnProperty("spherical") || czmlInterval.hasOwnProperty("cartographicRadians") || czmlInterval.hasOwnProperty("cartographicDegrees")) {
return Cartesian3_default;
} else if (czmlInterval.hasOwnProperty("unitCartesian") || czmlInterval.hasOwnProperty("unitSpherical")) {
return UnitCartesian3;
} else if (czmlInterval.hasOwnProperty("rgba") || czmlInterval.hasOwnProperty("rgbaf")) {
return Color_default;
} else if (czmlInterval.hasOwnProperty("arcType")) {
return ArcType_default;
} else if (czmlInterval.hasOwnProperty("classificationType")) {
return ClassificationType_default;
} else if (czmlInterval.hasOwnProperty("colorBlendMode")) {
return ColorBlendMode_default;
} else if (czmlInterval.hasOwnProperty("cornerType")) {
return CornerType_default;
} else if (czmlInterval.hasOwnProperty("heightReference")) {
return HeightReference_default;
} else if (czmlInterval.hasOwnProperty("horizontalOrigin")) {
return HorizontalOrigin_default;
} else if (czmlInterval.hasOwnProperty("date")) {
return JulianDate_default;
} else if (czmlInterval.hasOwnProperty("labelStyle")) {
return LabelStyle_default;
} else if (czmlInterval.hasOwnProperty("number")) {
return Number;
} else if (czmlInterval.hasOwnProperty("nearFarScalar")) {
return NearFarScalar_default;
} else if (czmlInterval.hasOwnProperty("distanceDisplayCondition")) {
return DistanceDisplayCondition_default;
} else if (czmlInterval.hasOwnProperty("object") || czmlInterval.hasOwnProperty("value")) {
return Object;
} else if (czmlInterval.hasOwnProperty("unitQuaternion")) {
return Quaternion_default;
} else if (czmlInterval.hasOwnProperty("shadowMode")) {
return ShadowMode_default;
} else if (czmlInterval.hasOwnProperty("string")) {
return String;
} else if (czmlInterval.hasOwnProperty("stripeOrientation")) {
return StripeOrientation_default;
} else if (czmlInterval.hasOwnProperty("wsen") || czmlInterval.hasOwnProperty("wsenDegrees")) {
return Rectangle_default;
} else if (czmlInterval.hasOwnProperty("uri")) {
return import_urijs10.default;
} else if (czmlInterval.hasOwnProperty("verticalOrigin")) {
return VerticalOrigin_default;
}
return Object;
}
function unwrapInterval(type, czmlInterval, sourceUri) {
switch (type) {
case ArcType_default:
return ArcType_default[defaultValue_default(czmlInterval.arcType, czmlInterval)];
case Array:
return czmlInterval.array;
case Boolean:
return defaultValue_default(czmlInterval["boolean"], czmlInterval);
case BoundingRectangle_default:
return czmlInterval.boundingRectangle;
case Cartesian2_default:
return czmlInterval.cartesian2;
case Cartesian3_default:
return unwrapCartesianInterval(czmlInterval);
case UnitCartesian3:
return unwrapUnitCartesianInterval(czmlInterval);
case Color_default:
return unwrapColorInterval(czmlInterval);
case ClassificationType_default:
return ClassificationType_default[defaultValue_default(czmlInterval.classificationType, czmlInterval)];
case ColorBlendMode_default:
return ColorBlendMode_default[defaultValue_default(czmlInterval.colorBlendMode, czmlInterval)];
case CornerType_default:
return CornerType_default[defaultValue_default(czmlInterval.cornerType, czmlInterval)];
case HeightReference_default:
return HeightReference_default[defaultValue_default(czmlInterval.heightReference, czmlInterval)];
case HorizontalOrigin_default:
return HorizontalOrigin_default[defaultValue_default(czmlInterval.horizontalOrigin, czmlInterval)];
case Image:
return unwrapUriInterval(czmlInterval, sourceUri);
case JulianDate_default:
return JulianDate_default.fromIso8601(
defaultValue_default(czmlInterval.date, czmlInterval)
);
case LabelStyle_default:
return LabelStyle_default[defaultValue_default(czmlInterval.labelStyle, czmlInterval)];
case Number:
return defaultValue_default(czmlInterval.number, czmlInterval);
case NearFarScalar_default:
return czmlInterval.nearFarScalar;
case DistanceDisplayCondition_default:
return czmlInterval.distanceDisplayCondition;
case Object:
return defaultValue_default(
defaultValue_default(czmlInterval.object, czmlInterval.value),
czmlInterval
);
case Quaternion_default:
return unwrapQuaternionInterval(czmlInterval);
case Rotation_default:
return defaultValue_default(czmlInterval.number, czmlInterval);
case ShadowMode_default:
return ShadowMode_default[defaultValue_default(
defaultValue_default(czmlInterval.shadowMode, czmlInterval.shadows),
czmlInterval
)];
case String:
return defaultValue_default(czmlInterval.string, czmlInterval);
case StripeOrientation_default:
return StripeOrientation_default[defaultValue_default(czmlInterval.stripeOrientation, czmlInterval)];
case Rectangle_default:
return unwrapRectangleInterval(czmlInterval);
case import_urijs10.default:
return unwrapUriInterval(czmlInterval, sourceUri);
case VerticalOrigin_default:
return VerticalOrigin_default[defaultValue_default(czmlInterval.verticalOrigin, czmlInterval)];
default:
throw new RuntimeError_default(type);
}
}
var interpolators = {
HERMITE: HermitePolynomialApproximation_default,
LAGRANGE: LagrangePolynomialApproximation_default,
LINEAR: LinearApproximation_default
};
function updateInterpolationSettings(packetData, property) {
const interpolationAlgorithm = packetData.interpolationAlgorithm;
const interpolationDegree = packetData.interpolationDegree;
if (defined_default(interpolationAlgorithm) || defined_default(interpolationDegree)) {
property.setInterpolationOptions({
interpolationAlgorithm: interpolators[interpolationAlgorithm],
interpolationDegree
});
}
const forwardExtrapolationType = packetData.forwardExtrapolationType;
if (defined_default(forwardExtrapolationType)) {
property.forwardExtrapolationType = ExtrapolationType_default[forwardExtrapolationType];
}
const forwardExtrapolationDuration = packetData.forwardExtrapolationDuration;
if (defined_default(forwardExtrapolationDuration)) {
property.forwardExtrapolationDuration = forwardExtrapolationDuration;
}
const backwardExtrapolationType = packetData.backwardExtrapolationType;
if (defined_default(backwardExtrapolationType)) {
property.backwardExtrapolationType = ExtrapolationType_default[backwardExtrapolationType];
}
const backwardExtrapolationDuration = packetData.backwardExtrapolationDuration;
if (defined_default(backwardExtrapolationDuration)) {
property.backwardExtrapolationDuration = backwardExtrapolationDuration;
}
}
var iso8601Scratch = {
iso8601: void 0
};
function intervalFromString(intervalString) {
if (!defined_default(intervalString)) {
return void 0;
}
iso8601Scratch.iso8601 = intervalString;
return TimeInterval_default.fromIso8601(iso8601Scratch);
}
function wrapPropertyInInfiniteInterval(property) {
const interval = Iso8601_default.MAXIMUM_INTERVAL.clone();
interval.data = property;
return interval;
}
function convertPropertyToComposite(property) {
const composite = new CompositeProperty_default();
composite.intervals.addInterval(wrapPropertyInInfiniteInterval(property));
return composite;
}
function convertPositionPropertyToComposite(property) {
const composite = new CompositePositionProperty_default(property.referenceFrame);
composite.intervals.addInterval(wrapPropertyInInfiniteInterval(property));
return composite;
}
function processProperty(type, object2, propertyName, packetData, constrainedInterval, sourceUri, entityCollection) {
let combinedInterval = intervalFromString(packetData.interval);
if (defined_default(constrainedInterval)) {
if (defined_default(combinedInterval)) {
combinedInterval = TimeInterval_default.intersect(
combinedInterval,
constrainedInterval,
scratchTimeInterval
);
} else {
combinedInterval = constrainedInterval;
}
}
let packedLength;
let unwrappedInterval;
let unwrappedIntervalLength;
const isValue = !defined_default(packetData.reference) && !defined_default(packetData.velocityReference);
const hasInterval = defined_default(combinedInterval) && !combinedInterval.equals(Iso8601_default.MAXIMUM_INTERVAL);
if (packetData.delete === true) {
if (!hasInterval) {
object2[propertyName] = void 0;
return;
}
return removePropertyData(object2[propertyName], combinedInterval);
}
let isSampled = false;
if (isValue) {
unwrappedInterval = unwrapInterval(type, packetData, sourceUri);
if (!defined_default(unwrappedInterval)) {
return;
}
packedLength = defaultValue_default(type.packedLength, 1);
unwrappedIntervalLength = defaultValue_default(unwrappedInterval.length, 1);
isSampled = !defined_default(packetData.array) && typeof unwrappedInterval !== "string" && unwrappedIntervalLength > packedLength && type !== Object;
}
const needsUnpacking = typeof type.unpack === "function" && type !== Rotation_default;
if (!isSampled && !hasInterval) {
if (isValue) {
object2[propertyName] = new ConstantProperty_default(
needsUnpacking ? type.unpack(unwrappedInterval, 0) : unwrappedInterval
);
} else {
object2[propertyName] = createSpecializedProperty(
type,
entityCollection,
packetData
);
}
return;
}
let property = object2[propertyName];
let epoch2;
const packetEpoch = packetData.epoch;
if (defined_default(packetEpoch)) {
epoch2 = JulianDate_default.fromIso8601(packetEpoch);
}
if (isSampled && !hasInterval) {
if (!(property instanceof SampledProperty_default)) {
object2[propertyName] = property = new SampledProperty_default(type);
}
property.addSamplesPackedArray(unwrappedInterval, epoch2);
updateInterpolationSettings(packetData, property);
return;
}
let interval;
if (!isSampled && hasInterval) {
combinedInterval = combinedInterval.clone();
if (isValue) {
combinedInterval.data = needsUnpacking ? type.unpack(unwrappedInterval, 0) : unwrappedInterval;
} else {
combinedInterval.data = createSpecializedProperty(
type,
entityCollection,
packetData
);
}
if (!defined_default(property)) {
object2[propertyName] = property = isValue ? new TimeIntervalCollectionProperty_default() : new CompositeProperty_default();
}
if (isValue && property instanceof TimeIntervalCollectionProperty_default) {
property.intervals.addInterval(combinedInterval);
} else if (property instanceof CompositeProperty_default) {
if (isValue) {
combinedInterval.data = new ConstantProperty_default(combinedInterval.data);
}
property.intervals.addInterval(combinedInterval);
} else {
object2[propertyName] = property = convertPropertyToComposite(property);
if (isValue) {
combinedInterval.data = new ConstantProperty_default(combinedInterval.data);
}
property.intervals.addInterval(combinedInterval);
}
return;
}
if (!defined_default(property)) {
object2[propertyName] = property = new CompositeProperty_default();
}
if (!(property instanceof CompositeProperty_default)) {
object2[propertyName] = property = convertPropertyToComposite(property);
}
const intervals = property.intervals;
interval = intervals.findInterval(combinedInterval);
if (!defined_default(interval) || !(interval.data instanceof SampledProperty_default)) {
interval = combinedInterval.clone();
interval.data = new SampledProperty_default(type);
intervals.addInterval(interval);
}
interval.data.addSamplesPackedArray(unwrappedInterval, epoch2);
updateInterpolationSettings(packetData, interval.data);
}
function removePropertyData(property, interval) {
if (property instanceof SampledProperty_default) {
property.removeSamples(interval);
return;
} else if (property instanceof TimeIntervalCollectionProperty_default) {
property.intervals.removeInterval(interval);
return;
} else if (property instanceof CompositeProperty_default) {
const intervals = property.intervals;
for (let i = 0; i < intervals.length; ++i) {
const intersection = TimeInterval_default.intersect(
intervals.get(i),
interval,
scratchTimeInterval
);
if (!intersection.isEmpty) {
removePropertyData(intersection.data, interval);
}
}
intervals.removeInterval(interval);
return;
}
}
function processPacketData(type, object2, propertyName, packetData, interval, sourceUri, entityCollection) {
if (!defined_default(packetData)) {
return;
}
if (Array.isArray(packetData)) {
for (let i = 0, len = packetData.length; i < len; ++i) {
processProperty(
type,
object2,
propertyName,
packetData[i],
interval,
sourceUri,
entityCollection
);
}
} else {
processProperty(
type,
object2,
propertyName,
packetData,
interval,
sourceUri,
entityCollection
);
}
}
function processPositionProperty(object2, propertyName, packetData, constrainedInterval, sourceUri, entityCollection) {
let combinedInterval = intervalFromString(packetData.interval);
if (defined_default(constrainedInterval)) {
if (defined_default(combinedInterval)) {
combinedInterval = TimeInterval_default.intersect(
combinedInterval,
constrainedInterval,
scratchTimeInterval
);
} else {
combinedInterval = constrainedInterval;
}
}
const numberOfDerivatives = defined_default(packetData.cartesianVelocity) ? 1 : 0;
const packedLength = Cartesian3_default.packedLength * (numberOfDerivatives + 1);
let unwrappedInterval;
let unwrappedIntervalLength;
const isValue = !defined_default(packetData.reference);
const hasInterval = defined_default(combinedInterval) && !combinedInterval.equals(Iso8601_default.MAXIMUM_INTERVAL);
if (packetData.delete === true) {
if (!hasInterval) {
object2[propertyName] = void 0;
return;
}
return removePositionPropertyData(object2[propertyName], combinedInterval);
}
let referenceFrame;
let isSampled = false;
if (isValue) {
if (defined_default(packetData.referenceFrame)) {
referenceFrame = ReferenceFrame_default[packetData.referenceFrame];
}
referenceFrame = defaultValue_default(referenceFrame, ReferenceFrame_default.FIXED);
unwrappedInterval = unwrapCartesianInterval(packetData);
unwrappedIntervalLength = defaultValue_default(unwrappedInterval.length, 1);
isSampled = unwrappedIntervalLength > packedLength;
}
if (!isSampled && !hasInterval) {
if (isValue) {
object2[propertyName] = new ConstantPositionProperty_default(
Cartesian3_default.unpack(unwrappedInterval),
referenceFrame
);
} else {
object2[propertyName] = createReferenceProperty(
entityCollection,
packetData.reference
);
}
return;
}
let property = object2[propertyName];
let epoch2;
const packetEpoch = packetData.epoch;
if (defined_default(packetEpoch)) {
epoch2 = JulianDate_default.fromIso8601(packetEpoch);
}
if (isSampled && !hasInterval) {
if (!(property instanceof SampledPositionProperty_default) || defined_default(referenceFrame) && property.referenceFrame !== referenceFrame) {
object2[propertyName] = property = new SampledPositionProperty_default(
referenceFrame,
numberOfDerivatives
);
}
property.addSamplesPackedArray(unwrappedInterval, epoch2);
updateInterpolationSettings(packetData, property);
return;
}
let interval;
if (!isSampled && hasInterval) {
combinedInterval = combinedInterval.clone();
if (isValue) {
combinedInterval.data = Cartesian3_default.unpack(unwrappedInterval);
} else {
combinedInterval.data = createReferenceProperty(
entityCollection,
packetData.reference
);
}
if (!defined_default(property)) {
if (isValue) {
property = new TimeIntervalCollectionPositionProperty_default(referenceFrame);
} else {
property = new CompositePositionProperty_default(referenceFrame);
}
object2[propertyName] = property;
}
if (isValue && property instanceof TimeIntervalCollectionPositionProperty_default && defined_default(referenceFrame) && property.referenceFrame === referenceFrame) {
property.intervals.addInterval(combinedInterval);
} else if (property instanceof CompositePositionProperty_default) {
if (isValue) {
combinedInterval.data = new ConstantPositionProperty_default(
combinedInterval.data,
referenceFrame
);
}
property.intervals.addInterval(combinedInterval);
} else {
object2[propertyName] = property = convertPositionPropertyToComposite(
property
);
if (isValue) {
combinedInterval.data = new ConstantPositionProperty_default(
combinedInterval.data,
referenceFrame
);
}
property.intervals.addInterval(combinedInterval);
}
return;
}
if (!defined_default(property)) {
object2[propertyName] = property = new CompositePositionProperty_default(
referenceFrame
);
} else if (!(property instanceof CompositePositionProperty_default)) {
object2[propertyName] = property = convertPositionPropertyToComposite(
property
);
}
const intervals = property.intervals;
interval = intervals.findInterval(combinedInterval);
if (!defined_default(interval) || !(interval.data instanceof SampledPositionProperty_default) || defined_default(referenceFrame) && interval.data.referenceFrame !== referenceFrame) {
interval = combinedInterval.clone();
interval.data = new SampledPositionProperty_default(
referenceFrame,
numberOfDerivatives
);
intervals.addInterval(interval);
}
interval.data.addSamplesPackedArray(unwrappedInterval, epoch2);
updateInterpolationSettings(packetData, interval.data);
}
function removePositionPropertyData(property, interval) {
if (property instanceof SampledPositionProperty_default) {
property.removeSamples(interval);
return;
} else if (property instanceof TimeIntervalCollectionPositionProperty_default) {
property.intervals.removeInterval(interval);
return;
} else if (property instanceof CompositePositionProperty_default) {
const intervals = property.intervals;
for (let i = 0; i < intervals.length; ++i) {
const intersection = TimeInterval_default.intersect(
intervals.get(i),
interval,
scratchTimeInterval
);
if (!intersection.isEmpty) {
removePositionPropertyData(intersection.data, interval);
}
}
intervals.removeInterval(interval);
return;
}
}
function processPositionPacketData(object2, propertyName, packetData, interval, sourceUri, entityCollection) {
if (!defined_default(packetData)) {
return;
}
if (Array.isArray(packetData)) {
for (let i = 0, len = packetData.length; i < len; ++i) {
processPositionProperty(
object2,
propertyName,
packetData[i],
interval,
sourceUri,
entityCollection
);
}
} else {
processPositionProperty(
object2,
propertyName,
packetData,
interval,
sourceUri,
entityCollection
);
}
}
function processShapePacketData(object2, propertyName, packetData, entityCollection) {
if (defined_default(packetData.references)) {
processReferencesArrayPacketData(
object2,
propertyName,
packetData.references,
packetData.interval,
entityCollection,
PropertyArray_default,
CompositeProperty_default
);
} else {
if (defined_default(packetData.cartesian2)) {
packetData.array = Cartesian2_default.unpackArray(packetData.cartesian2);
} else if (defined_default(packetData.cartesian)) {
packetData.array = Cartesian2_default.unpackArray(packetData.cartesian);
}
if (defined_default(packetData.array)) {
processPacketData(
Array,
object2,
propertyName,
packetData,
void 0,
void 0,
entityCollection
);
}
}
}
function processMaterialProperty(object2, propertyName, packetData, constrainedInterval, sourceUri, entityCollection) {
let combinedInterval = intervalFromString(packetData.interval);
if (defined_default(constrainedInterval)) {
if (defined_default(combinedInterval)) {
combinedInterval = TimeInterval_default.intersect(
combinedInterval,
constrainedInterval,
scratchTimeInterval
);
} else {
combinedInterval = constrainedInterval;
}
}
let property = object2[propertyName];
let existingMaterial;
let existingInterval;
if (defined_default(combinedInterval)) {
if (!(property instanceof CompositeMaterialProperty_default)) {
property = new CompositeMaterialProperty_default();
object2[propertyName] = property;
}
const thisIntervals = property.intervals;
existingInterval = thisIntervals.findInterval({
start: combinedInterval.start,
stop: combinedInterval.stop
});
if (defined_default(existingInterval)) {
existingMaterial = existingInterval.data;
} else {
existingInterval = combinedInterval.clone();
thisIntervals.addInterval(existingInterval);
}
} else {
existingMaterial = property;
}
let materialData;
if (defined_default(packetData.solidColor)) {
if (!(existingMaterial instanceof ColorMaterialProperty_default)) {
existingMaterial = new ColorMaterialProperty_default();
}
materialData = packetData.solidColor;
processPacketData(
Color_default,
existingMaterial,
"color",
materialData.color,
void 0,
void 0,
entityCollection
);
} else if (defined_default(packetData.grid)) {
if (!(existingMaterial instanceof GridMaterialProperty_default)) {
existingMaterial = new GridMaterialProperty_default();
}
materialData = packetData.grid;
processPacketData(
Color_default,
existingMaterial,
"color",
materialData.color,
void 0,
sourceUri,
entityCollection
);
processPacketData(
Number,
existingMaterial,
"cellAlpha",
materialData.cellAlpha,
void 0,
sourceUri,
entityCollection
);
processPacketData(
Cartesian2_default,
existingMaterial,
"lineCount",
materialData.lineCount,
void 0,
sourceUri,
entityCollection
);
processPacketData(
Cartesian2_default,
existingMaterial,
"lineThickness",
materialData.lineThickness,
void 0,
sourceUri,
entityCollection
);
processPacketData(
Cartesian2_default,
existingMaterial,
"lineOffset",
materialData.lineOffset,
void 0,
sourceUri,
entityCollection
);
} else if (defined_default(packetData.image)) {
if (!(existingMaterial instanceof ImageMaterialProperty_default)) {
existingMaterial = new ImageMaterialProperty_default();
}
materialData = packetData.image;
processPacketData(
Image,
existingMaterial,
"image",
materialData.image,
void 0,
sourceUri,
entityCollection
);
processPacketData(
Cartesian2_default,
existingMaterial,
"repeat",
materialData.repeat,
void 0,
sourceUri,
entityCollection
);
processPacketData(
Color_default,
existingMaterial,
"color",
materialData.color,
void 0,
sourceUri,
entityCollection
);
processPacketData(
Boolean,
existingMaterial,
"transparent",
materialData.transparent,
void 0,
sourceUri,
entityCollection
);
} else if (defined_default(packetData.stripe)) {
if (!(existingMaterial instanceof StripeMaterialProperty_default)) {
existingMaterial = new StripeMaterialProperty_default();
}
materialData = packetData.stripe;
processPacketData(
StripeOrientation_default,
existingMaterial,
"orientation",
materialData.orientation,
void 0,
sourceUri,
entityCollection
);
processPacketData(
Color_default,
existingMaterial,
"evenColor",
materialData.evenColor,
void 0,
sourceUri,
entityCollection
);
processPacketData(
Color_default,
existingMaterial,
"oddColor",
materialData.oddColor,
void 0,
sourceUri,
entityCollection
);
processPacketData(
Number,
existingMaterial,
"offset",
materialData.offset,
void 0,
sourceUri,
entityCollection
);
processPacketData(
Number,
existingMaterial,
"repeat",
materialData.repeat,
void 0,
sourceUri,
entityCollection
);
} else if (defined_default(packetData.polylineOutline)) {
if (!(existingMaterial instanceof PolylineOutlineMaterialProperty_default)) {
existingMaterial = new PolylineOutlineMaterialProperty_default();
}
materialData = packetData.polylineOutline;
processPacketData(
Color_default,
existingMaterial,
"color",
materialData.color,
void 0,
sourceUri,
entityCollection
);
processPacketData(
Color_default,
existingMaterial,
"outlineColor",
materialData.outlineColor,
void 0,
sourceUri,
entityCollection
);
processPacketData(
Number,
existingMaterial,
"outlineWidth",
materialData.outlineWidth,
void 0,
sourceUri,
entityCollection
);
} else if (defined_default(packetData.polylineGlow)) {
if (!(existingMaterial instanceof PolylineGlowMaterialProperty_default)) {
existingMaterial = new PolylineGlowMaterialProperty_default();
}
materialData = packetData.polylineGlow;
processPacketData(
Color_default,
existingMaterial,
"color",
materialData.color,
void 0,
sourceUri,
entityCollection
);
processPacketData(
Number,
existingMaterial,
"glowPower",
materialData.glowPower,
void 0,
sourceUri,
entityCollection
);
processPacketData(
Number,
existingMaterial,
"taperPower",
materialData.taperPower,
void 0,
sourceUri,
entityCollection
);
} else if (defined_default(packetData.polylineArrow)) {
if (!(existingMaterial instanceof PolylineArrowMaterialProperty_default)) {
existingMaterial = new PolylineArrowMaterialProperty_default();
}
materialData = packetData.polylineArrow;
processPacketData(
Color_default,
existingMaterial,
"color",
materialData.color,
void 0,
void 0,
entityCollection
);
} else if (defined_default(packetData.polylineDash)) {
if (!(existingMaterial instanceof PolylineDashMaterialProperty_default)) {
existingMaterial = new PolylineDashMaterialProperty_default();
}
materialData = packetData.polylineDash;
processPacketData(
Color_default,
existingMaterial,
"color",
materialData.color,
void 0,
void 0,
entityCollection
);
processPacketData(
Color_default,
existingMaterial,
"gapColor",
materialData.gapColor,
void 0,
void 0,
entityCollection
);
processPacketData(
Number,
existingMaterial,
"dashLength",
materialData.dashLength,
void 0,
sourceUri,
entityCollection
);
processPacketData(
Number,
existingMaterial,
"dashPattern",
materialData.dashPattern,
void 0,
sourceUri,
entityCollection
);
} else if (defined_default(packetData.checkerboard)) {
if (!(existingMaterial instanceof CheckerboardMaterialProperty_default)) {
existingMaterial = new CheckerboardMaterialProperty_default();
}
materialData = packetData.checkerboard;
processPacketData(
Color_default,
existingMaterial,
"evenColor",
materialData.evenColor,
void 0,
sourceUri,
entityCollection
);
processPacketData(
Color_default,
existingMaterial,
"oddColor",
materialData.oddColor,
void 0,
sourceUri,
entityCollection
);
processPacketData(
Cartesian2_default,
existingMaterial,
"repeat",
materialData.repeat,
void 0,
sourceUri,
entityCollection
);
}
if (defined_default(existingInterval)) {
existingInterval.data = existingMaterial;
} else {
object2[propertyName] = existingMaterial;
}
}
function processMaterialPacketData(object2, propertyName, packetData, interval, sourceUri, entityCollection) {
if (!defined_default(packetData)) {
return;
}
if (Array.isArray(packetData)) {
for (let i = 0, len = packetData.length; i < len; ++i) {
processMaterialProperty(
object2,
propertyName,
packetData[i],
interval,
sourceUri,
entityCollection
);
}
} else {
processMaterialProperty(
object2,
propertyName,
packetData,
interval,
sourceUri,
entityCollection
);
}
}
function processName(entity, packet, entityCollection, sourceUri) {
const nameData = packet.name;
if (defined_default(nameData)) {
entity.name = packet.name;
}
}
function processDescription(entity, packet, entityCollection, sourceUri) {
const descriptionData = packet.description;
if (defined_default(descriptionData)) {
processPacketData(
String,
entity,
"description",
descriptionData,
void 0,
sourceUri,
entityCollection
);
}
}
function processPosition(entity, packet, entityCollection, sourceUri) {
const positionData = packet.position;
if (defined_default(positionData)) {
processPositionPacketData(
entity,
"position",
positionData,
void 0,
sourceUri,
entityCollection
);
}
}
function processViewFrom(entity, packet, entityCollection, sourceUri) {
const viewFromData = packet.viewFrom;
if (defined_default(viewFromData)) {
processPacketData(
Cartesian3_default,
entity,
"viewFrom",
viewFromData,
void 0,
sourceUri,
entityCollection
);
}
}
function processOrientation(entity, packet, entityCollection, sourceUri) {
const orientationData = packet.orientation;
if (defined_default(orientationData)) {
processPacketData(
Quaternion_default,
entity,
"orientation",
orientationData,
void 0,
sourceUri,
entityCollection
);
}
}
function processProperties(entity, packet, entityCollection, sourceUri) {
const propertiesData = packet.properties;
if (defined_default(propertiesData)) {
if (!defined_default(entity.properties)) {
entity.properties = new PropertyBag_default();
}
for (const key in propertiesData) {
if (propertiesData.hasOwnProperty(key)) {
if (!entity.properties.hasProperty(key)) {
entity.properties.addProperty(key);
}
const propertyData = propertiesData[key];
if (Array.isArray(propertyData)) {
for (let i = 0, len = propertyData.length; i < len; ++i) {
processProperty(
getPropertyType(propertyData[i]),
entity.properties,
key,
propertyData[i],
void 0,
sourceUri,
entityCollection
);
}
} else {
processProperty(
getPropertyType(propertyData),
entity.properties,
key,
propertyData,
void 0,
sourceUri,
entityCollection
);
}
}
}
}
}
function processReferencesArrayPacketData(object2, propertyName, references, interval, entityCollection, PropertyArrayType, CompositePropertyArrayType) {
const properties = references.map(function(reference) {
return createReferenceProperty(entityCollection, reference);
});
if (defined_default(interval)) {
interval = intervalFromString(interval);
let property = object2[propertyName];
if (!(property instanceof CompositePropertyArrayType)) {
const composite = new CompositePropertyArrayType();
composite.intervals.addInterval(wrapPropertyInInfiniteInterval(property));
object2[propertyName] = property = composite;
}
interval.data = new PropertyArrayType(properties);
property.intervals.addInterval(interval);
} else {
object2[propertyName] = new PropertyArrayType(properties);
}
}
function processArrayPacketData(object2, propertyName, packetData, entityCollection) {
const references = packetData.references;
if (defined_default(references)) {
processReferencesArrayPacketData(
object2,
propertyName,
references,
packetData.interval,
entityCollection,
PropertyArray_default,
CompositeProperty_default
);
} else {
processPacketData(
Array,
object2,
propertyName,
packetData,
void 0,
void 0,
entityCollection
);
}
}
function processArray(object2, propertyName, packetData, entityCollection) {
if (!defined_default(packetData)) {
return;
}
if (Array.isArray(packetData)) {
for (let i = 0, length3 = packetData.length; i < length3; ++i) {
processArrayPacketData(
object2,
propertyName,
packetData[i],
entityCollection
);
}
} else {
processArrayPacketData(object2, propertyName, packetData, entityCollection);
}
}
function processPositionArrayPacketData(object2, propertyName, packetData, entityCollection) {
const references = packetData.references;
if (defined_default(references)) {
processReferencesArrayPacketData(
object2,
propertyName,
references,
packetData.interval,
entityCollection,
PositionPropertyArray_default,
CompositePositionProperty_default
);
} else {
if (defined_default(packetData.cartesian)) {
packetData.array = Cartesian3_default.unpackArray(packetData.cartesian);
} else if (defined_default(packetData.cartographicRadians)) {
packetData.array = Cartesian3_default.fromRadiansArrayHeights(
packetData.cartographicRadians
);
} else if (defined_default(packetData.cartographicDegrees)) {
packetData.array = Cartesian3_default.fromDegreesArrayHeights(
packetData.cartographicDegrees
);
}
if (defined_default(packetData.array)) {
processPacketData(
Array,
object2,
propertyName,
packetData,
void 0,
void 0,
entityCollection
);
}
}
}
function processPositionArray(object2, propertyName, packetData, entityCollection) {
if (!defined_default(packetData)) {
return;
}
if (Array.isArray(packetData)) {
for (let i = 0, length3 = packetData.length; i < length3; ++i) {
processPositionArrayPacketData(
object2,
propertyName,
packetData[i],
entityCollection
);
}
} else {
processPositionArrayPacketData(
object2,
propertyName,
packetData,
entityCollection
);
}
}
function unpackCartesianArray(array) {
return Cartesian3_default.unpackArray(array);
}
function unpackCartographicRadiansArray(array) {
return Cartesian3_default.fromRadiansArrayHeights(array);
}
function unpackCartographicDegreesArray(array) {
return Cartesian3_default.fromDegreesArrayHeights(array);
}
function processPositionArrayOfArraysPacketData(object2, propertyName, packetData, entityCollection) {
const references = packetData.references;
if (defined_default(references)) {
const properties = references.map(function(referenceArray) {
const tempObj = {};
processReferencesArrayPacketData(
tempObj,
"positions",
referenceArray,
packetData.interval,
entityCollection,
PositionPropertyArray_default,
CompositePositionProperty_default
);
return tempObj.positions;
});
object2[propertyName] = new PositionPropertyArray_default(properties);
} else {
if (defined_default(packetData.cartesian)) {
packetData.array = packetData.cartesian.map(unpackCartesianArray);
} else if (defined_default(packetData.cartographicRadians)) {
packetData.array = packetData.cartographicRadians.map(
unpackCartographicRadiansArray
);
} else if (defined_default(packetData.cartographicDegrees)) {
packetData.array = packetData.cartographicDegrees.map(
unpackCartographicDegreesArray
);
}
if (defined_default(packetData.array)) {
processPacketData(
Array,
object2,
propertyName,
packetData,
void 0,
void 0,
entityCollection
);
}
}
}
function processPositionArrayOfArrays(object2, propertyName, packetData, entityCollection) {
if (!defined_default(packetData)) {
return;
}
if (Array.isArray(packetData)) {
for (let i = 0, length3 = packetData.length; i < length3; ++i) {
processPositionArrayOfArraysPacketData(
object2,
propertyName,
packetData[i],
entityCollection
);
}
} else {
processPositionArrayOfArraysPacketData(
object2,
propertyName,
packetData,
entityCollection
);
}
}
function processShape(object2, propertyName, packetData, entityCollection) {
if (!defined_default(packetData)) {
return;
}
if (Array.isArray(packetData)) {
for (let i = 0, length3 = packetData.length; i < length3; i++) {
processShapePacketData(
object2,
propertyName,
packetData[i],
entityCollection
);
}
} else {
processShapePacketData(object2, propertyName, packetData, entityCollection);
}
}
function processAvailability(entity, packet, entityCollection, sourceUri) {
const packetData = packet.availability;
if (!defined_default(packetData)) {
return;
}
let intervals;
if (Array.isArray(packetData)) {
for (let i = 0, len = packetData.length; i < len; ++i) {
if (!defined_default(intervals)) {
intervals = new TimeIntervalCollection_default();
}
intervals.addInterval(intervalFromString(packetData[i]));
}
} else {
intervals = new TimeIntervalCollection_default();
intervals.addInterval(intervalFromString(packetData));
}
entity.availability = intervals;
}
function processAlignedAxis(billboard, packetData, interval, sourceUri, entityCollection) {
if (!defined_default(packetData)) {
return;
}
processPacketData(
UnitCartesian3,
billboard,
"alignedAxis",
packetData,
interval,
sourceUri,
entityCollection
);
}
function processBillboard(entity, packet, entityCollection, sourceUri) {
const billboardData = packet.billboard;
if (!defined_default(billboardData)) {
return;
}
const interval = intervalFromString(billboardData.interval);
let billboard = entity.billboard;
if (!defined_default(billboard)) {
entity.billboard = billboard = new BillboardGraphics_default();
}
processPacketData(
Boolean,
billboard,
"show",
billboardData.show,
interval,
sourceUri,
entityCollection
);
processPacketData(
Image,
billboard,
"image",
billboardData.image,
interval,
sourceUri,
entityCollection
);
processPacketData(
Number,
billboard,
"scale",
billboardData.scale,
interval,
sourceUri,
entityCollection
);
processPacketData(
Cartesian2_default,
billboard,
"pixelOffset",
billboardData.pixelOffset,
interval,
sourceUri,
entityCollection
);
processPacketData(
Cartesian3_default,
billboard,
"eyeOffset",
billboardData.eyeOffset,
interval,
sourceUri,
entityCollection
);
processPacketData(
HorizontalOrigin_default,
billboard,
"horizontalOrigin",
billboardData.horizontalOrigin,
interval,
sourceUri,
entityCollection
);
processPacketData(
VerticalOrigin_default,
billboard,
"verticalOrigin",
billboardData.verticalOrigin,
interval,
sourceUri,
entityCollection
);
processPacketData(
HeightReference_default,
billboard,
"heightReference",
billboardData.heightReference,
interval,
sourceUri,
entityCollection
);
processPacketData(
Color_default,
billboard,
"color",
billboardData.color,
interval,
sourceUri,
entityCollection
);
processPacketData(
Rotation_default,
billboard,
"rotation",
billboardData.rotation,
interval,
sourceUri,
entityCollection
);
processAlignedAxis(
billboard,
billboardData.alignedAxis,
interval,
sourceUri,
entityCollection
);
processPacketData(
Boolean,
billboard,
"sizeInMeters",
billboardData.sizeInMeters,
interval,
sourceUri,
entityCollection
);
processPacketData(
Number,
billboard,
"width",
billboardData.width,
interval,
sourceUri,
entityCollection
);
processPacketData(
Number,
billboard,
"height",
billboardData.height,
interval,
sourceUri,
entityCollection
);
processPacketData(
NearFarScalar_default,
billboard,
"scaleByDistance",
billboardData.scaleByDistance,
interval,
sourceUri,
entityCollection
);
processPacketData(
NearFarScalar_default,
billboard,
"translucencyByDistance",
billboardData.translucencyByDistance,
interval,
sourceUri,
entityCollection
);
processPacketData(
NearFarScalar_default,
billboard,
"pixelOffsetScaleByDistance",
billboardData.pixelOffsetScaleByDistance,
interval,
sourceUri,
entityCollection
);
processPacketData(
BoundingRectangle_default,
billboard,
"imageSubRegion",
billboardData.imageSubRegion,
interval,
sourceUri,
entityCollection
);
processPacketData(
DistanceDisplayCondition_default,
billboard,
"distanceDisplayCondition",
billboardData.distanceDisplayCondition,
interval,
sourceUri,
entityCollection
);
processPacketData(
Number,
billboard,
"disableDepthTestDistance",
billboardData.disableDepthTestDistance,
interval,
sourceUri,
entityCollection
);
}
function processBox(entity, packet, entityCollection, sourceUri) {
const boxData = packet.box;
if (!defined_default(boxData)) {
return;
}
const interval = intervalFromString(boxData.interval);
let box = entity.box;
if (!defined_default(box)) {
entity.box = box = new BoxGraphics_default();
}
processPacketData(
Boolean,
box,
"show",
boxData.show,
interval,
sourceUri,
entityCollection
);
processPacketData(
Cartesian3_default,
box,
"dimensions",
boxData.dimensions,
interval,
sourceUri,
entityCollection
);
processPacketData(
HeightReference_default,
box,
"heightReference",
boxData.heightReference,
interval,
sourceUri,
entityCollection
);
processPacketData(
Boolean,
box,
"fill",
boxData.fill,
interval,
sourceUri,
entityCollection
);
processMaterialPacketData(
box,
"material",
boxData.material,
interval,
sourceUri,
entityCollection
);
processPacketData(
Boolean,
box,
"outline",
boxData.outline,
interval,
sourceUri,
entityCollection
);
processPacketData(
Color_default,
box,
"outlineColor",
boxData.outlineColor,
interval,
sourceUri,
entityCollection
);
processPacketData(
Number,
box,
"outlineWidth",
boxData.outlineWidth,
interval,
sourceUri,
entityCollection
);
processPacketData(
ShadowMode_default,
box,
"shadows",
boxData.shadows,
interval,
sourceUri,
entityCollection
);
processPacketData(
DistanceDisplayCondition_default,
box,
"distanceDisplayCondition",
boxData.distanceDisplayCondition,
interval,
sourceUri,
entityCollection
);
}
function processCorridor(entity, packet, entityCollection, sourceUri) {
const corridorData = packet.corridor;
if (!defined_default(corridorData)) {
return;
}
const interval = intervalFromString(corridorData.interval);
let corridor = entity.corridor;
if (!defined_default(corridor)) {
entity.corridor = corridor = new CorridorGraphics_default();
}
processPacketData(
Boolean,
corridor,
"show",
corridorData.show,
interval,
sourceUri,
entityCollection
);
processPositionArray(
corridor,
"positions",
corridorData.positions,
entityCollection
);
processPacketData(
Number,
corridor,
"width",
corridorData.width,
interval,
sourceUri,
entityCollection
);
processPacketData(
Number,
corridor,
"height",
corridorData.height,
interval,
sourceUri,
entityCollection
);
processPacketData(
HeightReference_default,
corridor,
"heightReference",
corridorData.heightReference,
interval,
sourceUri,
entityCollection
);
processPacketData(
Number,
corridor,
"extrudedHeight",
corridorData.extrudedHeight,
interval,
sourceUri,
entityCollection
);
processPacketData(
HeightReference_default,
corridor,
"extrudedHeightReference",
corridorData.extrudedHeightReference,
interval,
sourceUri,
entityCollection
);
processPacketData(
CornerType_default,
corridor,
"cornerType",
corridorData.cornerType,
interval,
sourceUri,
entityCollection
);
processPacketData(
Number,
corridor,
"granularity",
corridorData.granularity,
interval,
sourceUri,
entityCollection
);
processPacketData(
Boolean,
corridor,
"fill",
corridorData.fill,
interval,
sourceUri,
entityCollection
);
processMaterialPacketData(
corridor,
"material",
corridorData.material,
interval,
sourceUri,
entityCollection
);
processPacketData(
Boolean,
corridor,
"outline",
corridorData.outline,
interval,
sourceUri,
entityCollection
);
processPacketData(
Color_default,
corridor,
"outlineColor",
corridorData.outlineColor,
interval,
sourceUri,
entityCollection
);
processPacketData(
Number,
corridor,
"outlineWidth",
corridorData.outlineWidth,
interval,
sourceUri,
entityCollection
);
processPacketData(
ShadowMode_default,
corridor,
"shadows",
corridorData.shadows,
interval,
sourceUri,
entityCollection
);
processPacketData(
DistanceDisplayCondition_default,
corridor,
"distanceDisplayCondition",
corridorData.distanceDisplayCondition,
interval,
sourceUri,
entityCollection
);
processPacketData(
ClassificationType_default,
corridor,
"classificationType",
corridorData.classificationType,
interval,
sourceUri,
entityCollection
);
processPacketData(
Number,
corridor,
"zIndex",
corridorData.zIndex,
interval,
sourceUri,
entityCollection
);
}
function processCylinder(entity, packet, entityCollection, sourceUri) {
const cylinderData = packet.cylinder;
if (!defined_default(cylinderData)) {
return;
}
const interval = intervalFromString(cylinderData.interval);
let cylinder = entity.cylinder;
if (!defined_default(cylinder)) {
entity.cylinder = cylinder = new CylinderGraphics_default();
}
processPacketData(
Boolean,
cylinder,
"show",
cylinderData.show,
interval,
sourceUri,
entityCollection
);
processPacketData(
Number,
cylinder,
"length",
cylinderData.length,
interval,
sourceUri,
entityCollection
);
processPacketData(
Number,
cylinder,
"topRadius",
cylinderData.topRadius,
interval,
sourceUri,
entityCollection
);
processPacketData(
Number,
cylinder,
"bottomRadius",
cylinderData.bottomRadius,
interval,
sourceUri,
entityCollection
);
processPacketData(
HeightReference_default,
cylinder,
"heightReference",
cylinderData.heightReference,
interval,
sourceUri,
entityCollection
);
processPacketData(
Boolean,
cylinder,
"fill",
cylinderData.fill,
interval,
sourceUri,
entityCollection
);
processMaterialPacketData(
cylinder,
"material",
cylinderData.material,
interval,
sourceUri,
entityCollection
);
processPacketData(
Boolean,
cylinder,
"outline",
cylinderData.outline,
interval,
sourceUri,
entityCollection
);
processPacketData(
Color_default,
cylinder,
"outlineColor",
cylinderData.outlineColor,
interval,
sourceUri,
entityCollection
);
processPacketData(
Number,
cylinder,
"outlineWidth",
cylinderData.outlineWidth,
interval,
sourceUri,
entityCollection
);
processPacketData(
Number,
cylinder,
"numberOfVerticalLines",
cylinderData.numberOfVerticalLines,
interval,
sourceUri,
entityCollection
);
processPacketData(
Number,
cylinder,
"slices",
cylinderData.slices,
interval,
sourceUri,
entityCollection
);
processPacketData(
ShadowMode_default,
cylinder,
"shadows",
cylinderData.shadows,
interval,
sourceUri,
entityCollection
);
processPacketData(
DistanceDisplayCondition_default,
cylinder,
"distanceDisplayCondition",
cylinderData.distanceDisplayCondition,
interval,
sourceUri,
entityCollection
);
}
function processDocument(packet, dataSource) {
const version2 = packet.version;
if (defined_default(version2)) {
if (typeof version2 === "string") {
const tokens = version2.split(".");
if (tokens.length === 2) {
if (tokens[0] !== "1") {
throw new RuntimeError_default("Cesium only supports CZML version 1.");
}
dataSource._version = version2;
}
}
}
if (!defined_default(dataSource._version)) {
throw new RuntimeError_default(
"CZML version information invalid. It is expected to be a property on the document object in the crsLinkHrefs
, assuming
* the link has a type specified.
* @memberof GeoJsonDataSource
* @type {object}
*/
crsLinkHrefs: {
get: function() {
return crsLinkHrefs;
}
},
/**
* Gets an object that maps the type property of a crs link to a callback function
* which takes the crs properties object and returns a Promise that resolves
* to a function that takes a GeoJSON coordinate and transforms it into a WGS84 Earth-fixed Cartesian.
* Items in crsLinkHrefs
take precedence over this object.
* @memberof GeoJsonDataSource
* @type {object}
*/
crsLinkTypes: {
get: function() {
return crsLinkTypes;
}
}
});
Object.defineProperties(GeoJsonDataSource.prototype, {
/**
* Gets or sets a human-readable name for this instance.
* @memberof GeoJsonDataSource.prototype
* @type {string}
*/
name: {
get: function() {
return this._name;
},
set: function(value) {
if (this._name !== value) {
this._name = value;
this._changed.raiseEvent(this);
}
}
},
/**
* This DataSource only defines static data, therefore this property is always undefined.
* @memberof GeoJsonDataSource.prototype
* @type {DataSourceClock}
*/
clock: {
value: void 0,
writable: false
},
/**
* Gets the collection of {@link Entity} instances.
* @memberof GeoJsonDataSource.prototype
* @type {EntityCollection}
*/
entities: {
get: function() {
return this._entityCollection;
}
},
/**
* Gets a value indicating if the data source is currently loading data.
* @memberof GeoJsonDataSource.prototype
* @type {boolean}
*/
isLoading: {
get: function() {
return this._isLoading;
}
},
/**
* Gets an event that will be raised when the underlying data changes.
* @memberof GeoJsonDataSource.prototype
* @type {Event}
*/
changedEvent: {
get: function() {
return this._changed;
}
},
/**
* Gets an event that will be raised if an error is encountered during processing.
* @memberof GeoJsonDataSource.prototype
* @type {Event}
*/
errorEvent: {
get: function() {
return this._error;
}
},
/**
* Gets an event that will be raised when the data source either starts or stops loading.
* @memberof GeoJsonDataSource.prototype
* @type {Event}
*/
loadingEvent: {
get: function() {
return this._loading;
}
},
/**
* Gets whether or not this data source should be displayed.
* @memberof GeoJsonDataSource.prototype
* @type {boolean}
*/
show: {
get: function() {
return this._entityCollection.show;
},
set: function(value) {
this._entityCollection.show = value;
}
},
/**
* Gets or sets the clustering options for this data source. This object can be shared between multiple data sources.
*
* @memberof GeoJsonDataSource.prototype
* @type {EntityCluster}
*/
clustering: {
get: function() {
return this._entityCluster;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value must be defined.");
}
this._entityCluster = value;
}
},
/**
* Gets the credit that will be displayed for the data source
* @memberof GeoJsonDataSource.prototype
* @type {Credit}
*/
credit: {
get: function() {
return this._credit;
}
}
});
GeoJsonDataSource.prototype.load = function(data, options) {
return preload(this, data, options, true);
};
GeoJsonDataSource.prototype.process = function(data, options) {
return preload(this, data, options, false);
};
function preload(that, data, options, clear2) {
if (!defined_default(data)) {
throw new DeveloperError_default("data is required.");
}
DataSource_default.setLoading(that, true);
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
let credit = options.credit;
if (typeof credit === "string") {
credit = new Credit_default(credit);
}
that._credit = credit;
let promise = data;
let sourceUri = options.sourceUri;
if (typeof data === "string" || data instanceof Resource_default) {
data = Resource_default.createIfNeeded(data);
promise = data.fetchJson();
sourceUri = defaultValue_default(sourceUri, data.getUrlComponent());
const resourceCredits = that._resourceCredits;
const credits = data.credits;
if (defined_default(credits)) {
const length3 = credits.length;
for (let i = 0; i < length3; i++) {
resourceCredits.push(credits[i]);
}
}
}
options = {
describe: defaultValue_default(options.describe, defaultDescribeProperty),
markerSize: defaultValue_default(options.markerSize, defaultMarkerSize),
markerSymbol: defaultValue_default(options.markerSymbol, defaultMarkerSymbol),
markerColor: defaultValue_default(options.markerColor, defaultMarkerColor),
strokeWidthProperty: new ConstantProperty_default(
defaultValue_default(options.strokeWidth, defaultStrokeWidth)
),
strokeMaterialProperty: new ColorMaterialProperty_default(
defaultValue_default(options.stroke, defaultStroke)
),
fillMaterialProperty: new ColorMaterialProperty_default(
defaultValue_default(options.fill, defaultFill2)
),
clampToGround: defaultValue_default(options.clampToGround, defaultClampToGround)
};
return Promise.resolve(promise).then(function(geoJson) {
return load2(that, geoJson, options, sourceUri, clear2);
}).catch(function(error) {
DataSource_default.setLoading(that, false);
that._error.raiseEvent(that, error);
throw error;
});
}
GeoJsonDataSource.prototype.update = function(time) {
return true;
};
function load2(that, geoJson, options, sourceUri, clear2) {
let name;
if (defined_default(sourceUri)) {
name = getFilenameFromUri_default(sourceUri);
}
if (defined_default(name) && that._name !== name) {
that._name = name;
that._changed.raiseEvent(that);
}
const typeHandler = geoJsonObjectTypes2[geoJson.type];
if (!defined_default(typeHandler)) {
throw new RuntimeError_default(`Unsupported GeoJSON object type: ${geoJson.type}`);
}
const crs = geoJson.crs;
let crsFunction = crs !== null ? defaultCrsFunction : null;
if (defined_default(crs)) {
if (!defined_default(crs.properties)) {
throw new RuntimeError_default("crs.properties is undefined.");
}
const properties = crs.properties;
if (crs.type === "name") {
crsFunction = crsNames[properties.name];
if (!defined_default(crsFunction)) {
throw new RuntimeError_default(`Unknown crs name: ${properties.name}`);
}
} else if (crs.type === "link") {
let handler = crsLinkHrefs[properties.href];
if (!defined_default(handler)) {
handler = crsLinkTypes[properties.type];
}
if (!defined_default(handler)) {
throw new RuntimeError_default(
`Unable to resolve crs link: ${JSON.stringify(properties)}`
);
}
crsFunction = handler(properties);
} else if (crs.type === "EPSG") {
crsFunction = crsNames[`EPSG:${properties.code}`];
if (!defined_default(crsFunction)) {
throw new RuntimeError_default(`Unknown crs EPSG code: ${properties.code}`);
}
} else {
throw new RuntimeError_default(`Unknown crs type: ${crs.type}`);
}
}
return Promise.resolve(crsFunction).then(function(crsFunction2) {
if (clear2) {
that._entityCollection.removeAll();
}
if (crsFunction2 !== null) {
typeHandler(that, geoJson, geoJson, crsFunction2, options);
}
return Promise.all(that._promises).then(function() {
that._promises.length = 0;
DataSource_default.setLoading(that, false);
return that;
});
});
}
var GeoJsonDataSource_default = GeoJsonDataSource;
// node_modules/autolinker/dist/es2015/version.js
var version = "4.0.0";
// node_modules/autolinker/dist/es2015/utils.js
function isUndefined(value) {
return value === void 0;
}
function isBoolean(value) {
return typeof value === "boolean";
}
function defaults(dest, src) {
for (var prop in src) {
if (src.hasOwnProperty(prop) && isUndefined(dest[prop])) {
dest[prop] = src[prop];
}
}
return dest;
}
function ellipsis(str, truncateLen, ellipsisChars) {
var ellipsisLength;
if (str.length > truncateLen) {
if (ellipsisChars == null) {
ellipsisChars = "…";
ellipsisLength = 3;
} else {
ellipsisLength = ellipsisChars.length;
}
str = str.substring(0, truncateLen - ellipsisLength) + ellipsisChars;
}
return str;
}
function remove2(arr, item) {
for (var i = arr.length - 1; i >= 0; i--) {
if (arr[i] === item) {
arr.splice(i, 1);
}
}
}
function removeWithPredicate(arr, fn) {
for (var i = arr.length - 1; i >= 0; i--) {
if (fn(arr[i]) === true) {
arr.splice(i, 1);
}
}
}
function assertNever(theValue) {
throw new Error("Unhandled case for value: '".concat(theValue, "'"));
}
// node_modules/autolinker/dist/es2015/regex-lib.js
var letterRe = /[A-Za-z]/;
var digitRe = /[\d]/;
var whitespaceRe = /\s/;
var quoteRe = /['"]/;
var controlCharsRe = /[\x00-\x1F\x7F]/;
var alphaCharsStr = /A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC/.source;
var emojiStr = /\u2700-\u27bf\udde6-\uddff\ud800-\udbff\udc00-\udfff\ufe0e\ufe0f\u0300-\u036f\ufe20-\ufe23\u20d0-\u20f0\ud83c\udffb-\udfff\u200d\u3299\u3297\u303d\u3030\u24c2\ud83c\udd70-\udd71\udd7e-\udd7f\udd8e\udd91-\udd9a\udde6-\uddff\ude01-\ude02\ude1a\ude2f\ude32-\ude3a\ude50-\ude51\u203c\u2049\u25aa-\u25ab\u25b6\u25c0\u25fb-\u25fe\u00a9\u00ae\u2122\u2139\udc04\u2600-\u26FF\u2b05\u2b06\u2b07\u2b1b\u2b1c\u2b50\u2b55\u231a\u231b\u2328\u23cf\u23e9-\u23f3\u23f8-\u23fa\udccf\u2935\u2934\u2190-\u21ff/.source;
var marksStr = /\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D4-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F/.source;
var alphaCharsAndMarksStr = alphaCharsStr + emojiStr + marksStr;
var decimalNumbersStr = /0-9\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0BE6-\u0BEF\u0C66-\u0C6F\u0CE6-\u0CEF\u0D66-\u0D6F\u0DE6-\u0DEF\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F29\u1040-\u1049\u1090-\u1099\u17E0-\u17E9\u1810-\u1819\u1946-\u194F\u19D0-\u19D9\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\uA620-\uA629\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uA9F0-\uA9F9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19/.source;
var alphaNumericCharsRe = new RegExp("[".concat(alphaCharsStr + decimalNumbersStr, "]"));
var alphaNumericAndMarksCharsStr = alphaCharsAndMarksStr + decimalNumbersStr;
var alphaNumericAndMarksRe = new RegExp("[".concat(alphaNumericAndMarksCharsStr, "]"));
// node_modules/autolinker/dist/es2015/html-tag.js
var HtmlTag = (
/** @class */
function() {
function HtmlTag2(cfg) {
if (cfg === void 0) {
cfg = {};
}
this.tagName = "";
this.attrs = {};
this.innerHTML = "";
this.tagName = cfg.tagName || "";
this.attrs = cfg.attrs || {};
this.innerHTML = cfg.innerHtml || cfg.innerHTML || "";
}
HtmlTag2.prototype.setTagName = function(tagName) {
this.tagName = tagName;
return this;
};
HtmlTag2.prototype.getTagName = function() {
return this.tagName || "";
};
HtmlTag2.prototype.setAttr = function(attrName, attrValue) {
var tagAttrs = this.getAttrs();
tagAttrs[attrName] = attrValue;
return this;
};
HtmlTag2.prototype.getAttr = function(attrName) {
return this.getAttrs()[attrName];
};
HtmlTag2.prototype.setAttrs = function(attrs) {
Object.assign(this.getAttrs(), attrs);
return this;
};
HtmlTag2.prototype.getAttrs = function() {
return this.attrs || (this.attrs = {});
};
HtmlTag2.prototype.setClass = function(cssClass) {
return this.setAttr("class", cssClass);
};
HtmlTag2.prototype.addClass = function(cssClass) {
var classAttr = this.getClass(), classes = !classAttr ? [] : classAttr.split(whitespaceRe), newClasses = cssClass.split(whitespaceRe), newClass;
while (newClass = newClasses.shift()) {
if (classes.indexOf(newClass) === -1) {
classes.push(newClass);
}
}
this.getAttrs()["class"] = classes.join(" ");
return this;
};
HtmlTag2.prototype.removeClass = function(cssClass) {
var classAttr = this.getClass(), classes = !classAttr ? [] : classAttr.split(whitespaceRe), removeClasses = cssClass.split(whitespaceRe), removeClass;
while (classes.length && (removeClass = removeClasses.shift())) {
var idx = classes.indexOf(removeClass);
if (idx !== -1) {
classes.splice(idx, 1);
}
}
this.getAttrs()["class"] = classes.join(" ");
return this;
};
HtmlTag2.prototype.getClass = function() {
return this.getAttrs()["class"] || "";
};
HtmlTag2.prototype.hasClass = function(cssClass) {
return (" " + this.getClass() + " ").indexOf(" " + cssClass + " ") !== -1;
};
HtmlTag2.prototype.setInnerHTML = function(html) {
this.innerHTML = html;
return this;
};
HtmlTag2.prototype.setInnerHtml = function(html) {
return this.setInnerHTML(html);
};
HtmlTag2.prototype.getInnerHTML = function() {
return this.innerHTML || "";
};
HtmlTag2.prototype.getInnerHtml = function() {
return this.getInnerHTML();
};
HtmlTag2.prototype.toAnchorString = function() {
var tagName = this.getTagName(), attrsStr = this.buildAttrsStr();
attrsStr = attrsStr ? " " + attrsStr : "";
return ["<", tagName, attrsStr, ">", this.getInnerHtml(), "", tagName, ">"].join("");
};
HtmlTag2.prototype.buildAttrsStr = function() {
if (!this.attrs)
return "";
var attrs = this.getAttrs(), attrsArr = [];
for (var prop in attrs) {
if (attrs.hasOwnProperty(prop)) {
attrsArr.push(prop + '="' + attrs[prop] + '"');
}
}
return attrsArr.join(" ");
};
return HtmlTag2;
}()
);
// node_modules/autolinker/dist/es2015/truncate/truncate-smart.js
function truncateSmart(url2, truncateLen, ellipsisChars) {
var ellipsisLengthBeforeParsing;
var ellipsisLength;
if (ellipsisChars == null) {
ellipsisChars = "…";
ellipsisLength = 3;
ellipsisLengthBeforeParsing = 8;
} else {
ellipsisLength = ellipsisChars.length;
ellipsisLengthBeforeParsing = ellipsisChars.length;
}
var parse_url = function(url3) {
var urlObj2 = {};
var urlSub = url3;
var match = urlSub.match(/^([a-z]+):\/\//i);
if (match) {
urlObj2.scheme = match[1];
urlSub = urlSub.substr(match[0].length);
}
match = urlSub.match(/^(.*?)(?=(\?|#|\/|$))/i);
if (match) {
urlObj2.host = match[1];
urlSub = urlSub.substr(match[0].length);
}
match = urlSub.match(/^\/(.*?)(?=(\?|#|$))/i);
if (match) {
urlObj2.path = match[1];
urlSub = urlSub.substr(match[0].length);
}
match = urlSub.match(/^\?(.*?)(?=(#|$))/i);
if (match) {
urlObj2.query = match[1];
urlSub = urlSub.substr(match[0].length);
}
match = urlSub.match(/^#(.*?)$/i);
if (match) {
urlObj2.fragment = match[1];
}
return urlObj2;
};
var buildUrl = function(urlObj2) {
var url3 = "";
if (urlObj2.scheme && urlObj2.host) {
url3 += urlObj2.scheme + "://";
}
if (urlObj2.host) {
url3 += urlObj2.host;
}
if (urlObj2.path) {
url3 += "/" + urlObj2.path;
}
if (urlObj2.query) {
url3 += "?" + urlObj2.query;
}
if (urlObj2.fragment) {
url3 += "#" + urlObj2.fragment;
}
return url3;
};
var buildSegment = function(segment, remainingAvailableLength3) {
var remainingAvailableLengthHalf = remainingAvailableLength3 / 2, startOffset = Math.ceil(remainingAvailableLengthHalf), endOffset = -1 * Math.floor(remainingAvailableLengthHalf), end2 = "";
if (endOffset < 0) {
end2 = segment.substr(endOffset);
}
return segment.substr(0, startOffset) + ellipsisChars + end2;
};
if (url2.length <= truncateLen) {
return url2;
}
var availableLength = truncateLen - ellipsisLength;
var urlObj = parse_url(url2);
if (urlObj.query) {
var matchQuery = urlObj.query.match(/^(.*?)(?=(\?|\#))(.*?)$/i);
if (matchQuery) {
urlObj.query = urlObj.query.substr(0, matchQuery[1].length);
url2 = buildUrl(urlObj);
}
}
if (url2.length <= truncateLen) {
return url2;
}
if (urlObj.host) {
urlObj.host = urlObj.host.replace(/^www\./, "");
url2 = buildUrl(urlObj);
}
if (url2.length <= truncateLen) {
return url2;
}
var str = "";
if (urlObj.host) {
str += urlObj.host;
}
if (str.length >= availableLength) {
if (urlObj.host.length == truncateLen) {
return (urlObj.host.substr(0, truncateLen - ellipsisLength) + ellipsisChars).substr(0, availableLength + ellipsisLengthBeforeParsing);
}
return buildSegment(str, availableLength).substr(0, availableLength + ellipsisLengthBeforeParsing);
}
var pathAndQuery = "";
if (urlObj.path) {
pathAndQuery += "/" + urlObj.path;
}
if (urlObj.query) {
pathAndQuery += "?" + urlObj.query;
}
if (pathAndQuery) {
if ((str + pathAndQuery).length >= availableLength) {
if ((str + pathAndQuery).length == truncateLen) {
return (str + pathAndQuery).substr(0, truncateLen);
}
var remainingAvailableLength = availableLength - str.length;
return (str + buildSegment(pathAndQuery, remainingAvailableLength)).substr(0, availableLength + ellipsisLengthBeforeParsing);
} else {
str += pathAndQuery;
}
}
if (urlObj.fragment) {
var fragment = "#" + urlObj.fragment;
if ((str + fragment).length >= availableLength) {
if ((str + fragment).length == truncateLen) {
return (str + fragment).substr(0, truncateLen);
}
var remainingAvailableLength2 = availableLength - str.length;
return (str + buildSegment(fragment, remainingAvailableLength2)).substr(0, availableLength + ellipsisLengthBeforeParsing);
} else {
str += fragment;
}
}
if (urlObj.scheme && urlObj.host) {
var scheme = urlObj.scheme + "://";
if ((str + scheme).length < availableLength) {
return (scheme + str).substr(0, truncateLen);
}
}
if (str.length <= truncateLen) {
return str;
}
var end = "";
if (availableLength > 0) {
end = str.substr(-1 * Math.floor(availableLength / 2));
}
return (str.substr(0, Math.ceil(availableLength / 2)) + ellipsisChars + end).substr(0, availableLength + ellipsisLengthBeforeParsing);
}
// node_modules/autolinker/dist/es2015/truncate/truncate-middle.js
function truncateMiddle(url2, truncateLen, ellipsisChars) {
if (url2.length <= truncateLen) {
return url2;
}
var ellipsisLengthBeforeParsing;
var ellipsisLength;
if (ellipsisChars == null) {
ellipsisChars = "…";
ellipsisLengthBeforeParsing = 8;
ellipsisLength = 3;
} else {
ellipsisLengthBeforeParsing = ellipsisChars.length;
ellipsisLength = ellipsisChars.length;
}
var availableLength = truncateLen - ellipsisLength;
var end = "";
if (availableLength > 0) {
end = url2.substr(-1 * Math.floor(availableLength / 2));
}
return (url2.substr(0, Math.ceil(availableLength / 2)) + ellipsisChars + end).substr(0, availableLength + ellipsisLengthBeforeParsing);
}
// node_modules/autolinker/dist/es2015/truncate/truncate-end.js
function truncateEnd(anchorText, truncateLen, ellipsisChars) {
return ellipsis(anchorText, truncateLen, ellipsisChars);
}
// node_modules/autolinker/dist/es2015/anchor-tag-builder.js
var AnchorTagBuilder = (
/** @class */
function() {
function AnchorTagBuilder2(cfg) {
if (cfg === void 0) {
cfg = {};
}
this.newWindow = false;
this.truncate = {};
this.className = "";
this.newWindow = cfg.newWindow || false;
this.truncate = cfg.truncate || {};
this.className = cfg.className || "";
}
AnchorTagBuilder2.prototype.build = function(match) {
return new HtmlTag({
tagName: "a",
attrs: this.createAttrs(match),
innerHtml: this.processAnchorText(match.getAnchorText())
});
};
AnchorTagBuilder2.prototype.createAttrs = function(match) {
var attrs = {
href: match.getAnchorHref()
// we'll always have the `href` attribute
};
var cssClass = this.createCssClass(match);
if (cssClass) {
attrs["class"] = cssClass;
}
if (this.newWindow) {
attrs["target"] = "_blank";
attrs["rel"] = "noopener noreferrer";
}
if (this.truncate) {
if (this.truncate.length && this.truncate.length < match.getAnchorText().length) {
attrs["title"] = match.getAnchorHref();
}
}
return attrs;
};
AnchorTagBuilder2.prototype.createCssClass = function(match) {
var className = this.className;
if (!className) {
return "";
} else {
var returnClasses = [className], cssClassSuffixes = match.getCssClassSuffixes();
for (var i = 0, len = cssClassSuffixes.length; i < len; i++) {
returnClasses.push(className + "-" + cssClassSuffixes[i]);
}
return returnClasses.join(" ");
}
};
AnchorTagBuilder2.prototype.processAnchorText = function(anchorText) {
anchorText = this.doTruncate(anchorText);
return anchorText;
};
AnchorTagBuilder2.prototype.doTruncate = function(anchorText) {
var truncate = this.truncate;
if (!truncate || !truncate.length)
return anchorText;
var truncateLength = truncate.length, truncateLocation = truncate.location;
if (truncateLocation === "smart") {
return truncateSmart(anchorText, truncateLength);
} else if (truncateLocation === "middle") {
return truncateMiddle(anchorText, truncateLength);
} else {
return truncateEnd(anchorText, truncateLength);
}
};
return AnchorTagBuilder2;
}()
);
// node_modules/tslib/tslib.es6.js
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
d2.__proto__ = b2;
} || function(d2, b2) {
for (var p in b2)
if (Object.prototype.hasOwnProperty.call(b2, p))
d2[p] = b2[p];
};
return extendStatics(d, b);
};
function __extends(d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign2(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
// node_modules/autolinker/dist/es2015/match/abstract-match.js
var AbstractMatch = (
/** @class */
function() {
function AbstractMatch2(cfg) {
this._ = null;
this.matchedText = "";
this.offset = 0;
this.tagBuilder = cfg.tagBuilder;
this.matchedText = cfg.matchedText;
this.offset = cfg.offset;
}
AbstractMatch2.prototype.getMatchedText = function() {
return this.matchedText;
};
AbstractMatch2.prototype.setOffset = function(offset2) {
this.offset = offset2;
};
AbstractMatch2.prototype.getOffset = function() {
return this.offset;
};
AbstractMatch2.prototype.getCssClassSuffixes = function() {
return [this.type];
};
AbstractMatch2.prototype.buildTag = function() {
return this.tagBuilder.build(this);
};
return AbstractMatch2;
}()
);
// node_modules/autolinker/dist/es2015/parser/tld-regex.js
var tldRegexStr = "(?:xn--vermgensberatung-pwb|xn--vermgensberater-ctb|xn--clchc0ea0b2g2a9gcd|xn--w4r85el8fhu5dnra|northwesternmutual|travelersinsurance|verm\xF6gensberatung|xn--5su34j936bgsg|xn--bck1b9a5dre4c|xn--mgbah1a3hjkrd|xn--mgbai9azgqp6j|xn--mgberp4a5d4ar|xn--xkc2dl3a5ee0h|verm\xF6gensberater|xn--fzys8d69uvgm|xn--mgba7c0bbn0a|xn--mgbcpq6gpa1a|xn--xkc2al3hye2a|americanexpress|kerryproperties|sandvikcoromant|xn--i1b6b1a6a2e|xn--kcrx77d1x4a|xn--lgbbat1ad8j|xn--mgba3a4f16a|xn--mgbaakc7dvf|xn--mgbc0a9azcg|xn--nqv7fs00ema|americanfamily|bananarepublic|cancerresearch|cookingchannel|kerrylogistics|weatherchannel|xn--54b7fta0cc|xn--6qq986b3xl|xn--80aqecdr1a|xn--b4w605ferd|xn--fiq228c5hs|xn--h2breg3eve|xn--jlq480n2rg|xn--jlq61u9w7b|xn--mgba3a3ejt|xn--mgbaam7a8h|xn--mgbayh7gpa|xn--mgbbh1a71e|xn--mgbca7dzdo|xn--mgbi4ecexp|xn--mgbx4cd0ab|xn--rvc1e0am3e|international|lifeinsurance|travelchannel|wolterskluwer|xn--cckwcxetd|xn--eckvdtc9d|xn--fpcrj9c3d|xn--fzc2c9e2c|xn--h2brj9c8c|xn--tiq49xqyj|xn--yfro4i67o|xn--ygbi2ammx|construction|lplfinancial|scholarships|versicherung|xn--3e0b707e|xn--45br5cyl|xn--4dbrk0ce|xn--80adxhks|xn--80asehdb|xn--8y0a063a|xn--gckr3f0f|xn--mgb9awbf|xn--mgbab2bd|xn--mgbgu82a|xn--mgbpl2fh|xn--mgbt3dhd|xn--mk1bu44c|xn--ngbc5azd|xn--ngbe9e0a|xn--ogbpf8fl|xn--qcka1pmc|accountants|barclaycard|blackfriday|blockbuster|bridgestone|calvinklein|contractors|creditunion|engineering|enterprises|foodnetwork|investments|kerryhotels|lamborghini|motorcycles|olayangroup|photography|playstation|productions|progressive|redumbrella|williamhill|xn--11b4c3d|xn--1ck2e1b|xn--1qqw23a|xn--2scrj9c|xn--3bst00m|xn--3ds443g|xn--3hcrj9c|xn--42c2d9a|xn--45brj9c|xn--55qw42g|xn--6frz82g|xn--80ao21a|xn--9krt00a|xn--cck2b3b|xn--czr694b|xn--d1acj3b|xn--efvy88h|xn--fct429k|xn--fjq720a|xn--flw351e|xn--g2xx48c|xn--gecrj9c|xn--gk3at1e|xn--h2brj9c|xn--hxt814e|xn--imr513n|xn--j6w193g|xn--jvr189m|xn--kprw13d|xn--kpry57d|xn--mgbbh1a|xn--mgbtx2b|xn--mix891f|xn--nyqy26a|xn--otu796d|xn--pgbs0dh|xn--q9jyb4c|xn--rhqv96g|xn--rovu88b|xn--s9brj9c|xn--ses554g|xn--t60b56a|xn--vuq861b|xn--w4rs40l|xn--xhq521b|xn--zfr164b|\u0B9A\u0BBF\u0B99\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0BC2\u0BB0\u0BCD|accountant|apartments|associates|basketball|bnpparibas|boehringer|capitalone|consulting|creditcard|cuisinella|eurovision|extraspace|foundation|healthcare|immobilien|industries|management|mitsubishi|nextdirect|properties|protection|prudential|realestate|republican|restaurant|schaeffler|tatamotors|technology|university|vlaanderen|volkswagen|xn--30rr7y|xn--3pxu8k|xn--45q11c|xn--4gbrim|xn--55qx5d|xn--5tzm5g|xn--80aswg|xn--90a3ac|xn--9dbq2a|xn--9et52u|xn--c2br7g|xn--cg4bki|xn--czrs0t|xn--czru2d|xn--fiq64b|xn--fiqs8s|xn--fiqz9s|xn--io0a7i|xn--kput3i|xn--mxtq1m|xn--o3cw4h|xn--pssy2u|xn--q7ce6a|xn--unup4y|xn--wgbh1c|xn--wgbl6a|xn--y9a3aq|accenture|alfaromeo|allfinanz|amsterdam|analytics|aquarelle|barcelona|bloomberg|christmas|community|directory|education|equipment|fairwinds|financial|firestone|fresenius|frontdoor|furniture|goldpoint|hisamitsu|homedepot|homegoods|homesense|institute|insurance|kuokgroup|lancaster|landrover|lifestyle|marketing|marshalls|melbourne|microsoft|panasonic|passagens|pramerica|richardli|shangrila|solutions|statebank|statefarm|stockholm|travelers|vacations|xn--90ais|xn--c1avg|xn--d1alf|xn--e1a4c|xn--fhbei|xn--j1aef|xn--j1amh|xn--l1acc|xn--ngbrx|xn--nqv7f|xn--p1acf|xn--qxa6a|xn--tckwe|xn--vhquv|yodobashi|\u0645\u0648\u0631\u064A\u062A\u0627\u0646\u064A\u0627|abudhabi|airforce|allstate|attorney|barclays|barefoot|bargains|baseball|boutique|bradesco|broadway|brussels|builders|business|capetown|catering|catholic|cipriani|cityeats|cleaning|clinique|clothing|commbank|computer|delivery|deloitte|democrat|diamonds|discount|discover|download|engineer|ericsson|etisalat|exchange|feedback|fidelity|firmdale|football|frontier|goodyear|grainger|graphics|guardian|hdfcbank|helsinki|holdings|hospital|infiniti|ipiranga|istanbul|jpmorgan|lighting|lundbeck|marriott|maserati|mckinsey|memorial|merckmsd|mortgage|observer|partners|pharmacy|pictures|plumbing|property|redstone|reliance|saarland|samsclub|security|services|shopping|showtime|softbank|software|stcgroup|supplies|training|vanguard|ventures|verisign|woodside|xn--90ae|xn--node|xn--p1ai|xn--qxam|yokohama|\u0627\u0644\u0633\u0639\u0648\u062F\u064A\u0629|abogado|academy|agakhan|alibaba|android|athleta|auction|audible|auspost|avianca|banamex|bauhaus|bentley|bestbuy|booking|brother|bugatti|capital|caravan|careers|channel|charity|chintai|citadel|clubmed|college|cologne|comcast|company|compare|contact|cooking|corsica|country|coupons|courses|cricket|cruises|dentist|digital|domains|exposed|express|farmers|fashion|ferrari|ferrero|finance|fishing|fitness|flights|florist|flowers|forsale|frogans|fujitsu|gallery|genting|godaddy|grocery|guitars|hamburg|hangout|hitachi|holiday|hosting|hoteles|hotmail|hyundai|ismaili|jewelry|juniper|kitchen|komatsu|lacaixa|lanxess|lasalle|latrobe|leclerc|limited|lincoln|markets|monster|netbank|netflix|network|neustar|okinawa|oldnavy|organic|origins|philips|pioneer|politie|realtor|recipes|rentals|reviews|rexroth|samsung|sandvik|schmidt|schwarz|science|shiksha|singles|staples|storage|support|surgery|systems|temasek|theater|theatre|tickets|tiffany|toshiba|trading|walmart|wanggou|watches|weather|website|wedding|whoswho|windows|winners|xfinity|yamaxun|youtube|zuerich|\u043A\u0430\u0442\u043E\u043B\u0438\u043A|\u0627\u062A\u0635\u0627\u0644\u0627\u062A|\u0627\u0644\u0628\u062D\u0631\u064A\u0646|\u0627\u0644\u062C\u0632\u0627\u0626\u0631|\u0627\u0644\u0639\u0644\u064A\u0627\u0646|\u067E\u0627\u06A9\u0633\u062A\u0627\u0646|\u0643\u0627\u062B\u0648\u0644\u064A\u0643|\u0B87\u0BA8\u0BCD\u0BA4\u0BBF\u0BAF\u0BBE|abarth|abbott|abbvie|africa|agency|airbus|airtel|alipay|alsace|alstom|amazon|anquan|aramco|author|bayern|beauty|berlin|bharti|bostik|boston|broker|camera|career|casino|center|chanel|chrome|church|circle|claims|clinic|coffee|comsec|condos|coupon|credit|cruise|dating|datsun|dealer|degree|dental|design|direct|doctor|dunlop|dupont|durban|emerck|energy|estate|events|expert|family|flickr|futbol|gallup|garden|george|giving|global|google|gratis|health|hermes|hiphop|hockey|hotels|hughes|imamat|insure|intuit|jaguar|joburg|juegos|kaufen|kinder|kindle|kosher|lancia|latino|lawyer|lefrak|living|locker|london|luxury|madrid|maison|makeup|market|mattel|mobile|monash|mormon|moscow|museum|mutual|nagoya|natura|nissan|nissay|norton|nowruz|office|olayan|online|oracle|orange|otsuka|pfizer|photos|physio|pictet|quebec|racing|realty|reisen|repair|report|review|rocher|rogers|ryukyu|safety|sakura|sanofi|school|schule|search|secure|select|shouji|soccer|social|stream|studio|supply|suzuki|swatch|sydney|taipei|taobao|target|tattoo|tennis|tienda|tjmaxx|tkmaxx|toyota|travel|unicom|viajes|viking|villas|virgin|vision|voting|voyage|vuelos|walter|webcam|xihuan|yachts|yandex|zappos|\u043C\u043E\u0441\u043A\u0432\u0430|\u043E\u043D\u043B\u0430\u0439\u043D|\u0627\u0628\u0648\u0638\u0628\u064A|\u0627\u0631\u0627\u0645\u0643\u0648|\u0627\u0644\u0627\u0631\u062F\u0646|\u0627\u0644\u0645\u063A\u0631\u0628|\u0627\u0645\u0627\u0631\u0627\u062A|\u0641\u0644\u0633\u0637\u064A\u0646|\u0645\u0644\u064A\u0633\u064A\u0627|\u092D\u093E\u0930\u0924\u092E\u094D|\u0B87\u0BB2\u0B99\u0BCD\u0B95\u0BC8|\u30D5\u30A1\u30C3\u30B7\u30E7\u30F3|actor|adult|aetna|amfam|amica|apple|archi|audio|autos|azure|baidu|beats|bible|bingo|black|boats|bosch|build|canon|cards|chase|cheap|cisco|citic|click|cloud|coach|codes|crown|cymru|dabur|dance|deals|delta|drive|dubai|earth|edeka|email|epson|faith|fedex|final|forex|forum|gallo|games|gifts|gives|glass|globo|gmail|green|gripe|group|gucci|guide|homes|honda|horse|house|hyatt|ikano|irish|jetzt|koeln|kyoto|lamer|lease|legal|lexus|lilly|linde|lipsy|loans|locus|lotte|lotto|macys|mango|media|miami|money|movie|music|nexus|nikon|ninja|nokia|nowtv|omega|osaka|paris|parts|party|phone|photo|pizza|place|poker|praxi|press|prime|promo|quest|radio|rehab|reise|ricoh|rocks|rodeo|rugby|salon|sener|seven|sharp|shell|shoes|skype|sling|smart|smile|solar|space|sport|stada|store|study|style|sucks|swiss|tatar|tires|tirol|tmall|today|tokyo|tools|toray|total|tours|trade|trust|tunes|tushu|ubank|vegas|video|vodka|volvo|wales|watch|weber|weibo|works|world|xerox|yahoo|\u05D9\u05E9\u05E8\u05D0\u05DC|\u0627\u06CC\u0631\u0627\u0646|\u0628\u0627\u0632\u0627\u0631|\u0628\u06BE\u0627\u0631\u062A|\u0633\u0648\u062F\u0627\u0646|\u0633\u0648\u0631\u064A\u0629|\u0647\u0645\u0631\u0627\u0647|\u092D\u093E\u0930\u094B\u0924|\u0938\u0902\u0917\u0920\u0928|\u09AC\u09BE\u0982\u09B2\u09BE|\u0C2D\u0C3E\u0C30\u0C24\u0C4D|\u0D2D\u0D3E\u0D30\u0D24\u0D02|\u5609\u91CC\u5927\u9152\u5E97|aarp|able|adac|aero|akdn|ally|amex|arab|army|arpa|arte|asda|asia|audi|auto|baby|band|bank|bbva|beer|best|bike|bing|blog|blue|bofa|bond|book|buzz|cafe|call|camp|care|cars|casa|case|cash|cbre|cern|chat|citi|city|club|cool|coop|cyou|data|date|dclk|deal|dell|desi|diet|dish|docs|dvag|erni|fage|fail|fans|farm|fast|fiat|fido|film|fire|fish|flir|food|ford|free|fund|game|gbiz|gent|ggee|gift|gmbh|gold|golf|goog|guge|guru|hair|haus|hdfc|help|here|hgtv|host|hsbc|icbc|ieee|imdb|immo|info|itau|java|jeep|jobs|jprs|kddi|kids|kiwi|kpmg|kred|land|lego|lgbt|lidl|life|like|limo|link|live|loan|loft|love|ltda|luxe|maif|meet|meme|menu|mini|mint|mobi|moda|moto|name|navy|news|next|nico|nike|ollo|open|page|pars|pccw|pics|ping|pink|play|plus|pohl|porn|post|prod|prof|qpon|read|reit|rent|rest|rich|room|rsvp|ruhr|safe|sale|sarl|save|saxo|scot|seat|seek|sexy|shaw|shia|shop|show|silk|sina|site|skin|sncf|sohu|song|sony|spot|star|surf|talk|taxi|team|tech|teva|tiaa|tips|town|toys|tube|vana|visa|viva|vivo|vote|voto|wang|weir|wien|wiki|wine|work|xbox|yoga|zara|zero|zone|\u0434\u0435\u0442\u0438|\u0441\u0430\u0439\u0442|\u0628\u0627\u0631\u062A|\u0628\u064A\u062A\u0643|\u0680\u0627\u0631\u062A|\u062A\u0648\u0646\u0633|\u0634\u0628\u0643\u0629|\u0639\u0631\u0627\u0642|\u0639\u0645\u0627\u0646|\u0645\u0648\u0642\u0639|\u092D\u093E\u0930\u0924|\u09AD\u09BE\u09B0\u09A4|\u09AD\u09BE\u09F0\u09A4|\u0A2D\u0A3E\u0A30\u0A24|\u0AAD\u0ABE\u0AB0\u0AA4|\u0B2D\u0B3E\u0B30\u0B24|\u0CAD\u0CBE\u0CB0\u0CA4|\u0DBD\u0D82\u0D9A\u0DCF|\u30A2\u30DE\u30BE\u30F3|\u30B0\u30FC\u30B0\u30EB|\u30AF\u30E9\u30A6\u30C9|\u30DD\u30A4\u30F3\u30C8|\u7EC4\u7EC7\u673A\u6784|\u96FB\u8A0A\u76C8\u79D1|\u9999\u683C\u91CC\u62C9|aaa|abb|abc|aco|ads|aeg|afl|aig|anz|aol|app|art|aws|axa|bar|bbc|bbt|bcg|bcn|bet|bid|bio|biz|bms|bmw|bom|boo|bot|box|buy|bzh|cab|cal|cam|car|cat|cba|cbn|cbs|ceo|cfa|cfd|com|cpa|crs|dad|day|dds|dev|dhl|diy|dnp|dog|dot|dtv|dvr|eat|eco|edu|esq|eus|fan|fit|fly|foo|fox|frl|ftr|fun|fyi|gal|gap|gay|gdn|gea|gle|gmo|gmx|goo|gop|got|gov|hbo|hiv|hkt|hot|how|ibm|ice|icu|ifm|inc|ing|ink|int|ist|itv|jcb|jio|jll|jmp|jnj|jot|joy|kfh|kia|kim|kpn|krd|lat|law|lds|llc|llp|lol|lpl|ltd|man|map|mba|med|men|mil|mit|mlb|mls|mma|moe|moi|mom|mov|msd|mtn|mtr|nab|nba|nec|net|new|nfl|ngo|nhk|now|nra|nrw|ntt|nyc|obi|one|ong|onl|ooo|org|ott|ovh|pay|pet|phd|pid|pin|pnc|pro|pru|pub|pwc|red|ren|ril|rio|rip|run|rwe|sap|sas|sbi|sbs|sca|scb|ses|sew|sex|sfr|ski|sky|soy|spa|srl|stc|tab|tax|tci|tdk|tel|thd|tjx|top|trv|tui|tvs|ubs|uno|uol|ups|vet|vig|vin|vip|wed|win|wme|wow|wtc|wtf|xin|xxx|xyz|you|yun|zip|\u0431\u0435\u043B|\u043A\u043E\u043C|\u049B\u0430\u0437|\u043C\u043A\u0434|\u043C\u043E\u043D|\u043E\u0440\u0433|\u0440\u0443\u0441|\u0441\u0440\u0431|\u0443\u043A\u0440|\u0570\u0561\u0575|\u05E7\u05D5\u05DD|\u0639\u0631\u0628|\u0642\u0637\u0631|\u0643\u0648\u0645|\u0645\u0635\u0631|\u0915\u0949\u092E|\u0928\u0947\u091F|\u0E04\u0E2D\u0E21|\u0E44\u0E17\u0E22|\u0EA5\u0EB2\u0EA7|\u30B9\u30C8\u30A2|\u30BB\u30FC\u30EB|\u307F\u3093\u306A|\u4E2D\u6587\u7F51|\u4E9A\u9A6C\u900A|\u5929\u4E3B\u6559|\u6211\u7231\u4F60|\u65B0\u52A0\u5761|\u6DE1\u9A6C\u9521|\u8BFA\u57FA\u4E9A|\u98DE\u5229\u6D66|ac|ad|ae|af|ag|ai|al|am|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cw|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|za|zm|zw|\u03B5\u03BB|\u03B5\u03C5|\u0431\u0433|\u0435\u044E|\u0440\u0444|\u10D2\u10D4|\uB2F7\uB137|\uB2F7\uCEF4|\uC0BC\uC131|\uD55C\uAD6D|\u30B3\u30E0|\u4E16\u754C|\u4E2D\u4FE1|\u4E2D\u56FD|\u4E2D\u570B|\u4F01\u4E1A|\u4F5B\u5C71|\u4FE1\u606F|\u5065\u5EB7|\u516B\u5366|\u516C\u53F8|\u516C\u76CA|\u53F0\u6E7E|\u53F0\u7063|\u5546\u57CE|\u5546\u5E97|\u5546\u6807|\u5609\u91CC|\u5728\u7EBF|\u5927\u62FF|\u5A31\u4E50|\u5BB6\u96FB|\u5E7F\u4E1C|\u5FAE\u535A|\u6148\u5584|\u624B\u673A|\u62DB\u8058|\u653F\u52A1|\u653F\u5E9C|\u65B0\u95FB|\u65F6\u5C1A|\u66F8\u7C4D|\u673A\u6784|\u6E38\u620F|\u6FB3\u9580|\u70B9\u770B|\u79FB\u52A8|\u7F51\u5740|\u7F51\u5E97|\u7F51\u7AD9|\u7F51\u7EDC|\u8054\u901A|\u8C37\u6B4C|\u8D2D\u7269|\u901A\u8CA9|\u96C6\u56E2|\u98DF\u54C1|\u9910\u5385|\u9999\u6E2F)";
var tldRegex = new RegExp("^" + tldRegexStr + "$");
// node_modules/autolinker/dist/es2015/parser/uri-utils.js
var urlSuffixStartCharsRe = /[\/?#]/;
var urlSuffixAllowedSpecialCharsRe = /[-+&@#/%=~_()|'$*\[\]{}\u2713]/;
var urlSuffixNotAllowedAsLastCharRe = /[?!:,.;^]/;
var httpSchemeRe = /https?:\/\//i;
var httpSchemePrefixRe = new RegExp("^" + httpSchemeRe.source, "i");
var urlSuffixedCharsNotAllowedAtEndRe = new RegExp(urlSuffixNotAllowedAsLastCharRe.source + "$");
var invalidSchemeRe = /^(javascript|vbscript):/i;
var schemeUrlRe = /^[A-Za-z][-.+A-Za-z0-9]*:(\/\/)?([^:/]*)/;
var tldUrlHostRe = /^(?:\/\/)?([^/#?:]+)/;
function isSchemeStartChar(char) {
return letterRe.test(char);
}
function isSchemeChar(char) {
return letterRe.test(char) || digitRe.test(char) || char === "+" || char === "-" || char === ".";
}
function isDomainLabelStartChar(char) {
return alphaNumericAndMarksRe.test(char);
}
function isDomainLabelChar(char) {
return char === "_" || isDomainLabelStartChar(char);
}
function isPathChar(char) {
return alphaNumericAndMarksRe.test(char) || urlSuffixAllowedSpecialCharsRe.test(char) || urlSuffixNotAllowedAsLastCharRe.test(char);
}
function isUrlSuffixStartChar(char) {
return urlSuffixStartCharsRe.test(char);
}
function isKnownTld(tld) {
return tldRegex.test(tld.toLowerCase());
}
function isValidSchemeUrl(url2) {
if (invalidSchemeRe.test(url2)) {
return false;
}
var schemeMatch = url2.match(schemeUrlRe);
if (!schemeMatch) {
return false;
}
var isAuthorityMatch = !!schemeMatch[1];
var host = schemeMatch[2];
if (isAuthorityMatch) {
return true;
}
if (host.indexOf(".") === -1 || !letterRe.test(host)) {
return false;
}
return true;
}
function isValidTldMatch(url2) {
var tldUrlHostMatch = url2.match(tldUrlHostRe);
if (!tldUrlHostMatch) {
return false;
}
var host = tldUrlHostMatch[0];
var hostLabels = host.split(".");
if (hostLabels.length < 2) {
return false;
}
var tld = hostLabels[hostLabels.length - 1];
if (!isKnownTld(tld)) {
return false;
}
return true;
}
var ipV4Re = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
var ipV4PartRe = /[:/?#]/;
function isValidIpV4Address(url2) {
var ipV4Part = url2.split(ipV4PartRe, 1)[0];
return ipV4Re.test(ipV4Part);
}
// node_modules/autolinker/dist/es2015/match/url-match.js
var wwwPrefixRegex = /^(https?:\/\/)?(www\.)?/i;
var protocolRelativeRegex = /^\/\//;
var UrlMatch = (
/** @class */
function(_super) {
__extends(UrlMatch2, _super);
function UrlMatch2(cfg) {
var _this = _super.call(this, cfg) || this;
_this.type = "url";
_this.url = "";
_this.urlMatchType = "scheme";
_this.protocolRelativeMatch = false;
_this.stripPrefix = {
scheme: true,
www: true
};
_this.stripTrailingSlash = true;
_this.decodePercentEncoding = true;
_this.protocolPrepended = false;
_this.urlMatchType = cfg.urlMatchType;
_this.url = cfg.url;
_this.protocolRelativeMatch = cfg.protocolRelativeMatch;
_this.stripPrefix = cfg.stripPrefix;
_this.stripTrailingSlash = cfg.stripTrailingSlash;
_this.decodePercentEncoding = cfg.decodePercentEncoding;
return _this;
}
UrlMatch2.prototype.getType = function() {
return "url";
};
UrlMatch2.prototype.getUrlMatchType = function() {
return this.urlMatchType;
};
UrlMatch2.prototype.getUrl = function() {
var url2 = this.url;
if (!this.protocolRelativeMatch && this.urlMatchType !== "scheme" && !this.protocolPrepended) {
url2 = this.url = "http://" + url2;
this.protocolPrepended = true;
}
return url2;
};
UrlMatch2.prototype.getAnchorHref = function() {
var url2 = this.getUrl();
return url2.replace(/&/g, "&");
};
UrlMatch2.prototype.getAnchorText = function() {
var anchorText = this.getMatchedText();
if (this.protocolRelativeMatch) {
anchorText = stripProtocolRelativePrefix(anchorText);
}
if (this.stripPrefix.scheme) {
anchorText = stripSchemePrefix(anchorText);
}
if (this.stripPrefix.www) {
anchorText = stripWwwPrefix(anchorText);
}
if (this.stripTrailingSlash) {
anchorText = removeTrailingSlash(anchorText);
}
if (this.decodePercentEncoding) {
anchorText = removePercentEncoding(anchorText);
}
return anchorText;
};
return UrlMatch2;
}(AbstractMatch)
);
function stripSchemePrefix(url2) {
return url2.replace(httpSchemePrefixRe, "");
}
function stripWwwPrefix(url2) {
return url2.replace(wwwPrefixRegex, "$1");
}
function stripProtocolRelativePrefix(text) {
return text.replace(protocolRelativeRegex, "");
}
function removeTrailingSlash(anchorText) {
if (anchorText.charAt(anchorText.length - 1) === "/") {
anchorText = anchorText.slice(0, -1);
}
return anchorText;
}
function removePercentEncoding(anchorText) {
var preProcessedEntityAnchorText = anchorText.replace(/%22/gi, """).replace(/%26/gi, "&").replace(/%27/gi, "'").replace(/%3C/gi, "<").replace(/%3E/gi, ">");
try {
return decodeURIComponent(preProcessedEntityAnchorText);
} catch (e) {
return preProcessedEntityAnchorText;
}
}
// node_modules/autolinker/dist/es2015/parser/email-utils.js
var mailtoSchemePrefixRe = /^mailto:/i;
var emailLocalPartCharRegex = new RegExp("[".concat(alphaNumericAndMarksCharsStr, "!#$%&'*+/=?^_`{|}~-]"));
function isEmailLocalPartStartChar(char) {
return alphaNumericAndMarksRe.test(char);
}
function isEmailLocalPartChar(char) {
return emailLocalPartCharRegex.test(char);
}
function isValidEmail(emailAddress) {
var emailAddressTld = emailAddress.split(".").pop() || "";
return isKnownTld(emailAddressTld);
}
// node_modules/autolinker/dist/es2015/match/email-match.js
var EmailMatch = (
/** @class */
function(_super) {
__extends(EmailMatch2, _super);
function EmailMatch2(cfg) {
var _this = _super.call(this, cfg) || this;
_this.type = "email";
_this.email = "";
_this.email = cfg.email;
return _this;
}
EmailMatch2.prototype.getType = function() {
return "email";
};
EmailMatch2.prototype.getEmail = function() {
return this.email;
};
EmailMatch2.prototype.getAnchorHref = function() {
return "mailto:" + this.email;
};
EmailMatch2.prototype.getAnchorText = function() {
return this.email;
};
return EmailMatch2;
}(AbstractMatch)
);
// node_modules/autolinker/dist/es2015/parser/hashtag-utils.js
function isHashtagTextChar(char) {
return char === "_" || alphaNumericAndMarksRe.test(char);
}
function isValidHashtag(hashtag) {
return hashtag.length <= 140;
}
var hashtagServices = ["twitter", "facebook", "instagram", "tiktok"];
// node_modules/autolinker/dist/es2015/match/hashtag-match.js
var HashtagMatch = (
/** @class */
function(_super) {
__extends(HashtagMatch2, _super);
function HashtagMatch2(cfg) {
var _this = _super.call(this, cfg) || this;
_this.type = "hashtag";
_this.serviceName = "twitter";
_this.hashtag = "";
_this.serviceName = cfg.serviceName;
_this.hashtag = cfg.hashtag;
return _this;
}
HashtagMatch2.prototype.getType = function() {
return "hashtag";
};
HashtagMatch2.prototype.getServiceName = function() {
return this.serviceName;
};
HashtagMatch2.prototype.getHashtag = function() {
return this.hashtag;
};
HashtagMatch2.prototype.getAnchorHref = function() {
var serviceName = this.serviceName, hashtag = this.hashtag;
switch (serviceName) {
case "twitter":
return "https://twitter.com/hashtag/" + hashtag;
case "facebook":
return "https://www.facebook.com/hashtag/" + hashtag;
case "instagram":
return "https://instagram.com/explore/tags/" + hashtag;
case "tiktok":
return "https://www.tiktok.com/tag/" + hashtag;
default:
assertNever(serviceName);
throw new Error("Invalid hashtag service: ".concat(serviceName));
}
};
HashtagMatch2.prototype.getAnchorText = function() {
return "#" + this.hashtag;
};
HashtagMatch2.prototype.getCssClassSuffixes = function() {
var cssClassSuffixes = _super.prototype.getCssClassSuffixes.call(this), serviceName = this.getServiceName();
if (serviceName) {
cssClassSuffixes.push(serviceName);
}
return cssClassSuffixes;
};
return HashtagMatch2;
}(AbstractMatch)
);
// node_modules/autolinker/dist/es2015/parser/mention-utils.js
var mentionRegexes = {
twitter: /^@\w{1,15}$/,
instagram: /^@[_\w]{1,30}$/,
soundcloud: /^@[-a-z0-9_]{3,25}$/,
// TikTok usernames are 1-24 characters containing letters, numbers, underscores
// and periods, but cannot end in a period: https://support.tiktok.com/en/getting-started/setting-up-your-profile/changing-your-username
tiktok: /^@[.\w]{1,23}[\w]$/
};
var mentionTextCharRe = /[-\w.]/;
function isMentionTextChar(char) {
return mentionTextCharRe.test(char);
}
function isValidMention(mention, serviceName) {
var re = mentionRegexes[serviceName];
return re.test(mention);
}
var mentionServices = ["twitter", "instagram", "soundcloud", "tiktok"];
// node_modules/autolinker/dist/es2015/match/mention-match.js
var MentionMatch = (
/** @class */
function(_super) {
__extends(MentionMatch2, _super);
function MentionMatch2(cfg) {
var _this = _super.call(this, cfg) || this;
_this.type = "mention";
_this.serviceName = "twitter";
_this.mention = "";
_this.mention = cfg.mention;
_this.serviceName = cfg.serviceName;
return _this;
}
MentionMatch2.prototype.getType = function() {
return "mention";
};
MentionMatch2.prototype.getMention = function() {
return this.mention;
};
MentionMatch2.prototype.getServiceName = function() {
return this.serviceName;
};
MentionMatch2.prototype.getAnchorHref = function() {
switch (this.serviceName) {
case "twitter":
return "https://twitter.com/" + this.mention;
case "instagram":
return "https://instagram.com/" + this.mention;
case "soundcloud":
return "https://soundcloud.com/" + this.mention;
case "tiktok":
return "https://www.tiktok.com/@" + this.mention;
default:
throw new Error("Unknown service name to point mention to: " + this.serviceName);
}
};
MentionMatch2.prototype.getAnchorText = function() {
return "@" + this.mention;
};
MentionMatch2.prototype.getCssClassSuffixes = function() {
var cssClassSuffixes = _super.prototype.getCssClassSuffixes.call(this), serviceName = this.getServiceName();
if (serviceName) {
cssClassSuffixes.push(serviceName);
}
return cssClassSuffixes;
};
return MentionMatch2;
}(AbstractMatch)
);
// node_modules/autolinker/dist/es2015/parser/phone-number-utils.js
var separatorCharRe = /[-. ]/;
var hasDelimCharsRe = /[-. ()]/;
var controlCharRe = /[,;]/;
var mostPhoneNumbers = /(?:(?:(?:(\+)?\d{1,3}[-. ]?)?\(?\d{3}\)?[-. ]?\d{3}[-. ]?\d{4})|(?:(\+)(?:9[976]\d|8[987530]\d|6[987]\d|5[90]\d|42\d|3[875]\d|2[98654321]\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|4[987654310]|3[9643210]|2[70]|7|1)[-. ]?(?:\d[-. ]?){6,12}\d+))([,;]+[0-9]+#?)*/;
var japanesePhoneRe = /(0([1-9]-?[1-9]\d{3}|[1-9]{2}-?\d{3}|[1-9]{2}\d{1}-?\d{2}|[1-9]{2}\d{2}-?\d{1})-?\d{4}|0[789]0-?\d{4}-?\d{4}|050-?\d{4}-?\d{4})/;
var validPhoneNumberRe = new RegExp("^".concat(mostPhoneNumbers.source, "|").concat(japanesePhoneRe.source, "$"));
function isPhoneNumberSeparatorChar(char) {
return separatorCharRe.test(char);
}
function isPhoneNumberControlChar(char) {
return controlCharRe.test(char);
}
function isValidPhoneNumber(phoneNumberText) {
var hasDelimiters = phoneNumberText.charAt(0) === "+" || hasDelimCharsRe.test(phoneNumberText);
return hasDelimiters && validPhoneNumberRe.test(phoneNumberText);
}
// node_modules/autolinker/dist/es2015/match/phone-match.js
var PhoneMatch = (
/** @class */
function(_super) {
__extends(PhoneMatch2, _super);
function PhoneMatch2(cfg) {
var _this = _super.call(this, cfg) || this;
_this.type = "phone";
_this.number = "";
_this.plusSign = false;
_this.number = cfg.number;
_this.plusSign = cfg.plusSign;
return _this;
}
PhoneMatch2.prototype.getType = function() {
return "phone";
};
PhoneMatch2.prototype.getPhoneNumber = function() {
return this.number;
};
PhoneMatch2.prototype.getNumber = function() {
return this.getPhoneNumber();
};
PhoneMatch2.prototype.getAnchorHref = function() {
return "tel:" + (this.plusSign ? "+" : "") + this.number;
};
PhoneMatch2.prototype.getAnchorText = function() {
return this.matchedText;
};
return PhoneMatch2;
}(AbstractMatch)
);
// node_modules/autolinker/dist/es2015/parser/parse-matches.js
function parseMatches(text, args) {
var tagBuilder = args.tagBuilder;
var stripPrefix = args.stripPrefix;
var stripTrailingSlash = args.stripTrailingSlash;
var decodePercentEncoding = args.decodePercentEncoding;
var hashtagServiceName = args.hashtagServiceName;
var mentionServiceName = args.mentionServiceName;
var matches = [];
var textLen = text.length;
var stateMachines = [];
var charIdx = 0;
for (; charIdx < textLen; charIdx++) {
var char = text.charAt(charIdx);
if (stateMachines.length === 0) {
stateNoMatch(char);
} else {
for (var stateIdx = stateMachines.length - 1; stateIdx >= 0; stateIdx--) {
var stateMachine = stateMachines[stateIdx];
switch (stateMachine.state) {
case 11:
stateProtocolRelativeSlash1(stateMachine, char);
break;
case 12:
stateProtocolRelativeSlash2(stateMachine, char);
break;
case 0:
stateSchemeChar(stateMachine, char);
break;
case 1:
stateSchemeHyphen(stateMachine, char);
break;
case 2:
stateSchemeColon(stateMachine, char);
break;
case 3:
stateSchemeSlash1(stateMachine, char);
break;
case 4:
stateSchemeSlash2(stateMachine, char);
break;
case 5:
stateDomainLabelChar(stateMachine, char);
break;
case 6:
stateDomainHyphen(stateMachine, char);
break;
case 7:
stateDomainDot(stateMachine, char);
break;
case 13:
stateIpV4Digit(stateMachine, char);
break;
case 14:
stateIPv4Dot(stateMachine, char);
break;
case 8:
statePortColon(stateMachine, char);
break;
case 9:
statePortNumber(stateMachine, char);
break;
case 10:
statePath(stateMachine, char);
break;
case 15:
stateEmailMailto_M(stateMachine, char);
break;
case 16:
stateEmailMailto_A(stateMachine, char);
break;
case 17:
stateEmailMailto_I(stateMachine, char);
break;
case 18:
stateEmailMailto_L(stateMachine, char);
break;
case 19:
stateEmailMailto_T(stateMachine, char);
break;
case 20:
stateEmailMailto_O(stateMachine, char);
break;
case 21:
stateEmailMailtoColon(stateMachine, char);
break;
case 22:
stateEmailLocalPart(stateMachine, char);
break;
case 23:
stateEmailLocalPartDot(stateMachine, char);
break;
case 24:
stateEmailAtSign(stateMachine, char);
break;
case 25:
stateEmailDomainChar(stateMachine, char);
break;
case 26:
stateEmailDomainHyphen(stateMachine, char);
break;
case 27:
stateEmailDomainDot(stateMachine, char);
break;
case 28:
stateHashtagHashChar(stateMachine, char);
break;
case 29:
stateHashtagTextChar(stateMachine, char);
break;
case 30:
stateMentionAtChar(stateMachine, char);
break;
case 31:
stateMentionTextChar(stateMachine, char);
break;
case 32:
statePhoneNumberOpenParen(stateMachine, char);
break;
case 33:
statePhoneNumberAreaCodeDigit1(stateMachine, char);
break;
case 34:
statePhoneNumberAreaCodeDigit2(stateMachine, char);
break;
case 35:
statePhoneNumberAreaCodeDigit3(stateMachine, char);
break;
case 36:
statePhoneNumberCloseParen(stateMachine, char);
break;
case 37:
statePhoneNumberPlus(stateMachine, char);
break;
case 38:
statePhoneNumberDigit(stateMachine, char);
break;
case 39:
statePhoneNumberSeparator(stateMachine, char);
break;
case 40:
statePhoneNumberControlChar(stateMachine, char);
break;
case 41:
statePhoneNumberPoundChar(stateMachine, char);
break;
default:
assertNever(stateMachine.state);
}
}
}
}
for (var i = stateMachines.length - 1; i >= 0; i--) {
stateMachines.forEach(function(stateMachine2) {
return captureMatchIfValidAndRemove(stateMachine2);
});
}
return matches;
function stateNoMatch(char2) {
if (char2 === "#") {
stateMachines.push(createHashtagStateMachine(
charIdx,
28
/* HashtagHashChar */
));
} else if (char2 === "@") {
stateMachines.push(createMentionStateMachine(
charIdx,
30
/* MentionAtChar */
));
} else if (char2 === "/") {
stateMachines.push(createTldUrlStateMachine(
charIdx,
11
/* ProtocolRelativeSlash1 */
));
} else if (char2 === "+") {
stateMachines.push(createPhoneNumberStateMachine(
charIdx,
37
/* PhoneNumberPlus */
));
} else if (char2 === "(") {
stateMachines.push(createPhoneNumberStateMachine(
charIdx,
32
/* PhoneNumberOpenParen */
));
} else {
if (digitRe.test(char2)) {
stateMachines.push(createPhoneNumberStateMachine(
charIdx,
38
/* PhoneNumberDigit */
));
stateMachines.push(createIpV4UrlStateMachine(
charIdx,
13
/* IpV4Digit */
));
}
if (isEmailLocalPartStartChar(char2)) {
var startState = char2.toLowerCase() === "m" ? 15 : 22;
stateMachines.push(createEmailStateMachine(charIdx, startState));
}
if (isSchemeStartChar(char2)) {
stateMachines.push(createSchemeUrlStateMachine(
charIdx,
0
/* SchemeChar */
));
}
if (alphaNumericAndMarksRe.test(char2)) {
stateMachines.push(createTldUrlStateMachine(
charIdx,
5
/* DomainLabelChar */
));
}
}
}
function stateSchemeChar(stateMachine2, char2) {
if (char2 === ":") {
stateMachine2.state = 2;
} else if (char2 === "-") {
stateMachine2.state = 1;
} else if (isSchemeChar(char2)) {
} else {
remove2(stateMachines, stateMachine2);
}
}
function stateSchemeHyphen(stateMachine2, char2) {
if (char2 === "-") {
} else if (char2 === "/") {
remove2(stateMachines, stateMachine2);
stateMachines.push(createTldUrlStateMachine(
charIdx,
11
/* ProtocolRelativeSlash1 */
));
} else if (isSchemeChar(char2)) {
stateMachine2.state = 0;
} else {
remove2(stateMachines, stateMachine2);
}
}
function stateSchemeColon(stateMachine2, char2) {
if (char2 === "/") {
stateMachine2.state = 3;
} else if (char2 === ".") {
remove2(stateMachines, stateMachine2);
} else if (isDomainLabelStartChar(char2)) {
stateMachine2.state = 5;
if (isSchemeStartChar(char2)) {
stateMachines.push(createSchemeUrlStateMachine(
charIdx,
0
/* SchemeChar */
));
}
} else {
remove2(stateMachines, stateMachine2);
}
}
function stateSchemeSlash1(stateMachine2, char2) {
if (char2 === "/") {
stateMachine2.state = 4;
} else if (isPathChar(char2)) {
stateMachine2.state = 10;
stateMachine2.acceptStateReached = true;
} else {
captureMatchIfValidAndRemove(stateMachine2);
}
}
function stateSchemeSlash2(stateMachine2, char2) {
if (char2 === "/") {
stateMachine2.state = 10;
} else if (isDomainLabelStartChar(char2)) {
stateMachine2.state = 5;
stateMachine2.acceptStateReached = true;
} else {
remove2(stateMachines, stateMachine2);
}
}
function stateProtocolRelativeSlash1(stateMachine2, char2) {
if (char2 === "/") {
stateMachine2.state = 12;
} else {
remove2(stateMachines, stateMachine2);
}
}
function stateProtocolRelativeSlash2(stateMachine2, char2) {
if (isDomainLabelStartChar(char2)) {
stateMachine2.state = 5;
} else {
remove2(stateMachines, stateMachine2);
}
}
function stateDomainLabelChar(stateMachine2, char2) {
if (char2 === ".") {
stateMachine2.state = 7;
} else if (char2 === "-") {
stateMachine2.state = 6;
} else if (char2 === ":") {
stateMachine2.state = 8;
} else if (isUrlSuffixStartChar(char2)) {
stateMachine2.state = 10;
} else if (isDomainLabelChar(char2)) {
} else {
captureMatchIfValidAndRemove(stateMachine2);
}
}
function stateDomainHyphen(stateMachine2, char2) {
if (char2 === "-") {
} else if (char2 === ".") {
captureMatchIfValidAndRemove(stateMachine2);
} else if (isDomainLabelStartChar(char2)) {
stateMachine2.state = 5;
} else {
captureMatchIfValidAndRemove(stateMachine2);
}
}
function stateDomainDot(stateMachine2, char2) {
if (char2 === ".") {
captureMatchIfValidAndRemove(stateMachine2);
} else if (isDomainLabelStartChar(char2)) {
stateMachine2.state = 5;
stateMachine2.acceptStateReached = true;
} else {
captureMatchIfValidAndRemove(stateMachine2);
}
}
function stateIpV4Digit(stateMachine2, char2) {
if (char2 === ".") {
stateMachine2.state = 14;
} else if (char2 === ":") {
stateMachine2.state = 8;
} else if (digitRe.test(char2)) {
} else if (isUrlSuffixStartChar(char2)) {
stateMachine2.state = 10;
} else if (alphaNumericAndMarksRe.test(char2)) {
remove2(stateMachines, stateMachine2);
} else {
captureMatchIfValidAndRemove(stateMachine2);
}
}
function stateIPv4Dot(stateMachine2, char2) {
if (digitRe.test(char2)) {
stateMachine2.octetsEncountered++;
if (stateMachine2.octetsEncountered === 4) {
stateMachine2.acceptStateReached = true;
}
stateMachine2.state = 13;
} else {
captureMatchIfValidAndRemove(stateMachine2);
}
}
function statePortColon(stateMachine2, char2) {
if (digitRe.test(char2)) {
stateMachine2.state = 9;
} else {
captureMatchIfValidAndRemove(stateMachine2);
}
}
function statePortNumber(stateMachine2, char2) {
if (digitRe.test(char2)) {
} else if (isUrlSuffixStartChar(char2)) {
stateMachine2.state = 10;
} else {
captureMatchIfValidAndRemove(stateMachine2);
}
}
function statePath(stateMachine2, char2) {
if (isPathChar(char2)) {
} else {
captureMatchIfValidAndRemove(stateMachine2);
}
}
function stateEmailMailto_M(stateMachine2, char2) {
if (char2.toLowerCase() === "a") {
stateMachine2.state = 16;
} else {
stateEmailLocalPart(stateMachine2, char2);
}
}
function stateEmailMailto_A(stateMachine2, char2) {
if (char2.toLowerCase() === "i") {
stateMachine2.state = 17;
} else {
stateEmailLocalPart(stateMachine2, char2);
}
}
function stateEmailMailto_I(stateMachine2, char2) {
if (char2.toLowerCase() === "l") {
stateMachine2.state = 18;
} else {
stateEmailLocalPart(stateMachine2, char2);
}
}
function stateEmailMailto_L(stateMachine2, char2) {
if (char2.toLowerCase() === "t") {
stateMachine2.state = 19;
} else {
stateEmailLocalPart(stateMachine2, char2);
}
}
function stateEmailMailto_T(stateMachine2, char2) {
if (char2.toLowerCase() === "o") {
stateMachine2.state = 20;
} else {
stateEmailLocalPart(stateMachine2, char2);
}
}
function stateEmailMailto_O(stateMachine2, char2) {
if (char2.toLowerCase() === ":") {
stateMachine2.state = 21;
} else {
stateEmailLocalPart(stateMachine2, char2);
}
}
function stateEmailMailtoColon(stateMachine2, char2) {
if (isEmailLocalPartChar(char2)) {
stateMachine2.state = 22;
} else {
remove2(stateMachines, stateMachine2);
}
}
function stateEmailLocalPart(stateMachine2, char2) {
if (char2 === ".") {
stateMachine2.state = 23;
} else if (char2 === "@") {
stateMachine2.state = 24;
} else if (isEmailLocalPartChar(char2)) {
stateMachine2.state = 22;
} else {
remove2(stateMachines, stateMachine2);
}
}
function stateEmailLocalPartDot(stateMachine2, char2) {
if (char2 === ".") {
remove2(stateMachines, stateMachine2);
} else if (char2 === "@") {
remove2(stateMachines, stateMachine2);
} else if (isEmailLocalPartChar(char2)) {
stateMachine2.state = 22;
} else {
remove2(stateMachines, stateMachine2);
}
}
function stateEmailAtSign(stateMachine2, char2) {
if (isDomainLabelStartChar(char2)) {
stateMachine2.state = 25;
} else {
remove2(stateMachines, stateMachine2);
}
}
function stateEmailDomainChar(stateMachine2, char2) {
if (char2 === ".") {
stateMachine2.state = 27;
} else if (char2 === "-") {
stateMachine2.state = 26;
} else if (isDomainLabelChar(char2)) {
} else {
captureMatchIfValidAndRemove(stateMachine2);
}
}
function stateEmailDomainHyphen(stateMachine2, char2) {
if (char2 === "-" || char2 === ".") {
captureMatchIfValidAndRemove(stateMachine2);
} else if (isDomainLabelChar(char2)) {
stateMachine2.state = 25;
} else {
captureMatchIfValidAndRemove(stateMachine2);
}
}
function stateEmailDomainDot(stateMachine2, char2) {
if (char2 === "." || char2 === "-") {
captureMatchIfValidAndRemove(stateMachine2);
} else if (isDomainLabelStartChar(char2)) {
stateMachine2.state = 25;
stateMachine2.acceptStateReached = true;
} else {
captureMatchIfValidAndRemove(stateMachine2);
}
}
function stateHashtagHashChar(stateMachine2, char2) {
if (isHashtagTextChar(char2)) {
stateMachine2.state = 29;
stateMachine2.acceptStateReached = true;
} else {
remove2(stateMachines, stateMachine2);
}
}
function stateHashtagTextChar(stateMachine2, char2) {
if (isHashtagTextChar(char2)) {
} else {
captureMatchIfValidAndRemove(stateMachine2);
}
}
function stateMentionAtChar(stateMachine2, char2) {
if (isMentionTextChar(char2)) {
stateMachine2.state = 31;
stateMachine2.acceptStateReached = true;
} else {
remove2(stateMachines, stateMachine2);
}
}
function stateMentionTextChar(stateMachine2, char2) {
if (isMentionTextChar(char2)) {
} else if (alphaNumericAndMarksRe.test(char2)) {
remove2(stateMachines, stateMachine2);
} else {
captureMatchIfValidAndRemove(stateMachine2);
}
}
function statePhoneNumberPlus(stateMachine2, char2) {
if (digitRe.test(char2)) {
stateMachine2.state = 38;
} else {
remove2(stateMachines, stateMachine2);
stateNoMatch(char2);
}
}
function statePhoneNumberOpenParen(stateMachine2, char2) {
if (digitRe.test(char2)) {
stateMachine2.state = 33;
} else {
remove2(stateMachines, stateMachine2);
}
stateNoMatch(char2);
}
function statePhoneNumberAreaCodeDigit1(stateMachine2, char2) {
if (digitRe.test(char2)) {
stateMachine2.state = 34;
} else {
remove2(stateMachines, stateMachine2);
}
}
function statePhoneNumberAreaCodeDigit2(stateMachine2, char2) {
if (digitRe.test(char2)) {
stateMachine2.state = 35;
} else {
remove2(stateMachines, stateMachine2);
}
}
function statePhoneNumberAreaCodeDigit3(stateMachine2, char2) {
if (char2 === ")") {
stateMachine2.state = 36;
} else {
remove2(stateMachines, stateMachine2);
}
}
function statePhoneNumberCloseParen(stateMachine2, char2) {
if (digitRe.test(char2)) {
stateMachine2.state = 38;
} else if (isPhoneNumberSeparatorChar(char2)) {
stateMachine2.state = 39;
} else {
remove2(stateMachines, stateMachine2);
}
}
function statePhoneNumberDigit(stateMachine2, char2) {
stateMachine2.acceptStateReached = true;
if (isPhoneNumberControlChar(char2)) {
stateMachine2.state = 40;
} else if (char2 === "#") {
stateMachine2.state = 41;
} else if (digitRe.test(char2)) {
} else if (char2 === "(") {
stateMachine2.state = 32;
} else if (isPhoneNumberSeparatorChar(char2)) {
stateMachine2.state = 39;
} else {
captureMatchIfValidAndRemove(stateMachine2);
if (isSchemeStartChar(char2)) {
stateMachines.push(createSchemeUrlStateMachine(
charIdx,
0
/* SchemeChar */
));
}
}
}
function statePhoneNumberSeparator(stateMachine2, char2) {
if (digitRe.test(char2)) {
stateMachine2.state = 38;
} else if (char2 === "(") {
stateMachine2.state = 32;
} else {
captureMatchIfValidAndRemove(stateMachine2);
stateNoMatch(char2);
}
}
function statePhoneNumberControlChar(stateMachine2, char2) {
if (isPhoneNumberControlChar(char2)) {
} else if (char2 === "#") {
stateMachine2.state = 41;
} else if (digitRe.test(char2)) {
stateMachine2.state = 38;
} else {
captureMatchIfValidAndRemove(stateMachine2);
}
}
function statePhoneNumberPoundChar(stateMachine2, char2) {
if (isPhoneNumberControlChar(char2)) {
stateMachine2.state = 40;
} else if (digitRe.test(char2)) {
remove2(stateMachines, stateMachine2);
} else {
captureMatchIfValidAndRemove(stateMachine2);
}
}
function captureMatchIfValidAndRemove(stateMachine2) {
remove2(stateMachines, stateMachine2);
if (!stateMachine2.acceptStateReached) {
return;
}
var startIdx = stateMachine2.startIdx;
var matchedText = text.slice(stateMachine2.startIdx, charIdx);
matchedText = excludeUnbalancedTrailingBracesAndPunctuation(matchedText);
if (stateMachine2.type === "url") {
var charBeforeUrlMatch = text.charAt(stateMachine2.startIdx - 1);
if (charBeforeUrlMatch === "@") {
return;
}
var urlMatchType = stateMachine2.matchType;
if (urlMatchType === "scheme") {
var httpSchemeMatch = httpSchemeRe.exec(matchedText);
if (httpSchemeMatch) {
startIdx = startIdx + httpSchemeMatch.index;
matchedText = matchedText.slice(httpSchemeMatch.index);
}
if (!isValidSchemeUrl(matchedText)) {
return;
}
} else if (urlMatchType === "tld") {
if (!isValidTldMatch(matchedText)) {
return;
}
} else if (urlMatchType === "ipV4") {
if (!isValidIpV4Address(matchedText)) {
return;
}
} else {
assertNever(urlMatchType);
}
matches.push(new UrlMatch({
tagBuilder,
matchedText,
offset: startIdx,
urlMatchType,
url: matchedText,
protocolRelativeMatch: matchedText.slice(0, 2) === "//",
// TODO: Do these settings need to be passed to the match,
// or should we handle them here in UrlMatcher?
stripPrefix,
stripTrailingSlash,
decodePercentEncoding
}));
} else if (stateMachine2.type === "email") {
if (isValidEmail(matchedText)) {
matches.push(new EmailMatch({
tagBuilder,
matchedText,
offset: startIdx,
email: matchedText.replace(mailtoSchemePrefixRe, "")
}));
}
} else if (stateMachine2.type === "hashtag") {
if (isValidHashtag(matchedText)) {
matches.push(new HashtagMatch({
tagBuilder,
matchedText,
offset: startIdx,
serviceName: hashtagServiceName,
hashtag: matchedText.slice(1)
}));
}
} else if (stateMachine2.type === "mention") {
if (isValidMention(matchedText, mentionServiceName)) {
matches.push(new MentionMatch({
tagBuilder,
matchedText,
offset: startIdx,
serviceName: mentionServiceName,
mention: matchedText.slice(1)
// strip off the '@' character at the beginning
}));
}
} else if (stateMachine2.type === "phone") {
matchedText = matchedText.replace(/ +$/g, "");
if (isValidPhoneNumber(matchedText)) {
var cleanNumber = matchedText.replace(/[^0-9,;#]/g, "");
matches.push(new PhoneMatch({
tagBuilder,
matchedText,
offset: startIdx,
number: cleanNumber,
plusSign: matchedText.charAt(0) === "+"
}));
}
} else {
assertNever(stateMachine2);
}
}
}
var openBraceRe = /[\(\{\[]/;
var closeBraceRe = /[\)\}\]]/;
var oppositeBrace = {
")": "(",
"}": "{",
"]": "["
};
function excludeUnbalancedTrailingBracesAndPunctuation(matchedText) {
var braceCounts = {
"(": 0,
"{": 0,
"[": 0
};
for (var i = 0; i < matchedText.length; i++) {
var char_1 = matchedText.charAt(i);
if (openBraceRe.test(char_1)) {
braceCounts[char_1]++;
} else if (closeBraceRe.test(char_1)) {
braceCounts[oppositeBrace[char_1]]--;
}
}
var endIdx = matchedText.length - 1;
var char;
while (endIdx >= 0) {
char = matchedText.charAt(endIdx);
if (closeBraceRe.test(char)) {
var oppositeBraceChar = oppositeBrace[char];
if (braceCounts[oppositeBraceChar] < 0) {
braceCounts[oppositeBraceChar]++;
endIdx--;
} else {
break;
}
} else if (urlSuffixedCharsNotAllowedAtEndRe.test(char)) {
endIdx--;
} else {
break;
}
}
return matchedText.slice(0, endIdx + 1);
}
function createSchemeUrlStateMachine(startIdx, state) {
return {
type: "url",
startIdx,
state,
acceptStateReached: false,
matchType: "scheme"
};
}
function createTldUrlStateMachine(startIdx, state) {
return {
type: "url",
startIdx,
state,
acceptStateReached: false,
matchType: "tld"
};
}
function createIpV4UrlStateMachine(startIdx, state) {
return {
type: "url",
startIdx,
state,
acceptStateReached: false,
matchType: "ipV4",
octetsEncountered: 1
// starts at 1 because we create this machine when encountering the first octet
};
}
function createEmailStateMachine(startIdx, state) {
return {
type: "email",
startIdx,
state,
acceptStateReached: false
};
}
function createHashtagStateMachine(startIdx, state) {
return {
type: "hashtag",
startIdx,
state,
acceptStateReached: false
};
}
function createMentionStateMachine(startIdx, state) {
return {
type: "mention",
startIdx,
state,
acceptStateReached: false
};
}
function createPhoneNumberStateMachine(startIdx, state) {
return {
type: "phone",
startIdx,
state,
acceptStateReached: false
};
}
// node_modules/autolinker/dist/es2015/htmlParser/parse-html.js
function parseHtml(html, _a) {
var onOpenTag = _a.onOpenTag, onCloseTag = _a.onCloseTag, onText = _a.onText, onComment = _a.onComment, onDoctype = _a.onDoctype;
var noCurrentTag = new CurrentTag();
var charIdx = 0, len = html.length, state = 0, currentDataIdx = 0, currentTag = noCurrentTag;
while (charIdx < len) {
var char = html.charAt(charIdx);
switch (state) {
case 0:
stateData(char);
break;
case 1:
stateTagOpen(char);
break;
case 2:
stateEndTagOpen(char);
break;
case 3:
stateTagName(char);
break;
case 4:
stateBeforeAttributeName(char);
break;
case 5:
stateAttributeName(char);
break;
case 6:
stateAfterAttributeName(char);
break;
case 7:
stateBeforeAttributeValue(char);
break;
case 8:
stateAttributeValueDoubleQuoted(char);
break;
case 9:
stateAttributeValueSingleQuoted(char);
break;
case 10:
stateAttributeValueUnquoted(char);
break;
case 11:
stateAfterAttributeValueQuoted(char);
break;
case 12:
stateSelfClosingStartTag(char);
break;
case 13:
stateMarkupDeclarationOpen(char);
break;
case 14:
stateCommentStart(char);
break;
case 15:
stateCommentStartDash(char);
break;
case 16:
stateComment(char);
break;
case 17:
stateCommentEndDash(char);
break;
case 18:
stateCommentEnd(char);
break;
case 19:
stateCommentEndBang(char);
break;
case 20:
stateDoctype(char);
break;
default:
assertNever(state);
}
charIdx++;
}
if (currentDataIdx < charIdx) {
emitText();
}
function stateData(char2) {
if (char2 === "<") {
startNewTag();
}
}
function stateTagOpen(char2) {
if (char2 === "!") {
state = 13;
} else if (char2 === "/") {
state = 2;
currentTag = new CurrentTag(__assign(__assign({}, currentTag), { isClosing: true }));
} else if (char2 === "<") {
startNewTag();
} else if (letterRe.test(char2)) {
state = 3;
currentTag = new CurrentTag(__assign(__assign({}, currentTag), { isOpening: true }));
} else {
state = 0;
currentTag = noCurrentTag;
}
}
function stateTagName(char2) {
if (whitespaceRe.test(char2)) {
currentTag = new CurrentTag(__assign(__assign({}, currentTag), { name: captureTagName() }));
state = 4;
} else if (char2 === "<") {
startNewTag();
} else if (char2 === "/") {
currentTag = new CurrentTag(__assign(__assign({}, currentTag), { name: captureTagName() }));
state = 12;
} else if (char2 === ">") {
currentTag = new CurrentTag(__assign(__assign({}, currentTag), { name: captureTagName() }));
emitTagAndPreviousTextNode();
} else if (!letterRe.test(char2) && !digitRe.test(char2) && char2 !== ":") {
resetToDataState();
} else {
}
}
function stateEndTagOpen(char2) {
if (char2 === ">") {
resetToDataState();
} else if (letterRe.test(char2)) {
state = 3;
} else {
resetToDataState();
}
}
function stateBeforeAttributeName(char2) {
if (whitespaceRe.test(char2)) {
} else if (char2 === "/") {
state = 12;
} else if (char2 === ">") {
emitTagAndPreviousTextNode();
} else if (char2 === "<") {
startNewTag();
} else if (char2 === "=" || quoteRe.test(char2) || controlCharsRe.test(char2)) {
resetToDataState();
} else {
state = 5;
}
}
function stateAttributeName(char2) {
if (whitespaceRe.test(char2)) {
state = 6;
} else if (char2 === "/") {
state = 12;
} else if (char2 === "=") {
state = 7;
} else if (char2 === ">") {
emitTagAndPreviousTextNode();
} else if (char2 === "<") {
startNewTag();
} else if (quoteRe.test(char2)) {
resetToDataState();
} else {
}
}
function stateAfterAttributeName(char2) {
if (whitespaceRe.test(char2)) {
} else if (char2 === "/") {
state = 12;
} else if (char2 === "=") {
state = 7;
} else if (char2 === ">") {
emitTagAndPreviousTextNode();
} else if (char2 === "<") {
startNewTag();
} else if (quoteRe.test(char2)) {
resetToDataState();
} else {
state = 5;
}
}
function stateBeforeAttributeValue(char2) {
if (whitespaceRe.test(char2)) {
} else if (char2 === '"') {
state = 8;
} else if (char2 === "'") {
state = 9;
} else if (/[>=`]/.test(char2)) {
resetToDataState();
} else if (char2 === "<") {
startNewTag();
} else {
state = 10;
}
}
function stateAttributeValueDoubleQuoted(char2) {
if (char2 === '"') {
state = 11;
} else {
}
}
function stateAttributeValueSingleQuoted(char2) {
if (char2 === "'") {
state = 11;
} else {
}
}
function stateAttributeValueUnquoted(char2) {
if (whitespaceRe.test(char2)) {
state = 4;
} else if (char2 === ">") {
emitTagAndPreviousTextNode();
} else if (char2 === "<") {
startNewTag();
} else {
}
}
function stateAfterAttributeValueQuoted(char2) {
if (whitespaceRe.test(char2)) {
state = 4;
} else if (char2 === "/") {
state = 12;
} else if (char2 === ">") {
emitTagAndPreviousTextNode();
} else if (char2 === "<") {
startNewTag();
} else {
state = 4;
reconsumeCurrentCharacter();
}
}
function stateSelfClosingStartTag(char2) {
if (char2 === ">") {
currentTag = new CurrentTag(__assign(__assign({}, currentTag), { isClosing: true }));
emitTagAndPreviousTextNode();
} else {
state = 4;
}
}
function stateMarkupDeclarationOpen(char2) {
if (html.substr(charIdx, 2) === "--") {
charIdx += 2;
currentTag = new CurrentTag(__assign(__assign({}, currentTag), { type: "comment" }));
state = 14;
} else if (html.substr(charIdx, 7).toUpperCase() === "DOCTYPE") {
charIdx += 7;
currentTag = new CurrentTag(__assign(__assign({}, currentTag), { type: "doctype" }));
state = 20;
} else {
resetToDataState();
}
}
function stateCommentStart(char2) {
if (char2 === "-") {
state = 15;
} else if (char2 === ">") {
resetToDataState();
} else {
state = 16;
}
}
function stateCommentStartDash(char2) {
if (char2 === "-") {
state = 18;
} else if (char2 === ">") {
resetToDataState();
} else {
state = 16;
}
}
function stateComment(char2) {
if (char2 === "-") {
state = 17;
} else {
}
}
function stateCommentEndDash(char2) {
if (char2 === "-") {
state = 18;
} else {
state = 16;
}
}
function stateCommentEnd(char2) {
if (char2 === ">") {
emitTagAndPreviousTextNode();
} else if (char2 === "!") {
state = 19;
} else if (char2 === "-") {
} else {
state = 16;
}
}
function stateCommentEndBang(char2) {
if (char2 === "-") {
state = 17;
} else if (char2 === ">") {
emitTagAndPreviousTextNode();
} else {
state = 16;
}
}
function stateDoctype(char2) {
if (char2 === ">") {
emitTagAndPreviousTextNode();
} else if (char2 === "<") {
startNewTag();
} else {
}
}
function resetToDataState() {
state = 0;
currentTag = noCurrentTag;
}
function startNewTag() {
state = 1;
currentTag = new CurrentTag({ idx: charIdx });
}
function emitTagAndPreviousTextNode() {
var textBeforeTag = html.slice(currentDataIdx, currentTag.idx);
if (textBeforeTag) {
onText(textBeforeTag, currentDataIdx);
}
if (currentTag.type === "comment") {
onComment(currentTag.idx);
} else if (currentTag.type === "doctype") {
onDoctype(currentTag.idx);
} else {
if (currentTag.isOpening) {
onOpenTag(currentTag.name, currentTag.idx);
}
if (currentTag.isClosing) {
onCloseTag(currentTag.name, currentTag.idx);
}
}
resetToDataState();
currentDataIdx = charIdx + 1;
}
function emitText() {
var text = html.slice(currentDataIdx, charIdx);
onText(text, currentDataIdx);
currentDataIdx = charIdx + 1;
}
function captureTagName() {
var startIdx = currentTag.idx + (currentTag.isClosing ? 2 : 1);
return html.slice(startIdx, charIdx).toLowerCase();
}
function reconsumeCurrentCharacter() {
charIdx--;
}
}
var CurrentTag = (
/** @class */
function() {
function CurrentTag2(cfg) {
if (cfg === void 0) {
cfg = {};
}
this.idx = cfg.idx !== void 0 ? cfg.idx : -1;
this.type = cfg.type || "tag";
this.name = cfg.name || "";
this.isOpening = !!cfg.isOpening;
this.isClosing = !!cfg.isClosing;
}
return CurrentTag2;
}()
);
// node_modules/autolinker/dist/es2015/autolinker.js
var Autolinker = (
/** @class */
function() {
function Autolinker2(cfg) {
if (cfg === void 0) {
cfg = {};
}
this.version = Autolinker2.version;
this.urls = {};
this.email = true;
this.phone = true;
this.hashtag = false;
this.mention = false;
this.newWindow = true;
this.stripPrefix = {
scheme: true,
www: true
};
this.stripTrailingSlash = true;
this.decodePercentEncoding = true;
this.truncate = {
length: 0,
location: "end"
};
this.className = "";
this.replaceFn = null;
this.context = void 0;
this.sanitizeHtml = false;
this.tagBuilder = null;
this.urls = normalizeUrlsCfg(cfg.urls);
this.email = isBoolean(cfg.email) ? cfg.email : this.email;
this.phone = isBoolean(cfg.phone) ? cfg.phone : this.phone;
this.hashtag = cfg.hashtag || this.hashtag;
this.mention = cfg.mention || this.mention;
this.newWindow = isBoolean(cfg.newWindow) ? cfg.newWindow : this.newWindow;
this.stripPrefix = normalizeStripPrefixCfg(cfg.stripPrefix);
this.stripTrailingSlash = isBoolean(cfg.stripTrailingSlash) ? cfg.stripTrailingSlash : this.stripTrailingSlash;
this.decodePercentEncoding = isBoolean(cfg.decodePercentEncoding) ? cfg.decodePercentEncoding : this.decodePercentEncoding;
this.sanitizeHtml = cfg.sanitizeHtml || false;
var mention = this.mention;
if (mention !== false && mentionServices.indexOf(mention) === -1) {
throw new Error("invalid `mention` cfg '".concat(mention, "' - see docs"));
}
var hashtag = this.hashtag;
if (hashtag !== false && hashtagServices.indexOf(hashtag) === -1) {
throw new Error("invalid `hashtag` cfg '".concat(hashtag, "' - see docs"));
}
this.truncate = normalizeTruncateCfg(cfg.truncate);
this.className = cfg.className || this.className;
this.replaceFn = cfg.replaceFn || this.replaceFn;
this.context = cfg.context || this;
}
Autolinker2.link = function(textOrHtml, options) {
var autolinker3 = new Autolinker2(options);
return autolinker3.link(textOrHtml);
};
Autolinker2.parse = function(textOrHtml, options) {
var autolinker3 = new Autolinker2(options);
return autolinker3.parse(textOrHtml);
};
Autolinker2.prototype.parse = function(textOrHtml) {
var _this = this;
var skipTagNames = ["a", "style", "script"], skipTagsStackCount = 0, matches = [];
parseHtml(textOrHtml, {
onOpenTag: function(tagName) {
if (skipTagNames.indexOf(tagName) >= 0) {
skipTagsStackCount++;
}
},
onText: function(text, offset2) {
if (skipTagsStackCount === 0) {
var htmlCharacterEntitiesRegex = /( | |<|<|>|>|"|"|')/gi;
var textSplit = text.split(htmlCharacterEntitiesRegex);
var currentOffset_1 = offset2;
textSplit.forEach(function(splitText, i) {
if (i % 2 === 0) {
var textNodeMatches = _this.parseText(splitText, currentOffset_1);
matches.push.apply(matches, textNodeMatches);
}
currentOffset_1 += splitText.length;
});
}
},
onCloseTag: function(tagName) {
if (skipTagNames.indexOf(tagName) >= 0) {
skipTagsStackCount = Math.max(skipTagsStackCount - 1, 0);
}
},
onComment: function(_offset) {
},
onDoctype: function(_offset) {
}
// no need to process doctype nodes
});
matches = this.compactMatches(matches);
matches = this.removeUnwantedMatches(matches);
return matches;
};
Autolinker2.prototype.compactMatches = function(matches) {
matches.sort(function(a3, b) {
return a3.getOffset() - b.getOffset();
});
var i = 0;
while (i < matches.length - 1) {
var match = matches[i], offset2 = match.getOffset(), matchedTextLength = match.getMatchedText().length, endIdx = offset2 + matchedTextLength;
if (i + 1 < matches.length) {
if (matches[i + 1].getOffset() === offset2) {
var removeIdx = matches[i + 1].getMatchedText().length > matchedTextLength ? i : i + 1;
matches.splice(removeIdx, 1);
continue;
}
if (matches[i + 1].getOffset() < endIdx) {
matches.splice(i + 1, 1);
continue;
}
}
i++;
}
return matches;
};
Autolinker2.prototype.removeUnwantedMatches = function(matches) {
if (!this.hashtag)
removeWithPredicate(matches, function(match) {
return match.getType() === "hashtag";
});
if (!this.email)
removeWithPredicate(matches, function(match) {
return match.getType() === "email";
});
if (!this.phone)
removeWithPredicate(matches, function(match) {
return match.getType() === "phone";
});
if (!this.mention)
removeWithPredicate(matches, function(match) {
return match.getType() === "mention";
});
if (!this.urls.schemeMatches) {
removeWithPredicate(matches, function(m) {
return m.getType() === "url" && m.getUrlMatchType() === "scheme";
});
}
if (!this.urls.tldMatches) {
removeWithPredicate(matches, function(m) {
return m.getType() === "url" && m.getUrlMatchType() === "tld";
});
}
if (!this.urls.ipV4Matches) {
removeWithPredicate(matches, function(m) {
return m.getType() === "url" && m.getUrlMatchType() === "ipV4";
});
}
return matches;
};
Autolinker2.prototype.parseText = function(text, offset2) {
if (offset2 === void 0) {
offset2 = 0;
}
offset2 = offset2 || 0;
var matches = parseMatches(text, {
tagBuilder: this.getTagBuilder(),
stripPrefix: this.stripPrefix,
stripTrailingSlash: this.stripTrailingSlash,
decodePercentEncoding: this.decodePercentEncoding,
hashtagServiceName: this.hashtag,
mentionServiceName: this.mention || "twitter"
});
for (var i = 0, numTextMatches = matches.length; i < numTextMatches; i++) {
matches[i].setOffset(offset2 + matches[i].getOffset());
}
return matches;
};
Autolinker2.prototype.link = function(textOrHtml) {
if (!textOrHtml) {
return "";
}
if (this.sanitizeHtml) {
textOrHtml = textOrHtml.replace(//g, ">");
}
var matches = this.parse(textOrHtml), newHtml = [], lastIndex = 0;
for (var i = 0, len = matches.length; i < len; i++) {
var match = matches[i];
newHtml.push(textOrHtml.substring(lastIndex, match.getOffset()));
newHtml.push(this.createMatchReturnVal(match));
lastIndex = match.getOffset() + match.getMatchedText().length;
}
newHtml.push(textOrHtml.substring(lastIndex));
return newHtml.join("");
};
Autolinker2.prototype.createMatchReturnVal = function(match) {
var replaceFnResult;
if (this.replaceFn) {
replaceFnResult = this.replaceFn.call(this.context, match);
}
if (typeof replaceFnResult === "string") {
return replaceFnResult;
} else if (replaceFnResult === false) {
return match.getMatchedText();
} else if (replaceFnResult instanceof HtmlTag) {
return replaceFnResult.toAnchorString();
} else {
var anchorTag = match.buildTag();
return anchorTag.toAnchorString();
}
};
Autolinker2.prototype.getTagBuilder = function() {
var tagBuilder = this.tagBuilder;
if (!tagBuilder) {
tagBuilder = this.tagBuilder = new AnchorTagBuilder({
newWindow: this.newWindow,
truncate: this.truncate,
className: this.className
});
}
return tagBuilder;
};
Autolinker2.version = version;
return Autolinker2;
}()
);
var autolinker_default = Autolinker;
function normalizeUrlsCfg(urls) {
if (urls == null)
urls = true;
if (isBoolean(urls)) {
return { schemeMatches: urls, tldMatches: urls, ipV4Matches: urls };
} else {
return {
schemeMatches: isBoolean(urls.schemeMatches) ? urls.schemeMatches : true,
tldMatches: isBoolean(urls.tldMatches) ? urls.tldMatches : true,
ipV4Matches: isBoolean(urls.ipV4Matches) ? urls.ipV4Matches : true
};
}
}
function normalizeStripPrefixCfg(stripPrefix) {
if (stripPrefix == null)
stripPrefix = true;
if (isBoolean(stripPrefix)) {
return { scheme: stripPrefix, www: stripPrefix };
} else {
return {
scheme: isBoolean(stripPrefix.scheme) ? stripPrefix.scheme : true,
www: isBoolean(stripPrefix.www) ? stripPrefix.www : true
};
}
}
function normalizeTruncateCfg(truncate) {
if (typeof truncate === "number") {
return { length: truncate, location: "end" };
} else {
return defaults(truncate || {}, {
length: Number.POSITIVE_INFINITY,
location: "end"
});
}
}
// node_modules/autolinker/dist/es2015/index.js
var es2015_default = autolinker_default;
// packages/engine/Source/DataSources/GpxDataSource.js
var parser;
if (typeof DOMParser !== "undefined") {
parser = new DOMParser();
}
var autolinker = new es2015_default({
stripPrefix: false,
email: false,
replaceFn: function(linker, match) {
return match.urlMatchType === "scheme" || match.urlMatchType === "www";
}
});
var BILLBOARD_SIZE = 32;
var BILLBOARD_NEAR_DISTANCE = 2414016;
var BILLBOARD_NEAR_RATIO = 1;
var BILLBOARD_FAR_DISTANCE = 16093e3;
var BILLBOARD_FAR_RATIO = 0.1;
var gpxNamespaces = [null, void 0, "http://www.topografix.com/GPX/1/1"];
var namespaces = {
gpx: gpxNamespaces
};
function readBlobAsText(blob) {
return new Promise((resolve2, reject) => {
const reader = new FileReader();
reader.addEventListener("load", function() {
resolve2(reader.result);
});
reader.addEventListener("error", function() {
reject(reader.error);
});
reader.readAsText(blob);
});
}
function getOrCreateEntity(node, entityCollection) {
let id = queryStringAttribute(node, "id");
id = defined_default(id) ? id : createGuid_default();
const entity = entityCollection.getOrCreateEntity(id);
return entity;
}
function readCoordinateFromNode(node) {
const longitude = queryNumericAttribute(node, "lon");
const latitude = queryNumericAttribute(node, "lat");
const elevation = queryNumericValue(node, "ele", namespaces.gpx);
return Cartesian3_default.fromDegrees(longitude, latitude, elevation);
}
function queryNumericAttribute(node, attributeName) {
if (!defined_default(node)) {
return void 0;
}
const value = node.getAttribute(attributeName);
if (value !== null) {
const result = parseFloat(value);
return !isNaN(result) ? result : void 0;
}
return void 0;
}
function queryStringAttribute(node, attributeName) {
if (!defined_default(node)) {
return void 0;
}
const value = node.getAttribute(attributeName);
return value !== null ? value : void 0;
}
function queryFirstNode(node, tagName, namespace) {
if (!defined_default(node)) {
return void 0;
}
const childNodes = node.childNodes;
const length3 = childNodes.length;
for (let q = 0; q < length3; q++) {
const child = childNodes[q];
if (child.localName === tagName && namespace.indexOf(child.namespaceURI) !== -1) {
return child;
}
}
return void 0;
}
function queryNodes(node, tagName, namespace) {
if (!defined_default(node)) {
return void 0;
}
const result = [];
const childNodes = node.getElementsByTagName(tagName);
const length3 = childNodes.length;
for (let q = 0; q < length3; q++) {
const child = childNodes[q];
if (child.localName === tagName && namespace.indexOf(child.namespaceURI) !== -1) {
result.push(child);
}
}
return result;
}
function queryNumericValue(node, tagName, namespace) {
const resultNode = queryFirstNode(node, tagName, namespace);
if (defined_default(resultNode)) {
const result = parseFloat(resultNode.textContent);
return !isNaN(result) ? result : void 0;
}
return void 0;
}
function queryStringValue(node, tagName, namespace) {
const result = queryFirstNode(node, tagName, namespace);
if (defined_default(result)) {
return result.textContent.trim();
}
return void 0;
}
function createDefaultBillboard(image) {
const billboard = new BillboardGraphics_default();
billboard.width = BILLBOARD_SIZE;
billboard.height = BILLBOARD_SIZE;
billboard.scaleByDistance = new NearFarScalar_default(
BILLBOARD_NEAR_DISTANCE,
BILLBOARD_NEAR_RATIO,
BILLBOARD_FAR_DISTANCE,
BILLBOARD_FAR_RATIO
);
billboard.pixelOffsetScaleByDistance = new NearFarScalar_default(
BILLBOARD_NEAR_DISTANCE,
BILLBOARD_NEAR_RATIO,
BILLBOARD_FAR_DISTANCE,
BILLBOARD_FAR_RATIO
);
billboard.verticalOrigin = new ConstantProperty_default(VerticalOrigin_default.BOTTOM);
billboard.image = image;
return billboard;
}
function createDefaultLabel() {
const label = new LabelGraphics_default();
label.translucencyByDistance = new NearFarScalar_default(3e6, 1, 5e6, 0);
label.pixelOffset = new Cartesian2_default(17, 0);
label.horizontalOrigin = HorizontalOrigin_default.LEFT;
label.font = "16px sans-serif";
label.style = LabelStyle_default.FILL_AND_OUTLINE;
return label;
}
function createDefaultPolyline(color) {
const polyline = new PolylineGraphics_default();
polyline.width = 4;
polyline.material = new PolylineOutlineMaterialProperty_default();
polyline.material.color = defined_default(color) ? color : Color_default.RED;
polyline.material.outlineWidth = 2;
polyline.material.outlineColor = Color_default.BLACK;
return polyline;
}
var descriptiveInfoTypes = {
time: {
text: "Time",
tag: "time"
},
comment: {
text: "Comment",
tag: "cmt"
},
description: {
text: "Description",
tag: "desc"
},
source: {
text: "Source",
tag: "src"
},
number: {
text: "GPS track/route number",
tag: "number"
},
type: {
text: "Type",
tag: "type"
}
};
var scratchDiv;
if (typeof document !== "undefined") {
scratchDiv = document.createElement("div");
}
function processDescription2(node, entity) {
let i;
let text = "";
const infoTypeNames = Object.keys(descriptiveInfoTypes);
const length3 = infoTypeNames.length;
for (i = 0; i < length3; i++) {
const infoTypeName = infoTypeNames[i];
const infoType = descriptiveInfoTypes[infoTypeName];
infoType.value = defaultValue_default(
queryStringValue(node, infoType.tag, namespaces.gpx),
""
);
if (defined_default(infoType.value) && infoType.value !== "") {
text = `${text}${infoType.text}: ${infoType.value}
`; } } if (!defined_default(text) || text === "") { return; } text = autolinker.link(text); scratchDiv.innerHTML = text; const links = scratchDiv.querySelectorAll("a"); for (i = 0; i < links.length; i++) { links[i].setAttribute("target", "_blank"); } const background = Color_default.WHITE; const foreground = Color_default.BLACK; let tmp2 = '${defaultValue_default( value.displayName, key )} | ${defaultValue_default(value.value, "")} |
---|
${key} | ${describe(value)} |
${key} | ${value} |
{z}
: The level of the tile in the tiling scheme. Level zero is the root of the quadtree pyramid.{x}
: The tile X coordinate in the tiling scheme, where 0 is the Westernmost tile.{y}
: The tile Y coordinate in the tiling scheme, where 0 is the Northernmost tile.{s}
: One of the available subdomains, used to overcome browser limits on the number of simultaneous requests per host.{reverseX}
: The tile X coordinate in the tiling scheme, where 0 is the Easternmost tile.{reverseY}
: The tile Y coordinate in the tiling scheme, where 0 is the Southernmost tile.{reverseZ}
: The level of the tile in the tiling scheme, where level zero is the maximum level of the quadtree pyramid. In order to use reverseZ, maximumLevel must be defined.{westDegrees}
: The Western edge of the tile in geodetic degrees.{southDegrees}
: The Southern edge of the tile in geodetic degrees.{eastDegrees}
: The Eastern edge of the tile in geodetic degrees.{northDegrees}
: The Northern edge of the tile in geodetic degrees.{westProjected}
: The Western edge of the tile in projected coordinates of the tiling scheme.{southProjected}
: The Southern edge of the tile in projected coordinates of the tiling scheme.{eastProjected}
: The Eastern edge of the tile in projected coordinates of the tiling scheme.{northProjected}
: The Northern edge of the tile in projected coordinates of the tiling scheme.{width}
: The width of each tile in pixels.{height}
: The height of each tile in pixels.{z}
: The zero padding for the level of the tile in the tiling scheme.{x}
: The zero padding for the tile X coordinate in the tiling scheme.{y}
: The zero padding for the the tile Y coordinate in the tiling scheme.{reverseX}
: The zero padding for the tile reverseX coordinate in the tiling scheme.{reverseY}
: The zero padding for the tile reverseY coordinate in the tiling scheme.{reverseZ}
: The zero padding for the reverseZ coordinate of the tile in the tiling scheme.{i}
: The pixel column (horizontal coordinate) of the picked position, where the Westernmost pixel is 0.{j}
: The pixel row (vertical coordinate) of the picked position, where the Northernmost pixel is 0.{reverseI}
: The pixel column (horizontal coordinate) of the picked position, where the Easternmost pixel is 0.{reverseJ}
: The pixel row (vertical coordinate) of the picked position, where the Southernmost pixel is 0.{longitudeDegrees}
: The longitude of the picked position in degrees.{latitudeDegrees}
: The latitude of the picked position in degrees.{longitudeProjected}
: The longitude of the picked position in the projected coordinates of the tiling scheme.{latitudeProjected}
: The latitude of the picked position in the projected coordinates of the tiling scheme.{format}
: The format in which to get feature information, as specified in the {@link GetFeatureInfoFormat}.GetFeatureInfo
service on the WMS server and attempt to interpret the features included in the response. If false,
* {@link WebMapServiceImageryProvider#pickFeatures} will immediately return undefined (indicating no pickable
* features) without communicating with the server. Set this property to false if you know your data
* source does not support picking features or if you don't want this provider's features to be pickable.
* @memberof WebMapServiceImageryProvider.prototype
* @type {boolean}
* @default true
*/
enablePickFeatures: {
get: function() {
return this._tileProvider.enablePickFeatures;
},
set: function(enablePickFeatures) {
this._tileProvider.enablePickFeatures = enablePickFeatures;
}
},
/**
* Gets or sets a clock that is used to get keep the time used for time dynamic parameters.
* @memberof WebMapServiceImageryProvider.prototype
* @type {Clock}
*/
clock: {
get: function() {
return this._timeDynamicImagery.clock;
},
set: function(value) {
this._timeDynamicImagery.clock = value;
}
},
/**
* Gets or sets a time interval collection that is used to get time dynamic parameters. The data of each
* TimeInterval is an object containing the keys and values of the properties that are used during
* tile requests.
* @memberof WebMapServiceImageryProvider.prototype
* @type {TimeIntervalCollection}
*/
times: {
get: function() {
return this._timeDynamicImagery.times;
},
set: function(value) {
this._timeDynamicImagery.times = value;
}
},
/**
* Gets the getFeatureInfo URL of the WMS server.
* @memberof WebMapServiceImageryProvider.prototype
* @type {Resource|string}
* @readonly
*/
getFeatureInfoUrl: {
get: function() {
return this._getFeatureInfoUrl;
}
},
/**
* The default alpha blending value of this provider, with 0.0 representing fully transparent and
* 1.0 representing fully opaque.
* @memberof WebMapServiceImageryProvider.prototype
* @type {Number|undefined}
* @deprecated
*/
defaultAlpha: {
get: function() {
deprecationWarning_default(
"WebMapServiceImageryProvider.defaultAlpha",
"WebMapServiceImageryProvider.defaultAlpha was deprecated in CesiumJS 1.104. It will be in CesiumJS 1.107. Use ImageryLayer.alpha instead."
);
return this._defaultAlpha;
},
set: function(value) {
deprecationWarning_default(
"WebMapServiceImageryProvider.defaultAlpha",
"WebMapServiceImageryProvider.defaultAlpha was deprecated in CesiumJS 1.104. It will be in CesiumJS 1.107. Use ImageryLayer.alpha instead."
);
this._defaultAlpha = value;
}
},
/**
* The default alpha blending value on the night side of the globe of this provider, with 0.0 representing fully transparent and
* 1.0 representing fully opaque.
* @memberof WebMapServiceImageryProvider.prototype
* @type {Number|undefined}
* @deprecated
*/
defaultNightAlpha: {
get: function() {
deprecationWarning_default(
"WebMapServiceImageryProvider.defaultNightAlpha",
"WebMapServiceImageryProvider.defaultNightAlpha was deprecated in CesiumJS 1.104. It will be in CesiumJS 1.107. Use ImageryLayer.nightAlpha instead."
);
return this._defaultNightAlpha;
},
set: function(value) {
deprecationWarning_default(
"WebMapServiceImageryProvider.defaultNightAlpha",
"WebMapServiceImageryProvider.defaultNightAlpha was deprecated in CesiumJS 1.104. It will be in CesiumJS 1.107. Use ImageryLayer.nightAlpha instead."
);
this._defaultNightAlpha = value;
}
},
/**
* The default alpha blending value on the day side of the globe of this provider, with 0.0 representing fully transparent and
* 1.0 representing fully opaque.
* @memberof WebMapServiceImageryProvider.prototype
* @type {Number|undefined}
* @deprecated
*/
defaultDayAlpha: {
get: function() {
deprecationWarning_default(
"WebMapServiceImageryProvider.defaultDayAlpha",
"WebMapServiceImageryProvider.defaultDayAlpha was deprecated in CesiumJS 1.104. It will be in CesiumJS 1.107. Use ImageryLayer.dayAlpha instead."
);
return this._defaultDayAlpha;
},
set: function(value) {
deprecationWarning_default(
"WebMapServiceImageryProvider.defaultDayAlpha",
"WebMapServiceImageryProvider.defaultDayAlpha was deprecated in CesiumJS 1.104. It will be in CesiumJS 1.107. Use ImageryLayer.dayAlpha instead."
);
this._defaultDayAlpha = value;
}
},
/**
* The default brightness of this provider. 1.0 uses the unmodified imagery color. Less than 1.0
* makes the imagery darker while greater than 1.0 makes it brighter.
* @memberof WebMapServiceImageryProvider.prototype
* @type {Number|undefined}
* @deprecated
*/
defaultBrightness: {
get: function() {
deprecationWarning_default(
"WebMapServiceImageryProvider.defaultBrightness",
"WebMapServiceImageryProvider.defaultBrightness was deprecated in CesiumJS 1.104. It will be in CesiumJS 1.107. Use ImageryLayer.brightness instead."
);
return this._defaultBrightness;
},
set: function(value) {
deprecationWarning_default(
"WebMapServiceImageryProvider.defaultBrightness",
"WebMapServiceImageryProvider.defaultBrightness was deprecated in CesiumJS 1.104. It will be in CesiumJS 1.107. Use ImageryLayer.brightness instead."
);
this._defaultBrightness = value;
}
},
/**
* The default contrast of this provider. 1.0 uses the unmodified imagery color. Less than 1.0 reduces
* the contrast while greater than 1.0 increases it.
* @memberof WebMapServiceImageryProvider.prototype
* @type {Number|undefined}
* @deprecated
*/
defaultContrast: {
get: function() {
deprecationWarning_default(
"WebMapServiceImageryProvider.defaultContrast",
"WebMapServiceImageryProvider.defaultContrast was deprecated in CesiumJS 1.104. It will be in CesiumJS 1.107. Use ImageryLayer.contrast instead."
);
return this._defaultContrast;
},
set: function(value) {
deprecationWarning_default(
"WebMapServiceImageryProvider.defaultContrast",
"WebMapServiceImageryProvider.defaultContrast was deprecated in CesiumJS 1.104. It will be in CesiumJS 1.107. Use ImageryLayer.contrast instead."
);
this._defaultContrast = value;
}
},
/**
* The default hue of this provider in radians. 0.0 uses the unmodified imagery color.
* @memberof WebMapServiceImageryProvider.prototype
* @type {Number|undefined}
* @deprecated
*/
defaultHue: {
get: function() {
deprecationWarning_default(
"WebMapServiceImageryProvider.defaultHue",
"WebMapServiceImageryProvider.defaultHue was deprecated in CesiumJS 1.104. It will be in CesiumJS 1.107. Use ImageryLayer.hue instead."
);
return this._defaultHue;
},
set: function(value) {
deprecationWarning_default(
"WebMapServiceImageryProvider.defaultHue",
"WebMapServiceImageryProvider.defaultHue was deprecated in CesiumJS 1.104. It will be in CesiumJS 1.107. Use ImageryLayer.hue instead."
);
this._defaultHue = value;
}
},
/**
* The default saturation of this provider. 1.0 uses the unmodified imagery color. Less than 1.0 reduces the
* saturation while greater than 1.0 increases it.
* @memberof WebMapServiceImageryProvider.prototype
* @type {Number|undefined}
* @deprecated
*/
defaultSaturation: {
get: function() {
deprecationWarning_default(
"WebMapServiceImageryProvider.defaultSaturation",
"WebMapServiceImageryProvider.defaultSaturation was deprecated in CesiumJS 1.104. It will be in CesiumJS 1.107. Use ImageryLayer.saturation instead."
);
return this._defaultSaturation;
},
set: function(value) {
deprecationWarning_default(
"WebMapServiceImageryProvider.defaultSaturation",
"WebMapServiceImageryProvider.defaultSaturation was deprecated in CesiumJS 1.104. It will be in CesiumJS 1.107. Use ImageryLayer.saturation instead."
);
this._defaultSaturation = value;
}
},
/**
* The default gamma correction to apply to this provider. 1.0 uses the unmodified imagery color.
* @memberof WebMapServiceImageryProvider.prototype
* @type {Number|undefined}
* @deprecated
*/
defaultGamma: {
get: function() {
deprecationWarning_default(
"WebMapServiceImageryProvider.defaultGamma",
"WebMapServiceImageryProvider.defaultGamma was deprecated in CesiumJS 1.104. It will be in CesiumJS 1.107. Use ImageryLayer.gamma instead."
);
return this._defaultGamma;
},
set: function(value) {
deprecationWarning_default(
"WebMapServiceImageryProvider.defaultGamma",
"WebMapServiceImageryProvider.defaultGamma was deprecated in CesiumJS 1.104. It will be in CesiumJS 1.107. Use ImageryLayer.gamma instead."
);
this._defaultGamma = value;
}
},
/**
* The default texture minification filter to apply to this provider.
* @memberof WebMapServiceImageryProvider.prototype
* @type {TextureMinificationFilter}
* @deprecated
*/
defaultMinificationFilter: {
get: function() {
deprecationWarning_default(
"WebMapServiceImageryProvider.defaultMinificationFilter",
"WebMapServiceImageryProvider.defaultMinificationFilter was deprecated in CesiumJS 1.104. It will be in CesiumJS 1.107. Use ImageryLayer.minificationFilter instead."
);
return this._defaultMinificationFilter;
},
set: function(value) {
deprecationWarning_default(
"WebMapServiceImageryProvider.defaultMinificationFilter",
"WebMapServiceImageryProvider.defaultMinificationFilter was deprecated in CesiumJS 1.104. It will be in CesiumJS 1.107. Use ImageryLayer.minificationFilter instead."
);
this._defaultMinificationFilter = value;
}
},
/**
* The default texture magnification filter to apply to this provider.
* @memberof WebMapServiceImageryProvider.prototype
* @type {TextureMagnificationFilter}
* @deprecated
*/
defaultMagnificationFilter: {
get: function() {
deprecationWarning_default(
"WebMapServiceImageryProvider.defaultMagnificationFilter",
"WebMapServiceImageryProvider.defaultMagnificationFilter was deprecated in CesiumJS 1.104. It will be in CesiumJS 1.107. Use ImageryLayer.magnificationFilter instead."
);
return this._defaultMagnificationFilter;
},
set: function(value) {
deprecationWarning_default(
"WebMapServiceImageryProvider.defaultMagnificationFilter",
"WebMapServiceImageryProvider.defaultMagnificationFilter was deprecated in CesiumJS 1.104. It will be in CesiumJS 1.107. Use ImageryLayer.magnificationFilter instead."
);
this._defaultMagnificationFilter = value;
}
}
});
WebMapServiceImageryProvider.prototype.getTileCredits = function(x, y, level) {
return this._tileProvider.getTileCredits(x, y, level);
};
WebMapServiceImageryProvider.prototype.requestImage = function(x, y, level, request) {
let result;
const timeDynamicImagery = this._timeDynamicImagery;
let currentInterval;
if (defined_default(timeDynamicImagery)) {
currentInterval = timeDynamicImagery.currentInterval;
result = timeDynamicImagery.getFromCache(x, y, level, request);
}
if (!defined_default(result)) {
result = requestImage(this, x, y, level, request, currentInterval);
}
if (defined_default(result) && defined_default(timeDynamicImagery)) {
timeDynamicImagery.checkApproachingInterval(x, y, level, request);
}
return result;
};
WebMapServiceImageryProvider.prototype.pickFeatures = function(x, y, level, longitude, latitude) {
const timeDynamicImagery = this._timeDynamicImagery;
const currentInterval = defined_default(timeDynamicImagery) ? timeDynamicImagery.currentInterval : void 0;
return pickFeatures(this, x, y, level, longitude, latitude, currentInterval);
};
WebMapServiceImageryProvider.DefaultParameters = Object.freeze({
service: "WMS",
version: "1.1.1",
request: "GetMap",
styles: "",
format: "image/jpeg"
});
WebMapServiceImageryProvider.GetFeatureInfoDefaultParameters = Object.freeze({
service: "WMS",
version: "1.1.1",
request: "GetFeatureInfo"
});
WebMapServiceImageryProvider.DefaultGetFeatureInfoFormats = Object.freeze([
Object.freeze(new GetFeatureInfoFormat_default("json", "application/json")),
Object.freeze(new GetFeatureInfoFormat_default("xml", "text/xml")),
Object.freeze(new GetFeatureInfoFormat_default("text", "text/html"))
]);
function objectToLowercase(obj) {
const result = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
result[key.toLowerCase()] = obj[key];
}
}
return result;
}
var WebMapServiceImageryProvider_default = WebMapServiceImageryProvider;
// packages/engine/Source/Scene/WebMapTileServiceImageryProvider.js
var defaultParameters = Object.freeze({
service: "WMTS",
version: "1.0.0",
request: "GetTile"
});
function WebMapTileServiceImageryProvider(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
if (!defined_default(options.url)) {
throw new DeveloperError_default("options.url is required.");
}
if (!defined_default(options.layer)) {
throw new DeveloperError_default("options.layer is required.");
}
if (!defined_default(options.style)) {
throw new DeveloperError_default("options.style is required.");
}
if (!defined_default(options.tileMatrixSetID)) {
throw new DeveloperError_default("options.tileMatrixSetID is required.");
}
if (defined_default(options.times) && !defined_default(options.clock)) {
throw new DeveloperError_default(
"options.times was specified, so options.clock is required."
);
}
this._defaultAlpha = void 0;
this._defaultNightAlpha = void 0;
this._defaultDayAlpha = void 0;
this._defaultBrightness = void 0;
this._defaultContrast = void 0;
this._defaultHue = void 0;
this._defaultSaturation = void 0;
this._defaultGamma = void 0;
this._defaultMinificationFilter = void 0;
this._defaultMagnificationFilter = void 0;
const resource = Resource_default.createIfNeeded(options.url);
const style = options.style;
const tileMatrixSetID = options.tileMatrixSetID;
const url2 = resource.url;
const bracketMatch = url2.match(/{/g);
if (!defined_default(bracketMatch) || bracketMatch.length === 1 && /{s}/.test(url2)) {
resource.setQueryParameters(defaultParameters);
this._useKvp = true;
} else {
const templateValues = {
style,
Style: style,
TileMatrixSet: tileMatrixSetID
};
resource.setTemplateValues(templateValues);
this._useKvp = false;
}
this._resource = resource;
this._layer = options.layer;
this._style = style;
this._tileMatrixSetID = tileMatrixSetID;
this._tileMatrixLabels = options.tileMatrixLabels;
this._format = defaultValue_default(options.format, "image/jpeg");
this._tileDiscardPolicy = options.tileDiscardPolicy;
this._tilingScheme = defined_default(options.tilingScheme) ? options.tilingScheme : new WebMercatorTilingScheme_default({ ellipsoid: options.ellipsoid });
this._tileWidth = defaultValue_default(options.tileWidth, 256);
this._tileHeight = defaultValue_default(options.tileHeight, 256);
this._minimumLevel = defaultValue_default(options.minimumLevel, 0);
this._maximumLevel = options.maximumLevel;
this._rectangle = defaultValue_default(
options.rectangle,
this._tilingScheme.rectangle
);
this._dimensions = options.dimensions;
const that = this;
this._reload = void 0;
if (defined_default(options.times)) {
this._timeDynamicImagery = new TimeDynamicImagery_default({
clock: options.clock,
times: options.times,
requestImageFunction: function(x, y, level, request, interval) {
return requestImage2(that, x, y, level, request, interval);
},
reloadFunction: function() {
if (defined_default(that._reload)) {
that._reload();
}
}
});
}
this._readyPromise = Promise.resolve(true);
this._ready = true;
const swTile = this._tilingScheme.positionToTileXY(
Rectangle_default.southwest(this._rectangle),
this._minimumLevel
);
const neTile = this._tilingScheme.positionToTileXY(
Rectangle_default.northeast(this._rectangle),
this._minimumLevel
);
const tileCount = (Math.abs(neTile.x - swTile.x) + 1) * (Math.abs(neTile.y - swTile.y) + 1);
if (tileCount > 4) {
throw new DeveloperError_default(
`The imagery provider's rectangle and minimumLevel indicate that there are ${tileCount} tiles at the minimum level. Imagery providers with more than four tiles at the minimum level are not supported.`
);
}
this._errorEvent = new Event_default();
const credit = options.credit;
this._credit = typeof credit === "string" ? new Credit_default(credit) : credit;
this._subdomains = options.subdomains;
if (Array.isArray(this._subdomains)) {
this._subdomains = this._subdomains.slice();
} else if (defined_default(this._subdomains) && this._subdomains.length > 0) {
this._subdomains = this._subdomains.split("");
} else {
this._subdomains = ["a", "b", "c"];
}
}
function requestImage2(imageryProvider, col, row, level, request, interval) {
const labels = imageryProvider._tileMatrixLabels;
const tileMatrix = defined_default(labels) ? labels[level] : level.toString();
const subdomains = imageryProvider._subdomains;
const staticDimensions = imageryProvider._dimensions;
const dynamicIntervalData = defined_default(interval) ? interval.data : void 0;
let resource;
let templateValues;
if (!imageryProvider._useKvp) {
templateValues = {
TileMatrix: tileMatrix,
TileRow: row.toString(),
TileCol: col.toString(),
s: subdomains[(col + row + level) % subdomains.length]
};
resource = imageryProvider._resource.getDerivedResource({
request
});
resource.setTemplateValues(templateValues);
if (defined_default(staticDimensions)) {
resource.setTemplateValues(staticDimensions);
}
if (defined_default(dynamicIntervalData)) {
resource.setTemplateValues(dynamicIntervalData);
}
} else {
let query = {};
query.tilematrix = tileMatrix;
query.layer = imageryProvider._layer;
query.style = imageryProvider._style;
query.tilerow = row;
query.tilecol = col;
query.tilematrixset = imageryProvider._tileMatrixSetID;
query.format = imageryProvider._format;
if (defined_default(staticDimensions)) {
query = combine_default(query, staticDimensions);
}
if (defined_default(dynamicIntervalData)) {
query = combine_default(query, dynamicIntervalData);
}
templateValues = {
s: subdomains[(col + row + level) % subdomains.length]
};
resource = imageryProvider._resource.getDerivedResource({
queryParameters: query,
request
});
resource.setTemplateValues(templateValues);
}
return ImageryProvider_default.loadImage(imageryProvider, resource);
}
Object.defineProperties(WebMapTileServiceImageryProvider.prototype, {
/**
* Gets the URL of the service hosting the imagery.
* @memberof WebMapTileServiceImageryProvider.prototype
* @type {string}
* @readonly
*/
url: {
get: function() {
return this._resource.url;
}
},
/**
* Gets the proxy used by this provider.
* @memberof WebMapTileServiceImageryProvider.prototype
* @type {Proxy}
* @readonly
*/
proxy: {
get: function() {
return this._resource.proxy;
}
},
/**
* Gets the width of each tile, in pixels.
* @memberof WebMapTileServiceImageryProvider.prototype
* @type {number}
* @readonly
*/
tileWidth: {
get: function() {
return this._tileWidth;
}
},
/**
* Gets the height of each tile, in pixels.
* @memberof WebMapTileServiceImageryProvider.prototype
* @type {number}
* @readonly
*/
tileHeight: {
get: function() {
return this._tileHeight;
}
},
/**
* Gets the maximum level-of-detail that can be requested.
* @memberof WebMapTileServiceImageryProvider.prototype
* @type {number|undefined}
* @readonly
*/
maximumLevel: {
get: function() {
return this._maximumLevel;
}
},
/**
* Gets the minimum level-of-detail that can be requested.
* @memberof WebMapTileServiceImageryProvider.prototype
* @type {number}
* @readonly
*/
minimumLevel: {
get: function() {
return this._minimumLevel;
}
},
/**
* Gets the tiling scheme used by this provider.
* @memberof WebMapTileServiceImageryProvider.prototype
* @type {TilingScheme}
* @readonly
*/
tilingScheme: {
get: function() {
return this._tilingScheme;
}
},
/**
* Gets the rectangle, in radians, of the imagery provided by this instance.
* @memberof WebMapTileServiceImageryProvider.prototype
* @type {Rectangle}
* @readonly
*/
rectangle: {
get: function() {
return this._rectangle;
}
},
/**
* Gets the tile discard policy. If not undefined, the discard policy is responsible
* for filtering out "missing" tiles via its shouldDiscardImage function. If this function
* returns undefined, no tiles are filtered.
* @memberof WebMapTileServiceImageryProvider.prototype
* @type {TileDiscardPolicy}
* @readonly
*/
tileDiscardPolicy: {
get: function() {
return this._tileDiscardPolicy;
}
},
/**
* Gets an event that is raised when the imagery provider encounters an asynchronous error. By subscribing
* to the event, you will be notified of the error and can potentially recover from it. Event listeners
* are passed an instance of {@link TileProviderError}.
* @memberof WebMapTileServiceImageryProvider.prototype
* @type {Event}
* @readonly
*/
errorEvent: {
get: function() {
return this._errorEvent;
}
},
/**
* Gets the mime type of images returned by this imagery provider.
* @memberof WebMapTileServiceImageryProvider.prototype
* @type {string}
* @readonly
*/
format: {
get: function() {
return this._format;
}
},
/**
* Gets a value indicating whether or not the provider is ready for use.
* @memberof WebMapTileServiceImageryProvider.prototype
* @type {boolean}
* @readonly
* @deprecated
*/
ready: {
get: function() {
deprecationWarning_default(
"WebMapTileServiceImageryProvider.ready",
"WebMapTileServiceImageryProvider.ready was deprecated in CesiumJS 1.104. It will be in CesiumJS 1.107."
);
return true;
}
},
/**
* Gets a promise that resolves to true when the provider is ready for use.
* @memberof WebMapTileServiceImageryProvider.prototype
* @type {PromiseRENDERED_AND_KICKED
* or REFINED_AND_KICKED
.
*
* @param {TileSelectionResult} value The selection result to test.
* @returns {boolean} true if the tile was kicked, no matter if it was originally rendered or refined.
*/
wasKicked: function(value) {
return value >= TileSelectionResult.RENDERED_AND_KICKED;
},
/**
* Determines the original selection result prior to being kicked or CULLED_BUT_NEEDED.
* If the tile wasn't kicked or CULLED_BUT_NEEDED, the original value is returned.
* @param {TileSelectionResult} value The selection result.
* @returns {TileSelectionResult} The original selection result prior to kicking.
*/
originalResult: function(value) {
return value & 3;
},
/**
* Converts this selection result to a kick.
* @param {TileSelectionResult} value The original selection result.
* @returns {TileSelectionResult} The kicked form of the selection result.
*/
kick: function(value) {
return value | 4;
}
};
var TileSelectionResult_default = TileSelectionResult;
// packages/engine/Source/Scene/TerrainFillMesh.js
function TerrainFillMesh(tile) {
this.tile = tile;
this.frameLastUpdated = void 0;
this.westMeshes = [];
this.westTiles = [];
this.southMeshes = [];
this.southTiles = [];
this.eastMeshes = [];
this.eastTiles = [];
this.northMeshes = [];
this.northTiles = [];
this.southwestMesh = void 0;
this.southwestTile = void 0;
this.southeastMesh = void 0;
this.southeastTile = void 0;
this.northwestMesh = void 0;
this.northwestTile = void 0;
this.northeastMesh = void 0;
this.northeastTile = void 0;
this.changedThisFrame = true;
this.visitedFrame = void 0;
this.enqueuedFrame = void 0;
this.mesh = void 0;
this.vertexArray = void 0;
this.waterMaskTexture = void 0;
this.waterMaskTranslationAndScale = new Cartesian4_default();
}
TerrainFillMesh.prototype.update = function(tileProvider, frameState, vertexArraysToDestroy) {
if (this.changedThisFrame) {
createFillMesh(tileProvider, frameState, this.tile, vertexArraysToDestroy);
this.changedThisFrame = false;
}
};
TerrainFillMesh.prototype.destroy = function(vertexArraysToDestroy) {
this._destroyVertexArray(vertexArraysToDestroy);
if (defined_default(this.waterMaskTexture)) {
--this.waterMaskTexture.referenceCount;
if (this.waterMaskTexture.referenceCount === 0) {
this.waterMaskTexture.destroy();
}
this.waterMaskTexture = void 0;
}
return void 0;
};
TerrainFillMesh.prototype._destroyVertexArray = function(vertexArraysToDestroy) {
if (defined_default(this.vertexArray)) {
if (defined_default(vertexArraysToDestroy)) {
vertexArraysToDestroy.push(this.vertexArray);
} else {
GlobeSurfaceTile_default._freeVertexArray(this.vertexArray);
}
this.vertexArray = void 0;
}
};
var traversalQueueScratch = new Queue_default();
TerrainFillMesh.updateFillTiles = function(tileProvider, renderedTiles, frameState, vertexArraysToDestroy) {
const quadtree = tileProvider._quadtree;
const levelZeroTiles = quadtree._levelZeroTiles;
const lastSelectionFrameNumber = quadtree._lastSelectionFrameNumber;
const traversalQueue = traversalQueueScratch;
traversalQueue.clear();
for (let i = 0; i < renderedTiles.length; ++i) {
const renderedTile = renderedTiles[i];
if (defined_default(renderedTile.data.vertexArray)) {
traversalQueue.enqueue(renderedTiles[i]);
}
}
let tile = traversalQueue.dequeue();
while (tile !== void 0) {
const tileToWest = tile.findTileToWest(levelZeroTiles);
const tileToSouth = tile.findTileToSouth(levelZeroTiles);
const tileToEast = tile.findTileToEast(levelZeroTiles);
const tileToNorth = tile.findTileToNorth(levelZeroTiles);
visitRenderedTiles(
tileProvider,
frameState,
tile,
tileToWest,
lastSelectionFrameNumber,
TileEdge_default.EAST,
false,
traversalQueue,
vertexArraysToDestroy
);
visitRenderedTiles(
tileProvider,
frameState,
tile,
tileToSouth,
lastSelectionFrameNumber,
TileEdge_default.NORTH,
false,
traversalQueue,
vertexArraysToDestroy
);
visitRenderedTiles(
tileProvider,
frameState,
tile,
tileToEast,
lastSelectionFrameNumber,
TileEdge_default.WEST,
false,
traversalQueue,
vertexArraysToDestroy
);
visitRenderedTiles(
tileProvider,
frameState,
tile,
tileToNorth,
lastSelectionFrameNumber,
TileEdge_default.SOUTH,
false,
traversalQueue,
vertexArraysToDestroy
);
const tileToNorthwest = tileToWest.findTileToNorth(levelZeroTiles);
const tileToSouthwest = tileToWest.findTileToSouth(levelZeroTiles);
const tileToNortheast = tileToEast.findTileToNorth(levelZeroTiles);
const tileToSoutheast = tileToEast.findTileToSouth(levelZeroTiles);
visitRenderedTiles(
tileProvider,
frameState,
tile,
tileToNorthwest,
lastSelectionFrameNumber,
TileEdge_default.SOUTHEAST,
false,
traversalQueue,
vertexArraysToDestroy
);
visitRenderedTiles(
tileProvider,
frameState,
tile,
tileToNortheast,
lastSelectionFrameNumber,
TileEdge_default.SOUTHWEST,
false,
traversalQueue,
vertexArraysToDestroy
);
visitRenderedTiles(
tileProvider,
frameState,
tile,
tileToSouthwest,
lastSelectionFrameNumber,
TileEdge_default.NORTHEAST,
false,
traversalQueue,
vertexArraysToDestroy
);
visitRenderedTiles(
tileProvider,
frameState,
tile,
tileToSoutheast,
lastSelectionFrameNumber,
TileEdge_default.NORTHWEST,
false,
traversalQueue,
vertexArraysToDestroy
);
tile = traversalQueue.dequeue();
}
};
function visitRenderedTiles(tileProvider, frameState, sourceTile, startTile, currentFrameNumber, tileEdge, downOnly, traversalQueue, vertexArraysToDestroy) {
if (startTile === void 0) {
return;
}
let tile = startTile;
while (tile && (tile._lastSelectionResultFrame !== currentFrameNumber || TileSelectionResult_default.wasKicked(tile._lastSelectionResult) || TileSelectionResult_default.originalResult(tile._lastSelectionResult) === TileSelectionResult_default.CULLED)) {
if (downOnly) {
return;
}
const parent = tile.parent;
if (tileEdge >= TileEdge_default.NORTHWEST && parent !== void 0) {
switch (tileEdge) {
case TileEdge_default.NORTHWEST:
tile = tile === parent.northwestChild ? parent : void 0;
break;
case TileEdge_default.NORTHEAST:
tile = tile === parent.northeastChild ? parent : void 0;
break;
case TileEdge_default.SOUTHWEST:
tile = tile === parent.southwestChild ? parent : void 0;
break;
case TileEdge_default.SOUTHEAST:
tile = tile === parent.southeastChild ? parent : void 0;
break;
}
} else {
tile = parent;
}
}
if (tile === void 0) {
return;
}
if (tile._lastSelectionResult === TileSelectionResult_default.RENDERED) {
if (defined_default(tile.data.vertexArray)) {
return;
}
visitTile(
tileProvider,
frameState,
sourceTile,
tile,
tileEdge,
currentFrameNumber,
traversalQueue,
vertexArraysToDestroy
);
return;
}
if (TileSelectionResult_default.originalResult(startTile._lastSelectionResult) === TileSelectionResult_default.CULLED) {
return;
}
switch (tileEdge) {
case TileEdge_default.WEST:
visitRenderedTiles(
tileProvider,
frameState,
sourceTile,
startTile.northwestChild,
currentFrameNumber,
tileEdge,
true,
traversalQueue,
vertexArraysToDestroy
);
visitRenderedTiles(
tileProvider,
frameState,
sourceTile,
startTile.southwestChild,
currentFrameNumber,
tileEdge,
true,
traversalQueue,
vertexArraysToDestroy
);
break;
case TileEdge_default.EAST:
visitRenderedTiles(
tileProvider,
frameState,
sourceTile,
startTile.southeastChild,
currentFrameNumber,
tileEdge,
true,
traversalQueue,
vertexArraysToDestroy
);
visitRenderedTiles(
tileProvider,
frameState,
sourceTile,
startTile.northeastChild,
currentFrameNumber,
tileEdge,
true,
traversalQueue,
vertexArraysToDestroy
);
break;
case TileEdge_default.SOUTH:
visitRenderedTiles(
tileProvider,
frameState,
sourceTile,
startTile.southwestChild,
currentFrameNumber,
tileEdge,
true,
traversalQueue,
vertexArraysToDestroy
);
visitRenderedTiles(
tileProvider,
frameState,
sourceTile,
startTile.southeastChild,
currentFrameNumber,
tileEdge,
true,
traversalQueue,
vertexArraysToDestroy
);
break;
case TileEdge_default.NORTH:
visitRenderedTiles(
tileProvider,
frameState,
sourceTile,
startTile.northeastChild,
currentFrameNumber,
tileEdge,
true,
traversalQueue,
vertexArraysToDestroy
);
visitRenderedTiles(
tileProvider,
frameState,
sourceTile,
startTile.northwestChild,
currentFrameNumber,
tileEdge,
true,
traversalQueue,
vertexArraysToDestroy
);
break;
case TileEdge_default.NORTHWEST:
visitRenderedTiles(
tileProvider,
frameState,
sourceTile,
startTile.northwestChild,
currentFrameNumber,
tileEdge,
true,
traversalQueue,
vertexArraysToDestroy
);
break;
case TileEdge_default.NORTHEAST:
visitRenderedTiles(
tileProvider,
frameState,
sourceTile,
startTile.northeastChild,
currentFrameNumber,
tileEdge,
true,
traversalQueue,
vertexArraysToDestroy
);
break;
case TileEdge_default.SOUTHWEST:
visitRenderedTiles(
tileProvider,
frameState,
sourceTile,
startTile.southwestChild,
currentFrameNumber,
tileEdge,
true,
traversalQueue,
vertexArraysToDestroy
);
break;
case TileEdge_default.SOUTHEAST:
visitRenderedTiles(
tileProvider,
frameState,
sourceTile,
startTile.southeastChild,
currentFrameNumber,
tileEdge,
true,
traversalQueue,
vertexArraysToDestroy
);
break;
default:
throw new DeveloperError_default("Invalid edge");
}
}
function visitTile(tileProvider, frameState, sourceTile, destinationTile, tileEdge, frameNumber, traversalQueue, vertexArraysToDestroy) {
const destinationSurfaceTile = destinationTile.data;
if (destinationSurfaceTile.fill === void 0) {
destinationSurfaceTile.fill = new TerrainFillMesh(destinationTile);
} else if (destinationSurfaceTile.fill.visitedFrame === frameNumber) {
return;
}
if (destinationSurfaceTile.fill.enqueuedFrame !== frameNumber) {
destinationSurfaceTile.fill.enqueuedFrame = frameNumber;
destinationSurfaceTile.fill.changedThisFrame = false;
traversalQueue.enqueue(destinationTile);
}
propagateEdge(
tileProvider,
frameState,
sourceTile,
destinationTile,
tileEdge,
vertexArraysToDestroy
);
}
function propagateEdge(tileProvider, frameState, sourceTile, destinationTile, tileEdge, vertexArraysToDestroy) {
const destinationFill = destinationTile.data.fill;
let sourceMesh;
const sourceFill = sourceTile.data.fill;
if (defined_default(sourceFill)) {
sourceFill.visitedFrame = frameState.frameNumber;
if (sourceFill.changedThisFrame) {
createFillMesh(
tileProvider,
frameState,
sourceTile,
vertexArraysToDestroy
);
sourceFill.changedThisFrame = false;
}
sourceMesh = sourceTile.data.fill.mesh;
} else {
sourceMesh = sourceTile.data.mesh;
}
let edgeMeshes;
let edgeTiles;
switch (tileEdge) {
case TileEdge_default.WEST:
edgeMeshes = destinationFill.westMeshes;
edgeTiles = destinationFill.westTiles;
break;
case TileEdge_default.SOUTH:
edgeMeshes = destinationFill.southMeshes;
edgeTiles = destinationFill.southTiles;
break;
case TileEdge_default.EAST:
edgeMeshes = destinationFill.eastMeshes;
edgeTiles = destinationFill.eastTiles;
break;
case TileEdge_default.NORTH:
edgeMeshes = destinationFill.northMeshes;
edgeTiles = destinationFill.northTiles;
break;
case TileEdge_default.NORTHWEST:
destinationFill.changedThisFrame = destinationFill.changedThisFrame || destinationFill.northwestMesh !== sourceMesh;
destinationFill.northwestMesh = sourceMesh;
destinationFill.northwestTile = sourceTile;
return;
case TileEdge_default.NORTHEAST:
destinationFill.changedThisFrame = destinationFill.changedThisFrame || destinationFill.northeastMesh !== sourceMesh;
destinationFill.northeastMesh = sourceMesh;
destinationFill.northeastTile = sourceTile;
return;
case TileEdge_default.SOUTHWEST:
destinationFill.changedThisFrame = destinationFill.changedThisFrame || destinationFill.southwestMesh !== sourceMesh;
destinationFill.southwestMesh = sourceMesh;
destinationFill.southwestTile = sourceTile;
return;
case TileEdge_default.SOUTHEAST:
destinationFill.changedThisFrame = destinationFill.changedThisFrame || destinationFill.southeastMesh !== sourceMesh;
destinationFill.southeastMesh = sourceMesh;
destinationFill.southeastTile = sourceTile;
return;
}
if (sourceTile.level <= destinationTile.level) {
destinationFill.changedThisFrame = destinationFill.changedThisFrame || edgeMeshes[0] !== sourceMesh || edgeMeshes.length !== 1;
edgeMeshes[0] = sourceMesh;
edgeTiles[0] = sourceTile;
edgeMeshes.length = 1;
edgeTiles.length = 1;
return;
}
let startIndex, endIndex, existingTile, existingRectangle;
const sourceRectangle = sourceTile.rectangle;
let epsilon;
const destinationRectangle = destinationTile.rectangle;
switch (tileEdge) {
case TileEdge_default.WEST:
epsilon = (destinationRectangle.north - destinationRectangle.south) * Math_default.EPSILON5;
for (startIndex = 0; startIndex < edgeTiles.length; ++startIndex) {
existingTile = edgeTiles[startIndex];
existingRectangle = existingTile.rectangle;
if (Math_default.greaterThan(
sourceRectangle.north,
existingRectangle.south,
epsilon
)) {
break;
}
}
for (endIndex = startIndex; endIndex < edgeTiles.length; ++endIndex) {
existingTile = edgeTiles[endIndex];
existingRectangle = existingTile.rectangle;
if (Math_default.greaterThanOrEquals(
sourceRectangle.south,
existingRectangle.north,
epsilon
)) {
break;
}
}
break;
case TileEdge_default.SOUTH:
epsilon = (destinationRectangle.east - destinationRectangle.west) * Math_default.EPSILON5;
for (startIndex = 0; startIndex < edgeTiles.length; ++startIndex) {
existingTile = edgeTiles[startIndex];
existingRectangle = existingTile.rectangle;
if (Math_default.lessThan(
sourceRectangle.west,
existingRectangle.east,
epsilon
)) {
break;
}
}
for (endIndex = startIndex; endIndex < edgeTiles.length; ++endIndex) {
existingTile = edgeTiles[endIndex];
existingRectangle = existingTile.rectangle;
if (Math_default.lessThanOrEquals(
sourceRectangle.east,
existingRectangle.west,
epsilon
)) {
break;
}
}
break;
case TileEdge_default.EAST:
epsilon = (destinationRectangle.north - destinationRectangle.south) * Math_default.EPSILON5;
for (startIndex = 0; startIndex < edgeTiles.length; ++startIndex) {
existingTile = edgeTiles[startIndex];
existingRectangle = existingTile.rectangle;
if (Math_default.lessThan(
sourceRectangle.south,
existingRectangle.north,
epsilon
)) {
break;
}
}
for (endIndex = startIndex; endIndex < edgeTiles.length; ++endIndex) {
existingTile = edgeTiles[endIndex];
existingRectangle = existingTile.rectangle;
if (Math_default.lessThanOrEquals(
sourceRectangle.north,
existingRectangle.south,
epsilon
)) {
break;
}
}
break;
case TileEdge_default.NORTH:
epsilon = (destinationRectangle.east - destinationRectangle.west) * Math_default.EPSILON5;
for (startIndex = 0; startIndex < edgeTiles.length; ++startIndex) {
existingTile = edgeTiles[startIndex];
existingRectangle = existingTile.rectangle;
if (Math_default.greaterThan(
sourceRectangle.east,
existingRectangle.west,
epsilon
)) {
break;
}
}
for (endIndex = startIndex; endIndex < edgeTiles.length; ++endIndex) {
existingTile = edgeTiles[endIndex];
existingRectangle = existingTile.rectangle;
if (Math_default.greaterThanOrEquals(
sourceRectangle.west,
existingRectangle.east,
epsilon
)) {
break;
}
}
break;
}
if (endIndex - startIndex === 1) {
destinationFill.changedThisFrame = destinationFill.changedThisFrame || edgeMeshes[startIndex] !== sourceMesh;
edgeMeshes[startIndex] = sourceMesh;
edgeTiles[startIndex] = sourceTile;
} else {
destinationFill.changedThisFrame = true;
edgeMeshes.splice(startIndex, endIndex - startIndex, sourceMesh);
edgeTiles.splice(startIndex, endIndex - startIndex, sourceTile);
}
}
var cartographicScratch4 = new Cartographic_default();
var centerCartographicScratch2 = new Cartographic_default();
var cartesianScratch = new Cartesian3_default();
var normalScratch5 = new Cartesian3_default();
var octEncodedNormalScratch = new Cartesian2_default();
var uvScratch2 = new Cartesian2_default();
var uvScratch = new Cartesian2_default();
function HeightAndNormal() {
this.height = 0;
this.encodedNormal = new Cartesian2_default();
}
function fillMissingCorner(fill, ellipsoid, u3, v7, corner, adjacentCorner1, adjacentCorner2, oppositeCorner, vertex) {
if (defined_default(corner)) {
return corner;
}
let height;
if (defined_default(adjacentCorner1) && defined_default(adjacentCorner2)) {
height = (adjacentCorner1.height + adjacentCorner2.height) * 0.5;
} else if (defined_default(adjacentCorner1)) {
height = adjacentCorner1.height;
} else if (defined_default(adjacentCorner2)) {
height = adjacentCorner2.height;
} else if (defined_default(oppositeCorner)) {
height = oppositeCorner.height;
} else {
const surfaceTile = fill.tile.data;
const tileBoundingRegion = surfaceTile.tileBoundingRegion;
let minimumHeight = 0;
let maximumHeight = 0;
if (defined_default(tileBoundingRegion)) {
minimumHeight = tileBoundingRegion.minimumHeight;
maximumHeight = tileBoundingRegion.maximumHeight;
}
height = (minimumHeight + maximumHeight) * 0.5;
}
getVertexWithHeightAtCorner(fill, ellipsoid, u3, v7, height, vertex);
return vertex;
}
var heightRangeScratch = {
minimumHeight: 0,
maximumHeight: 0
};
var scratchCenter8 = new Cartesian3_default();
var swVertexScratch = new HeightAndNormal();
var seVertexScratch = new HeightAndNormal();
var nwVertexScratch = new HeightAndNormal();
var neVertexScratch = new HeightAndNormal();
var heightmapBuffer = typeof Uint8Array !== "undefined" ? new Uint8Array(9 * 9) : void 0;
var scratchCreateMeshSyncOptions = {
tilingScheme: void 0,
x: 0,
y: 0,
level: 0,
exaggeration: 1,
exaggerationRelativeHeight: 0
};
function createFillMesh(tileProvider, frameState, tile, vertexArraysToDestroy) {
GlobeSurfaceTile_default.initialize(
tile,
tileProvider.terrainProvider,
tileProvider._imageryLayers
);
const surfaceTile = tile.data;
const fill = surfaceTile.fill;
const rectangle = tile.rectangle;
const exaggeration = frameState.terrainExaggeration;
const exaggerationRelativeHeight = frameState.terrainExaggerationRelativeHeight;
const hasExaggeration = exaggeration !== 1;
const ellipsoid = tile.tilingScheme.ellipsoid;
let nwCorner = getCorner(
fill,
ellipsoid,
0,
1,
fill.northwestTile,
fill.northwestMesh,
fill.northTiles,
fill.northMeshes,
fill.westTiles,
fill.westMeshes,
nwVertexScratch
);
let swCorner = getCorner(
fill,
ellipsoid,
0,
0,
fill.southwestTile,
fill.southwestMesh,
fill.westTiles,
fill.westMeshes,
fill.southTiles,
fill.southMeshes,
swVertexScratch
);
let seCorner = getCorner(
fill,
ellipsoid,
1,
0,
fill.southeastTile,
fill.southeastMesh,
fill.southTiles,
fill.southMeshes,
fill.eastTiles,
fill.eastMeshes,
seVertexScratch
);
let neCorner = getCorner(
fill,
ellipsoid,
1,
1,
fill.northeastTile,
fill.northeastMesh,
fill.eastTiles,
fill.eastMeshes,
fill.northTiles,
fill.northMeshes,
neVertexScratch
);
nwCorner = fillMissingCorner(
fill,
ellipsoid,
0,
1,
nwCorner,
swCorner,
neCorner,
seCorner,
nwVertexScratch
);
swCorner = fillMissingCorner(
fill,
ellipsoid,
0,
0,
swCorner,
nwCorner,
seCorner,
neCorner,
swVertexScratch
);
seCorner = fillMissingCorner(
fill,
ellipsoid,
1,
1,
seCorner,
swCorner,
neCorner,
nwCorner,
seVertexScratch
);
neCorner = fillMissingCorner(
fill,
ellipsoid,
1,
1,
neCorner,
seCorner,
nwCorner,
swCorner,
neVertexScratch
);
const southwestHeight = swCorner.height;
const southeastHeight = seCorner.height;
const northwestHeight = nwCorner.height;
const northeastHeight = neCorner.height;
let minimumHeight = Math.min(
southwestHeight,
southeastHeight,
northwestHeight,
northeastHeight
);
let maximumHeight = Math.max(
southwestHeight,
southeastHeight,
northwestHeight,
northeastHeight
);
const middleHeight = (minimumHeight + maximumHeight) * 0.5;
let i;
let len;
const geometricError = tileProvider.getLevelMaximumGeometricError(tile.level);
const minCutThroughRadius = ellipsoid.maximumRadius - geometricError;
let maxTileWidth = Math.acos(minCutThroughRadius / ellipsoid.maximumRadius) * 4;
maxTileWidth *= 1.5;
if (rectangle.width > maxTileWidth && maximumHeight - minimumHeight <= geometricError) {
const terrainData = new HeightmapTerrainData_default({
width: 9,
height: 9,
buffer: heightmapBuffer,
structure: {
// Use the maximum as the constant height so that this tile's skirt
// covers any cracks with adjacent tiles.
heightOffset: maximumHeight
}
});
const createMeshSyncOptions = scratchCreateMeshSyncOptions;
createMeshSyncOptions.tilingScheme = tile.tilingScheme;
createMeshSyncOptions.x = tile.x;
createMeshSyncOptions.y = tile.y;
createMeshSyncOptions.level = tile.level;
createMeshSyncOptions.exaggeration = exaggeration;
createMeshSyncOptions.exaggerationRelativeHeight = exaggerationRelativeHeight;
fill.mesh = terrainData._createMeshSync(createMeshSyncOptions);
} else {
const hasGeodeticSurfaceNormals = hasExaggeration;
const centerCartographic = Rectangle_default.center(
rectangle,
centerCartographicScratch2
);
centerCartographic.height = middleHeight;
const center = ellipsoid.cartographicToCartesian(
centerCartographic,
scratchCenter8
);
const encoding = new TerrainEncoding_default(
center,
void 0,
void 0,
void 0,
void 0,
true,
true,
hasGeodeticSurfaceNormals,
exaggeration,
exaggerationRelativeHeight
);
let maxVertexCount = 5;
let meshes;
meshes = fill.westMeshes;
for (i = 0, len = meshes.length; i < len; ++i) {
maxVertexCount += meshes[i].eastIndicesNorthToSouth.length;
}
meshes = fill.southMeshes;
for (i = 0, len = meshes.length; i < len; ++i) {
maxVertexCount += meshes[i].northIndicesWestToEast.length;
}
meshes = fill.eastMeshes;
for (i = 0, len = meshes.length; i < len; ++i) {
maxVertexCount += meshes[i].westIndicesSouthToNorth.length;
}
meshes = fill.northMeshes;
for (i = 0, len = meshes.length; i < len; ++i) {
maxVertexCount += meshes[i].southIndicesEastToWest.length;
}
const heightRange = heightRangeScratch;
heightRange.minimumHeight = minimumHeight;
heightRange.maximumHeight = maximumHeight;
const stride = encoding.stride;
let typedArray = new Float32Array(maxVertexCount * stride);
let nextIndex = 0;
const northwestIndex = nextIndex;
nextIndex = addVertexWithComputedPosition(
ellipsoid,
rectangle,
encoding,
typedArray,
nextIndex,
0,
1,
nwCorner.height,
nwCorner.encodedNormal,
1,
heightRange
);
nextIndex = addEdge(
fill,
ellipsoid,
encoding,
typedArray,
nextIndex,
fill.westTiles,
fill.westMeshes,
TileEdge_default.EAST,
heightRange
);
const southwestIndex = nextIndex;
nextIndex = addVertexWithComputedPosition(
ellipsoid,
rectangle,
encoding,
typedArray,
nextIndex,
0,
0,
swCorner.height,
swCorner.encodedNormal,
0,
heightRange
);
nextIndex = addEdge(
fill,
ellipsoid,
encoding,
typedArray,
nextIndex,
fill.southTiles,
fill.southMeshes,
TileEdge_default.NORTH,
heightRange
);
const southeastIndex = nextIndex;
nextIndex = addVertexWithComputedPosition(
ellipsoid,
rectangle,
encoding,
typedArray,
nextIndex,
1,
0,
seCorner.height,
seCorner.encodedNormal,
0,
heightRange
);
nextIndex = addEdge(
fill,
ellipsoid,
encoding,
typedArray,
nextIndex,
fill.eastTiles,
fill.eastMeshes,
TileEdge_default.WEST,
heightRange
);
const northeastIndex = nextIndex;
nextIndex = addVertexWithComputedPosition(
ellipsoid,
rectangle,
encoding,
typedArray,
nextIndex,
1,
1,
neCorner.height,
neCorner.encodedNormal,
1,
heightRange
);
nextIndex = addEdge(
fill,
ellipsoid,
encoding,
typedArray,
nextIndex,
fill.northTiles,
fill.northMeshes,
TileEdge_default.SOUTH,
heightRange
);
minimumHeight = heightRange.minimumHeight;
maximumHeight = heightRange.maximumHeight;
const obb = OrientedBoundingBox_default.fromRectangle(
rectangle,
minimumHeight,
maximumHeight,
tile.tilingScheme.ellipsoid
);
const southMercatorY = WebMercatorProjection_default.geodeticLatitudeToMercatorAngle(
rectangle.south
);
const oneOverMercatorHeight = 1 / (WebMercatorProjection_default.geodeticLatitudeToMercatorAngle(rectangle.north) - southMercatorY);
const centerWebMercatorT = (WebMercatorProjection_default.geodeticLatitudeToMercatorAngle(
centerCartographic.latitude
) - southMercatorY) * oneOverMercatorHeight;
const geodeticSurfaceNormal = ellipsoid.geodeticSurfaceNormalCartographic(
cartographicScratch4,
normalScratch5
);
const centerEncodedNormal = AttributeCompression_default.octEncode(
geodeticSurfaceNormal,
octEncodedNormalScratch
);
const centerIndex = nextIndex;
encoding.encode(
typedArray,
nextIndex * stride,
obb.center,
Cartesian2_default.fromElements(0.5, 0.5, uvScratch),
middleHeight,
centerEncodedNormal,
centerWebMercatorT,
geodeticSurfaceNormal
);
++nextIndex;
const vertexCount = nextIndex;
const bytesPerIndex = vertexCount < 256 ? 1 : 2;
const indexCount = (vertexCount - 1) * 3;
const indexDataBytes = indexCount * bytesPerIndex;
const availableBytesInBuffer = (typedArray.length - vertexCount * stride) * Float32Array.BYTES_PER_ELEMENT;
let indices2;
if (availableBytesInBuffer >= indexDataBytes) {
const startIndex = vertexCount * stride * Float32Array.BYTES_PER_ELEMENT;
indices2 = vertexCount < 256 ? new Uint8Array(typedArray.buffer, startIndex, indexCount) : new Uint16Array(typedArray.buffer, startIndex, indexCount);
} else {
indices2 = vertexCount < 256 ? new Uint8Array(indexCount) : new Uint16Array(indexCount);
}
typedArray = new Float32Array(typedArray.buffer, 0, vertexCount * stride);
let indexOut = 0;
for (i = 0; i < vertexCount - 2; ++i) {
indices2[indexOut++] = centerIndex;
indices2[indexOut++] = i;
indices2[indexOut++] = i + 1;
}
indices2[indexOut++] = centerIndex;
indices2[indexOut++] = i;
indices2[indexOut++] = 0;
const westIndicesSouthToNorth = [];
for (i = southwestIndex; i >= northwestIndex; --i) {
westIndicesSouthToNorth.push(i);
}
const southIndicesEastToWest = [];
for (i = southeastIndex; i >= southwestIndex; --i) {
southIndicesEastToWest.push(i);
}
const eastIndicesNorthToSouth = [];
for (i = northeastIndex; i >= southeastIndex; --i) {
eastIndicesNorthToSouth.push(i);
}
const northIndicesWestToEast = [];
northIndicesWestToEast.push(0);
for (i = centerIndex - 1; i >= northeastIndex; --i) {
northIndicesWestToEast.push(i);
}
fill.mesh = new TerrainMesh_default(
encoding.center,
typedArray,
indices2,
indexCount,
vertexCount,
minimumHeight,
maximumHeight,
BoundingSphere_default.fromOrientedBoundingBox(obb),
computeOccludeePoint(
tileProvider,
obb.center,
rectangle,
minimumHeight,
maximumHeight
),
encoding.stride,
obb,
encoding,
westIndicesSouthToNorth,
southIndicesEastToWest,
eastIndicesNorthToSouth,
northIndicesWestToEast
);
}
const context = frameState.context;
fill._destroyVertexArray(vertexArraysToDestroy);
fill.vertexArray = GlobeSurfaceTile_default._createVertexArrayForMesh(
context,
fill.mesh
);
surfaceTile.processImagery(
tile,
tileProvider.terrainProvider,
frameState,
true
);
const oldTexture = fill.waterMaskTexture;
fill.waterMaskTexture = void 0;
if (tileProvider.terrainProvider.hasWaterMask) {
const waterSourceTile = surfaceTile._findAncestorTileWithTerrainData(tile);
if (defined_default(waterSourceTile) && defined_default(waterSourceTile.data.waterMaskTexture)) {
fill.waterMaskTexture = waterSourceTile.data.waterMaskTexture;
++fill.waterMaskTexture.referenceCount;
surfaceTile._computeWaterMaskTranslationAndScale(
tile,
waterSourceTile,
fill.waterMaskTranslationAndScale
);
}
}
if (defined_default(oldTexture)) {
--oldTexture.referenceCount;
if (oldTexture.referenceCount === 0) {
oldTexture.destroy();
}
}
}
function addVertexWithComputedPosition(ellipsoid, rectangle, encoding, buffer, index, u3, v7, height, encodedNormal, webMercatorT, heightRange) {
const cartographic2 = cartographicScratch4;
cartographic2.longitude = Math_default.lerp(rectangle.west, rectangle.east, u3);
cartographic2.latitude = Math_default.lerp(rectangle.south, rectangle.north, v7);
cartographic2.height = height;
const position = ellipsoid.cartographicToCartesian(
cartographic2,
cartesianScratch
);
let geodeticSurfaceNormal;
if (encoding.hasGeodeticSurfaceNormals) {
geodeticSurfaceNormal = ellipsoid.geodeticSurfaceNormal(
position,
normalScratch5
);
}
const uv = uvScratch2;
uv.x = u3;
uv.y = v7;
encoding.encode(
buffer,
index * encoding.stride,
position,
uv,
height,
encodedNormal,
webMercatorT,
geodeticSurfaceNormal
);
heightRange.minimumHeight = Math.min(heightRange.minimumHeight, height);
heightRange.maximumHeight = Math.max(heightRange.maximumHeight, height);
return index + 1;
}
var sourceRectangleScratch = new Rectangle_default();
function transformTextureCoordinates(sourceTile, targetTile, coordinates, result) {
let sourceRectangle = sourceTile.rectangle;
const targetRectangle = targetTile.rectangle;
if (targetTile.x === 0 && coordinates.x === 1 && sourceTile.x === sourceTile.tilingScheme.getNumberOfXTilesAtLevel(sourceTile.level) - 1) {
sourceRectangle = Rectangle_default.clone(
sourceTile.rectangle,
sourceRectangleScratch
);
sourceRectangle.west -= Math_default.TWO_PI;
sourceRectangle.east -= Math_default.TWO_PI;
} else if (sourceTile.x === 0 && coordinates.x === 0 && targetTile.x === targetTile.tilingScheme.getNumberOfXTilesAtLevel(targetTile.level) - 1) {
sourceRectangle = Rectangle_default.clone(
sourceTile.rectangle,
sourceRectangleScratch
);
sourceRectangle.west += Math_default.TWO_PI;
sourceRectangle.east += Math_default.TWO_PI;
}
const sourceWidth = sourceRectangle.east - sourceRectangle.west;
const umin = (targetRectangle.west - sourceRectangle.west) / sourceWidth;
const umax = (targetRectangle.east - sourceRectangle.west) / sourceWidth;
const sourceHeight = sourceRectangle.north - sourceRectangle.south;
const vmin = (targetRectangle.south - sourceRectangle.south) / sourceHeight;
const vmax = (targetRectangle.north - sourceRectangle.south) / sourceHeight;
let u3 = (coordinates.x - umin) / (umax - umin);
let v7 = (coordinates.y - vmin) / (vmax - vmin);
if (Math.abs(u3) < Math.EPSILON5) {
u3 = 0;
} else if (Math.abs(u3 - 1) < Math.EPSILON5) {
u3 = 1;
}
if (Math.abs(v7) < Math.EPSILON5) {
v7 = 0;
} else if (Math.abs(v7 - 1) < Math.EPSILON5) {
v7 = 1;
}
result.x = u3;
result.y = v7;
return result;
}
var encodedNormalScratch = new Cartesian2_default();
function getVertexFromTileAtCorner(sourceMesh, sourceIndex, u3, v7, vertex) {
const sourceEncoding = sourceMesh.encoding;
const sourceVertices = sourceMesh.vertices;
vertex.height = sourceEncoding.decodeHeight(sourceVertices, sourceIndex);
if (sourceEncoding.hasVertexNormals) {
sourceEncoding.getOctEncodedNormal(
sourceVertices,
sourceIndex,
vertex.encodedNormal
);
} else {
const normal2 = vertex.encodedNormal;
normal2.x = 0;
normal2.y = 0;
}
}
var encodedNormalScratch2 = new Cartesian2_default();
var cartesianScratch2 = new Cartesian3_default();
function getInterpolatedVertexAtCorner(ellipsoid, sourceTile, targetTile, sourceMesh, previousIndex, nextIndex, u3, v7, interpolateU, vertex) {
const sourceEncoding = sourceMesh.encoding;
const sourceVertices = sourceMesh.vertices;
const previousUv = transformTextureCoordinates(
sourceTile,
targetTile,
sourceEncoding.decodeTextureCoordinates(
sourceVertices,
previousIndex,
uvScratch
),
uvScratch
);
const nextUv = transformTextureCoordinates(
sourceTile,
targetTile,
sourceEncoding.decodeTextureCoordinates(
sourceVertices,
nextIndex,
uvScratch2
),
uvScratch2
);
let ratio;
if (interpolateU) {
ratio = (u3 - previousUv.x) / (nextUv.x - previousUv.x);
} else {
ratio = (v7 - previousUv.y) / (nextUv.y - previousUv.y);
}
const height1 = sourceEncoding.decodeHeight(sourceVertices, previousIndex);
const height2 = sourceEncoding.decodeHeight(sourceVertices, nextIndex);
const targetRectangle = targetTile.rectangle;
cartographicScratch4.longitude = Math_default.lerp(
targetRectangle.west,
targetRectangle.east,
u3
);
cartographicScratch4.latitude = Math_default.lerp(
targetRectangle.south,
targetRectangle.north,
v7
);
vertex.height = cartographicScratch4.height = Math_default.lerp(
height1,
height2,
ratio
);
let normal2;
if (sourceEncoding.hasVertexNormals) {
const encodedNormal1 = sourceEncoding.getOctEncodedNormal(
sourceVertices,
previousIndex,
encodedNormalScratch
);
const encodedNormal2 = sourceEncoding.getOctEncodedNormal(
sourceVertices,
nextIndex,
encodedNormalScratch2
);
const normal1 = AttributeCompression_default.octDecode(
encodedNormal1.x,
encodedNormal1.y,
cartesianScratch
);
const normal22 = AttributeCompression_default.octDecode(
encodedNormal2.x,
encodedNormal2.y,
cartesianScratch2
);
normal2 = Cartesian3_default.lerp(normal1, normal22, ratio, cartesianScratch);
Cartesian3_default.normalize(normal2, normal2);
AttributeCompression_default.octEncode(normal2, vertex.encodedNormal);
} else {
normal2 = ellipsoid.geodeticSurfaceNormalCartographic(
cartographicScratch4,
cartesianScratch
);
AttributeCompression_default.octEncode(normal2, vertex.encodedNormal);
}
}
function getVertexWithHeightAtCorner(terrainFillMesh, ellipsoid, u3, v7, height, vertex) {
vertex.height = height;
const normal2 = ellipsoid.geodeticSurfaceNormalCartographic(
cartographicScratch4,
cartesianScratch
);
AttributeCompression_default.octEncode(normal2, vertex.encodedNormal);
}
function getCorner(terrainFillMesh, ellipsoid, u3, v7, cornerTile, cornerMesh, previousEdgeTiles, previousEdgeMeshes, nextEdgeTiles, nextEdgeMeshes, vertex) {
const gotCorner = getCornerFromEdge(
terrainFillMesh,
ellipsoid,
previousEdgeMeshes,
previousEdgeTiles,
false,
u3,
v7,
vertex
) || getCornerFromEdge(
terrainFillMesh,
ellipsoid,
nextEdgeMeshes,
nextEdgeTiles,
true,
u3,
v7,
vertex
);
if (gotCorner) {
return vertex;
}
let vertexIndex;
if (meshIsUsable(cornerTile, cornerMesh)) {
if (u3 === 0) {
if (v7 === 0) {
vertexIndex = cornerMesh.eastIndicesNorthToSouth[0];
} else {
vertexIndex = cornerMesh.southIndicesEastToWest[0];
}
} else if (v7 === 0) {
vertexIndex = cornerMesh.northIndicesWestToEast[0];
} else {
vertexIndex = cornerMesh.westIndicesSouthToNorth[0];
}
getVertexFromTileAtCorner(cornerMesh, vertexIndex, u3, v7, vertex);
return vertex;
}
let height;
if (u3 === 0) {
if (v7 === 0) {
height = getClosestHeightToCorner(
terrainFillMesh.westMeshes,
terrainFillMesh.westTiles,
TileEdge_default.EAST,
terrainFillMesh.southMeshes,
terrainFillMesh.southTiles,
TileEdge_default.NORTH,
u3,
v7
);
} else {
height = getClosestHeightToCorner(
terrainFillMesh.northMeshes,
terrainFillMesh.northTiles,
TileEdge_default.SOUTH,
terrainFillMesh.westMeshes,
terrainFillMesh.westTiles,
TileEdge_default.EAST,
u3,
v7
);
}
} else if (v7 === 0) {
height = getClosestHeightToCorner(
terrainFillMesh.southMeshes,
terrainFillMesh.southTiles,
TileEdge_default.NORTH,
terrainFillMesh.eastMeshes,
terrainFillMesh.eastTiles,
TileEdge_default.WEST,
u3,
v7
);
} else {
height = getClosestHeightToCorner(
terrainFillMesh.eastMeshes,
terrainFillMesh.eastTiles,
TileEdge_default.WEST,
terrainFillMesh.northMeshes,
terrainFillMesh.northTiles,
TileEdge_default.SOUTH,
u3,
v7
);
}
if (defined_default(height)) {
getVertexWithHeightAtCorner(
terrainFillMesh,
ellipsoid,
u3,
v7,
height,
vertex
);
return vertex;
}
return void 0;
}
function getClosestHeightToCorner(previousMeshes, previousTiles, previousEdge, nextMeshes, nextTiles, nextEdge, u3, v7) {
const height1 = getNearestHeightOnEdge(
previousMeshes,
previousTiles,
false,
previousEdge,
u3,
v7
);
const height2 = getNearestHeightOnEdge(
nextMeshes,
nextTiles,
true,
nextEdge,
u3,
v7
);
if (defined_default(height1) && defined_default(height2)) {
return (height1 + height2) * 0.5;
} else if (defined_default(height1)) {
return height1;
}
return height2;
}
function addEdge(terrainFillMesh, ellipsoid, encoding, typedArray, nextIndex, edgeTiles, edgeMeshes, tileEdge, heightRange) {
for (let i = 0; i < edgeTiles.length; ++i) {
nextIndex = addEdgeMesh(
terrainFillMesh,
ellipsoid,
encoding,
typedArray,
nextIndex,
edgeTiles[i],
edgeMeshes[i],
tileEdge,
heightRange
);
}
return nextIndex;
}
function addEdgeMesh(terrainFillMesh, ellipsoid, encoding, typedArray, nextIndex, edgeTile, edgeMesh, tileEdge, heightRange) {
let sourceRectangle = edgeTile.rectangle;
if (tileEdge === TileEdge_default.EAST && terrainFillMesh.tile.x === 0) {
sourceRectangle = Rectangle_default.clone(
edgeTile.rectangle,
sourceRectangleScratch
);
sourceRectangle.west -= Math_default.TWO_PI;
sourceRectangle.east -= Math_default.TWO_PI;
} else if (tileEdge === TileEdge_default.WEST && edgeTile.x === 0) {
sourceRectangle = Rectangle_default.clone(
edgeTile.rectangle,
sourceRectangleScratch
);
sourceRectangle.west += Math_default.TWO_PI;
sourceRectangle.east += Math_default.TWO_PI;
}
const targetRectangle = terrainFillMesh.tile.rectangle;
let lastU;
let lastV;
if (nextIndex > 0) {
encoding.decodeTextureCoordinates(typedArray, nextIndex - 1, uvScratch);
lastU = uvScratch.x;
lastV = uvScratch.y;
}
let indices2;
let compareU;
switch (tileEdge) {
case TileEdge_default.WEST:
indices2 = edgeMesh.westIndicesSouthToNorth;
compareU = false;
break;
case TileEdge_default.NORTH:
indices2 = edgeMesh.northIndicesWestToEast;
compareU = true;
break;
case TileEdge_default.EAST:
indices2 = edgeMesh.eastIndicesNorthToSouth;
compareU = false;
break;
case TileEdge_default.SOUTH:
indices2 = edgeMesh.southIndicesEastToWest;
compareU = true;
break;
}
const sourceTile = edgeTile;
const targetTile = terrainFillMesh.tile;
const sourceEncoding = edgeMesh.encoding;
const sourceVertices = edgeMesh.vertices;
const targetStride = encoding.stride;
let southMercatorY;
let oneOverMercatorHeight;
if (sourceEncoding.hasWebMercatorT) {
southMercatorY = WebMercatorProjection_default.geodeticLatitudeToMercatorAngle(
targetRectangle.south
);
oneOverMercatorHeight = 1 / (WebMercatorProjection_default.geodeticLatitudeToMercatorAngle(
targetRectangle.north
) - southMercatorY);
}
for (let i = 0; i < indices2.length; ++i) {
const index = indices2[i];
const uv = sourceEncoding.decodeTextureCoordinates(
sourceVertices,
index,
uvScratch
);
transformTextureCoordinates(sourceTile, targetTile, uv, uv);
const u3 = uv.x;
const v7 = uv.y;
const uOrV = compareU ? u3 : v7;
if (uOrV < 0 || uOrV > 1) {
continue;
}
if (Math.abs(u3 - lastU) < Math_default.EPSILON5 && Math.abs(v7 - lastV) < Math_default.EPSILON5) {
continue;
}
const nearlyEdgeU = Math.abs(u3) < Math_default.EPSILON5 || Math.abs(u3 - 1) < Math_default.EPSILON5;
const nearlyEdgeV = Math.abs(v7) < Math_default.EPSILON5 || Math.abs(v7 - 1) < Math_default.EPSILON5;
if (nearlyEdgeU && nearlyEdgeV) {
continue;
}
const position = sourceEncoding.decodePosition(
sourceVertices,
index,
cartesianScratch
);
const height = sourceEncoding.decodeHeight(sourceVertices, index);
let normal2;
if (sourceEncoding.hasVertexNormals) {
normal2 = sourceEncoding.getOctEncodedNormal(
sourceVertices,
index,
octEncodedNormalScratch
);
} else {
normal2 = octEncodedNormalScratch;
normal2.x = 0;
normal2.y = 0;
}
let webMercatorT = v7;
if (sourceEncoding.hasWebMercatorT) {
const latitude = Math_default.lerp(
targetRectangle.south,
targetRectangle.north,
v7
);
webMercatorT = (WebMercatorProjection_default.geodeticLatitudeToMercatorAngle(latitude) - southMercatorY) * oneOverMercatorHeight;
}
let geodeticSurfaceNormal;
if (encoding.hasGeodeticSurfaceNormals) {
geodeticSurfaceNormal = ellipsoid.geodeticSurfaceNormal(
position,
normalScratch5
);
}
encoding.encode(
typedArray,
nextIndex * targetStride,
position,
uv,
height,
normal2,
webMercatorT,
geodeticSurfaceNormal
);
heightRange.minimumHeight = Math.min(heightRange.minimumHeight, height);
heightRange.maximumHeight = Math.max(heightRange.maximumHeight, height);
++nextIndex;
}
return nextIndex;
}
function getNearestHeightOnEdge(meshes, tiles, isNext, edge, u3, v7) {
let meshStart;
let meshEnd;
let meshStep;
if (isNext) {
meshStart = 0;
meshEnd = meshes.length;
meshStep = 1;
} else {
meshStart = meshes.length - 1;
meshEnd = -1;
meshStep = -1;
}
for (let meshIndex = meshStart; meshIndex !== meshEnd; meshIndex += meshStep) {
const mesh = meshes[meshIndex];
const tile = tiles[meshIndex];
if (!meshIsUsable(tile, mesh)) {
continue;
}
let indices2;
switch (edge) {
case TileEdge_default.WEST:
indices2 = mesh.westIndicesSouthToNorth;
break;
case TileEdge_default.SOUTH:
indices2 = mesh.southIndicesEastToWest;
break;
case TileEdge_default.EAST:
indices2 = mesh.eastIndicesNorthToSouth;
break;
case TileEdge_default.NORTH:
indices2 = mesh.northIndicesWestToEast;
break;
}
const index = indices2[isNext ? 0 : indices2.length - 1];
if (defined_default(index)) {
return mesh.encoding.decodeHeight(mesh.vertices, index);
}
}
return void 0;
}
function meshIsUsable(tile, mesh) {
return defined_default(mesh) && (!defined_default(tile.data.fill) || !tile.data.fill.changedThisFrame);
}
function getCornerFromEdge(terrainFillMesh, ellipsoid, edgeMeshes, edgeTiles, isNext, u3, v7, vertex) {
let edgeVertices;
let compareU;
let increasing;
let vertexIndexIndex;
let vertexIndex;
const sourceTile = edgeTiles[isNext ? 0 : edgeMeshes.length - 1];
const sourceMesh = edgeMeshes[isNext ? 0 : edgeMeshes.length - 1];
if (meshIsUsable(sourceTile, sourceMesh)) {
if (u3 === 0) {
if (v7 === 0) {
edgeVertices = isNext ? sourceMesh.northIndicesWestToEast : sourceMesh.eastIndicesNorthToSouth;
compareU = isNext;
increasing = isNext;
} else {
edgeVertices = isNext ? sourceMesh.eastIndicesNorthToSouth : sourceMesh.southIndicesEastToWest;
compareU = !isNext;
increasing = false;
}
} else if (v7 === 0) {
edgeVertices = isNext ? sourceMesh.westIndicesSouthToNorth : sourceMesh.northIndicesWestToEast;
compareU = !isNext;
increasing = true;
} else {
edgeVertices = isNext ? sourceMesh.southIndicesEastToWest : sourceMesh.westIndicesSouthToNorth;
compareU = isNext;
increasing = !isNext;
}
if (edgeVertices.length > 0) {
vertexIndexIndex = isNext ? 0 : edgeVertices.length - 1;
vertexIndex = edgeVertices[vertexIndexIndex];
sourceMesh.encoding.decodeTextureCoordinates(
sourceMesh.vertices,
vertexIndex,
uvScratch
);
const targetUv = transformTextureCoordinates(
sourceTile,
terrainFillMesh.tile,
uvScratch,
uvScratch
);
if (targetUv.x === u3 && targetUv.y === v7) {
getVertexFromTileAtCorner(sourceMesh, vertexIndex, u3, v7, vertex);
return true;
}
vertexIndexIndex = binarySearch_default(edgeVertices, compareU ? u3 : v7, function(vertexIndex2, textureCoordinate) {
sourceMesh.encoding.decodeTextureCoordinates(
sourceMesh.vertices,
vertexIndex2,
uvScratch
);
const targetUv2 = transformTextureCoordinates(
sourceTile,
terrainFillMesh.tile,
uvScratch,
uvScratch
);
if (increasing) {
if (compareU) {
return targetUv2.x - u3;
}
return targetUv2.y - v7;
} else if (compareU) {
return u3 - targetUv2.x;
}
return v7 - targetUv2.y;
});
if (vertexIndexIndex < 0) {
vertexIndexIndex = ~vertexIndexIndex;
if (vertexIndexIndex > 0 && vertexIndexIndex < edgeVertices.length) {
getInterpolatedVertexAtCorner(
ellipsoid,
sourceTile,
terrainFillMesh.tile,
sourceMesh,
edgeVertices[vertexIndexIndex - 1],
edgeVertices[vertexIndexIndex],
u3,
v7,
compareU,
vertex
);
return true;
}
} else {
getVertexFromTileAtCorner(
sourceMesh,
edgeVertices[vertexIndexIndex],
u3,
v7,
vertex
);
return true;
}
}
}
return false;
}
var cornerPositionsScratch = [
new Cartesian3_default(),
new Cartesian3_default(),
new Cartesian3_default(),
new Cartesian3_default()
];
function computeOccludeePoint(tileProvider, center, rectangle, minimumHeight, maximumHeight, result) {
const ellipsoidalOccluder = tileProvider.quadtree._occluders.ellipsoid;
const ellipsoid = ellipsoidalOccluder.ellipsoid;
const cornerPositions = cornerPositionsScratch;
Cartesian3_default.fromRadians(
rectangle.west,
rectangle.south,
maximumHeight,
ellipsoid,
cornerPositions[0]
);
Cartesian3_default.fromRadians(
rectangle.east,
rectangle.south,
maximumHeight,
ellipsoid,
cornerPositions[1]
);
Cartesian3_default.fromRadians(
rectangle.west,
rectangle.north,
maximumHeight,
ellipsoid,
cornerPositions[2]
);
Cartesian3_default.fromRadians(
rectangle.east,
rectangle.north,
maximumHeight,
ellipsoid,
cornerPositions[3]
);
return ellipsoidalOccluder.computeHorizonCullingPointPossiblyUnderEllipsoid(
center,
cornerPositions,
minimumHeight,
result
);
}
var TerrainFillMesh_default = TerrainFillMesh;
// packages/engine/Source/Scene/GlobeSurfaceTileProvider.js
function GlobeSurfaceTileProvider(options) {
if (!defined_default(options)) {
throw new DeveloperError_default("options is required.");
}
if (!defined_default(options.terrainProvider)) {
throw new DeveloperError_default("options.terrainProvider is required.");
} else if (!defined_default(options.imageryLayers)) {
throw new DeveloperError_default("options.imageryLayers is required.");
} else if (!defined_default(options.surfaceShaderSet)) {
throw new DeveloperError_default("options.surfaceShaderSet is required.");
}
this.lightingFadeOutDistance = 65e5;
this.lightingFadeInDistance = 9e6;
this.hasWaterMask = false;
this.oceanNormalMap = void 0;
this.zoomedOutOceanSpecularIntensity = 0.5;
this.enableLighting = false;
this.dynamicAtmosphereLighting = false;
this.dynamicAtmosphereLightingFromSun = false;
this.showGroundAtmosphere = false;
this.shadows = ShadowMode_default.RECEIVE_ONLY;
this.vertexShadowDarkness = 0.3;
this.fillHighlightColor = void 0;
this.hueShift = 0;
this.saturationShift = 0;
this.brightnessShift = 0;
this.showSkirts = true;
this.backFaceCulling = true;
this.undergroundColor = void 0;
this.undergroundColorAlphaByDistance = void 0;
this.lambertDiffuseMultiplier = 0;
this.materialUniformMap = void 0;
this._materialUniformMap = void 0;
this._quadtree = void 0;
this._terrainProvider = options.terrainProvider;
this._imageryLayers = options.imageryLayers;
this._surfaceShaderSet = options.surfaceShaderSet;
this._renderState = void 0;
this._blendRenderState = void 0;
this._disableCullingRenderState = void 0;
this._disableCullingBlendRenderState = void 0;
this._errorEvent = new Event_default();
this._removeLayerAddedListener = this._imageryLayers.layerAdded.addEventListener(
GlobeSurfaceTileProvider.prototype._onLayerAdded,
this
);
this._removeLayerRemovedListener = this._imageryLayers.layerRemoved.addEventListener(
GlobeSurfaceTileProvider.prototype._onLayerRemoved,
this
);
this._removeLayerMovedListener = this._imageryLayers.layerMoved.addEventListener(
GlobeSurfaceTileProvider.prototype._onLayerMoved,
this
);
this._removeLayerShownListener = this._imageryLayers.layerShownOrHidden.addEventListener(
GlobeSurfaceTileProvider.prototype._onLayerShownOrHidden,
this
);
this._imageryLayersUpdatedEvent = new Event_default();
this._layerOrderChanged = false;
this._tilesToRenderByTextureCount = [];
this._drawCommands = [];
this._uniformMaps = [];
this._usedDrawCommands = 0;
this._vertexArraysToDestroy = [];
this._debug = {
wireframe: false,
boundingSphereTile: void 0
};
this._baseColor = void 0;
this._firstPassInitialColor = void 0;
this.baseColor = new Color_default(0, 0, 0.5, 1);
this._clippingPlanes = void 0;
this.cartographicLimitRectangle = Rectangle_default.clone(Rectangle_default.MAX_VALUE);
this._hasLoadedTilesThisFrame = false;
this._hasFillTilesThisFrame = false;
this._oldTerrainExaggeration = void 0;
this._oldTerrainExaggerationRelativeHeight = void 0;
}
Object.defineProperties(GlobeSurfaceTileProvider.prototype, {
/**
* Gets or sets the color of the globe when no imagery is available.
* @memberof GlobeSurfaceTileProvider.prototype
* @type {Color}
*/
baseColor: {
get: function() {
return this._baseColor;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
this._baseColor = value;
this._firstPassInitialColor = Cartesian4_default.fromColor(
value,
this._firstPassInitialColor
);
}
},
/**
* Gets or sets the {@link QuadtreePrimitive} for which this provider is
* providing tiles. This property may be undefined if the provider is not yet associated
* with a {@link QuadtreePrimitive}.
* @memberof GlobeSurfaceTileProvider.prototype
* @type {QuadtreePrimitive}
*/
quadtree: {
get: function() {
return this._quadtree;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
this._quadtree = value;
}
},
/**
* Gets a value indicating whether or not the provider is ready for use.
* @memberof GlobeSurfaceTileProvider.prototype
* @type {boolean}
* @deprecated
*/
ready: {
get: function() {
return defined_default(this._terrainProvider) && // TerrainProvider.ready is deprecated; This is here for backwards compatibility
this._terrainProvider._ready && (this._imageryLayers.length === 0 || // ImageryProvider.ready is deprecated; This is here for backwards compatibility
this._imageryLayers.get(0).ready && this._imageryLayers.get(0).imageryProvider._ready);
}
},
/**
* Gets the tiling scheme used by the provider.
* @memberof GlobeSurfaceTileProvider.prototype
* @type {TilingScheme}
*/
tilingScheme: {
get: function() {
return this._terrainProvider.tilingScheme;
}
},
/**
* Gets an event that is raised when the geometry provider encounters an asynchronous error. By subscribing
* to the event, you will be notified of the error and can potentially recover from it. Event listeners
* are passed an instance of {@link TileProviderError}.
* @memberof GlobeSurfaceTileProvider.prototype
* @type {Event}
*/
errorEvent: {
get: function() {
return this._errorEvent;
}
},
/**
* Gets an event that is raised when an imagery layer is added, shown, hidden, moved, or removed.
* @memberof GlobeSurfaceTileProvider.prototype
* @type {Event}
*/
imageryLayersUpdatedEvent: {
get: function() {
return this._imageryLayersUpdatedEvent;
}
},
/**
* Gets or sets the terrain provider that describes the surface geometry.
* @memberof GlobeSurfaceTileProvider.prototype
* @type {TerrainProvider}
*/
terrainProvider: {
get: function() {
return this._terrainProvider;
},
set: function(terrainProvider) {
if (this._terrainProvider === terrainProvider) {
return;
}
this._terrainProvider = terrainProvider;
if (defined_default(this._quadtree)) {
this._quadtree.invalidateAllTiles();
}
}
},
/**
* The {@link ClippingPlaneCollection} used to selectively disable rendering the tileset.
*
* @type {ClippingPlaneCollection}
*
* @private
*/
clippingPlanes: {
get: function() {
return this._clippingPlanes;
},
set: function(value) {
ClippingPlaneCollection_default.setOwner(value, this, "_clippingPlanes");
}
}
});
function sortTileImageryByLayerIndex(a3, b) {
let aImagery = a3.loadingImagery;
if (!defined_default(aImagery)) {
aImagery = a3.readyImagery;
}
let bImagery = b.loadingImagery;
if (!defined_default(bImagery)) {
bImagery = b.readyImagery;
}
return aImagery.imageryLayer._layerIndex - bImagery.imageryLayer._layerIndex;
}
GlobeSurfaceTileProvider.prototype.update = function(frameState) {
this._imageryLayers._update();
};
function updateCredits(surface, frameState) {
const creditDisplay = frameState.creditDisplay;
if (defined_default(surface._terrainProvider) && // ready is deprecated; This is here for backwards compatibility
surface._terrainProvider._ready && defined_default(surface._terrainProvider.credit)) {
creditDisplay.addCreditToNextFrame(surface._terrainProvider.credit);
}
const imageryLayers = surface._imageryLayers;
for (let i = 0, len = imageryLayers.length; i < len; ++i) {
const layer = imageryLayers.get(i);
if (layer.ready && layer.imageryProvider._ready && defined_default(layer.imageryProvider.credit)) {
creditDisplay.addCreditToNextFrame(layer.imageryProvider.credit);
}
}
}
GlobeSurfaceTileProvider.prototype.initialize = function(frameState) {
this._imageryLayers.queueReprojectionCommands(frameState);
if (this._layerOrderChanged) {
this._layerOrderChanged = false;
this._quadtree.forEachLoadedTile(function(tile) {
tile.data.imagery.sort(sortTileImageryByLayerIndex);
});
}
updateCredits(this, frameState);
const vertexArraysToDestroy = this._vertexArraysToDestroy;
const length3 = vertexArraysToDestroy.length;
for (let j = 0; j < length3; ++j) {
GlobeSurfaceTile_default._freeVertexArray(vertexArraysToDestroy[j]);
}
vertexArraysToDestroy.length = 0;
};
GlobeSurfaceTileProvider.prototype.beginUpdate = function(frameState) {
const tilesToRenderByTextureCount = this._tilesToRenderByTextureCount;
for (let i = 0, len = tilesToRenderByTextureCount.length; i < len; ++i) {
const tiles = tilesToRenderByTextureCount[i];
if (defined_default(tiles)) {
tiles.length = 0;
}
}
const clippingPlanes = this._clippingPlanes;
if (defined_default(clippingPlanes) && clippingPlanes.enabled) {
clippingPlanes.update(frameState);
}
this._usedDrawCommands = 0;
this._hasLoadedTilesThisFrame = false;
this._hasFillTilesThisFrame = false;
};
GlobeSurfaceTileProvider.prototype.endUpdate = function(frameState) {
if (!defined_default(this._renderState)) {
this._renderState = RenderState_default.fromCache({
// Write color and depth
cull: {
enabled: true
},
depthTest: {
enabled: true,
func: DepthFunction_default.LESS
}
});
this._blendRenderState = RenderState_default.fromCache({
// Write color and depth
cull: {
enabled: true
},
depthTest: {
enabled: true,
func: DepthFunction_default.LESS_OR_EQUAL
},
blending: BlendingState_default.ALPHA_BLEND
});
let rs = clone_default(this._renderState, true);
rs.cull.enabled = false;
this._disableCullingRenderState = RenderState_default.fromCache(rs);
rs = clone_default(this._blendRenderState, true);
rs.cull.enabled = false;
this._disableCullingBlendRenderState = RenderState_default.fromCache(rs);
}
if (this._hasFillTilesThisFrame && this._hasLoadedTilesThisFrame) {
TerrainFillMesh_default.updateFillTiles(
this,
this._quadtree._tilesToRender,
frameState,
this._vertexArraysToDestroy
);
}
const quadtree = this.quadtree;
const exaggeration = frameState.terrainExaggeration;
const exaggerationRelativeHeight = frameState.terrainExaggerationRelativeHeight;
const exaggerationChanged = this._oldTerrainExaggeration !== exaggeration || this._oldTerrainExaggerationRelativeHeight !== exaggerationRelativeHeight;
this._oldTerrainExaggeration = exaggeration;
this._oldTerrainExaggerationRelativeHeight = exaggerationRelativeHeight;
if (exaggerationChanged) {
quadtree.forEachLoadedTile(function(tile) {
const surfaceTile = tile.data;
surfaceTile.updateExaggeration(tile, frameState, quadtree);
});
}
const tilesToRenderByTextureCount = this._tilesToRenderByTextureCount;
for (let textureCountIndex = 0, textureCountLength = tilesToRenderByTextureCount.length; textureCountIndex < textureCountLength; ++textureCountIndex) {
const tilesToRender = tilesToRenderByTextureCount[textureCountIndex];
if (!defined_default(tilesToRender)) {
continue;
}
for (let tileIndex = 0, tileLength = tilesToRender.length; tileIndex < tileLength; ++tileIndex) {
const tile = tilesToRender[tileIndex];
const tileBoundingRegion = tile.data.tileBoundingRegion;
addDrawCommandsForTile(this, tile, frameState);
frameState.minimumTerrainHeight = Math.min(
frameState.minimumTerrainHeight,
tileBoundingRegion.minimumHeight
);
}
}
};
function pushCommand2(command, frameState) {
const globeTranslucencyState = frameState.globeTranslucencyState;
if (globeTranslucencyState.translucent) {
const isBlendCommand = command.renderState.blending.enabled;
globeTranslucencyState.pushDerivedCommands(
command,
isBlendCommand,
frameState
);
} else {
frameState.commandList.push(command);
}
}
GlobeSurfaceTileProvider.prototype.updateForPick = function(frameState) {
const drawCommands = this._drawCommands;
for (let i = 0, length3 = this._usedDrawCommands; i < length3; ++i) {
pushCommand2(drawCommands[i], frameState);
}
};
GlobeSurfaceTileProvider.prototype.cancelReprojections = function() {
this._imageryLayers.cancelReprojections();
};
GlobeSurfaceTileProvider.prototype.getLevelMaximumGeometricError = function(level) {
if (!defined_default(this._terrainProvider)) {
return 0;
}
return this._terrainProvider.getLevelMaximumGeometricError(level);
};
GlobeSurfaceTileProvider.prototype.loadTile = function(frameState, tile) {
let surfaceTile = tile.data;
let terrainOnly = true;
let terrainStateBefore;
if (defined_default(surfaceTile)) {
terrainOnly = surfaceTile.boundingVolumeSourceTile !== tile || tile._lastSelectionResult === TileSelectionResult_default.CULLED_BUT_NEEDED;
terrainStateBefore = surfaceTile.terrainState;
}
GlobeSurfaceTile_default.processStateMachine(
tile,
frameState,
this.terrainProvider,
this._imageryLayers,
this.quadtree,
this._vertexArraysToDestroy,
terrainOnly
);
surfaceTile = tile.data;
if (terrainOnly && terrainStateBefore !== tile.data.terrainState) {
if (this.computeTileVisibility(tile, frameState, this.quadtree.occluders) !== Visibility_default.NONE && surfaceTile.boundingVolumeSourceTile === tile) {
terrainOnly = false;
GlobeSurfaceTile_default.processStateMachine(
tile,
frameState,
this.terrainProvider,
this._imageryLayers,
this.quadtree,
this._vertexArraysToDestroy,
terrainOnly
);
}
}
};
var boundingSphereScratch3 = new BoundingSphere_default();
var rectangleIntersectionScratch = new Rectangle_default();
var splitCartographicLimitRectangleScratch = new Rectangle_default();
var rectangleCenterScratch4 = new Cartographic_default();
function clipRectangleAntimeridian(tileRectangle, cartographicLimitRectangle) {
if (cartographicLimitRectangle.west < cartographicLimitRectangle.east) {
return cartographicLimitRectangle;
}
const splitRectangle = Rectangle_default.clone(
cartographicLimitRectangle,
splitCartographicLimitRectangleScratch
);
const tileCenter = Rectangle_default.center(tileRectangle, rectangleCenterScratch4);
if (tileCenter.longitude > 0) {
splitRectangle.east = Math_default.PI;
} else {
splitRectangle.west = -Math_default.PI;
}
return splitRectangle;
}
function isUndergroundVisible(tileProvider, frameState) {
if (frameState.cameraUnderground) {
return true;
}
if (frameState.globeTranslucencyState.translucent) {
return true;
}
if (tileProvider.backFaceCulling) {
return false;
}
const clippingPlanes = tileProvider._clippingPlanes;
if (defined_default(clippingPlanes) && clippingPlanes.enabled) {
return true;
}
if (!Rectangle_default.equals(
tileProvider.cartographicLimitRectangle,
Rectangle_default.MAX_VALUE
)) {
return true;
}
return false;
}
GlobeSurfaceTileProvider.prototype.computeTileVisibility = function(tile, frameState, occluders) {
const distance2 = this.computeDistanceToTile(tile, frameState);
tile._distance = distance2;
const undergroundVisible = isUndergroundVisible(this, frameState);
if (frameState.fog.enabled && !undergroundVisible) {
if (Math_default.fog(distance2, frameState.fog.density) >= 1) {
return Visibility_default.NONE;
}
}
const surfaceTile = tile.data;
const tileBoundingRegion = surfaceTile.tileBoundingRegion;
if (surfaceTile.boundingVolumeSourceTile === void 0) {
return Visibility_default.PARTIAL;
}
const cullingVolume = frameState.cullingVolume;
let boundingVolume = tileBoundingRegion.boundingVolume;
if (!defined_default(boundingVolume)) {
boundingVolume = tileBoundingRegion.boundingSphere;
}
surfaceTile.clippedByBoundaries = false;
const clippedCartographicLimitRectangle = clipRectangleAntimeridian(
tile.rectangle,
this.cartographicLimitRectangle
);
const areaLimitIntersection = Rectangle_default.simpleIntersection(
clippedCartographicLimitRectangle,
tile.rectangle,
rectangleIntersectionScratch
);
if (!defined_default(areaLimitIntersection)) {
return Visibility_default.NONE;
}
if (!Rectangle_default.equals(areaLimitIntersection, tile.rectangle)) {
surfaceTile.clippedByBoundaries = true;
}
if (frameState.mode !== SceneMode_default.SCENE3D) {
boundingVolume = boundingSphereScratch3;
BoundingSphere_default.fromRectangleWithHeights2D(
tile.rectangle,
frameState.mapProjection,
tileBoundingRegion.minimumHeight,
tileBoundingRegion.maximumHeight,
boundingVolume
);
Cartesian3_default.fromElements(
boundingVolume.center.z,
boundingVolume.center.x,
boundingVolume.center.y,
boundingVolume.center
);
if (frameState.mode === SceneMode_default.MORPHING && defined_default(surfaceTile.renderedMesh)) {
boundingVolume = BoundingSphere_default.union(
tileBoundingRegion.boundingSphere,
boundingVolume,
boundingVolume
);
}
}
if (!defined_default(boundingVolume)) {
return Visibility_default.PARTIAL;
}
const clippingPlanes = this._clippingPlanes;
if (defined_default(clippingPlanes) && clippingPlanes.enabled) {
const planeIntersection = clippingPlanes.computeIntersectionWithBoundingVolume(
boundingVolume
);
tile.isClipped = planeIntersection !== Intersect_default.INSIDE;
if (planeIntersection === Intersect_default.OUTSIDE) {
return Visibility_default.NONE;
}
}
let visibility;
const intersection = cullingVolume.computeVisibility(boundingVolume);
if (intersection === Intersect_default.OUTSIDE) {
visibility = Visibility_default.NONE;
} else if (intersection === Intersect_default.INTERSECTING) {
visibility = Visibility_default.PARTIAL;
} else if (intersection === Intersect_default.INSIDE) {
visibility = Visibility_default.FULL;
}
if (visibility === Visibility_default.NONE) {
return visibility;
}
const ortho3D = frameState.mode === SceneMode_default.SCENE3D && frameState.camera.frustum instanceof OrthographicFrustum_default;
if (frameState.mode === SceneMode_default.SCENE3D && !ortho3D && defined_default(occluders) && !undergroundVisible) {
const occludeePointInScaledSpace = surfaceTile.occludeePointInScaledSpace;
if (!defined_default(occludeePointInScaledSpace)) {
return visibility;
}
if (occluders.ellipsoid.isScaledSpacePointVisiblePossiblyUnderEllipsoid(
occludeePointInScaledSpace,
tileBoundingRegion.minimumHeight
)) {
return visibility;
}
return Visibility_default.NONE;
}
return visibility;
};
GlobeSurfaceTileProvider.prototype.canRefine = function(tile) {
if (defined_default(tile.data.terrainData)) {
return true;
}
const childAvailable = this.terrainProvider.getTileDataAvailable(
tile.x * 2,
tile.y * 2,
tile.level + 1
);
return childAvailable !== void 0;
};
var readyImageryScratch = [];
var canRenderTraversalStack = [];
GlobeSurfaceTileProvider.prototype.canRenderWithoutLosingDetail = function(tile, frameState) {
const surfaceTile = tile.data;
const readyImagery = readyImageryScratch;
readyImagery.length = this._imageryLayers.length;
let terrainReady = false;
let initialImageryState = false;
let imagery;
if (defined_default(surfaceTile)) {
terrainReady = surfaceTile.terrainState === TerrainState_default.READY;
initialImageryState = true;
imagery = surfaceTile.imagery;
}
let i;
let len;
for (i = 0, len = readyImagery.length; i < len; ++i) {
readyImagery[i] = initialImageryState;
}
if (defined_default(imagery)) {
for (i = 0, len = imagery.length; i < len; ++i) {
const tileImagery = imagery[i];
const loadingImagery = tileImagery.loadingImagery;
const isReady = !defined_default(loadingImagery) || loadingImagery.state === ImageryState_default.FAILED || loadingImagery.state === ImageryState_default.INVALID;
const layerIndex = (tileImagery.loadingImagery || tileImagery.readyImagery).imageryLayer._layerIndex;
readyImagery[layerIndex] = isReady && readyImagery[layerIndex];
}
}
const lastFrame = this.quadtree._lastSelectionFrameNumber;
const stack = canRenderTraversalStack;
stack.length = 0;
stack.push(
tile.southwestChild,
tile.southeastChild,
tile.northwestChild,
tile.northeastChild
);
while (stack.length > 0) {
const descendant = stack.pop();
const lastFrameSelectionResult = descendant._lastSelectionResultFrame === lastFrame ? descendant._lastSelectionResult : TileSelectionResult_default.NONE;
if (lastFrameSelectionResult === TileSelectionResult_default.RENDERED) {
const descendantSurface = descendant.data;
if (!defined_default(descendantSurface)) {
continue;
}
if (!terrainReady && descendant.data.terrainState === TerrainState_default.READY) {
return false;
}
const descendantImagery = descendant.data.imagery;
for (i = 0, len = descendantImagery.length; i < len; ++i) {
const descendantTileImagery = descendantImagery[i];
const descendantLoadingImagery = descendantTileImagery.loadingImagery;
const descendantIsReady = !defined_default(descendantLoadingImagery) || descendantLoadingImagery.state === ImageryState_default.FAILED || descendantLoadingImagery.state === ImageryState_default.INVALID;
const descendantLayerIndex = (descendantTileImagery.loadingImagery || descendantTileImagery.readyImagery).imageryLayer._layerIndex;
if (descendantIsReady && !readyImagery[descendantLayerIndex]) {
return false;
}
}
} else if (lastFrameSelectionResult === TileSelectionResult_default.REFINED) {
stack.push(
descendant.southwestChild,
descendant.southeastChild,
descendant.northwestChild,
descendant.northeastChild
);
}
}
return true;
};
var tileDirectionScratch = new Cartesian3_default();
GlobeSurfaceTileProvider.prototype.computeTileLoadPriority = function(tile, frameState) {
const surfaceTile = tile.data;
if (surfaceTile === void 0) {
return 0;
}
const obb = surfaceTile.tileBoundingRegion.boundingVolume;
if (obb === void 0) {
return 0;
}
const cameraPosition = frameState.camera.positionWC;
const cameraDirection = frameState.camera.directionWC;
const tileDirection = Cartesian3_default.subtract(
obb.center,
cameraPosition,
tileDirectionScratch
);
const magnitude = Cartesian3_default.magnitude(tileDirection);
if (magnitude < Math_default.EPSILON5) {
return 0;
}
Cartesian3_default.divideByScalar(tileDirection, magnitude, tileDirection);
return (1 - Cartesian3_default.dot(tileDirection, cameraDirection)) * tile._distance;
};
var modifiedModelViewScratch5 = new Matrix4_default();
var modifiedModelViewProjectionScratch = new Matrix4_default();
var tileRectangleScratch = new Cartesian4_default();
var localizedCartographicLimitRectangleScratch = new Cartesian4_default();
var localizedTranslucencyRectangleScratch = new Cartesian4_default();
var rtcScratch5 = new Cartesian3_default();
var centerEyeScratch = new Cartesian3_default();
var southwestScratch = new Cartesian3_default();
var northeastScratch = new Cartesian3_default();
GlobeSurfaceTileProvider.prototype.showTileThisFrame = function(tile, frameState) {
let readyTextureCount = 0;
const tileImageryCollection = tile.data.imagery;
for (let i = 0, len = tileImageryCollection.length; i < len; ++i) {
const tileImagery = tileImageryCollection[i];
if (defined_default(tileImagery.readyImagery) && tileImagery.readyImagery.imageryLayer.alpha !== 0) {
++readyTextureCount;
}
}
let tileSet = this._tilesToRenderByTextureCount[readyTextureCount];
if (!defined_default(tileSet)) {
tileSet = [];
this._tilesToRenderByTextureCount[readyTextureCount] = tileSet;
}
tileSet.push(tile);
const surfaceTile = tile.data;
if (!defined_default(surfaceTile.vertexArray)) {
this._hasFillTilesThisFrame = true;
} else {
this._hasLoadedTilesThisFrame = true;
}
const debug = this._debug;
++debug.tilesRendered;
debug.texturesRendered += readyTextureCount;
};
var cornerPositionsScratch2 = [
new Cartesian3_default(),
new Cartesian3_default(),
new Cartesian3_default(),
new Cartesian3_default()
];
function computeOccludeePoint2(tileProvider, center, rectangle, minimumHeight, maximumHeight, result) {
const ellipsoidalOccluder = tileProvider.quadtree._occluders.ellipsoid;
const ellipsoid = ellipsoidalOccluder.ellipsoid;
const cornerPositions = cornerPositionsScratch2;
Cartesian3_default.fromRadians(
rectangle.west,
rectangle.south,
maximumHeight,
ellipsoid,
cornerPositions[0]
);
Cartesian3_default.fromRadians(
rectangle.east,
rectangle.south,
maximumHeight,
ellipsoid,
cornerPositions[1]
);
Cartesian3_default.fromRadians(
rectangle.west,
rectangle.north,
maximumHeight,
ellipsoid,
cornerPositions[2]
);
Cartesian3_default.fromRadians(
rectangle.east,
rectangle.north,
maximumHeight,
ellipsoid,
cornerPositions[3]
);
return ellipsoidalOccluder.computeHorizonCullingPointPossiblyUnderEllipsoid(
center,
cornerPositions,
minimumHeight,
result
);
}
GlobeSurfaceTileProvider.prototype.computeDistanceToTile = function(tile, frameState) {
updateTileBoundingRegion(tile, this, frameState);
const surfaceTile = tile.data;
const boundingVolumeSourceTile = surfaceTile.boundingVolumeSourceTile;
if (boundingVolumeSourceTile === void 0) {
return 9999999999;
}
const tileBoundingRegion = surfaceTile.tileBoundingRegion;
const min3 = tileBoundingRegion.minimumHeight;
const max3 = tileBoundingRegion.maximumHeight;
if (surfaceTile.boundingVolumeSourceTile !== tile) {
const cameraHeight = frameState.camera.positionCartographic.height;
const distanceToMin = Math.abs(cameraHeight - min3);
const distanceToMax = Math.abs(cameraHeight - max3);
if (distanceToMin > distanceToMax) {
tileBoundingRegion.minimumHeight = min3;
tileBoundingRegion.maximumHeight = min3;
} else {
tileBoundingRegion.minimumHeight = max3;
tileBoundingRegion.maximumHeight = max3;
}
}
const result = tileBoundingRegion.distanceToCamera(frameState);
tileBoundingRegion.minimumHeight = min3;
tileBoundingRegion.maximumHeight = max3;
return result;
};
function updateTileBoundingRegion(tile, tileProvider, frameState) {
let surfaceTile = tile.data;
if (surfaceTile === void 0) {
surfaceTile = tile.data = new GlobeSurfaceTile_default();
}
const ellipsoid = tile.tilingScheme.ellipsoid;
if (surfaceTile.tileBoundingRegion === void 0) {
surfaceTile.tileBoundingRegion = new TileBoundingRegion_default({
computeBoundingVolumes: false,
rectangle: tile.rectangle,
ellipsoid,
minimumHeight: 0,
maximumHeight: 0
});
}
const tileBoundingRegion = surfaceTile.tileBoundingRegion;
const oldMinimumHeight = tileBoundingRegion.minimumHeight;
const oldMaximumHeight = tileBoundingRegion.maximumHeight;
let hasBoundingVolumesFromMesh = false;
let sourceTile = tile;
const mesh = surfaceTile.mesh;
const terrainData = surfaceTile.terrainData;
if (mesh !== void 0 && mesh.minimumHeight !== void 0 && mesh.maximumHeight !== void 0) {
tileBoundingRegion.minimumHeight = mesh.minimumHeight;
tileBoundingRegion.maximumHeight = mesh.maximumHeight;
hasBoundingVolumesFromMesh = true;
} else if (terrainData !== void 0 && terrainData._minimumHeight !== void 0 && terrainData._maximumHeight !== void 0) {
tileBoundingRegion.minimumHeight = terrainData._minimumHeight;
tileBoundingRegion.maximumHeight = terrainData._maximumHeight;
} else {
tileBoundingRegion.minimumHeight = Number.NaN;
tileBoundingRegion.maximumHeight = Number.NaN;
let ancestorTile = tile.parent;
while (ancestorTile !== void 0) {
const ancestorSurfaceTile = ancestorTile.data;
if (ancestorSurfaceTile !== void 0) {
const ancestorMesh = ancestorSurfaceTile.mesh;
const ancestorTerrainData = ancestorSurfaceTile.terrainData;
if (ancestorMesh !== void 0 && ancestorMesh.minimumHeight !== void 0 && ancestorMesh.maximumHeight !== void 0) {
tileBoundingRegion.minimumHeight = ancestorMesh.minimumHeight;
tileBoundingRegion.maximumHeight = ancestorMesh.maximumHeight;
break;
} else if (ancestorTerrainData !== void 0 && ancestorTerrainData._minimumHeight !== void 0 && ancestorTerrainData._maximumHeight !== void 0) {
tileBoundingRegion.minimumHeight = ancestorTerrainData._minimumHeight;
tileBoundingRegion.maximumHeight = ancestorTerrainData._maximumHeight;
break;
}
}
ancestorTile = ancestorTile.parent;
}
sourceTile = ancestorTile;
}
if (sourceTile !== void 0) {
const exaggeration = frameState.terrainExaggeration;
const exaggerationRelativeHeight = frameState.terrainExaggerationRelativeHeight;
const hasExaggeration = exaggeration !== 1;
if (hasExaggeration) {
hasBoundingVolumesFromMesh = false;
tileBoundingRegion.minimumHeight = TerrainExaggeration_default.getHeight(
tileBoundingRegion.minimumHeight,
exaggeration,
exaggerationRelativeHeight
);
tileBoundingRegion.maximumHeight = TerrainExaggeration_default.getHeight(
tileBoundingRegion.maximumHeight,
exaggeration,
exaggerationRelativeHeight
);
}
if (hasBoundingVolumesFromMesh) {
if (!surfaceTile.boundingVolumeIsFromMesh) {
tileBoundingRegion._orientedBoundingBox = OrientedBoundingBox_default.clone(
mesh.orientedBoundingBox,
tileBoundingRegion._orientedBoundingBox
);
tileBoundingRegion._boundingSphere = BoundingSphere_default.clone(
mesh.boundingSphere3D,
tileBoundingRegion._boundingSphere
);
surfaceTile.occludeePointInScaledSpace = Cartesian3_default.clone(
mesh.occludeePointInScaledSpace,
surfaceTile.occludeePointInScaledSpace
);
if (!defined_default(surfaceTile.occludeePointInScaledSpace)) {
surfaceTile.occludeePointInScaledSpace = computeOccludeePoint2(
tileProvider,
tileBoundingRegion._orientedBoundingBox.center,
tile.rectangle,
tileBoundingRegion.minimumHeight,
tileBoundingRegion.maximumHeight,
surfaceTile.occludeePointInScaledSpace
);
}
}
} else {
const needsBounds = tileBoundingRegion._orientedBoundingBox === void 0 || tileBoundingRegion._boundingSphere === void 0;
const heightChanged = tileBoundingRegion.minimumHeight !== oldMinimumHeight || tileBoundingRegion.maximumHeight !== oldMaximumHeight;
if (heightChanged || needsBounds) {
tileBoundingRegion.computeBoundingVolumes(ellipsoid);
surfaceTile.occludeePointInScaledSpace = computeOccludeePoint2(
tileProvider,
tileBoundingRegion._orientedBoundingBox.center,
tile.rectangle,
tileBoundingRegion.minimumHeight,
tileBoundingRegion.maximumHeight,
surfaceTile.occludeePointInScaledSpace
);
}
}
surfaceTile.boundingVolumeSourceTile = sourceTile;
surfaceTile.boundingVolumeIsFromMesh = hasBoundingVolumesFromMesh;
} else {
surfaceTile.boundingVolumeSourceTile = void 0;
surfaceTile.boundingVolumeIsFromMesh = false;
}
}
GlobeSurfaceTileProvider.prototype.isDestroyed = function() {
return false;
};
GlobeSurfaceTileProvider.prototype.destroy = function() {
this._tileProvider = this._tileProvider && this._tileProvider.destroy();
this._clippingPlanes = this._clippingPlanes && this._clippingPlanes.destroy();
this._removeLayerAddedListener = this._removeLayerAddedListener && this._removeLayerAddedListener();
this._removeLayerRemovedListener = this._removeLayerRemovedListener && this._removeLayerRemovedListener();
this._removeLayerMovedListener = this._removeLayerMovedListener && this._removeLayerMovedListener();
this._removeLayerShownListener = this._removeLayerShownListener && this._removeLayerShownListener();
return destroyObject_default(this);
};
function getTileReadyCallback(tileImageriesToFree, layer, terrainProvider) {
return function(tile) {
let tileImagery;
let imagery;
let startIndex = -1;
const tileImageryCollection = tile.data.imagery;
const length3 = tileImageryCollection.length;
let i;
for (i = 0; i < length3; ++i) {
tileImagery = tileImageryCollection[i];
imagery = defaultValue_default(
tileImagery.readyImagery,
tileImagery.loadingImagery
);
if (imagery.imageryLayer === layer) {
startIndex = i;
break;
}
}
if (startIndex !== -1) {
const endIndex = startIndex + tileImageriesToFree;
tileImagery = tileImageryCollection[endIndex];
imagery = defined_default(tileImagery) ? defaultValue_default(tileImagery.readyImagery, tileImagery.loadingImagery) : void 0;
if (!defined_default(imagery) || imagery.imageryLayer !== layer) {
return !layer._createTileImagerySkeletons(
tile,
terrainProvider,
endIndex
);
}
for (i = startIndex; i < endIndex; ++i) {
tileImageryCollection[i].freeResources();
}
tileImageryCollection.splice(startIndex, tileImageriesToFree);
}
return true;
};
}
GlobeSurfaceTileProvider.prototype._onLayerAdded = function(layer, index) {
if (this.isDestroyed()) {
return;
}
if (layer.show) {
const terrainProvider = this._terrainProvider;
const that = this;
const tileImageryUpdatedEvent = this._imageryLayersUpdatedEvent;
const reloadFunction = function() {
layer._imageryCache = {};
that._quadtree.forEachLoadedTile(function(tile) {
if (defined_default(tile._loadedCallbacks[layer._layerIndex])) {
return;
}
let i;
const tileImageryCollection = tile.data.imagery;
const length3 = tileImageryCollection.length;
let startIndex = -1;
let tileImageriesToFree = 0;
for (i = 0; i < length3; ++i) {
const tileImagery = tileImageryCollection[i];
const imagery = defaultValue_default(
tileImagery.readyImagery,
tileImagery.loadingImagery
);
if (imagery.imageryLayer === layer) {
if (startIndex === -1) {
startIndex = i;
}
++tileImageriesToFree;
} else if (startIndex !== -1) {
break;
}
}
if (startIndex === -1) {
return;
}
const insertionPoint = startIndex + tileImageriesToFree;
if (layer._createTileImagerySkeletons(
tile,
terrainProvider,
insertionPoint
)) {
tile._loadedCallbacks[layer._layerIndex] = getTileReadyCallback(
tileImageriesToFree,
layer,
terrainProvider
);
tile.state = QuadtreeTileLoadState_default.LOADING;
}
});
};
if (layer.ready) {
const imageryProvider = layer.imageryProvider;
imageryProvider._reload = reloadFunction;
}
this._quadtree.forEachLoadedTile(function(tile) {
if (layer._createTileImagerySkeletons(tile, terrainProvider)) {
tile.state = QuadtreeTileLoadState_default.LOADING;
if (tile.level !== 0 && (tile._lastSelectionResultFrame !== that.quadtree._lastSelectionFrameNumber || tile._lastSelectionResult !== TileSelectionResult_default.RENDERED)) {
tile.renderable = false;
}
}
});
this._layerOrderChanged = true;
tileImageryUpdatedEvent.raiseEvent();
}
};
GlobeSurfaceTileProvider.prototype._onLayerRemoved = function(layer, index) {
this._quadtree.forEachLoadedTile(function(tile) {
const tileImageryCollection = tile.data.imagery;
let startIndex = -1;
let numDestroyed = 0;
for (let i = 0, len = tileImageryCollection.length; i < len; ++i) {
const tileImagery = tileImageryCollection[i];
let imagery = tileImagery.loadingImagery;
if (!defined_default(imagery)) {
imagery = tileImagery.readyImagery;
}
if (imagery.imageryLayer === layer) {
if (startIndex === -1) {
startIndex = i;
}
tileImagery.freeResources();
++numDestroyed;
} else if (startIndex !== -1) {
break;
}
}
if (startIndex !== -1) {
tileImageryCollection.splice(startIndex, numDestroyed);
}
});
if (defined_default(layer.imageryProvider)) {
layer.imageryProvider._reload = void 0;
}
this._imageryLayersUpdatedEvent.raiseEvent();
};
GlobeSurfaceTileProvider.prototype._onLayerMoved = function(layer, newIndex, oldIndex) {
this._layerOrderChanged = true;
this._imageryLayersUpdatedEvent.raiseEvent();
};
GlobeSurfaceTileProvider.prototype._onLayerShownOrHidden = function(layer, index, show) {
if (show) {
this._onLayerAdded(layer, index);
} else {
this._onLayerRemoved(layer, index);
}
};
var scratchClippingPlanesMatrix2 = new Matrix4_default();
var scratchInverseTransposeClippingPlanesMatrix = new Matrix4_default();
function createTileUniformMap(frameState, globeSurfaceTileProvider) {
const uniformMap2 = {
u_initialColor: function() {
return this.properties.initialColor;
},
u_fillHighlightColor: function() {
return this.properties.fillHighlightColor;
},
u_zoomedOutOceanSpecularIntensity: function() {
return this.properties.zoomedOutOceanSpecularIntensity;
},
u_oceanNormalMap: function() {
return this.properties.oceanNormalMap;
},
u_atmosphereLightIntensity: function() {
return this.properties.atmosphereLightIntensity;
},
u_atmosphereRayleighCoefficient: function() {
return this.properties.atmosphereRayleighCoefficient;
},
u_atmosphereMieCoefficient: function() {
return this.properties.atmosphereMieCoefficient;
},
u_atmosphereRayleighScaleHeight: function() {
return this.properties.atmosphereRayleighScaleHeight;
},
u_atmosphereMieScaleHeight: function() {
return this.properties.atmosphereMieScaleHeight;
},
u_atmosphereMieAnisotropy: function() {
return this.properties.atmosphereMieAnisotropy;
},
u_lightingFadeDistance: function() {
return this.properties.lightingFadeDistance;
},
u_nightFadeDistance: function() {
return this.properties.nightFadeDistance;
},
u_center3D: function() {
return this.properties.center3D;
},
u_terrainExaggerationAndRelativeHeight: function() {
return this.properties.terrainExaggerationAndRelativeHeight;
},
u_tileRectangle: function() {
return this.properties.tileRectangle;
},
u_modifiedModelView: function() {
const viewMatrix = frameState.context.uniformState.view;
const centerEye = Matrix4_default.multiplyByPoint(
viewMatrix,
this.properties.rtc,
centerEyeScratch
);
Matrix4_default.setTranslation(viewMatrix, centerEye, modifiedModelViewScratch5);
return modifiedModelViewScratch5;
},
u_modifiedModelViewProjection: function() {
const viewMatrix = frameState.context.uniformState.view;
const projectionMatrix = frameState.context.uniformState.projection;
const centerEye = Matrix4_default.multiplyByPoint(
viewMatrix,
this.properties.rtc,
centerEyeScratch
);
Matrix4_default.setTranslation(
viewMatrix,
centerEye,
modifiedModelViewProjectionScratch
);
Matrix4_default.multiply(
projectionMatrix,
modifiedModelViewProjectionScratch,
modifiedModelViewProjectionScratch
);
return modifiedModelViewProjectionScratch;
},
u_dayTextures: function() {
return this.properties.dayTextures;
},
u_dayTextureTranslationAndScale: function() {
return this.properties.dayTextureTranslationAndScale;
},
u_dayTextureTexCoordsRectangle: function() {
return this.properties.dayTextureTexCoordsRectangle;
},
u_dayTextureUseWebMercatorT: function() {
return this.properties.dayTextureUseWebMercatorT;
},
u_dayTextureAlpha: function() {
return this.properties.dayTextureAlpha;
},
u_dayTextureNightAlpha: function() {
return this.properties.dayTextureNightAlpha;
},
u_dayTextureDayAlpha: function() {
return this.properties.dayTextureDayAlpha;
},
u_dayTextureBrightness: function() {
return this.properties.dayTextureBrightness;
},
u_dayTextureContrast: function() {
return this.properties.dayTextureContrast;
},
u_dayTextureHue: function() {
return this.properties.dayTextureHue;
},
u_dayTextureSaturation: function() {
return this.properties.dayTextureSaturation;
},
u_dayTextureOneOverGamma: function() {
return this.properties.dayTextureOneOverGamma;
},
u_dayIntensity: function() {
return this.properties.dayIntensity;
},
u_southAndNorthLatitude: function() {
return this.properties.southAndNorthLatitude;
},
u_southMercatorYAndOneOverHeight: function() {
return this.properties.southMercatorYAndOneOverHeight;
},
u_waterMask: function() {
return this.properties.waterMask;
},
u_waterMaskTranslationAndScale: function() {
return this.properties.waterMaskTranslationAndScale;
},
u_minMaxHeight: function() {
return this.properties.minMaxHeight;
},
u_scaleAndBias: function() {
return this.properties.scaleAndBias;
},
u_dayTextureSplit: function() {
return this.properties.dayTextureSplit;
},
u_dayTextureCutoutRectangles: function() {
return this.properties.dayTextureCutoutRectangles;
},
u_clippingPlanes: function() {
const clippingPlanes = globeSurfaceTileProvider._clippingPlanes;
if (defined_default(clippingPlanes) && defined_default(clippingPlanes.texture)) {
return clippingPlanes.texture;
}
return frameState.context.defaultTexture;
},
u_cartographicLimitRectangle: function() {
return this.properties.localizedCartographicLimitRectangle;
},
u_clippingPlanesMatrix: function() {
const clippingPlanes = globeSurfaceTileProvider._clippingPlanes;
const transform3 = defined_default(clippingPlanes) ? Matrix4_default.multiply(
frameState.context.uniformState.view,
clippingPlanes.modelMatrix,
scratchClippingPlanesMatrix2
) : Matrix4_default.IDENTITY;
return Matrix4_default.inverseTranspose(
transform3,
scratchInverseTransposeClippingPlanesMatrix
);
},
u_clippingPlanesEdgeStyle: function() {
const style = this.properties.clippingPlanesEdgeColor;
style.alpha = this.properties.clippingPlanesEdgeWidth;
return style;
},
u_minimumBrightness: function() {
return frameState.fog.minimumBrightness;
},
u_hsbShift: function() {
return this.properties.hsbShift;
},
u_colorsToAlpha: function() {
return this.properties.colorsToAlpha;
},
u_frontFaceAlphaByDistance: function() {
return this.properties.frontFaceAlphaByDistance;
},
u_backFaceAlphaByDistance: function() {
return this.properties.backFaceAlphaByDistance;
},
u_translucencyRectangle: function() {
return this.properties.localizedTranslucencyRectangle;
},
u_undergroundColor: function() {
return this.properties.undergroundColor;
},
u_undergroundColorAlphaByDistance: function() {
return this.properties.undergroundColorAlphaByDistance;
},
u_lambertDiffuseMultiplier: function() {
return this.properties.lambertDiffuseMultiplier;
},
u_vertexShadowDarkness: function() {
return this.properties.vertexShadowDarkness;
},
// make a separate object so that changes to the properties are seen on
// derived commands that combine another uniform map with this one.
properties: {
initialColor: new Cartesian4_default(0, 0, 0.5, 1),
fillHighlightColor: new Color_default(0, 0, 0, 0),
zoomedOutOceanSpecularIntensity: 0.5,
oceanNormalMap: void 0,
lightingFadeDistance: new Cartesian2_default(65e5, 9e6),
nightFadeDistance: new Cartesian2_default(1e7, 4e7),
atmosphereLightIntensity: 10,
atmosphereRayleighCoefficient: new Cartesian3_default(55e-7, 13e-6, 284e-7),
atmosphereMieCoefficient: new Cartesian3_default(21e-6, 21e-6, 21e-6),
atmosphereRayleighScaleHeight: 1e4,
atmosphereMieScaleHeight: 3200,
atmosphereMieAnisotropy: 0.9,
hsbShift: new Cartesian3_default(),
center3D: void 0,
rtc: new Cartesian3_default(),
modifiedModelView: new Matrix4_default(),
tileRectangle: new Cartesian4_default(),
terrainExaggerationAndRelativeHeight: new Cartesian2_default(1, 0),
dayTextures: [],
dayTextureTranslationAndScale: [],
dayTextureTexCoordsRectangle: [],
dayTextureUseWebMercatorT: [],
dayTextureAlpha: [],
dayTextureNightAlpha: [],
dayTextureDayAlpha: [],
dayTextureBrightness: [],
dayTextureContrast: [],
dayTextureHue: [],
dayTextureSaturation: [],
dayTextureOneOverGamma: [],
dayTextureSplit: [],
dayTextureCutoutRectangles: [],
dayIntensity: 0,
colorsToAlpha: [],
southAndNorthLatitude: new Cartesian2_default(),
southMercatorYAndOneOverHeight: new Cartesian2_default(),
waterMask: void 0,
waterMaskTranslationAndScale: new Cartesian4_default(),
minMaxHeight: new Cartesian2_default(),
scaleAndBias: new Matrix4_default(),
clippingPlanesEdgeColor: Color_default.clone(Color_default.WHITE),
clippingPlanesEdgeWidth: 0,
localizedCartographicLimitRectangle: new Cartesian4_default(),
frontFaceAlphaByDistance: new Cartesian4_default(),
backFaceAlphaByDistance: new Cartesian4_default(),
localizedTranslucencyRectangle: new Cartesian4_default(),
undergroundColor: Color_default.clone(Color_default.TRANSPARENT),
undergroundColorAlphaByDistance: new Cartesian4_default(),
lambertDiffuseMultiplier: 0,
vertexShadowDarkness: 0
}
};
if (defined_default(globeSurfaceTileProvider.materialUniformMap)) {
return combine_default(uniformMap2, globeSurfaceTileProvider.materialUniformMap);
}
return uniformMap2;
}
function createWireframeVertexArrayIfNecessary(context, provider, tile) {
const surfaceTile = tile.data;
let mesh;
let vertexArray;
if (defined_default(surfaceTile.vertexArray)) {
mesh = surfaceTile.mesh;
vertexArray = surfaceTile.vertexArray;
} else if (defined_default(surfaceTile.fill) && defined_default(surfaceTile.fill.vertexArray)) {
mesh = surfaceTile.fill.mesh;
vertexArray = surfaceTile.fill.vertexArray;
}
if (!defined_default(mesh) || !defined_default(vertexArray)) {
return;
}
if (defined_default(surfaceTile.wireframeVertexArray)) {
if (surfaceTile.wireframeVertexArray.mesh === mesh) {
return;
}
surfaceTile.wireframeVertexArray.destroy();
surfaceTile.wireframeVertexArray = void 0;
}
surfaceTile.wireframeVertexArray = createWireframeVertexArray(
context,
vertexArray,
mesh
);
surfaceTile.wireframeVertexArray.mesh = mesh;
}
function createWireframeVertexArray(context, vertexArray, terrainMesh) {
const indices2 = terrainMesh.indices;
const geometry = {
indices: indices2,
primitiveType: PrimitiveType_default.TRIANGLES
};
GeometryPipeline_default.toWireframe(geometry);
const wireframeIndices = geometry.indices;
const wireframeIndexBuffer = Buffer_default.createIndexBuffer({
context,
typedArray: wireframeIndices,
usage: BufferUsage_default.STATIC_DRAW,
indexDatatype: IndexDatatype_default.fromSizeInBytes(
wireframeIndices.BYTES_PER_ELEMENT
)
});
return new VertexArray_default({
context,
attributes: vertexArray._attributes,
indexBuffer: wireframeIndexBuffer
});
}
var getDebugOrientedBoundingBox;
var getDebugBoundingSphere;
var debugDestroyPrimitive;
(function() {
const instanceOBB = new GeometryInstance_default({
geometry: BoxOutlineGeometry_default.fromDimensions({
dimensions: new Cartesian3_default(2, 2, 2)
})
});
const instanceSphere = new GeometryInstance_default({
geometry: new SphereOutlineGeometry_default({ radius: 1 })
});
let modelMatrix = new Matrix4_default();
let previousVolume;
let primitive;
function createDebugPrimitive(instance) {
return new Primitive_default({
geometryInstances: instance,
appearance: new PerInstanceColorAppearance_default({
translucent: false,
flat: true
}),
asynchronous: false
});
}
getDebugOrientedBoundingBox = function(obb, color) {
if (obb === previousVolume) {
return primitive;
}
debugDestroyPrimitive();
previousVolume = obb;
modelMatrix = Matrix4_default.fromRotationTranslation(
obb.halfAxes,
obb.center,
modelMatrix
);
instanceOBB.modelMatrix = modelMatrix;
instanceOBB.attributes.color = ColorGeometryInstanceAttribute_default.fromColor(
color
);
primitive = createDebugPrimitive(instanceOBB);
return primitive;
};
getDebugBoundingSphere = function(sphere, color) {
if (sphere === previousVolume) {
return primitive;
}
debugDestroyPrimitive();
previousVolume = sphere;
modelMatrix = Matrix4_default.fromTranslation(sphere.center, modelMatrix);
modelMatrix = Matrix4_default.multiplyByUniformScale(
modelMatrix,
sphere.radius,
modelMatrix
);
instanceSphere.modelMatrix = modelMatrix;
instanceSphere.attributes.color = ColorGeometryInstanceAttribute_default.fromColor(
color
);
primitive = createDebugPrimitive(instanceSphere);
return primitive;
};
debugDestroyPrimitive = function() {
if (defined_default(primitive)) {
primitive.destroy();
primitive = void 0;
previousVolume = void 0;
}
};
})();
var otherPassesInitialColor = new Cartesian4_default(0, 0, 0, 0);
var surfaceShaderSetOptionsScratch = {
frameState: void 0,
surfaceTile: void 0,
numberOfDayTextures: void 0,
applyBrightness: void 0,
applyContrast: void 0,
applyHue: void 0,
applySaturation: void 0,
applyGamma: void 0,
applyAlpha: void 0,
applyDayNightAlpha: void 0,
applySplit: void 0,
showReflectiveOcean: void 0,
showOceanWaves: void 0,
enableLighting: void 0,
dynamicAtmosphereLighting: void 0,
dynamicAtmosphereLightingFromSun: void 0,
showGroundAtmosphere: void 0,
perFragmentGroundAtmosphere: void 0,
hasVertexNormals: void 0,
useWebMercatorProjection: void 0,
enableFog: void 0,
enableClippingPlanes: void 0,
clippingPlanes: void 0,
clippedByBoundaries: void 0,
hasImageryLayerCutout: void 0,
colorCorrect: void 0,
colorToAlpha: void 0,
hasGeodeticSurfaceNormals: void 0,
hasExaggeration: void 0
};
var defaultUndergroundColor = Color_default.TRANSPARENT;
var defaultUndergroundColorAlphaByDistance = new NearFarScalar_default();
function addDrawCommandsForTile(tileProvider, tile, frameState) {
const surfaceTile = tile.data;
if (!defined_default(surfaceTile.vertexArray)) {
if (surfaceTile.fill === void 0) {
surfaceTile.fill = new TerrainFillMesh_default(tile);
}
surfaceTile.fill.update(tileProvider, frameState);
}
const creditDisplay = frameState.creditDisplay;
const terrainData = surfaceTile.terrainData;
if (defined_default(terrainData) && defined_default(terrainData.credits)) {
const tileCredits = terrainData.credits;
for (let tileCreditIndex = 0, tileCreditLength = tileCredits.length; tileCreditIndex < tileCreditLength; ++tileCreditIndex) {
creditDisplay.addCreditToNextFrame(tileCredits[tileCreditIndex]);
}
}
let maxTextures = ContextLimits_default.maximumTextureImageUnits;
let waterMaskTexture = surfaceTile.waterMaskTexture;
let waterMaskTranslationAndScale = surfaceTile.waterMaskTranslationAndScale;
if (!defined_default(waterMaskTexture) && defined_default(surfaceTile.fill)) {
waterMaskTexture = surfaceTile.fill.waterMaskTexture;
waterMaskTranslationAndScale = surfaceTile.fill.waterMaskTranslationAndScale;
}
const cameraUnderground = frameState.cameraUnderground;
const globeTranslucencyState = frameState.globeTranslucencyState;
const translucent = globeTranslucencyState.translucent;
const frontFaceAlphaByDistance = globeTranslucencyState.frontFaceAlphaByDistance;
const backFaceAlphaByDistance = globeTranslucencyState.backFaceAlphaByDistance;
const translucencyRectangle = globeTranslucencyState.rectangle;
const undergroundColor = defaultValue_default(
tileProvider.undergroundColor,
defaultUndergroundColor
);
const undergroundColorAlphaByDistance = defaultValue_default(
tileProvider.undergroundColorAlphaByDistance,
defaultUndergroundColorAlphaByDistance
);
const showUndergroundColor = isUndergroundVisible(tileProvider, frameState) && frameState.mode === SceneMode_default.SCENE3D && undergroundColor.alpha > 0 && (undergroundColorAlphaByDistance.nearValue > 0 || undergroundColorAlphaByDistance.farValue > 0);
const lambertDiffuseMultiplier = tileProvider.lambertDiffuseMultiplier;
const vertexShadowDarkness = tileProvider.vertexShadowDarkness;
const showReflectiveOcean = tileProvider.hasWaterMask && defined_default(waterMaskTexture);
const oceanNormalMap = tileProvider.oceanNormalMap;
const showOceanWaves = showReflectiveOcean && defined_default(oceanNormalMap);
const hasVertexNormals = defined_default(tileProvider.terrainProvider) && // ready is deprecated; This is here for backwards compatibility
tileProvider.terrainProvider._ready && tileProvider.terrainProvider.hasVertexNormals;
const enableFog = frameState.fog.enabled && frameState.fog.renderable && !cameraUnderground;
const showGroundAtmosphere = tileProvider.showGroundAtmosphere && frameState.mode === SceneMode_default.SCENE3D;
const castShadows = ShadowMode_default.castShadows(tileProvider.shadows) && !translucent;
const receiveShadows = ShadowMode_default.receiveShadows(tileProvider.shadows) && !translucent;
const hueShift = tileProvider.hueShift;
const saturationShift = tileProvider.saturationShift;
const brightnessShift = tileProvider.brightnessShift;
let colorCorrect = !(Math_default.equalsEpsilon(hueShift, 0, Math_default.EPSILON7) && Math_default.equalsEpsilon(saturationShift, 0, Math_default.EPSILON7) && Math_default.equalsEpsilon(brightnessShift, 0, Math_default.EPSILON7));
let perFragmentGroundAtmosphere = false;
if (showGroundAtmosphere) {
const cameraDistance = Cartesian3_default.magnitude(frameState.camera.positionWC);
const fadeOutDistance = tileProvider.nightFadeOutDistance;
perFragmentGroundAtmosphere = cameraDistance > fadeOutDistance;
}
if (showReflectiveOcean) {
--maxTextures;
}
if (showOceanWaves) {
--maxTextures;
}
if (defined_default(frameState.shadowState) && frameState.shadowState.shadowsEnabled) {
--maxTextures;
}
if (defined_default(tileProvider.clippingPlanes) && tileProvider.clippingPlanes.enabled) {
--maxTextures;
}
maxTextures -= globeTranslucencyState.numberOfTextureUniforms;
const mesh = surfaceTile.renderedMesh;
let rtc = mesh.center;
const encoding = mesh.encoding;
const tileBoundingRegion = surfaceTile.tileBoundingRegion;
const exaggeration = frameState.terrainExaggeration;
const exaggerationRelativeHeight = frameState.terrainExaggerationRelativeHeight;
const hasExaggeration = exaggeration !== 1;
const hasGeodeticSurfaceNormals = encoding.hasGeodeticSurfaceNormals;
const tileRectangle = tileRectangleScratch;
let southLatitude = 0;
let northLatitude = 0;
let southMercatorY = 0;
let oneOverMercatorHeight = 0;
let useWebMercatorProjection = false;
if (frameState.mode !== SceneMode_default.SCENE3D) {
const projection = frameState.mapProjection;
const southwest = projection.project(
Rectangle_default.southwest(tile.rectangle),
southwestScratch
);
const northeast = projection.project(
Rectangle_default.northeast(tile.rectangle),
northeastScratch
);
tileRectangle.x = southwest.x;
tileRectangle.y = southwest.y;
tileRectangle.z = northeast.x;
tileRectangle.w = northeast.y;
if (frameState.mode !== SceneMode_default.MORPHING) {
rtc = rtcScratch5;
rtc.x = 0;
rtc.y = (tileRectangle.z + tileRectangle.x) * 0.5;
rtc.z = (tileRectangle.w + tileRectangle.y) * 0.5;
tileRectangle.x -= rtc.y;
tileRectangle.y -= rtc.z;
tileRectangle.z -= rtc.y;
tileRectangle.w -= rtc.z;
}
if (frameState.mode === SceneMode_default.SCENE2D && encoding.quantization === TerrainQuantization_default.BITS12) {
const epsilon = 1 / (Math.pow(2, 12) - 1) * 0.5;
const widthEpsilon = (tileRectangle.z - tileRectangle.x) * epsilon;
const heightEpsilon = (tileRectangle.w - tileRectangle.y) * epsilon;
tileRectangle.x -= widthEpsilon;
tileRectangle.y -= heightEpsilon;
tileRectangle.z += widthEpsilon;
tileRectangle.w += heightEpsilon;
}
if (projection instanceof WebMercatorProjection_default) {
southLatitude = tile.rectangle.south;
northLatitude = tile.rectangle.north;
southMercatorY = WebMercatorProjection_default.geodeticLatitudeToMercatorAngle(
southLatitude
);
oneOverMercatorHeight = 1 / (WebMercatorProjection_default.geodeticLatitudeToMercatorAngle(northLatitude) - southMercatorY);
useWebMercatorProjection = true;
}
}
const surfaceShaderSetOptions = surfaceShaderSetOptionsScratch;
surfaceShaderSetOptions.frameState = frameState;
surfaceShaderSetOptions.surfaceTile = surfaceTile;
surfaceShaderSetOptions.showReflectiveOcean = showReflectiveOcean;
surfaceShaderSetOptions.showOceanWaves = showOceanWaves;
surfaceShaderSetOptions.enableLighting = tileProvider.enableLighting;
surfaceShaderSetOptions.dynamicAtmosphereLighting = tileProvider.dynamicAtmosphereLighting;
surfaceShaderSetOptions.dynamicAtmosphereLightingFromSun = tileProvider.dynamicAtmosphereLightingFromSun;
surfaceShaderSetOptions.showGroundAtmosphere = showGroundAtmosphere;
surfaceShaderSetOptions.atmosphereLightIntensity = tileProvider.atmosphereLightIntensity;
surfaceShaderSetOptions.atmosphereRayleighCoefficient = tileProvider.atmosphereRayleighCoefficient;
surfaceShaderSetOptions.atmosphereMieCoefficient = tileProvider.atmosphereMieCoefficient;
surfaceShaderSetOptions.atmosphereRayleighScaleHeight = tileProvider.atmosphereRayleighScaleHeight;
surfaceShaderSetOptions.atmosphereMieScaleHeight = tileProvider.atmosphereMieScaleHeight;
surfaceShaderSetOptions.atmosphereMieAnisotropy = tileProvider.atmosphereMieAnisotropy;
surfaceShaderSetOptions.perFragmentGroundAtmosphere = perFragmentGroundAtmosphere;
surfaceShaderSetOptions.hasVertexNormals = hasVertexNormals;
surfaceShaderSetOptions.useWebMercatorProjection = useWebMercatorProjection;
surfaceShaderSetOptions.clippedByBoundaries = surfaceTile.clippedByBoundaries;
surfaceShaderSetOptions.hasGeodeticSurfaceNormals = hasGeodeticSurfaceNormals;
surfaceShaderSetOptions.hasExaggeration = hasExaggeration;
const tileImageryCollection = surfaceTile.imagery;
let imageryIndex = 0;
const imageryLen = tileImageryCollection.length;
const showSkirts = tileProvider.showSkirts && !cameraUnderground && !translucent;
const backFaceCulling = tileProvider.backFaceCulling && !cameraUnderground && !translucent;
const firstPassRenderState = backFaceCulling ? tileProvider._renderState : tileProvider._disableCullingRenderState;
const otherPassesRenderState = backFaceCulling ? tileProvider._blendRenderState : tileProvider._disableCullingBlendRenderState;
let renderState = firstPassRenderState;
let initialColor = tileProvider._firstPassInitialColor;
const context = frameState.context;
if (!defined_default(tileProvider._debug.boundingSphereTile)) {
debugDestroyPrimitive();
}
const materialUniformMapChanged = tileProvider._materialUniformMap !== tileProvider.materialUniformMap;
if (materialUniformMapChanged) {
tileProvider._materialUniformMap = tileProvider.materialUniformMap;
const drawCommandsLength = tileProvider._drawCommands.length;
for (let i = 0; i < drawCommandsLength; ++i) {
tileProvider._uniformMaps[i] = createTileUniformMap(
frameState,
tileProvider
);
}
}
do {
let numberOfDayTextures = 0;
let command;
let uniformMap2;
if (tileProvider._drawCommands.length <= tileProvider._usedDrawCommands) {
command = new DrawCommand_default();
command.owner = tile;
command.cull = false;
command.boundingVolume = new BoundingSphere_default();
command.orientedBoundingBox = void 0;
uniformMap2 = createTileUniformMap(frameState, tileProvider);
tileProvider._drawCommands.push(command);
tileProvider._uniformMaps.push(uniformMap2);
} else {
command = tileProvider._drawCommands[tileProvider._usedDrawCommands];
uniformMap2 = tileProvider._uniformMaps[tileProvider._usedDrawCommands];
}
command.owner = tile;
++tileProvider._usedDrawCommands;
if (tile === tileProvider._debug.boundingSphereTile) {
const obb = tileBoundingRegion.boundingVolume;
const boundingSphere = tileBoundingRegion.boundingSphere;
if (defined_default(obb)) {
getDebugOrientedBoundingBox(obb, Color_default.RED).update(frameState);
} else if (defined_default(boundingSphere)) {
getDebugBoundingSphere(boundingSphere, Color_default.RED).update(frameState);
}
}
const uniformMapProperties = uniformMap2.properties;
Cartesian4_default.clone(initialColor, uniformMapProperties.initialColor);
uniformMapProperties.oceanNormalMap = oceanNormalMap;
uniformMapProperties.lightingFadeDistance.x = tileProvider.lightingFadeOutDistance;
uniformMapProperties.lightingFadeDistance.y = tileProvider.lightingFadeInDistance;
uniformMapProperties.nightFadeDistance.x = tileProvider.nightFadeOutDistance;
uniformMapProperties.nightFadeDistance.y = tileProvider.nightFadeInDistance;
uniformMapProperties.atmosphereLightIntensity = tileProvider.atmosphereLightIntensity;
uniformMapProperties.atmosphereRayleighCoefficient = tileProvider.atmosphereRayleighCoefficient;
uniformMapProperties.atmosphereMieCoefficient = tileProvider.atmosphereMieCoefficient;
uniformMapProperties.atmosphereRayleighScaleHeight = tileProvider.atmosphereRayleighScaleHeight;
uniformMapProperties.atmosphereMieScaleHeight = tileProvider.atmosphereMieScaleHeight;
uniformMapProperties.atmosphereMieAnisotropy = tileProvider.atmosphereMieAnisotropy;
uniformMapProperties.zoomedOutOceanSpecularIntensity = tileProvider.zoomedOutOceanSpecularIntensity;
const frontFaceAlphaByDistanceFinal = cameraUnderground ? backFaceAlphaByDistance : frontFaceAlphaByDistance;
const backFaceAlphaByDistanceFinal = cameraUnderground ? frontFaceAlphaByDistance : backFaceAlphaByDistance;
if (defined_default(frontFaceAlphaByDistanceFinal)) {
Cartesian4_default.fromElements(
frontFaceAlphaByDistanceFinal.near,
frontFaceAlphaByDistanceFinal.nearValue,
frontFaceAlphaByDistanceFinal.far,
frontFaceAlphaByDistanceFinal.farValue,
uniformMapProperties.frontFaceAlphaByDistance
);
Cartesian4_default.fromElements(
backFaceAlphaByDistanceFinal.near,
backFaceAlphaByDistanceFinal.nearValue,
backFaceAlphaByDistanceFinal.far,
backFaceAlphaByDistanceFinal.farValue,
uniformMapProperties.backFaceAlphaByDistance
);
}
Cartesian4_default.fromElements(
undergroundColorAlphaByDistance.near,
undergroundColorAlphaByDistance.nearValue,
undergroundColorAlphaByDistance.far,
undergroundColorAlphaByDistance.farValue,
uniformMapProperties.undergroundColorAlphaByDistance
);
Color_default.clone(undergroundColor, uniformMapProperties.undergroundColor);
uniformMapProperties.lambertDiffuseMultiplier = lambertDiffuseMultiplier;
uniformMapProperties.vertexShadowDarkness = vertexShadowDarkness;
const highlightFillTile = !defined_default(surfaceTile.vertexArray) && defined_default(tileProvider.fillHighlightColor) && tileProvider.fillHighlightColor.alpha > 0;
if (highlightFillTile) {
Color_default.clone(
tileProvider.fillHighlightColor,
uniformMapProperties.fillHighlightColor
);
}
uniformMapProperties.terrainExaggerationAndRelativeHeight.x = exaggeration;
uniformMapProperties.terrainExaggerationAndRelativeHeight.y = exaggerationRelativeHeight;
uniformMapProperties.center3D = mesh.center;
Cartesian3_default.clone(rtc, uniformMapProperties.rtc);
Cartesian4_default.clone(tileRectangle, uniformMapProperties.tileRectangle);
uniformMapProperties.southAndNorthLatitude.x = southLatitude;
uniformMapProperties.southAndNorthLatitude.y = northLatitude;
uniformMapProperties.southMercatorYAndOneOverHeight.x = southMercatorY;
uniformMapProperties.southMercatorYAndOneOverHeight.y = oneOverMercatorHeight;
const localizedCartographicLimitRectangle = localizedCartographicLimitRectangleScratch;
const cartographicLimitRectangle = clipRectangleAntimeridian(
tile.rectangle,
tileProvider.cartographicLimitRectangle
);
const localizedTranslucencyRectangle = localizedTranslucencyRectangleScratch;
const clippedTranslucencyRectangle = clipRectangleAntimeridian(
tile.rectangle,
translucencyRectangle
);
Cartesian3_default.fromElements(
hueShift,
saturationShift,
brightnessShift,
uniformMapProperties.hsbShift
);
const cartographicTileRectangle = tile.rectangle;
const inverseTileWidth = 1 / cartographicTileRectangle.width;
const inverseTileHeight = 1 / cartographicTileRectangle.height;
localizedCartographicLimitRectangle.x = (cartographicLimitRectangle.west - cartographicTileRectangle.west) * inverseTileWidth;
localizedCartographicLimitRectangle.y = (cartographicLimitRectangle.south - cartographicTileRectangle.south) * inverseTileHeight;
localizedCartographicLimitRectangle.z = (cartographicLimitRectangle.east - cartographicTileRectangle.west) * inverseTileWidth;
localizedCartographicLimitRectangle.w = (cartographicLimitRectangle.north - cartographicTileRectangle.south) * inverseTileHeight;
Cartesian4_default.clone(
localizedCartographicLimitRectangle,
uniformMapProperties.localizedCartographicLimitRectangle
);
localizedTranslucencyRectangle.x = (clippedTranslucencyRectangle.west - cartographicTileRectangle.west) * inverseTileWidth;
localizedTranslucencyRectangle.y = (clippedTranslucencyRectangle.south - cartographicTileRectangle.south) * inverseTileHeight;
localizedTranslucencyRectangle.z = (clippedTranslucencyRectangle.east - cartographicTileRectangle.west) * inverseTileWidth;
localizedTranslucencyRectangle.w = (clippedTranslucencyRectangle.north - cartographicTileRectangle.south) * inverseTileHeight;
Cartesian4_default.clone(
localizedTranslucencyRectangle,
uniformMapProperties.localizedTranslucencyRectangle
);
const applyFog = enableFog && Math_default.fog(tile._distance, frameState.fog.density) > Math_default.EPSILON3;
colorCorrect = colorCorrect && (applyFog || showGroundAtmosphere);
let applyBrightness = false;
let applyContrast = false;
let applyHue = false;
let applySaturation = false;
let applyGamma = false;
let applyAlpha = false;
let applyDayNightAlpha = false;
let applySplit = false;
let applyCutout = false;
let applyColorToAlpha = false;
while (numberOfDayTextures < maxTextures && imageryIndex < imageryLen) {
const tileImagery = tileImageryCollection[imageryIndex];
const imagery = tileImagery.readyImagery;
++imageryIndex;
if (!defined_default(imagery) || imagery.imageryLayer.alpha === 0) {
continue;
}
const texture = tileImagery.useWebMercatorT ? imagery.textureWebMercator : imagery.texture;
if (!defined_default(texture)) {
throw new DeveloperError_default("readyImagery is not actually ready!");
}
const imageryLayer = imagery.imageryLayer;
if (!defined_default(tileImagery.textureTranslationAndScale)) {
tileImagery.textureTranslationAndScale = imageryLayer._calculateTextureTranslationAndScale(
tile,
tileImagery
);
}
uniformMapProperties.dayTextures[numberOfDayTextures] = texture;
uniformMapProperties.dayTextureTranslationAndScale[numberOfDayTextures] = tileImagery.textureTranslationAndScale;
uniformMapProperties.dayTextureTexCoordsRectangle[numberOfDayTextures] = tileImagery.textureCoordinateRectangle;
uniformMapProperties.dayTextureUseWebMercatorT[numberOfDayTextures] = tileImagery.useWebMercatorT;
uniformMapProperties.dayTextureAlpha[numberOfDayTextures] = imageryLayer.alpha;
applyAlpha = applyAlpha || uniformMapProperties.dayTextureAlpha[numberOfDayTextures] !== 1;
uniformMapProperties.dayTextureNightAlpha[numberOfDayTextures] = imageryLayer.nightAlpha;
applyDayNightAlpha = applyDayNightAlpha || uniformMapProperties.dayTextureNightAlpha[numberOfDayTextures] !== 1;
uniformMapProperties.dayTextureDayAlpha[numberOfDayTextures] = imageryLayer.dayAlpha;
applyDayNightAlpha = applyDayNightAlpha || uniformMapProperties.dayTextureDayAlpha[numberOfDayTextures] !== 1;
uniformMapProperties.dayTextureBrightness[numberOfDayTextures] = imageryLayer.brightness;
applyBrightness = applyBrightness || uniformMapProperties.dayTextureBrightness[numberOfDayTextures] !== ImageryLayer_default.DEFAULT_BRIGHTNESS;
uniformMapProperties.dayTextureContrast[numberOfDayTextures] = imageryLayer.contrast;
applyContrast = applyContrast || uniformMapProperties.dayTextureContrast[numberOfDayTextures] !== ImageryLayer_default.DEFAULT_CONTRAST;
uniformMapProperties.dayTextureHue[numberOfDayTextures] = imageryLayer.hue;
applyHue = applyHue || uniformMapProperties.dayTextureHue[numberOfDayTextures] !== ImageryLayer_default.DEFAULT_HUE;
uniformMapProperties.dayTextureSaturation[numberOfDayTextures] = imageryLayer.saturation;
applySaturation = applySaturation || uniformMapProperties.dayTextureSaturation[numberOfDayTextures] !== ImageryLayer_default.DEFAULT_SATURATION;
uniformMapProperties.dayTextureOneOverGamma[numberOfDayTextures] = 1 / imageryLayer.gamma;
applyGamma = applyGamma || uniformMapProperties.dayTextureOneOverGamma[numberOfDayTextures] !== 1 / ImageryLayer_default.DEFAULT_GAMMA;
uniformMapProperties.dayTextureSplit[numberOfDayTextures] = imageryLayer.splitDirection;
applySplit = applySplit || uniformMapProperties.dayTextureSplit[numberOfDayTextures] !== 0;
let dayTextureCutoutRectangle = uniformMapProperties.dayTextureCutoutRectangles[numberOfDayTextures];
if (!defined_default(dayTextureCutoutRectangle)) {
dayTextureCutoutRectangle = uniformMapProperties.dayTextureCutoutRectangles[numberOfDayTextures] = new Cartesian4_default();
}
Cartesian4_default.clone(Cartesian4_default.ZERO, dayTextureCutoutRectangle);
if (defined_default(imageryLayer.cutoutRectangle)) {
const cutoutRectangle = clipRectangleAntimeridian(
cartographicTileRectangle,
imageryLayer.cutoutRectangle
);
const intersection = Rectangle_default.simpleIntersection(
cutoutRectangle,
cartographicTileRectangle,
rectangleIntersectionScratch
);
applyCutout = defined_default(intersection) || applyCutout;
dayTextureCutoutRectangle.x = (cutoutRectangle.west - cartographicTileRectangle.west) * inverseTileWidth;
dayTextureCutoutRectangle.y = (cutoutRectangle.south - cartographicTileRectangle.south) * inverseTileHeight;
dayTextureCutoutRectangle.z = (cutoutRectangle.east - cartographicTileRectangle.west) * inverseTileWidth;
dayTextureCutoutRectangle.w = (cutoutRectangle.north - cartographicTileRectangle.south) * inverseTileHeight;
}
let colorToAlpha = uniformMapProperties.colorsToAlpha[numberOfDayTextures];
if (!defined_default(colorToAlpha)) {
colorToAlpha = uniformMapProperties.colorsToAlpha[numberOfDayTextures] = new Cartesian4_default();
}
const hasColorToAlpha = defined_default(imageryLayer.colorToAlpha) && imageryLayer.colorToAlphaThreshold > 0;
applyColorToAlpha = applyColorToAlpha || hasColorToAlpha;
if (hasColorToAlpha) {
const color = imageryLayer.colorToAlpha;
colorToAlpha.x = color.red;
colorToAlpha.y = color.green;
colorToAlpha.z = color.blue;
colorToAlpha.w = imageryLayer.colorToAlphaThreshold;
} else {
colorToAlpha.w = -1;
}
if (defined_default(imagery.credits)) {
const credits = imagery.credits;
for (let creditIndex = 0, creditLength = credits.length; creditIndex < creditLength; ++creditIndex) {
creditDisplay.addCreditToNextFrame(credits[creditIndex]);
}
}
++numberOfDayTextures;
}
uniformMapProperties.dayTextures.length = numberOfDayTextures;
uniformMapProperties.waterMask = waterMaskTexture;
Cartesian4_default.clone(
waterMaskTranslationAndScale,
uniformMapProperties.waterMaskTranslationAndScale
);
uniformMapProperties.minMaxHeight.x = encoding.minimumHeight;
uniformMapProperties.minMaxHeight.y = encoding.maximumHeight;
Matrix4_default.clone(encoding.matrix, uniformMapProperties.scaleAndBias);
const clippingPlanes = tileProvider._clippingPlanes;
const clippingPlanesEnabled = defined_default(clippingPlanes) && clippingPlanes.enabled && tile.isClipped;
if (clippingPlanesEnabled) {
uniformMapProperties.clippingPlanesEdgeColor = Color_default.clone(
clippingPlanes.edgeColor,
uniformMapProperties.clippingPlanesEdgeColor
);
uniformMapProperties.clippingPlanesEdgeWidth = clippingPlanes.edgeWidth;
}
surfaceShaderSetOptions.numberOfDayTextures = numberOfDayTextures;
surfaceShaderSetOptions.applyBrightness = applyBrightness;
surfaceShaderSetOptions.applyContrast = applyContrast;
surfaceShaderSetOptions.applyHue = applyHue;
surfaceShaderSetOptions.applySaturation = applySaturation;
surfaceShaderSetOptions.applyGamma = applyGamma;
surfaceShaderSetOptions.applyAlpha = applyAlpha;
surfaceShaderSetOptions.applyDayNightAlpha = applyDayNightAlpha;
surfaceShaderSetOptions.applySplit = applySplit;
surfaceShaderSetOptions.enableFog = applyFog;
surfaceShaderSetOptions.enableClippingPlanes = clippingPlanesEnabled;
surfaceShaderSetOptions.clippingPlanes = clippingPlanes;
surfaceShaderSetOptions.hasImageryLayerCutout = applyCutout;
surfaceShaderSetOptions.colorCorrect = colorCorrect;
surfaceShaderSetOptions.highlightFillTile = highlightFillTile;
surfaceShaderSetOptions.colorToAlpha = applyColorToAlpha;
surfaceShaderSetOptions.showUndergroundColor = showUndergroundColor;
surfaceShaderSetOptions.translucent = translucent;
let count = surfaceTile.renderedMesh.indices.length;
if (!showSkirts) {
count = surfaceTile.renderedMesh.indexCountWithoutSkirts;
}
command.shaderProgram = tileProvider._surfaceShaderSet.getShaderProgram(
surfaceShaderSetOptions
);
command.castShadows = castShadows;
command.receiveShadows = receiveShadows;
command.renderState = renderState;
command.primitiveType = PrimitiveType_default.TRIANGLES;
command.vertexArray = surfaceTile.vertexArray || surfaceTile.fill.vertexArray;
command.count = count;
command.uniformMap = uniformMap2;
command.pass = Pass_default.GLOBE;
if (tileProvider._debug.wireframe) {
createWireframeVertexArrayIfNecessary(context, tileProvider, tile);
if (defined_default(surfaceTile.wireframeVertexArray)) {
command.vertexArray = surfaceTile.wireframeVertexArray;
command.primitiveType = PrimitiveType_default.LINES;
command.count = count * 2;
}
}
let boundingVolume = command.boundingVolume;
const orientedBoundingBox = command.orientedBoundingBox;
if (frameState.mode !== SceneMode_default.SCENE3D) {
BoundingSphere_default.fromRectangleWithHeights2D(
tile.rectangle,
frameState.mapProjection,
tileBoundingRegion.minimumHeight,
tileBoundingRegion.maximumHeight,
boundingVolume
);
Cartesian3_default.fromElements(
boundingVolume.center.z,
boundingVolume.center.x,
boundingVolume.center.y,
boundingVolume.center
);
if (frameState.mode === SceneMode_default.MORPHING) {
boundingVolume = BoundingSphere_default.union(
tileBoundingRegion.boundingSphere,
boundingVolume,
boundingVolume
);
}
} else {
command.boundingVolume = BoundingSphere_default.clone(
tileBoundingRegion.boundingSphere,
boundingVolume
);
command.orientedBoundingBox = OrientedBoundingBox_default.clone(
tileBoundingRegion.boundingVolume,
orientedBoundingBox
);
}
command.dirty = true;
if (translucent) {
globeTranslucencyState.updateDerivedCommands(command, frameState);
}
pushCommand2(command, frameState);
renderState = otherPassesRenderState;
initialColor = otherPassesInitialColor;
} while (imageryIndex < imageryLen);
}
var GlobeSurfaceTileProvider_default = GlobeSurfaceTileProvider;
// packages/engine/Source/Scene/GlobeTranslucency.js
function GlobeTranslucency() {
this._enabled = false;
this._frontFaceAlpha = 1;
this._frontFaceAlphaByDistance = void 0;
this._backFaceAlpha = 1;
this._backFaceAlphaByDistance = void 0;
this._rectangle = Rectangle_default.clone(Rectangle_default.MAX_VALUE);
}
Object.defineProperties(GlobeTranslucency.prototype, {
/**
* When true, the globe is rendered as a translucent surface.
* START
or LOADING
.
* @memberof QuadtreeTile.prototype
* @type {boolean}
*/
needsLoading: {
get: function() {
return this.state < QuadtreeTileLoadState_default.DONE;
}
},
/**
* Gets a value indicating whether or not this tile is eligible to be unloaded.
* Typically, a tile is ineligible to be unloaded while an asynchronous operation,
* such as a request for data, is in progress on it. A tile will never be
* unloaded while it is needed for rendering, regardless of the value of this
* property. If {@link QuadtreeTile#data} is defined and has an
* eligibleForUnloading
property, the value of that property is returned.
* Otherwise, this property returns true.
* @memberof QuadtreeTile.prototype
* @type {boolean}
*/
eligibleForUnloading: {
get: function() {
let result = true;
if (defined_default(this.data)) {
result = this.data.eligibleForUnloading;
if (!defined_default(result)) {
result = true;
}
}
return result;
}
}
});
QuadtreeTile.prototype.findLevelZeroTile = function(levelZeroTiles, x, y) {
const xTiles = this.tilingScheme.getNumberOfXTilesAtLevel(0);
if (x < 0) {
x += xTiles;
} else if (x >= xTiles) {
x -= xTiles;
}
if (y < 0 || y >= this.tilingScheme.getNumberOfYTilesAtLevel(0)) {
return void 0;
}
return levelZeroTiles.filter(function(tile) {
return tile.x === x && tile.y === y;
})[0];
};
QuadtreeTile.prototype.findTileToWest = function(levelZeroTiles) {
const parent = this.parent;
if (parent === void 0) {
return this.findLevelZeroTile(levelZeroTiles, this.x - 1, this.y);
}
if (parent.southeastChild === this) {
return parent.southwestChild;
} else if (parent.northeastChild === this) {
return parent.northwestChild;
}
const westOfParent = parent.findTileToWest(levelZeroTiles);
if (westOfParent === void 0) {
return void 0;
} else if (parent.southwestChild === this) {
return westOfParent.southeastChild;
}
return westOfParent.northeastChild;
};
QuadtreeTile.prototype.findTileToEast = function(levelZeroTiles) {
const parent = this.parent;
if (parent === void 0) {
return this.findLevelZeroTile(levelZeroTiles, this.x + 1, this.y);
}
if (parent.southwestChild === this) {
return parent.southeastChild;
} else if (parent.northwestChild === this) {
return parent.northeastChild;
}
const eastOfParent = parent.findTileToEast(levelZeroTiles);
if (eastOfParent === void 0) {
return void 0;
} else if (parent.southeastChild === this) {
return eastOfParent.southwestChild;
}
return eastOfParent.northwestChild;
};
QuadtreeTile.prototype.findTileToSouth = function(levelZeroTiles) {
const parent = this.parent;
if (parent === void 0) {
return this.findLevelZeroTile(levelZeroTiles, this.x, this.y + 1);
}
if (parent.northwestChild === this) {
return parent.southwestChild;
} else if (parent.northeastChild === this) {
return parent.southeastChild;
}
const southOfParent = parent.findTileToSouth(levelZeroTiles);
if (southOfParent === void 0) {
return void 0;
} else if (parent.southwestChild === this) {
return southOfParent.northwestChild;
}
return southOfParent.northeastChild;
};
QuadtreeTile.prototype.findTileToNorth = function(levelZeroTiles) {
const parent = this.parent;
if (parent === void 0) {
return this.findLevelZeroTile(levelZeroTiles, this.x, this.y - 1);
}
if (parent.southwestChild === this) {
return parent.northwestChild;
} else if (parent.southeastChild === this) {
return parent.northeastChild;
}
const northOfParent = parent.findTileToNorth(levelZeroTiles);
if (northOfParent === void 0) {
return void 0;
} else if (parent.northwestChild === this) {
return northOfParent.southwestChild;
}
return northOfParent.southeastChild;
};
QuadtreeTile.prototype.freeResources = function() {
this.state = QuadtreeTileLoadState_default.START;
this.renderable = false;
this.upsampledFromParent = false;
if (defined_default(this.data) && defined_default(this.data.freeResources)) {
this.data.freeResources();
}
freeTile(this._southwestChild);
this._southwestChild = void 0;
freeTile(this._southeastChild);
this._southeastChild = void 0;
freeTile(this._northwestChild);
this._northwestChild = void 0;
freeTile(this._northeastChild);
this._northeastChild = void 0;
};
function freeTile(tile) {
if (defined_default(tile)) {
tile.freeResources();
}
}
var QuadtreeTile_default = QuadtreeTile;
// packages/engine/Source/Scene/TileReplacementQueue.js
function TileReplacementQueue() {
this.head = void 0;
this.tail = void 0;
this.count = 0;
this._lastBeforeStartOfFrame = void 0;
}
TileReplacementQueue.prototype.markStartOfRenderFrame = function() {
this._lastBeforeStartOfFrame = this.head;
};
TileReplacementQueue.prototype.trimTiles = function(maximumTiles) {
let tileToTrim = this.tail;
let keepTrimming = true;
while (keepTrimming && defined_default(this._lastBeforeStartOfFrame) && this.count > maximumTiles && defined_default(tileToTrim)) {
keepTrimming = tileToTrim !== this._lastBeforeStartOfFrame;
const previous = tileToTrim.replacementPrevious;
if (tileToTrim.eligibleForUnloading) {
tileToTrim.freeResources();
remove4(this, tileToTrim);
}
tileToTrim = previous;
}
};
function remove4(tileReplacementQueue, item) {
const previous = item.replacementPrevious;
const next = item.replacementNext;
if (item === tileReplacementQueue._lastBeforeStartOfFrame) {
tileReplacementQueue._lastBeforeStartOfFrame = next;
}
if (item === tileReplacementQueue.head) {
tileReplacementQueue.head = next;
} else {
previous.replacementNext = next;
}
if (item === tileReplacementQueue.tail) {
tileReplacementQueue.tail = previous;
} else {
next.replacementPrevious = previous;
}
item.replacementPrevious = void 0;
item.replacementNext = void 0;
--tileReplacementQueue.count;
}
TileReplacementQueue.prototype.markTileRendered = function(item) {
const head = this.head;
if (head === item) {
if (item === this._lastBeforeStartOfFrame) {
this._lastBeforeStartOfFrame = item.replacementNext;
}
return;
}
++this.count;
if (!defined_default(head)) {
item.replacementPrevious = void 0;
item.replacementNext = void 0;
this.head = item;
this.tail = item;
return;
}
if (defined_default(item.replacementPrevious) || defined_default(item.replacementNext)) {
remove4(this, item);
}
item.replacementPrevious = void 0;
item.replacementNext = head;
head.replacementPrevious = item;
this.head = item;
};
var TileReplacementQueue_default = TileReplacementQueue;
// packages/engine/Source/Scene/QuadtreePrimitive.js
function QuadtreePrimitive(options) {
if (!defined_default(options) || !defined_default(options.tileProvider)) {
throw new DeveloperError_default("options.tileProvider is required.");
}
if (defined_default(options.tileProvider.quadtree)) {
throw new DeveloperError_default(
"A QuadtreeTileProvider can only be used with a single QuadtreePrimitive"
);
}
this._tileProvider = options.tileProvider;
this._tileProvider.quadtree = this;
this._debug = {
enableDebugOutput: false,
maxDepth: 0,
maxDepthVisited: 0,
tilesVisited: 0,
tilesCulled: 0,
tilesRendered: 0,
tilesWaitingForChildren: 0,
lastMaxDepth: -1,
lastMaxDepthVisited: -1,
lastTilesVisited: -1,
lastTilesCulled: -1,
lastTilesRendered: -1,
lastTilesWaitingForChildren: -1,
suspendLodUpdate: false
};
const tilingScheme2 = this._tileProvider.tilingScheme;
const ellipsoid = tilingScheme2.ellipsoid;
this._tilesToRender = [];
this._tileLoadQueueHigh = [];
this._tileLoadQueueMedium = [];
this._tileLoadQueueLow = [];
this._tileReplacementQueue = new TileReplacementQueue_default();
this._levelZeroTiles = void 0;
this._loadQueueTimeSlice = 5;
this._tilesInvalidated = false;
this._addHeightCallbacks = [];
this._removeHeightCallbacks = [];
this._tileToUpdateHeights = [];
this._lastTileIndex = 0;
this._updateHeightsTimeSlice = 2;
this._cameraPositionCartographic = void 0;
this._cameraReferenceFrameOriginCartographic = void 0;
this.maximumScreenSpaceError = defaultValue_default(
options.maximumScreenSpaceError,
2
);
this.tileCacheSize = defaultValue_default(options.tileCacheSize, 100);
this.loadingDescendantLimit = 20;
this.preloadAncestors = true;
this.preloadSiblings = false;
this._occluders = new QuadtreeOccluders_default({
ellipsoid
});
this._tileLoadProgressEvent = new Event_default();
this._lastTileLoadQueueLength = 0;
this._lastSelectionFrameNumber = void 0;
}
Object.defineProperties(QuadtreePrimitive.prototype, {
/**
* Gets the provider of {@link QuadtreeTile} instances for this quadtree.
* @type {QuadtreeTile}
* @memberof QuadtreePrimitive.prototype
*/
tileProvider: {
get: function() {
return this._tileProvider;
}
},
/**
* Gets an event that's raised when the length of the tile load queue has changed since the last render frame. When the load queue is empty,
* all terrain and imagery for the current view have been loaded. The event passes the new length of the tile load queue.
*
* @memberof QuadtreePrimitive.prototype
* @type {Event}
*/
tileLoadProgressEvent: {
get: function() {
return this._tileLoadProgressEvent;
}
},
occluders: {
get: function() {
return this._occluders;
}
}
});
QuadtreePrimitive.prototype.invalidateAllTiles = function() {
this._tilesInvalidated = true;
};
function invalidateAllTiles(primitive) {
const replacementQueue = primitive._tileReplacementQueue;
replacementQueue.head = void 0;
replacementQueue.tail = void 0;
replacementQueue.count = 0;
clearTileLoadQueue(primitive);
const levelZeroTiles = primitive._levelZeroTiles;
if (defined_default(levelZeroTiles)) {
for (let i = 0; i < levelZeroTiles.length; ++i) {
const tile = levelZeroTiles[i];
const customData = tile.customData;
const customDataLength = customData.length;
for (let j = 0; j < customDataLength; ++j) {
const data = customData[j];
data.level = 0;
primitive._addHeightCallbacks.push(data);
}
levelZeroTiles[i].freeResources();
}
}
primitive._levelZeroTiles = void 0;
primitive._tileProvider.cancelReprojections();
}
QuadtreePrimitive.prototype.forEachLoadedTile = function(tileFunction) {
let tile = this._tileReplacementQueue.head;
while (defined_default(tile)) {
if (tile.state !== QuadtreeTileLoadState_default.START) {
tileFunction(tile);
}
tile = tile.replacementNext;
}
};
QuadtreePrimitive.prototype.forEachRenderedTile = function(tileFunction) {
const tilesRendered = this._tilesToRender;
for (let i = 0, len = tilesRendered.length; i < len; ++i) {
tileFunction(tilesRendered[i]);
}
};
QuadtreePrimitive.prototype.updateHeight = function(cartographic2, callback) {
const primitive = this;
const object2 = {
positionOnEllipsoidSurface: void 0,
positionCartographic: cartographic2,
level: -1,
callback
};
object2.removeFunc = function() {
const addedCallbacks = primitive._addHeightCallbacks;
const length3 = addedCallbacks.length;
for (let i = 0; i < length3; ++i) {
if (addedCallbacks[i] === object2) {
addedCallbacks.splice(i, 1);
break;
}
}
primitive._removeHeightCallbacks.push(object2);
if (object2.callback) {
object2.callback = void 0;
}
};
primitive._addHeightCallbacks.push(object2);
return object2.removeFunc;
};
QuadtreePrimitive.prototype.update = function(frameState) {
if (defined_default(this._tileProvider.update)) {
this._tileProvider.update(frameState);
}
};
function clearTileLoadQueue(primitive) {
const debug = primitive._debug;
debug.maxDepth = 0;
debug.maxDepthVisited = 0;
debug.tilesVisited = 0;
debug.tilesCulled = 0;
debug.tilesRendered = 0;
debug.tilesWaitingForChildren = 0;
primitive._tileLoadQueueHigh.length = 0;
primitive._tileLoadQueueMedium.length = 0;
primitive._tileLoadQueueLow.length = 0;
}
QuadtreePrimitive.prototype.beginFrame = function(frameState) {
const passes = frameState.passes;
if (!passes.render) {
return;
}
if (this._tilesInvalidated) {
invalidateAllTiles(this);
this._tilesInvalidated = false;
}
this._tileProvider.initialize(frameState);
clearTileLoadQueue(this);
if (this._debug.suspendLodUpdate) {
return;
}
this._tileReplacementQueue.markStartOfRenderFrame();
};
QuadtreePrimitive.prototype.render = function(frameState) {
const passes = frameState.passes;
const tileProvider = this._tileProvider;
if (passes.render) {
tileProvider.beginUpdate(frameState);
selectTilesForRendering(this, frameState);
createRenderCommandsForSelectedTiles(this, frameState);
tileProvider.endUpdate(frameState);
}
if (passes.pick && this._tilesToRender.length > 0) {
tileProvider.updateForPick(frameState);
}
};
function updateTileLoadProgress(primitive, frameState) {
const currentLoadQueueLength = primitive._tileLoadQueueHigh.length + primitive._tileLoadQueueMedium.length + primitive._tileLoadQueueLow.length;
if (currentLoadQueueLength !== primitive._lastTileLoadQueueLength || primitive._tilesInvalidated) {
const raiseEvent = Event_default.prototype.raiseEvent.bind(
primitive._tileLoadProgressEvent,
currentLoadQueueLength
);
frameState.afterRender.push(() => {
raiseEvent();
return true;
});
primitive._lastTileLoadQueueLength = currentLoadQueueLength;
}
const debug = primitive._debug;
if (debug.enableDebugOutput && !debug.suspendLodUpdate) {
debug.maxDepth = primitive._tilesToRender.reduce(function(max3, tile) {
return Math.max(max3, tile.level);
}, -1);
debug.tilesRendered = primitive._tilesToRender.length;
if (debug.tilesVisited !== debug.lastTilesVisited || debug.tilesRendered !== debug.lastTilesRendered || debug.tilesCulled !== debug.lastTilesCulled || debug.maxDepth !== debug.lastMaxDepth || debug.tilesWaitingForChildren !== debug.lastTilesWaitingForChildren || debug.maxDepthVisited !== debug.lastMaxDepthVisited) {
console.log(
`Visited ${debug.tilesVisited}, Rendered: ${debug.tilesRendered}, Culled: ${debug.tilesCulled}, Max Depth Rendered: ${debug.maxDepth}, Max Depth Visited: ${debug.maxDepthVisited}, Waiting for children: ${debug.tilesWaitingForChildren}`
);
debug.lastTilesVisited = debug.tilesVisited;
debug.lastTilesRendered = debug.tilesRendered;
debug.lastTilesCulled = debug.tilesCulled;
debug.lastMaxDepth = debug.maxDepth;
debug.lastTilesWaitingForChildren = debug.tilesWaitingForChildren;
debug.lastMaxDepthVisited = debug.maxDepthVisited;
}
}
}
QuadtreePrimitive.prototype.endFrame = function(frameState) {
const passes = frameState.passes;
if (!passes.render || frameState.mode === SceneMode_default.MORPHING) {
return;
}
processTileLoadQueue(this, frameState);
updateHeights2(this, frameState);
updateTileLoadProgress(this, frameState);
};
QuadtreePrimitive.prototype.isDestroyed = function() {
return false;
};
QuadtreePrimitive.prototype.destroy = function() {
this._tileProvider = this._tileProvider && this._tileProvider.destroy();
};
var comparisonPoint;
var centerScratch5 = new Cartographic_default();
function compareDistanceToPoint(a3, b) {
let center = Rectangle_default.center(a3.rectangle, centerScratch5);
const alon = center.longitude - comparisonPoint.longitude;
const alat = center.latitude - comparisonPoint.latitude;
center = Rectangle_default.center(b.rectangle, centerScratch5);
const blon = center.longitude - comparisonPoint.longitude;
const blat = center.latitude - comparisonPoint.latitude;
return alon * alon + alat * alat - (blon * blon + blat * blat);
}
var cameraOriginScratch = new Cartesian3_default();
var rootTraversalDetails = [];
function selectTilesForRendering(primitive, frameState) {
const debug = primitive._debug;
if (debug.suspendLodUpdate) {
return;
}
const tilesToRender = primitive._tilesToRender;
tilesToRender.length = 0;
let i;
const tileProvider = primitive._tileProvider;
if (!defined_default(primitive._levelZeroTiles)) {
if (tileProvider.ready) {
const tilingScheme2 = tileProvider.tilingScheme;
primitive._levelZeroTiles = QuadtreeTile_default.createLevelZeroTiles(
tilingScheme2
);
const numberOfRootTiles = primitive._levelZeroTiles.length;
if (rootTraversalDetails.length < numberOfRootTiles) {
rootTraversalDetails = new Array(numberOfRootTiles);
for (i = 0; i < numberOfRootTiles; ++i) {
if (rootTraversalDetails[i] === void 0) {
rootTraversalDetails[i] = new TraversalDetails();
}
}
}
} else {
return;
}
}
primitive._occluders.ellipsoid.cameraPosition = frameState.camera.positionWC;
let tile;
const levelZeroTiles = primitive._levelZeroTiles;
const occluders = levelZeroTiles.length > 1 ? primitive._occluders : void 0;
comparisonPoint = frameState.camera.positionCartographic;
levelZeroTiles.sort(compareDistanceToPoint);
const customDataAdded = primitive._addHeightCallbacks;
const customDataRemoved = primitive._removeHeightCallbacks;
const frameNumber = frameState.frameNumber;
let len;
if (customDataAdded.length > 0 || customDataRemoved.length > 0) {
for (i = 0, len = levelZeroTiles.length; i < len; ++i) {
tile = levelZeroTiles[i];
tile._updateCustomData(frameNumber, customDataAdded, customDataRemoved);
}
customDataAdded.length = 0;
customDataRemoved.length = 0;
}
const camera = frameState.camera;
primitive._cameraPositionCartographic = camera.positionCartographic;
const cameraFrameOrigin = Matrix4_default.getTranslation(
camera.transform,
cameraOriginScratch
);
primitive._cameraReferenceFrameOriginCartographic = primitive.tileProvider.tilingScheme.ellipsoid.cartesianToCartographic(
cameraFrameOrigin,
primitive._cameraReferenceFrameOriginCartographic
);
for (i = 0, len = levelZeroTiles.length; i < len; ++i) {
tile = levelZeroTiles[i];
primitive._tileReplacementQueue.markTileRendered(tile);
if (!tile.renderable) {
queueTileLoad(primitive, primitive._tileLoadQueueHigh, tile, frameState);
++debug.tilesWaitingForChildren;
} else {
visitIfVisible(
primitive,
tile,
tileProvider,
frameState,
occluders,
false,
rootTraversalDetails[i]
);
}
}
primitive._lastSelectionFrameNumber = frameNumber;
}
function queueTileLoad(primitive, queue, tile, frameState) {
if (!tile.needsLoading) {
return;
}
if (primitive.tileProvider.computeTileLoadPriority !== void 0) {
tile._loadPriority = primitive.tileProvider.computeTileLoadPriority(
tile,
frameState
);
}
queue.push(tile);
}
function TraversalDetails() {
this.allAreRenderable = true;
this.anyWereRenderedLastFrame = false;
this.notYetRenderableCount = 0;
}
function TraversalQuadDetails() {
this.southwest = new TraversalDetails();
this.southeast = new TraversalDetails();
this.northwest = new TraversalDetails();
this.northeast = new TraversalDetails();
}
TraversalQuadDetails.prototype.combine = function(result) {
const southwest = this.southwest;
const southeast = this.southeast;
const northwest = this.northwest;
const northeast = this.northeast;
result.allAreRenderable = southwest.allAreRenderable && southeast.allAreRenderable && northwest.allAreRenderable && northeast.allAreRenderable;
result.anyWereRenderedLastFrame = southwest.anyWereRenderedLastFrame || southeast.anyWereRenderedLastFrame || northwest.anyWereRenderedLastFrame || northeast.anyWereRenderedLastFrame;
result.notYetRenderableCount = southwest.notYetRenderableCount + southeast.notYetRenderableCount + northwest.notYetRenderableCount + northeast.notYetRenderableCount;
};
var traversalQuadsByLevel = new Array(31);
for (let i = 0; i < traversalQuadsByLevel.length; ++i) {
traversalQuadsByLevel[i] = new TraversalQuadDetails();
}
function visitTile2(primitive, frameState, tile, ancestorMeetsSse, traversalDetails) {
const debug = primitive._debug;
++debug.tilesVisited;
primitive._tileReplacementQueue.markTileRendered(tile);
tile._updateCustomData(frameState.frameNumber);
if (tile.level > debug.maxDepthVisited) {
debug.maxDepthVisited = tile.level;
}
const meetsSse = screenSpaceError(primitive, frameState, tile) < primitive.maximumScreenSpaceError;
const southwestChild = tile.southwestChild;
const southeastChild = tile.southeastChild;
const northwestChild = tile.northwestChild;
const northeastChild = tile.northeastChild;
const lastFrame = primitive._lastSelectionFrameNumber;
const lastFrameSelectionResult = tile._lastSelectionResultFrame === lastFrame ? tile._lastSelectionResult : TileSelectionResult_default.NONE;
const tileProvider = primitive.tileProvider;
if (meetsSse || ancestorMeetsSse) {
const oneRenderedLastFrame = TileSelectionResult_default.originalResult(lastFrameSelectionResult) === TileSelectionResult_default.RENDERED;
const twoCulledOrNotVisited = TileSelectionResult_default.originalResult(lastFrameSelectionResult) === TileSelectionResult_default.CULLED || lastFrameSelectionResult === TileSelectionResult_default.NONE;
const threeCompletelyLoaded = tile.state === QuadtreeTileLoadState_default.DONE;
let renderable = oneRenderedLastFrame || twoCulledOrNotVisited || threeCompletelyLoaded;
if (!renderable) {
if (defined_default(tileProvider.canRenderWithoutLosingDetail)) {
renderable = tileProvider.canRenderWithoutLosingDetail(tile);
}
}
if (renderable) {
if (meetsSse) {
queueTileLoad(
primitive,
primitive._tileLoadQueueMedium,
tile,
frameState
);
}
addTileToRenderList(primitive, tile);
traversalDetails.allAreRenderable = tile.renderable;
traversalDetails.anyWereRenderedLastFrame = lastFrameSelectionResult === TileSelectionResult_default.RENDERED;
traversalDetails.notYetRenderableCount = tile.renderable ? 0 : 1;
tile._lastSelectionResultFrame = frameState.frameNumber;
tile._lastSelectionResult = TileSelectionResult_default.RENDERED;
if (!traversalDetails.anyWereRenderedLastFrame) {
primitive._tileToUpdateHeights.push(tile);
}
return;
}
ancestorMeetsSse = true;
if (meetsSse) {
queueTileLoad(primitive, primitive._tileLoadQueueHigh, tile, frameState);
}
}
if (tileProvider.canRefine(tile)) {
const allAreUpsampled = southwestChild.upsampledFromParent && southeastChild.upsampledFromParent && northwestChild.upsampledFromParent && northeastChild.upsampledFromParent;
if (allAreUpsampled) {
addTileToRenderList(primitive, tile);
queueTileLoad(
primitive,
primitive._tileLoadQueueMedium,
tile,
frameState
);
primitive._tileReplacementQueue.markTileRendered(southwestChild);
primitive._tileReplacementQueue.markTileRendered(southeastChild);
primitive._tileReplacementQueue.markTileRendered(northwestChild);
primitive._tileReplacementQueue.markTileRendered(northeastChild);
traversalDetails.allAreRenderable = tile.renderable;
traversalDetails.anyWereRenderedLastFrame = lastFrameSelectionResult === TileSelectionResult_default.RENDERED;
traversalDetails.notYetRenderableCount = tile.renderable ? 0 : 1;
tile._lastSelectionResultFrame = frameState.frameNumber;
tile._lastSelectionResult = TileSelectionResult_default.RENDERED;
if (!traversalDetails.anyWereRenderedLastFrame) {
primitive._tileToUpdateHeights.push(tile);
}
return;
}
tile._lastSelectionResultFrame = frameState.frameNumber;
tile._lastSelectionResult = TileSelectionResult_default.REFINED;
const firstRenderedDescendantIndex = primitive._tilesToRender.length;
const loadIndexLow = primitive._tileLoadQueueLow.length;
const loadIndexMedium = primitive._tileLoadQueueMedium.length;
const loadIndexHigh = primitive._tileLoadQueueHigh.length;
const tilesToUpdateHeightsIndex = primitive._tileToUpdateHeights.length;
visitVisibleChildrenNearToFar(
primitive,
southwestChild,
southeastChild,
northwestChild,
northeastChild,
frameState,
ancestorMeetsSse,
traversalDetails
);
if (firstRenderedDescendantIndex !== primitive._tilesToRender.length) {
const allAreRenderable = traversalDetails.allAreRenderable;
const anyWereRenderedLastFrame = traversalDetails.anyWereRenderedLastFrame;
const notYetRenderableCount = traversalDetails.notYetRenderableCount;
let queuedForLoad = false;
if (!allAreRenderable && !anyWereRenderedLastFrame) {
const renderList = primitive._tilesToRender;
for (let i = firstRenderedDescendantIndex; i < renderList.length; ++i) {
let workTile = renderList[i];
while (workTile !== void 0 && workTile._lastSelectionResult !== TileSelectionResult_default.KICKED && workTile !== tile) {
workTile._lastSelectionResult = TileSelectionResult_default.kick(
workTile._lastSelectionResult
);
workTile = workTile.parent;
}
}
primitive._tilesToRender.length = firstRenderedDescendantIndex;
primitive._tileToUpdateHeights.length = tilesToUpdateHeightsIndex;
addTileToRenderList(primitive, tile);
tile._lastSelectionResult = TileSelectionResult_default.RENDERED;
const wasRenderedLastFrame = lastFrameSelectionResult === TileSelectionResult_default.RENDERED;
if (!wasRenderedLastFrame && notYetRenderableCount > primitive.loadingDescendantLimit) {
primitive._tileLoadQueueLow.length = loadIndexLow;
primitive._tileLoadQueueMedium.length = loadIndexMedium;
primitive._tileLoadQueueHigh.length = loadIndexHigh;
queueTileLoad(
primitive,
primitive._tileLoadQueueMedium,
tile,
frameState
);
traversalDetails.notYetRenderableCount = tile.renderable ? 0 : 1;
queuedForLoad = true;
}
traversalDetails.allAreRenderable = tile.renderable;
traversalDetails.anyWereRenderedLastFrame = wasRenderedLastFrame;
if (!wasRenderedLastFrame) {
primitive._tileToUpdateHeights.push(tile);
}
++debug.tilesWaitingForChildren;
}
if (primitive.preloadAncestors && !queuedForLoad) {
queueTileLoad(primitive, primitive._tileLoadQueueLow, tile, frameState);
}
}
return;
}
tile._lastSelectionResultFrame = frameState.frameNumber;
tile._lastSelectionResult = TileSelectionResult_default.RENDERED;
addTileToRenderList(primitive, tile);
queueTileLoad(primitive, primitive._tileLoadQueueHigh, tile, frameState);
traversalDetails.allAreRenderable = tile.renderable;
traversalDetails.anyWereRenderedLastFrame = lastFrameSelectionResult === TileSelectionResult_default.RENDERED;
traversalDetails.notYetRenderableCount = tile.renderable ? 0 : 1;
}
function visitVisibleChildrenNearToFar(primitive, southwest, southeast, northwest, northeast, frameState, ancestorMeetsSse, traversalDetails) {
const cameraPosition = frameState.camera.positionCartographic;
const tileProvider = primitive._tileProvider;
const occluders = primitive._occluders;
const quadDetails = traversalQuadsByLevel[southwest.level];
const southwestDetails = quadDetails.southwest;
const southeastDetails = quadDetails.southeast;
const northwestDetails = quadDetails.northwest;
const northeastDetails = quadDetails.northeast;
if (cameraPosition.longitude < southwest.rectangle.east) {
if (cameraPosition.latitude < southwest.rectangle.north) {
visitIfVisible(
primitive,
southwest,
tileProvider,
frameState,
occluders,
ancestorMeetsSse,
southwestDetails
);
visitIfVisible(
primitive,
southeast,
tileProvider,
frameState,
occluders,
ancestorMeetsSse,
southeastDetails
);
visitIfVisible(
primitive,
northwest,
tileProvider,
frameState,
occluders,
ancestorMeetsSse,
northwestDetails
);
visitIfVisible(
primitive,
northeast,
tileProvider,
frameState,
occluders,
ancestorMeetsSse,
northeastDetails
);
} else {
visitIfVisible(
primitive,
northwest,
tileProvider,
frameState,
occluders,
ancestorMeetsSse,
northwestDetails
);
visitIfVisible(
primitive,
southwest,
tileProvider,
frameState,
occluders,
ancestorMeetsSse,
southwestDetails
);
visitIfVisible(
primitive,
northeast,
tileProvider,
frameState,
occluders,
ancestorMeetsSse,
northeastDetails
);
visitIfVisible(
primitive,
southeast,
tileProvider,
frameState,
occluders,
ancestorMeetsSse,
southeastDetails
);
}
} else if (cameraPosition.latitude < southwest.rectangle.north) {
visitIfVisible(
primitive,
southeast,
tileProvider,
frameState,
occluders,
ancestorMeetsSse,
southeastDetails
);
visitIfVisible(
primitive,
southwest,
tileProvider,
frameState,
occluders,
ancestorMeetsSse,
southwestDetails
);
visitIfVisible(
primitive,
northeast,
tileProvider,
frameState,
occluders,
ancestorMeetsSse,
northeastDetails
);
visitIfVisible(
primitive,
northwest,
tileProvider,
frameState,
occluders,
ancestorMeetsSse,
northwestDetails
);
} else {
visitIfVisible(
primitive,
northeast,
tileProvider,
frameState,
occluders,
ancestorMeetsSse,
northeastDetails
);
visitIfVisible(
primitive,
northwest,
tileProvider,
frameState,
occluders,
ancestorMeetsSse,
northwestDetails
);
visitIfVisible(
primitive,
southeast,
tileProvider,
frameState,
occluders,
ancestorMeetsSse,
southeastDetails
);
visitIfVisible(
primitive,
southwest,
tileProvider,
frameState,
occluders,
ancestorMeetsSse,
southwestDetails
);
}
quadDetails.combine(traversalDetails);
}
function containsNeededPosition(primitive, tile) {
const rectangle = tile.rectangle;
return defined_default(primitive._cameraPositionCartographic) && Rectangle_default.contains(rectangle, primitive._cameraPositionCartographic) || defined_default(primitive._cameraReferenceFrameOriginCartographic) && Rectangle_default.contains(
rectangle,
primitive._cameraReferenceFrameOriginCartographic
);
}
function visitIfVisible(primitive, tile, tileProvider, frameState, occluders, ancestorMeetsSse, traversalDetails) {
if (tileProvider.computeTileVisibility(tile, frameState, occluders) !== Visibility_default.NONE) {
return visitTile2(
primitive,
frameState,
tile,
ancestorMeetsSse,
traversalDetails
);
}
++primitive._debug.tilesCulled;
primitive._tileReplacementQueue.markTileRendered(tile);
traversalDetails.allAreRenderable = true;
traversalDetails.anyWereRenderedLastFrame = false;
traversalDetails.notYetRenderableCount = 0;
if (containsNeededPosition(primitive, tile)) {
if (!defined_default(tile.data) || !defined_default(tile.data.vertexArray)) {
queueTileLoad(
primitive,
primitive._tileLoadQueueMedium,
tile,
frameState
);
}
const lastFrame = primitive._lastSelectionFrameNumber;
const lastFrameSelectionResult = tile._lastSelectionResultFrame === lastFrame ? tile._lastSelectionResult : TileSelectionResult_default.NONE;
if (lastFrameSelectionResult !== TileSelectionResult_default.CULLED_BUT_NEEDED && lastFrameSelectionResult !== TileSelectionResult_default.RENDERED) {
primitive._tileToUpdateHeights.push(tile);
}
tile._lastSelectionResult = TileSelectionResult_default.CULLED_BUT_NEEDED;
} else if (primitive.preloadSiblings || tile.level === 0) {
queueTileLoad(primitive, primitive._tileLoadQueueLow, tile, frameState);
tile._lastSelectionResult = TileSelectionResult_default.CULLED;
} else {
tile._lastSelectionResult = TileSelectionResult_default.CULLED;
}
tile._lastSelectionResultFrame = frameState.frameNumber;
}
function screenSpaceError(primitive, frameState, tile) {
if (frameState.mode === SceneMode_default.SCENE2D || frameState.camera.frustum instanceof OrthographicFrustum_default || frameState.camera.frustum instanceof OrthographicOffCenterFrustum_default) {
return screenSpaceError2D(primitive, frameState, tile);
}
const maxGeometricError = primitive._tileProvider.getLevelMaximumGeometricError(
tile.level
);
const distance2 = tile._distance;
const height = frameState.context.drawingBufferHeight;
const sseDenominator = frameState.camera.frustum.sseDenominator;
let error = maxGeometricError * height / (distance2 * sseDenominator);
if (frameState.fog.enabled) {
error -= Math_default.fog(distance2, frameState.fog.density) * frameState.fog.sse;
}
error /= frameState.pixelRatio;
return error;
}
function screenSpaceError2D(primitive, frameState, tile) {
const camera = frameState.camera;
let frustum = camera.frustum;
const offCenterFrustum = frustum.offCenterFrustum;
if (defined_default(offCenterFrustum)) {
frustum = offCenterFrustum;
}
const context = frameState.context;
const width = context.drawingBufferWidth;
const height = context.drawingBufferHeight;
const maxGeometricError = primitive._tileProvider.getLevelMaximumGeometricError(
tile.level
);
const pixelSize = Math.max(frustum.top - frustum.bottom, frustum.right - frustum.left) / Math.max(width, height);
let error = maxGeometricError / pixelSize;
if (frameState.fog.enabled && frameState.mode !== SceneMode_default.SCENE2D) {
error -= Math_default.fog(tile._distance, frameState.fog.density) * frameState.fog.sse;
}
error /= frameState.pixelRatio;
return error;
}
function addTileToRenderList(primitive, tile) {
primitive._tilesToRender.push(tile);
}
function processTileLoadQueue(primitive, frameState) {
const tileLoadQueueHigh = primitive._tileLoadQueueHigh;
const tileLoadQueueMedium = primitive._tileLoadQueueMedium;
const tileLoadQueueLow = primitive._tileLoadQueueLow;
if (tileLoadQueueHigh.length === 0 && tileLoadQueueMedium.length === 0 && tileLoadQueueLow.length === 0) {
return;
}
primitive._tileReplacementQueue.trimTiles(primitive.tileCacheSize);
const endTime = getTimestamp_default() + primitive._loadQueueTimeSlice;
const tileProvider = primitive._tileProvider;
let didSomeLoading = processSinglePriorityLoadQueue(
primitive,
frameState,
tileProvider,
endTime,
tileLoadQueueHigh,
false
);
didSomeLoading = processSinglePriorityLoadQueue(
primitive,
frameState,
tileProvider,
endTime,
tileLoadQueueMedium,
didSomeLoading
);
processSinglePriorityLoadQueue(
primitive,
frameState,
tileProvider,
endTime,
tileLoadQueueLow,
didSomeLoading
);
}
function sortByLoadPriority(a3, b) {
return a3._loadPriority - b._loadPriority;
}
function processSinglePriorityLoadQueue(primitive, frameState, tileProvider, endTime, loadQueue, didSomeLoading) {
if (tileProvider.computeTileLoadPriority !== void 0) {
loadQueue.sort(sortByLoadPriority);
}
for (let i = 0, len = loadQueue.length; i < len && (getTimestamp_default() < endTime || !didSomeLoading); ++i) {
const tile = loadQueue[i];
primitive._tileReplacementQueue.markTileRendered(tile);
tileProvider.loadTile(frameState, tile);
didSomeLoading = true;
}
return didSomeLoading;
}
var scratchRay = new Ray_default();
var scratchCartographic17 = new Cartographic_default();
var scratchPosition14 = new Cartesian3_default();
var scratchArray2 = [];
function updateHeights2(primitive, frameState) {
if (!primitive.tileProvider.ready) {
return;
}
const tryNextFrame = scratchArray2;
tryNextFrame.length = 0;
const tilesToUpdateHeights = primitive._tileToUpdateHeights;
const startTime = getTimestamp_default();
const timeSlice = primitive._updateHeightsTimeSlice;
const endTime = startTime + timeSlice;
const mode2 = frameState.mode;
const projection = frameState.mapProjection;
const ellipsoid = primitive.tileProvider.tilingScheme.ellipsoid;
let i;
while (tilesToUpdateHeights.length > 0) {
const tile = tilesToUpdateHeights[0];
if (!defined_default(tile.data) || !defined_default(tile.data.mesh)) {
const selectionResult = tile._lastSelectionResultFrame === primitive._lastSelectionFrameNumber ? tile._lastSelectionResult : TileSelectionResult_default.NONE;
if (selectionResult === TileSelectionResult_default.RENDERED || selectionResult === TileSelectionResult_default.CULLED_BUT_NEEDED) {
tryNextFrame.push(tile);
}
tilesToUpdateHeights.shift();
primitive._lastTileIndex = 0;
continue;
}
const customData = tile.customData;
const customDataLength = customData.length;
let timeSliceMax = false;
for (i = primitive._lastTileIndex; i < customDataLength; ++i) {
const data = customData[i];
const terrainData = tile.data.terrainData;
const upsampledGeometryFromParent = defined_default(terrainData) && terrainData.wasCreatedByUpsampling();
if (tile.level > data.level && !upsampledGeometryFromParent) {
if (!defined_default(data.positionOnEllipsoidSurface)) {
data.positionOnEllipsoidSurface = Cartesian3_default.fromRadians(
data.positionCartographic.longitude,
data.positionCartographic.latitude,
0,
ellipsoid
);
}
if (mode2 === SceneMode_default.SCENE3D) {
const surfaceNormal = ellipsoid.geodeticSurfaceNormal(
data.positionOnEllipsoidSurface,
scratchRay.direction
);
const rayOrigin = ellipsoid.getSurfaceNormalIntersectionWithZAxis(
data.positionOnEllipsoidSurface,
11500,
scratchRay.origin
);
if (!defined_default(rayOrigin)) {
let minimumHeight = 0;
if (defined_default(tile.data.tileBoundingRegion)) {
minimumHeight = tile.data.tileBoundingRegion.minimumHeight;
}
const magnitude = Math.min(minimumHeight, -11500);
const vectorToMinimumPoint = Cartesian3_default.multiplyByScalar(
surfaceNormal,
Math.abs(magnitude) + 1,
scratchPosition14
);
Cartesian3_default.subtract(
data.positionOnEllipsoidSurface,
vectorToMinimumPoint,
scratchRay.origin
);
}
} else {
Cartographic_default.clone(data.positionCartographic, scratchCartographic17);
scratchCartographic17.height = -11500;
projection.project(scratchCartographic17, scratchPosition14);
Cartesian3_default.fromElements(
scratchPosition14.z,
scratchPosition14.x,
scratchPosition14.y,
scratchPosition14
);
Cartesian3_default.clone(scratchPosition14, scratchRay.origin);
Cartesian3_default.clone(Cartesian3_default.UNIT_X, scratchRay.direction);
}
const position = tile.data.pick(
scratchRay,
mode2,
projection,
false,
scratchPosition14
);
if (defined_default(position)) {
if (defined_default(data.callback)) {
data.callback(position);
}
data.level = tile.level;
}
}
if (getTimestamp_default() >= endTime) {
timeSliceMax = true;
break;
}
}
if (timeSliceMax) {
primitive._lastTileIndex = i;
break;
} else {
primitive._lastTileIndex = 0;
tilesToUpdateHeights.shift();
}
}
for (i = 0; i < tryNextFrame.length; i++) {
tilesToUpdateHeights.push(tryNextFrame[i]);
}
}
function createRenderCommandsForSelectedTiles(primitive, frameState) {
const tileProvider = primitive._tileProvider;
const tilesToRender = primitive._tilesToRender;
for (let i = 0, len = tilesToRender.length; i < len; ++i) {
const tile = tilesToRender[i];
tileProvider.showTileThisFrame(tile, frameState);
}
}
var QuadtreePrimitive_default = QuadtreePrimitive;
// packages/engine/Source/Scene/Globe.js
function Globe(ellipsoid) {
ellipsoid = defaultValue_default(ellipsoid, Ellipsoid_default.WGS84);
const terrainProvider = new EllipsoidTerrainProvider_default({
ellipsoid
});
const imageryLayerCollection = new ImageryLayerCollection_default();
this._ellipsoid = ellipsoid;
this._imageryLayerCollection = imageryLayerCollection;
this._surfaceShaderSet = new GlobeSurfaceShaderSet_default();
this._material = void 0;
this._surface = new QuadtreePrimitive_default({
tileProvider: new GlobeSurfaceTileProvider_default({
terrainProvider,
imageryLayers: imageryLayerCollection,
surfaceShaderSet: this._surfaceShaderSet
})
});
this._terrainProvider = terrainProvider;
this._terrainProviderChanged = new Event_default();
this._undergroundColor = Color_default.clone(Color_default.BLACK);
this._undergroundColorAlphaByDistance = new NearFarScalar_default(
ellipsoid.maximumRadius / 1e3,
0,
ellipsoid.maximumRadius / 5,
1
);
this._translucency = new GlobeTranslucency_default();
makeShadersDirty(this);
this.show = true;
this._oceanNormalMapResourceDirty = true;
this._oceanNormalMapResource = new Resource_default({
url: buildModuleUrl_default("Assets/Textures/waterNormalsSmall.jpg")
});
this.maximumScreenSpaceError = 2;
this.tileCacheSize = 100;
this.loadingDescendantLimit = 20;
this.preloadAncestors = true;
this.preloadSiblings = false;
this.fillHighlightColor = void 0;
this.enableLighting = false;
this.lambertDiffuseMultiplier = 0.9;
this.dynamicAtmosphereLighting = true;
this.dynamicAtmosphereLightingFromSun = false;
this.showGroundAtmosphere = true;
this.atmosphereLightIntensity = 10;
this.atmosphereRayleighCoefficient = new Cartesian3_default(55e-7, 13e-6, 284e-7);
this.atmosphereMieCoefficient = new Cartesian3_default(21e-6, 21e-6, 21e-6);
this.atmosphereRayleighScaleHeight = 1e4;
this.atmosphereMieScaleHeight = 3200;
this.atmosphereMieAnisotropy = 0.9;
this.lightingFadeOutDistance = 1e7;
this.lightingFadeInDistance = 2e7;
this.nightFadeOutDistance = 1e7;
this.nightFadeInDistance = 5e7;
this.showWaterEffect = true;
this.depthTestAgainstTerrain = false;
this.shadows = ShadowMode_default.RECEIVE_ONLY;
this.atmosphereHueShift = 0;
this.atmosphereSaturationShift = 0;
this.atmosphereBrightnessShift = 0;
this.terrainExaggeration = 1;
this.terrainExaggerationRelativeHeight = 0;
this.showSkirts = true;
this.backFaceCulling = true;
this._oceanNormalMap = void 0;
this._zoomedOutOceanSpecularIntensity = void 0;
this.vertexShadowDarkness = 0.3;
}
Object.defineProperties(Globe.prototype, {
/**
* Gets an ellipsoid describing the shape of this globe.
* @memberof Globe.prototype
* @type {Ellipsoid}
*/
ellipsoid: {
get: function() {
return this._ellipsoid;
}
},
/**
* Gets the collection of image layers that will be rendered on this globe.
* @memberof Globe.prototype
* @type {ImageryLayerCollection}
*/
imageryLayers: {
get: function() {
return this._imageryLayerCollection;
}
},
/**
* Gets an event that's raised when an imagery layer is added, shown, hidden, moved, or removed.
*
* @memberof Globe.prototype
* @type {Event}
* @readonly
*/
imageryLayersUpdatedEvent: {
get: function() {
return this._surface.tileProvider.imageryLayersUpdatedEvent;
}
},
/**
* Returns true
when the tile load queue is empty, false
otherwise. When the load queue is empty,
* all terrain and imagery for the current view have been loaded.
* @memberof Globe.prototype
* @type {boolean}
* @readonly
*/
tilesLoaded: {
get: function() {
if (!defined_default(this._surface)) {
return true;
}
return (
// ready is deprecated. This is here for backwards compatibility
this._surface.tileProvider.ready && this._surface._tileLoadQueueHigh.length === 0 && this._surface._tileLoadQueueMedium.length === 0 && this._surface._tileLoadQueueLow.length === 0
);
}
},
/**
* Gets or sets the color of the globe when no imagery is available.
* @memberof Globe.prototype
* @type {Color}
*/
baseColor: {
get: function() {
return this._surface.tileProvider.baseColor;
},
set: function(value) {
this._surface.tileProvider.baseColor = value;
}
},
/**
* A property specifying a {@link ClippingPlaneCollection} used to selectively disable rendering on the outside of each plane.
*
* @memberof Globe.prototype
* @type {ClippingPlaneCollection}
*/
clippingPlanes: {
get: function() {
return this._surface.tileProvider.clippingPlanes;
},
set: function(value) {
this._surface.tileProvider.clippingPlanes = value;
}
},
/**
* A property specifying a {@link Rectangle} used to limit globe rendering to a cartographic area.
* Defaults to the maximum extent of cartographic coordinates.
*
* @memberof Globe.prototype
* @type {Rectangle}
* @default {@link Rectangle.MAX_VALUE}
*/
cartographicLimitRectangle: {
get: function() {
return this._surface.tileProvider.cartographicLimitRectangle;
},
set: function(value) {
if (!defined_default(value)) {
value = Rectangle_default.clone(Rectangle_default.MAX_VALUE);
}
this._surface.tileProvider.cartographicLimitRectangle = value;
}
},
/**
* The normal map to use for rendering waves in the ocean. Setting this property will
* only have an effect if the configured terrain provider includes a water mask.
* @memberof Globe.prototype
* @type {string}
* @default buildModuleUrl('Assets/Textures/waterNormalsSmall.jpg')
*/
oceanNormalMapUrl: {
get: function() {
return this._oceanNormalMapResource.url;
},
set: function(value) {
this._oceanNormalMapResource.url = value;
this._oceanNormalMapResourceDirty = true;
}
},
/**
* The terrain provider providing surface geometry for this globe.
* @type {TerrainProvider}
*
* @memberof Globe.prototype
* @type {TerrainProvider}
*
*/
terrainProvider: {
get: function() {
return this._terrainProvider;
},
set: function(value) {
if (value !== this._terrainProvider) {
this._terrainProvider = value;
this._terrainProviderChanged.raiseEvent(value);
if (defined_default(this._material)) {
makeShadersDirty(this);
}
}
}
},
/**
* Gets an event that's raised when the terrain provider is changed
*
* @memberof Globe.prototype
* @type {Event}
* @readonly
*/
terrainProviderChanged: {
get: function() {
return this._terrainProviderChanged;
}
},
/**
* Gets an event that's raised when the length of the tile load queue has changed since the last render frame. When the load queue is empty,
* all terrain and imagery for the current view have been loaded. The event passes the new length of the tile load queue.
*
* @memberof Globe.prototype
* @type {Event}
*/
tileLoadProgressEvent: {
get: function() {
return this._surface.tileLoadProgressEvent;
}
},
/**
* Gets or sets the material appearance of the Globe. This can be one of several built-in {@link Material} objects or a custom material, scripted with
* {@link https://github.com/CesiumGS/cesium/wiki/Fabric|Fabric}.
* @memberof Globe.prototype
* @type {Material | undefined}
*/
material: {
get: function() {
return this._material;
},
set: function(material) {
if (this._material !== material) {
this._material = material;
makeShadersDirty(this);
}
}
},
/**
* The color to render the back side of the globe when the camera is underground or the globe is translucent,
* blended with the globe color based on the camera's distance.
* undergroundColor
to undefined
.
*
* @memberof Globe.prototype
* @type {Color}
* @default {@link Color.BLACK}
*
* @see Globe#undergroundColorAlphaByDistance
*/
undergroundColor: {
get: function() {
return this._undergroundColor;
},
set: function(value) {
this._undergroundColor = Color_default.clone(value, this._undergroundColor);
}
},
/**
* Gets or sets the near and far distance for blending {@link Globe#undergroundColor} with the globe color.
* The alpha will interpolate between the {@link NearFarScalar#nearValue} and
* {@link NearFarScalar#farValue} while the camera distance falls within the lower and upper bounds
* of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}.
* Outside of these ranges the alpha remains clamped to the nearest bound. If undefined,
* the underground color will not be blended with the globe color.
* percentageChanged
.
* @memberof Camera.prototype
* @type {Event}
* @readonly
*/
changed: {
get: function() {
return this._changed;
}
}
});
Camera.prototype.update = function(mode2) {
if (!defined_default(mode2)) {
throw new DeveloperError_default("mode is required.");
}
if (mode2 === SceneMode_default.SCENE2D && !(this.frustum instanceof OrthographicOffCenterFrustum_default)) {
throw new DeveloperError_default(
"An OrthographicOffCenterFrustum is required in 2D."
);
}
if ((mode2 === SceneMode_default.SCENE3D || mode2 === SceneMode_default.COLUMBUS_VIEW) && !(this.frustum instanceof PerspectiveFrustum_default) && !(this.frustum instanceof OrthographicFrustum_default)) {
throw new DeveloperError_default(
"A PerspectiveFrustum or OrthographicFrustum is required in 3D and Columbus view"
);
}
let updateFrustum = false;
if (mode2 !== this._mode) {
this._mode = mode2;
this._modeChanged = mode2 !== SceneMode_default.MORPHING;
updateFrustum = this._mode === SceneMode_default.SCENE2D;
}
if (updateFrustum) {
const frustum = this._max2Dfrustum = this.frustum.clone();
if (!(frustum instanceof OrthographicOffCenterFrustum_default)) {
throw new DeveloperError_default(
"The camera frustum is expected to be orthographic for 2D camera control."
);
}
const maxZoomOut = 2;
const ratio = frustum.top / frustum.right;
frustum.right = this._maxCoord.x * maxZoomOut;
frustum.left = -frustum.right;
frustum.top = ratio * frustum.right;
frustum.bottom = -frustum.top;
}
if (this._mode === SceneMode_default.SCENE2D) {
clampMove2D(this, this.position);
}
};
var setTransformPosition = new Cartesian3_default();
var setTransformUp = new Cartesian3_default();
var setTransformDirection = new Cartesian3_default();
Camera.prototype._setTransform = function(transform3) {
const position = Cartesian3_default.clone(this.positionWC, setTransformPosition);
const up = Cartesian3_default.clone(this.upWC, setTransformUp);
const direction2 = Cartesian3_default.clone(this.directionWC, setTransformDirection);
Matrix4_default.clone(transform3, this._transform);
this._transformChanged = true;
updateMembers(this);
const inverse = this._actualInvTransform;
Matrix4_default.multiplyByPoint(inverse, position, this.position);
Matrix4_default.multiplyByPointAsVector(inverse, direction2, this.direction);
Matrix4_default.multiplyByPointAsVector(inverse, up, this.up);
Cartesian3_default.cross(this.direction, this.up, this.right);
updateMembers(this);
};
var scratchAdjustOrthographicFrustumMousePosition = new Cartesian2_default();
var scratchPickRay = new Ray_default();
var scratchRayIntersection = new Cartesian3_default();
var scratchDepthIntersection = new Cartesian3_default();
function calculateOrthographicFrustumWidth(camera) {
if (!Matrix4_default.equals(Matrix4_default.IDENTITY, camera.transform)) {
return Cartesian3_default.magnitude(camera.position);
}
const scene = camera._scene;
const globe = scene.globe;
const mousePosition = scratchAdjustOrthographicFrustumMousePosition;
mousePosition.x = scene.drawingBufferWidth / 2;
mousePosition.y = scene.drawingBufferHeight / 2;
let rayIntersection;
if (defined_default(globe)) {
const ray = camera.getPickRay(mousePosition, scratchPickRay);
rayIntersection = globe.pickWorldCoordinates(
ray,
scene,
true,
scratchRayIntersection
);
}
let depthIntersection;
if (scene.pickPositionSupported) {
depthIntersection = scene.pickPositionWorldCoordinates(
mousePosition,
scratchDepthIntersection
);
}
let distance2;
if (defined_default(rayIntersection) || defined_default(depthIntersection)) {
const depthDistance = defined_default(depthIntersection) ? Cartesian3_default.distance(depthIntersection, camera.positionWC) : Number.POSITIVE_INFINITY;
const rayDistance = defined_default(rayIntersection) ? Cartesian3_default.distance(rayIntersection, camera.positionWC) : Number.POSITIVE_INFINITY;
distance2 = Math.min(depthDistance, rayDistance);
} else {
distance2 = Math.max(camera.positionCartographic.height, 0);
}
return distance2;
}
Camera.prototype._adjustOrthographicFrustum = function(zooming) {
if (!(this.frustum instanceof OrthographicFrustum_default)) {
return;
}
if (!zooming && this._positionCartographic.height < 15e4) {
return;
}
this.frustum.width = calculateOrthographicFrustumWidth(this);
};
var scratchSetViewCartesian = new Cartesian3_default();
var scratchSetViewTransform1 = new Matrix4_default();
var scratchSetViewTransform2 = new Matrix4_default();
var scratchSetViewQuaternion = new Quaternion_default();
var scratchSetViewMatrix3 = new Matrix3_default();
var scratchSetViewCartographic = new Cartographic_default();
function setView3D(camera, position, hpr) {
const currentTransform = Matrix4_default.clone(
camera.transform,
scratchSetViewTransform1
);
const localTransform = Transforms_default.eastNorthUpToFixedFrame(
position,
camera._projection.ellipsoid,
scratchSetViewTransform2
);
camera._setTransform(localTransform);
Cartesian3_default.clone(Cartesian3_default.ZERO, camera.position);
hpr.heading = hpr.heading - Math_default.PI_OVER_TWO;
const rotQuat = Quaternion_default.fromHeadingPitchRoll(
hpr,
scratchSetViewQuaternion
);
const rotMat = Matrix3_default.fromQuaternion(rotQuat, scratchSetViewMatrix3);
Matrix3_default.getColumn(rotMat, 0, camera.direction);
Matrix3_default.getColumn(rotMat, 2, camera.up);
Cartesian3_default.cross(camera.direction, camera.up, camera.right);
camera._setTransform(currentTransform);
camera._adjustOrthographicFrustum(true);
}
function setViewCV(camera, position, hpr, convert) {
const currentTransform = Matrix4_default.clone(
camera.transform,
scratchSetViewTransform1
);
camera._setTransform(Matrix4_default.IDENTITY);
if (!Cartesian3_default.equals(position, camera.positionWC)) {
if (convert) {
const projection = camera._projection;
const cartographic2 = projection.ellipsoid.cartesianToCartographic(
position,
scratchSetViewCartographic
);
position = projection.project(cartographic2, scratchSetViewCartesian);
}
Cartesian3_default.clone(position, camera.position);
}
hpr.heading = hpr.heading - Math_default.PI_OVER_TWO;
const rotQuat = Quaternion_default.fromHeadingPitchRoll(
hpr,
scratchSetViewQuaternion
);
const rotMat = Matrix3_default.fromQuaternion(rotQuat, scratchSetViewMatrix3);
Matrix3_default.getColumn(rotMat, 0, camera.direction);
Matrix3_default.getColumn(rotMat, 2, camera.up);
Cartesian3_default.cross(camera.direction, camera.up, camera.right);
camera._setTransform(currentTransform);
camera._adjustOrthographicFrustum(true);
}
function setView2D(camera, position, hpr, convert) {
const currentTransform = Matrix4_default.clone(
camera.transform,
scratchSetViewTransform1
);
camera._setTransform(Matrix4_default.IDENTITY);
if (!Cartesian3_default.equals(position, camera.positionWC)) {
if (convert) {
const projection = camera._projection;
const cartographic2 = projection.ellipsoid.cartesianToCartographic(
position,
scratchSetViewCartographic
);
position = projection.project(cartographic2, scratchSetViewCartesian);
}
Cartesian2_default.clone(position, camera.position);
const newLeft = -position.z * 0.5;
const newRight = -newLeft;
const frustum = camera.frustum;
if (newRight > newLeft) {
const ratio = frustum.top / frustum.right;
frustum.right = newRight;
frustum.left = newLeft;
frustum.top = frustum.right * ratio;
frustum.bottom = -frustum.top;
}
}
if (camera._scene.mapMode2D === MapMode2D_default.ROTATE) {
hpr.heading = hpr.heading - Math_default.PI_OVER_TWO;
hpr.pitch = -Math_default.PI_OVER_TWO;
hpr.roll = 0;
const rotQuat = Quaternion_default.fromHeadingPitchRoll(
hpr,
scratchSetViewQuaternion
);
const rotMat = Matrix3_default.fromQuaternion(rotQuat, scratchSetViewMatrix3);
Matrix3_default.getColumn(rotMat, 2, camera.up);
Cartesian3_default.cross(camera.direction, camera.up, camera.right);
}
camera._setTransform(currentTransform);
}
var scratchToHPRDirection = new Cartesian3_default();
var scratchToHPRUp = new Cartesian3_default();
var scratchToHPRRight = new Cartesian3_default();
function directionUpToHeadingPitchRoll(camera, position, orientation, result) {
const direction2 = Cartesian3_default.clone(
orientation.direction,
scratchToHPRDirection
);
const up = Cartesian3_default.clone(orientation.up, scratchToHPRUp);
if (camera._scene.mode === SceneMode_default.SCENE3D) {
const ellipsoid = camera._projection.ellipsoid;
const transform3 = Transforms_default.eastNorthUpToFixedFrame(
position,
ellipsoid,
scratchHPRMatrix1
);
const invTransform = Matrix4_default.inverseTransformation(
transform3,
scratchHPRMatrix2
);
Matrix4_default.multiplyByPointAsVector(invTransform, direction2, direction2);
Matrix4_default.multiplyByPointAsVector(invTransform, up, up);
}
const right = Cartesian3_default.cross(direction2, up, scratchToHPRRight);
result.heading = getHeading(direction2, up);
result.pitch = getPitch(direction2);
result.roll = getRoll(direction2, up, right);
return result;
}
var scratchSetViewOptions = {
destination: void 0,
orientation: {
direction: void 0,
up: void 0,
heading: void 0,
pitch: void 0,
roll: void 0
},
convert: void 0,
endTransform: void 0
};
var scratchHpr = new HeadingPitchRoll_default();
Camera.prototype.setView = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
let orientation = defaultValue_default(
options.orientation,
defaultValue_default.EMPTY_OBJECT
);
const mode2 = this._mode;
if (mode2 === SceneMode_default.MORPHING) {
return;
}
if (defined_default(options.endTransform)) {
this._setTransform(options.endTransform);
}
let convert = defaultValue_default(options.convert, true);
let destination = defaultValue_default(
options.destination,
Cartesian3_default.clone(this.positionWC, scratchSetViewCartesian)
);
if (defined_default(destination) && defined_default(destination.west)) {
destination = this.getRectangleCameraCoordinates(
destination,
scratchSetViewCartesian
);
convert = false;
}
if (defined_default(orientation.direction)) {
orientation = directionUpToHeadingPitchRoll(
this,
destination,
orientation,
scratchSetViewOptions.orientation
);
}
scratchHpr.heading = defaultValue_default(orientation.heading, 0);
scratchHpr.pitch = defaultValue_default(orientation.pitch, -Math_default.PI_OVER_TWO);
scratchHpr.roll = defaultValue_default(orientation.roll, 0);
if (mode2 === SceneMode_default.SCENE3D) {
setView3D(this, destination, scratchHpr);
} else if (mode2 === SceneMode_default.SCENE2D) {
setView2D(this, destination, scratchHpr, convert);
} else {
setViewCV(this, destination, scratchHpr, convert);
}
};
var pitchScratch = new Cartesian3_default();
Camera.prototype.flyHome = function(duration) {
const mode2 = this._mode;
if (mode2 === SceneMode_default.MORPHING) {
this._scene.completeMorph();
}
if (mode2 === SceneMode_default.SCENE2D) {
this.flyTo({
destination: Camera.DEFAULT_VIEW_RECTANGLE,
duration,
endTransform: Matrix4_default.IDENTITY
});
} else if (mode2 === SceneMode_default.SCENE3D) {
const destination = this.getRectangleCameraCoordinates(
Camera.DEFAULT_VIEW_RECTANGLE
);
let mag = Cartesian3_default.magnitude(destination);
mag += mag * Camera.DEFAULT_VIEW_FACTOR;
Cartesian3_default.normalize(destination, destination);
Cartesian3_default.multiplyByScalar(destination, mag, destination);
this.flyTo({
destination,
duration,
endTransform: Matrix4_default.IDENTITY
});
} else if (mode2 === SceneMode_default.COLUMBUS_VIEW) {
const maxRadii = this._projection.ellipsoid.maximumRadius;
let position = new Cartesian3_default(0, -1, 1);
position = Cartesian3_default.multiplyByScalar(
Cartesian3_default.normalize(position, position),
5 * maxRadii,
position
);
this.flyTo({
destination: position,
duration,
orientation: {
heading: 0,
pitch: -Math.acos(Cartesian3_default.normalize(position, pitchScratch).z),
roll: 0
},
endTransform: Matrix4_default.IDENTITY,
convert: false
});
}
};
Camera.prototype.worldToCameraCoordinates = function(cartesian11, result) {
if (!defined_default(cartesian11)) {
throw new DeveloperError_default("cartesian is required.");
}
if (!defined_default(result)) {
result = new Cartesian4_default();
}
updateMembers(this);
return Matrix4_default.multiplyByVector(this._actualInvTransform, cartesian11, result);
};
Camera.prototype.worldToCameraCoordinatesPoint = function(cartesian11, result) {
if (!defined_default(cartesian11)) {
throw new DeveloperError_default("cartesian is required.");
}
if (!defined_default(result)) {
result = new Cartesian3_default();
}
updateMembers(this);
return Matrix4_default.multiplyByPoint(this._actualInvTransform, cartesian11, result);
};
Camera.prototype.worldToCameraCoordinatesVector = function(cartesian11, result) {
if (!defined_default(cartesian11)) {
throw new DeveloperError_default("cartesian is required.");
}
if (!defined_default(result)) {
result = new Cartesian3_default();
}
updateMembers(this);
return Matrix4_default.multiplyByPointAsVector(
this._actualInvTransform,
cartesian11,
result
);
};
Camera.prototype.cameraToWorldCoordinates = function(cartesian11, result) {
if (!defined_default(cartesian11)) {
throw new DeveloperError_default("cartesian is required.");
}
if (!defined_default(result)) {
result = new Cartesian4_default();
}
updateMembers(this);
return Matrix4_default.multiplyByVector(this._actualTransform, cartesian11, result);
};
Camera.prototype.cameraToWorldCoordinatesPoint = function(cartesian11, result) {
if (!defined_default(cartesian11)) {
throw new DeveloperError_default("cartesian is required.");
}
if (!defined_default(result)) {
result = new Cartesian3_default();
}
updateMembers(this);
return Matrix4_default.multiplyByPoint(this._actualTransform, cartesian11, result);
};
Camera.prototype.cameraToWorldCoordinatesVector = function(cartesian11, result) {
if (!defined_default(cartesian11)) {
throw new DeveloperError_default("cartesian is required.");
}
if (!defined_default(result)) {
result = new Cartesian3_default();
}
updateMembers(this);
return Matrix4_default.multiplyByPointAsVector(
this._actualTransform,
cartesian11,
result
);
};
function clampMove2D(camera, position) {
const rotatable2D = camera._scene.mapMode2D === MapMode2D_default.ROTATE;
const maxProjectedX = camera._maxCoord.x;
const maxProjectedY = camera._maxCoord.y;
let minX;
let maxX;
if (rotatable2D) {
maxX = maxProjectedX;
minX = -maxX;
} else {
maxX = position.x - maxProjectedX * 2;
minX = position.x + maxProjectedX * 2;
}
if (position.x > maxProjectedX) {
position.x = maxX;
}
if (position.x < -maxProjectedX) {
position.x = minX;
}
if (position.y > maxProjectedY) {
position.y = maxProjectedY;
}
if (position.y < -maxProjectedY) {
position.y = -maxProjectedY;
}
}
var moveScratch = new Cartesian3_default();
Camera.prototype.move = function(direction2, amount) {
if (!defined_default(direction2)) {
throw new DeveloperError_default("direction is required.");
}
const cameraPosition = this.position;
Cartesian3_default.multiplyByScalar(direction2, amount, moveScratch);
Cartesian3_default.add(cameraPosition, moveScratch, cameraPosition);
if (this._mode === SceneMode_default.SCENE2D) {
clampMove2D(this, cameraPosition);
}
this._adjustOrthographicFrustum(true);
};
Camera.prototype.moveForward = function(amount) {
amount = defaultValue_default(amount, this.defaultMoveAmount);
if (this._mode === SceneMode_default.SCENE2D) {
zoom2D(this, amount);
} else {
this.move(this.direction, amount);
}
};
Camera.prototype.moveBackward = function(amount) {
amount = defaultValue_default(amount, this.defaultMoveAmount);
if (this._mode === SceneMode_default.SCENE2D) {
zoom2D(this, -amount);
} else {
this.move(this.direction, -amount);
}
};
Camera.prototype.moveUp = function(amount) {
amount = defaultValue_default(amount, this.defaultMoveAmount);
this.move(this.up, amount);
};
Camera.prototype.moveDown = function(amount) {
amount = defaultValue_default(amount, this.defaultMoveAmount);
this.move(this.up, -amount);
};
Camera.prototype.moveRight = function(amount) {
amount = defaultValue_default(amount, this.defaultMoveAmount);
this.move(this.right, amount);
};
Camera.prototype.moveLeft = function(amount) {
amount = defaultValue_default(amount, this.defaultMoveAmount);
this.move(this.right, -amount);
};
Camera.prototype.lookLeft = function(amount) {
amount = defaultValue_default(amount, this.defaultLookAmount);
if (this._mode !== SceneMode_default.SCENE2D) {
this.look(this.up, -amount);
}
};
Camera.prototype.lookRight = function(amount) {
amount = defaultValue_default(amount, this.defaultLookAmount);
if (this._mode !== SceneMode_default.SCENE2D) {
this.look(this.up, amount);
}
};
Camera.prototype.lookUp = function(amount) {
amount = defaultValue_default(amount, this.defaultLookAmount);
if (this._mode !== SceneMode_default.SCENE2D) {
this.look(this.right, -amount);
}
};
Camera.prototype.lookDown = function(amount) {
amount = defaultValue_default(amount, this.defaultLookAmount);
if (this._mode !== SceneMode_default.SCENE2D) {
this.look(this.right, amount);
}
};
var lookScratchQuaternion = new Quaternion_default();
var lookScratchMatrix = new Matrix3_default();
Camera.prototype.look = function(axis, angle) {
if (!defined_default(axis)) {
throw new DeveloperError_default("axis is required.");
}
const turnAngle = defaultValue_default(angle, this.defaultLookAmount);
const quaternion = Quaternion_default.fromAxisAngle(
axis,
-turnAngle,
lookScratchQuaternion
);
const rotation = Matrix3_default.fromQuaternion(quaternion, lookScratchMatrix);
const direction2 = this.direction;
const up = this.up;
const right = this.right;
Matrix3_default.multiplyByVector(rotation, direction2, direction2);
Matrix3_default.multiplyByVector(rotation, up, up);
Matrix3_default.multiplyByVector(rotation, right, right);
};
Camera.prototype.twistLeft = function(amount) {
amount = defaultValue_default(amount, this.defaultLookAmount);
this.look(this.direction, amount);
};
Camera.prototype.twistRight = function(amount) {
amount = defaultValue_default(amount, this.defaultLookAmount);
this.look(this.direction, -amount);
};
var rotateScratchQuaternion = new Quaternion_default();
var rotateScratchMatrix = new Matrix3_default();
Camera.prototype.rotate = function(axis, angle) {
if (!defined_default(axis)) {
throw new DeveloperError_default("axis is required.");
}
const turnAngle = defaultValue_default(angle, this.defaultRotateAmount);
const quaternion = Quaternion_default.fromAxisAngle(
axis,
-turnAngle,
rotateScratchQuaternion
);
const rotation = Matrix3_default.fromQuaternion(quaternion, rotateScratchMatrix);
Matrix3_default.multiplyByVector(rotation, this.position, this.position);
Matrix3_default.multiplyByVector(rotation, this.direction, this.direction);
Matrix3_default.multiplyByVector(rotation, this.up, this.up);
Cartesian3_default.cross(this.direction, this.up, this.right);
Cartesian3_default.cross(this.right, this.direction, this.up);
this._adjustOrthographicFrustum(false);
};
Camera.prototype.rotateDown = function(angle) {
angle = defaultValue_default(angle, this.defaultRotateAmount);
rotateVertical(this, angle);
};
Camera.prototype.rotateUp = function(angle) {
angle = defaultValue_default(angle, this.defaultRotateAmount);
rotateVertical(this, -angle);
};
var rotateVertScratchP = new Cartesian3_default();
var rotateVertScratchA = new Cartesian3_default();
var rotateVertScratchTan = new Cartesian3_default();
var rotateVertScratchNegate = new Cartesian3_default();
function rotateVertical(camera, angle) {
const position = camera.position;
if (defined_default(camera.constrainedAxis) && !Cartesian3_default.equalsEpsilon(
camera.position,
Cartesian3_default.ZERO,
Math_default.EPSILON2
)) {
const p = Cartesian3_default.normalize(position, rotateVertScratchP);
const northParallel = Cartesian3_default.equalsEpsilon(
p,
camera.constrainedAxis,
Math_default.EPSILON2
);
const southParallel = Cartesian3_default.equalsEpsilon(
p,
Cartesian3_default.negate(camera.constrainedAxis, rotateVertScratchNegate),
Math_default.EPSILON2
);
if (!northParallel && !southParallel) {
const constrainedAxis = Cartesian3_default.normalize(
camera.constrainedAxis,
rotateVertScratchA
);
let dot2 = Cartesian3_default.dot(p, constrainedAxis);
let angleToAxis = Math_default.acosClamped(dot2);
if (angle > 0 && angle > angleToAxis) {
angle = angleToAxis - Math_default.EPSILON4;
}
dot2 = Cartesian3_default.dot(
p,
Cartesian3_default.negate(constrainedAxis, rotateVertScratchNegate)
);
angleToAxis = Math_default.acosClamped(dot2);
if (angle < 0 && -angle > angleToAxis) {
angle = -angleToAxis + Math_default.EPSILON4;
}
const tangent = Cartesian3_default.cross(
constrainedAxis,
p,
rotateVertScratchTan
);
camera.rotate(tangent, angle);
} else if (northParallel && angle < 0 || southParallel && angle > 0) {
camera.rotate(camera.right, angle);
}
} else {
camera.rotate(camera.right, angle);
}
}
Camera.prototype.rotateRight = function(angle) {
angle = defaultValue_default(angle, this.defaultRotateAmount);
rotateHorizontal(this, -angle);
};
Camera.prototype.rotateLeft = function(angle) {
angle = defaultValue_default(angle, this.defaultRotateAmount);
rotateHorizontal(this, angle);
};
function rotateHorizontal(camera, angle) {
if (defined_default(camera.constrainedAxis)) {
camera.rotate(camera.constrainedAxis, angle);
} else {
camera.rotate(camera.up, angle);
}
}
function zoom2D(camera, amount) {
const frustum = camera.frustum;
if (!(frustum instanceof OrthographicOffCenterFrustum_default) || !defined_default(frustum.left) || !defined_default(frustum.right) || !defined_default(frustum.bottom) || !defined_default(frustum.top)) {
throw new DeveloperError_default(
"The camera frustum is expected to be orthographic for 2D camera control."
);
}
let ratio;
amount = amount * 0.5;
if (Math.abs(frustum.top) + Math.abs(frustum.bottom) > Math.abs(frustum.left) + Math.abs(frustum.right)) {
let newTop = frustum.top - amount;
let newBottom = frustum.bottom + amount;
let maxBottom = camera._maxCoord.y;
if (camera._scene.mapMode2D === MapMode2D_default.ROTATE) {
maxBottom *= camera.maximumZoomFactor;
}
if (newBottom > maxBottom) {
newBottom = maxBottom;
newTop = -maxBottom;
}
if (newTop <= newBottom) {
newTop = 1;
newBottom = -1;
}
ratio = frustum.right / frustum.top;
frustum.top = newTop;
frustum.bottom = newBottom;
frustum.right = frustum.top * ratio;
frustum.left = -frustum.right;
} else {
let newRight = frustum.right - amount;
let newLeft = frustum.left + amount;
let maxRight = camera._maxCoord.x;
if (camera._scene.mapMode2D === MapMode2D_default.ROTATE) {
maxRight *= camera.maximumZoomFactor;
}
if (newRight > maxRight) {
newRight = maxRight;
newLeft = -maxRight;
}
if (newRight <= newLeft) {
newRight = 1;
newLeft = -1;
}
ratio = frustum.top / frustum.right;
frustum.right = newRight;
frustum.left = newLeft;
frustum.top = frustum.right * ratio;
frustum.bottom = -frustum.top;
}
}
function zoom3D(camera, amount) {
camera.move(camera.direction, amount);
}
Camera.prototype.zoomIn = function(amount) {
amount = defaultValue_default(amount, this.defaultZoomAmount);
if (this._mode === SceneMode_default.SCENE2D) {
zoom2D(this, amount);
} else {
zoom3D(this, amount);
}
};
Camera.prototype.zoomOut = function(amount) {
amount = defaultValue_default(amount, this.defaultZoomAmount);
if (this._mode === SceneMode_default.SCENE2D) {
zoom2D(this, -amount);
} else {
zoom3D(this, -amount);
}
};
Camera.prototype.getMagnitude = function() {
if (this._mode === SceneMode_default.SCENE3D) {
return Cartesian3_default.magnitude(this.position);
} else if (this._mode === SceneMode_default.COLUMBUS_VIEW) {
return Math.abs(this.position.z);
} else if (this._mode === SceneMode_default.SCENE2D) {
return Math.max(
this.frustum.right - this.frustum.left,
this.frustum.top - this.frustum.bottom
);
}
};
var scratchLookAtMatrix4 = new Matrix4_default();
Camera.prototype.lookAt = function(target, offset2) {
if (!defined_default(target)) {
throw new DeveloperError_default("target is required");
}
if (!defined_default(offset2)) {
throw new DeveloperError_default("offset is required");
}
if (this._mode === SceneMode_default.MORPHING) {
throw new DeveloperError_default("lookAt is not supported while morphing.");
}
const transform3 = Transforms_default.eastNorthUpToFixedFrame(
target,
Ellipsoid_default.WGS84,
scratchLookAtMatrix4
);
this.lookAtTransform(transform3, offset2);
};
var scratchLookAtHeadingPitchRangeOffset = new Cartesian3_default();
var scratchLookAtHeadingPitchRangeQuaternion1 = new Quaternion_default();
var scratchLookAtHeadingPitchRangeQuaternion2 = new Quaternion_default();
var scratchHeadingPitchRangeMatrix3 = new Matrix3_default();
function offsetFromHeadingPitchRange(heading, pitch, range) {
pitch = Math_default.clamp(
pitch,
-Math_default.PI_OVER_TWO,
Math_default.PI_OVER_TWO
);
heading = Math_default.zeroToTwoPi(heading) - Math_default.PI_OVER_TWO;
const pitchQuat = Quaternion_default.fromAxisAngle(
Cartesian3_default.UNIT_Y,
-pitch,
scratchLookAtHeadingPitchRangeQuaternion1
);
const headingQuat = Quaternion_default.fromAxisAngle(
Cartesian3_default.UNIT_Z,
-heading,
scratchLookAtHeadingPitchRangeQuaternion2
);
const rotQuat = Quaternion_default.multiply(headingQuat, pitchQuat, headingQuat);
const rotMatrix3 = Matrix3_default.fromQuaternion(
rotQuat,
scratchHeadingPitchRangeMatrix3
);
const offset2 = Cartesian3_default.clone(
Cartesian3_default.UNIT_X,
scratchLookAtHeadingPitchRangeOffset
);
Matrix3_default.multiplyByVector(rotMatrix3, offset2, offset2);
Cartesian3_default.negate(offset2, offset2);
Cartesian3_default.multiplyByScalar(offset2, range, offset2);
return offset2;
}
Camera.prototype.lookAtTransform = function(transform3, offset2) {
if (!defined_default(transform3)) {
throw new DeveloperError_default("transform is required");
}
if (this._mode === SceneMode_default.MORPHING) {
throw new DeveloperError_default(
"lookAtTransform is not supported while morphing."
);
}
this._setTransform(transform3);
if (!defined_default(offset2)) {
return;
}
let cartesianOffset;
if (defined_default(offset2.heading)) {
cartesianOffset = offsetFromHeadingPitchRange(
offset2.heading,
offset2.pitch,
offset2.range
);
} else {
cartesianOffset = offset2;
}
if (this._mode === SceneMode_default.SCENE2D) {
Cartesian2_default.clone(Cartesian2_default.ZERO, this.position);
Cartesian3_default.negate(cartesianOffset, this.up);
this.up.z = 0;
if (Cartesian3_default.magnitudeSquared(this.up) < Math_default.EPSILON10) {
Cartesian3_default.clone(Cartesian3_default.UNIT_Y, this.up);
}
Cartesian3_default.normalize(this.up, this.up);
this._setTransform(Matrix4_default.IDENTITY);
Cartesian3_default.negate(Cartesian3_default.UNIT_Z, this.direction);
Cartesian3_default.cross(this.direction, this.up, this.right);
Cartesian3_default.normalize(this.right, this.right);
const frustum = this.frustum;
const ratio = frustum.top / frustum.right;
frustum.right = Cartesian3_default.magnitude(cartesianOffset) * 0.5;
frustum.left = -frustum.right;
frustum.top = ratio * frustum.right;
frustum.bottom = -frustum.top;
this._setTransform(transform3);
return;
}
Cartesian3_default.clone(cartesianOffset, this.position);
Cartesian3_default.negate(this.position, this.direction);
Cartesian3_default.normalize(this.direction, this.direction);
Cartesian3_default.cross(this.direction, Cartesian3_default.UNIT_Z, this.right);
if (Cartesian3_default.magnitudeSquared(this.right) < Math_default.EPSILON10) {
Cartesian3_default.clone(Cartesian3_default.UNIT_X, this.right);
}
Cartesian3_default.normalize(this.right, this.right);
Cartesian3_default.cross(this.right, this.direction, this.up);
Cartesian3_default.normalize(this.up, this.up);
this._adjustOrthographicFrustum(true);
};
var viewRectangle3DCartographic1 = new Cartographic_default();
var viewRectangle3DCartographic2 = new Cartographic_default();
var viewRectangle3DNorthEast = new Cartesian3_default();
var viewRectangle3DSouthWest = new Cartesian3_default();
var viewRectangle3DNorthWest = new Cartesian3_default();
var viewRectangle3DSouthEast = new Cartesian3_default();
var viewRectangle3DNorthCenter = new Cartesian3_default();
var viewRectangle3DSouthCenter = new Cartesian3_default();
var viewRectangle3DCenter = new Cartesian3_default();
var viewRectangle3DEquator = new Cartesian3_default();
var defaultRF = {
direction: new Cartesian3_default(),
right: new Cartesian3_default(),
up: new Cartesian3_default()
};
var viewRectangle3DEllipsoidGeodesic;
function computeD(direction2, upOrRight, corner, tanThetaOrPhi) {
const opposite = Math.abs(Cartesian3_default.dot(upOrRight, corner));
return opposite / tanThetaOrPhi - Cartesian3_default.dot(direction2, corner);
}
function rectangleCameraPosition3D(camera, rectangle, result, updateCamera) {
const ellipsoid = camera._projection.ellipsoid;
const cameraRF = updateCamera ? camera : defaultRF;
const north = rectangle.north;
const south = rectangle.south;
let east = rectangle.east;
const west = rectangle.west;
if (west > east) {
east += Math_default.TWO_PI;
}
const longitude = (west + east) * 0.5;
let latitude;
if (south < -Math_default.PI_OVER_TWO + Math_default.RADIANS_PER_DEGREE && north > Math_default.PI_OVER_TWO - Math_default.RADIANS_PER_DEGREE) {
latitude = 0;
} else {
const northCartographic = viewRectangle3DCartographic1;
northCartographic.longitude = longitude;
northCartographic.latitude = north;
northCartographic.height = 0;
const southCartographic = viewRectangle3DCartographic2;
southCartographic.longitude = longitude;
southCartographic.latitude = south;
southCartographic.height = 0;
let ellipsoidGeodesic3 = viewRectangle3DEllipsoidGeodesic;
if (!defined_default(ellipsoidGeodesic3) || ellipsoidGeodesic3.ellipsoid !== ellipsoid) {
viewRectangle3DEllipsoidGeodesic = ellipsoidGeodesic3 = new EllipsoidGeodesic_default(
void 0,
void 0,
ellipsoid
);
}
ellipsoidGeodesic3.setEndPoints(northCartographic, southCartographic);
latitude = ellipsoidGeodesic3.interpolateUsingFraction(
0.5,
viewRectangle3DCartographic1
).latitude;
}
const centerCartographic = viewRectangle3DCartographic1;
centerCartographic.longitude = longitude;
centerCartographic.latitude = latitude;
centerCartographic.height = 0;
const center = ellipsoid.cartographicToCartesian(
centerCartographic,
viewRectangle3DCenter
);
const cart = viewRectangle3DCartographic1;
cart.longitude = east;
cart.latitude = north;
const northEast = ellipsoid.cartographicToCartesian(
cart,
viewRectangle3DNorthEast
);
cart.longitude = west;
const northWest = ellipsoid.cartographicToCartesian(
cart,
viewRectangle3DNorthWest
);
cart.longitude = longitude;
const northCenter = ellipsoid.cartographicToCartesian(
cart,
viewRectangle3DNorthCenter
);
cart.latitude = south;
const southCenter = ellipsoid.cartographicToCartesian(
cart,
viewRectangle3DSouthCenter
);
cart.longitude = east;
const southEast = ellipsoid.cartographicToCartesian(
cart,
viewRectangle3DSouthEast
);
cart.longitude = west;
const southWest = ellipsoid.cartographicToCartesian(
cart,
viewRectangle3DSouthWest
);
Cartesian3_default.subtract(northWest, center, northWest);
Cartesian3_default.subtract(southEast, center, southEast);
Cartesian3_default.subtract(northEast, center, northEast);
Cartesian3_default.subtract(southWest, center, southWest);
Cartesian3_default.subtract(northCenter, center, northCenter);
Cartesian3_default.subtract(southCenter, center, southCenter);
const direction2 = ellipsoid.geodeticSurfaceNormal(center, cameraRF.direction);
Cartesian3_default.negate(direction2, direction2);
const right = Cartesian3_default.cross(direction2, Cartesian3_default.UNIT_Z, cameraRF.right);
Cartesian3_default.normalize(right, right);
const up = Cartesian3_default.cross(right, direction2, cameraRF.up);
let d;
if (camera.frustum instanceof OrthographicFrustum_default) {
const width = Math.max(
Cartesian3_default.distance(northEast, northWest),
Cartesian3_default.distance(southEast, southWest)
);
const height = Math.max(
Cartesian3_default.distance(northEast, southEast),
Cartesian3_default.distance(northWest, southWest)
);
let rightScalar;
let topScalar;
const offCenterFrustum = camera.frustum._offCenterFrustum;
const ratio = offCenterFrustum.right / offCenterFrustum.top;
const heightRatio = height * ratio;
if (width > heightRatio) {
rightScalar = width;
topScalar = rightScalar / ratio;
} else {
topScalar = height;
rightScalar = heightRatio;
}
d = Math.max(rightScalar, topScalar);
} else {
const tanPhi = Math.tan(camera.frustum.fovy * 0.5);
const tanTheta = camera.frustum.aspectRatio * tanPhi;
d = Math.max(
computeD(direction2, up, northWest, tanPhi),
computeD(direction2, up, southEast, tanPhi),
computeD(direction2, up, northEast, tanPhi),
computeD(direction2, up, southWest, tanPhi),
computeD(direction2, up, northCenter, tanPhi),
computeD(direction2, up, southCenter, tanPhi),
computeD(direction2, right, northWest, tanTheta),
computeD(direction2, right, southEast, tanTheta),
computeD(direction2, right, northEast, tanTheta),
computeD(direction2, right, southWest, tanTheta),
computeD(direction2, right, northCenter, tanTheta),
computeD(direction2, right, southCenter, tanTheta)
);
if (south < 0 && north > 0) {
const equatorCartographic = viewRectangle3DCartographic1;
equatorCartographic.longitude = west;
equatorCartographic.latitude = 0;
equatorCartographic.height = 0;
let equatorPosition = ellipsoid.cartographicToCartesian(
equatorCartographic,
viewRectangle3DEquator
);
Cartesian3_default.subtract(equatorPosition, center, equatorPosition);
d = Math.max(
d,
computeD(direction2, up, equatorPosition, tanPhi),
computeD(direction2, right, equatorPosition, tanTheta)
);
equatorCartographic.longitude = east;
equatorPosition = ellipsoid.cartographicToCartesian(
equatorCartographic,
viewRectangle3DEquator
);
Cartesian3_default.subtract(equatorPosition, center, equatorPosition);
d = Math.max(
d,
computeD(direction2, up, equatorPosition, tanPhi),
computeD(direction2, right, equatorPosition, tanTheta)
);
}
}
return Cartesian3_default.add(
center,
Cartesian3_default.multiplyByScalar(direction2, -d, viewRectangle3DEquator),
result
);
}
var viewRectangleCVCartographic = new Cartographic_default();
var viewRectangleCVNorthEast = new Cartesian3_default();
var viewRectangleCVSouthWest = new Cartesian3_default();
function rectangleCameraPositionColumbusView(camera, rectangle, result) {
const projection = camera._projection;
if (rectangle.west > rectangle.east) {
rectangle = Rectangle_default.MAX_VALUE;
}
const transform3 = camera._actualTransform;
const invTransform = camera._actualInvTransform;
const cart = viewRectangleCVCartographic;
cart.longitude = rectangle.east;
cart.latitude = rectangle.north;
const northEast = projection.project(cart, viewRectangleCVNorthEast);
Matrix4_default.multiplyByPoint(transform3, northEast, northEast);
Matrix4_default.multiplyByPoint(invTransform, northEast, northEast);
cart.longitude = rectangle.west;
cart.latitude = rectangle.south;
const southWest = projection.project(cart, viewRectangleCVSouthWest);
Matrix4_default.multiplyByPoint(transform3, southWest, southWest);
Matrix4_default.multiplyByPoint(invTransform, southWest, southWest);
result.x = (northEast.x - southWest.x) * 0.5 + southWest.x;
result.y = (northEast.y - southWest.y) * 0.5 + southWest.y;
if (defined_default(camera.frustum.fovy)) {
const tanPhi = Math.tan(camera.frustum.fovy * 0.5);
const tanTheta = camera.frustum.aspectRatio * tanPhi;
result.z = Math.max(
(northEast.x - southWest.x) / tanTheta,
(northEast.y - southWest.y) / tanPhi
) * 0.5;
} else {
const width = northEast.x - southWest.x;
const height = northEast.y - southWest.y;
result.z = Math.max(width, height);
}
return result;
}
var viewRectangle2DCartographic = new Cartographic_default();
var viewRectangle2DNorthEast = new Cartesian3_default();
var viewRectangle2DSouthWest = new Cartesian3_default();
function rectangleCameraPosition2D(camera, rectangle, result) {
const projection = camera._projection;
let east = rectangle.east;
if (rectangle.west > rectangle.east) {
if (camera._scene.mapMode2D === MapMode2D_default.INFINITE_SCROLL) {
east += Math_default.TWO_PI;
} else {
rectangle = Rectangle_default.MAX_VALUE;
east = rectangle.east;
}
}
let cart = viewRectangle2DCartographic;
cart.longitude = east;
cart.latitude = rectangle.north;
const northEast = projection.project(cart, viewRectangle2DNorthEast);
cart.longitude = rectangle.west;
cart.latitude = rectangle.south;
const southWest = projection.project(cart, viewRectangle2DSouthWest);
const width = Math.abs(northEast.x - southWest.x) * 0.5;
let height = Math.abs(northEast.y - southWest.y) * 0.5;
let right, top;
const ratio = camera.frustum.right / camera.frustum.top;
const heightRatio = height * ratio;
if (width > heightRatio) {
right = width;
top = right / ratio;
} else {
top = height;
right = heightRatio;
}
height = Math.max(2 * right, 2 * top);
result.x = (northEast.x - southWest.x) * 0.5 + southWest.x;
result.y = (northEast.y - southWest.y) * 0.5 + southWest.y;
cart = projection.unproject(result, cart);
cart.height = height;
result = projection.project(cart, result);
return result;
}
Camera.prototype.getRectangleCameraCoordinates = function(rectangle, result) {
if (!defined_default(rectangle)) {
throw new DeveloperError_default("rectangle is required");
}
const mode2 = this._mode;
if (!defined_default(result)) {
result = new Cartesian3_default();
}
if (mode2 === SceneMode_default.SCENE3D) {
return rectangleCameraPosition3D(this, rectangle, result);
} else if (mode2 === SceneMode_default.COLUMBUS_VIEW) {
return rectangleCameraPositionColumbusView(this, rectangle, result);
} else if (mode2 === SceneMode_default.SCENE2D) {
return rectangleCameraPosition2D(this, rectangle, result);
}
return void 0;
};
var pickEllipsoid3DRay = new Ray_default();
function pickEllipsoid3D(camera, windowPosition, ellipsoid, result) {
ellipsoid = defaultValue_default(ellipsoid, Ellipsoid_default.WGS84);
const ray = camera.getPickRay(windowPosition, pickEllipsoid3DRay);
const intersection = IntersectionTests_default.rayEllipsoid(ray, ellipsoid);
if (!intersection) {
return void 0;
}
const t = intersection.start > 0 ? intersection.start : intersection.stop;
return Ray_default.getPoint(ray, t, result);
}
var pickEllipsoid2DRay = new Ray_default();
function pickMap2D(camera, windowPosition, projection, result) {
const ray = camera.getPickRay(windowPosition, pickEllipsoid2DRay);
let position = ray.origin;
position = Cartesian3_default.fromElements(position.y, position.z, 0, position);
const cart = projection.unproject(position);
if (cart.latitude < -Math_default.PI_OVER_TWO || cart.latitude > Math_default.PI_OVER_TWO) {
return void 0;
}
return projection.ellipsoid.cartographicToCartesian(cart, result);
}
var pickEllipsoidCVRay = new Ray_default();
function pickMapColumbusView(camera, windowPosition, projection, result) {
const ray = camera.getPickRay(windowPosition, pickEllipsoidCVRay);
const scalar = -ray.origin.x / ray.direction.x;
Ray_default.getPoint(ray, scalar, result);
const cart = projection.unproject(new Cartesian3_default(result.y, result.z, 0));
if (cart.latitude < -Math_default.PI_OVER_TWO || cart.latitude > Math_default.PI_OVER_TWO || cart.longitude < -Math.PI || cart.longitude > Math.PI) {
return void 0;
}
return projection.ellipsoid.cartographicToCartesian(cart, result);
}
Camera.prototype.pickEllipsoid = function(windowPosition, ellipsoid, result) {
if (!defined_default(windowPosition)) {
throw new DeveloperError_default("windowPosition is required.");
}
const canvas = this._scene.canvas;
if (canvas.clientWidth === 0 || canvas.clientHeight === 0) {
return void 0;
}
if (!defined_default(result)) {
result = new Cartesian3_default();
}
ellipsoid = defaultValue_default(ellipsoid, Ellipsoid_default.WGS84);
if (this._mode === SceneMode_default.SCENE3D) {
result = pickEllipsoid3D(this, windowPosition, ellipsoid, result);
} else if (this._mode === SceneMode_default.SCENE2D) {
result = pickMap2D(this, windowPosition, this._projection, result);
} else if (this._mode === SceneMode_default.COLUMBUS_VIEW) {
result = pickMapColumbusView(
this,
windowPosition,
this._projection,
result
);
} else {
return void 0;
}
return result;
};
var pickPerspCenter = new Cartesian3_default();
var pickPerspXDir = new Cartesian3_default();
var pickPerspYDir = new Cartesian3_default();
function getPickRayPerspective(camera, windowPosition, result) {
const canvas = camera._scene.canvas;
const width = canvas.clientWidth;
const height = canvas.clientHeight;
const tanPhi = Math.tan(camera.frustum.fovy * 0.5);
const tanTheta = camera.frustum.aspectRatio * tanPhi;
const near = camera.frustum.near;
const x = 2 / width * windowPosition.x - 1;
const y = 2 / height * (height - windowPosition.y) - 1;
const position = camera.positionWC;
Cartesian3_default.clone(position, result.origin);
const nearCenter = Cartesian3_default.multiplyByScalar(
camera.directionWC,
near,
pickPerspCenter
);
Cartesian3_default.add(position, nearCenter, nearCenter);
const xDir = Cartesian3_default.multiplyByScalar(
camera.rightWC,
x * near * tanTheta,
pickPerspXDir
);
const yDir = Cartesian3_default.multiplyByScalar(
camera.upWC,
y * near * tanPhi,
pickPerspYDir
);
const direction2 = Cartesian3_default.add(nearCenter, xDir, result.direction);
Cartesian3_default.add(direction2, yDir, direction2);
Cartesian3_default.subtract(direction2, position, direction2);
Cartesian3_default.normalize(direction2, direction2);
return result;
}
var scratchDirection2 = new Cartesian3_default();
function getPickRayOrthographic(camera, windowPosition, result) {
const canvas = camera._scene.canvas;
const width = canvas.clientWidth;
const height = canvas.clientHeight;
let frustum = camera.frustum;
const offCenterFrustum = frustum.offCenterFrustum;
if (defined_default(offCenterFrustum)) {
frustum = offCenterFrustum;
}
let x = 2 / width * windowPosition.x - 1;
x *= (frustum.right - frustum.left) * 0.5;
let y = 2 / height * (height - windowPosition.y) - 1;
y *= (frustum.top - frustum.bottom) * 0.5;
const origin = result.origin;
Cartesian3_default.clone(camera.position, origin);
Cartesian3_default.multiplyByScalar(camera.right, x, scratchDirection2);
Cartesian3_default.add(scratchDirection2, origin, origin);
Cartesian3_default.multiplyByScalar(camera.up, y, scratchDirection2);
Cartesian3_default.add(scratchDirection2, origin, origin);
Cartesian3_default.clone(camera.directionWC, result.direction);
if (camera._mode === SceneMode_default.COLUMBUS_VIEW || camera._mode === SceneMode_default.SCENE2D) {
Cartesian3_default.fromElements(
result.origin.z,
result.origin.x,
result.origin.y,
result.origin
);
}
return result;
}
Camera.prototype.getPickRay = function(windowPosition, result) {
if (!defined_default(windowPosition)) {
throw new DeveloperError_default("windowPosition is required.");
}
if (!defined_default(result)) {
result = new Ray_default();
}
const canvas = this._scene.canvas;
if (canvas.clientWidth <= 0 || canvas.clientHeight <= 0) {
return void 0;
}
const frustum = this.frustum;
if (defined_default(frustum.aspectRatio) && defined_default(frustum.fov) && defined_default(frustum.near)) {
return getPickRayPerspective(this, windowPosition, result);
}
return getPickRayOrthographic(this, windowPosition, result);
};
var scratchToCenter2 = new Cartesian3_default();
var scratchProj = new Cartesian3_default();
Camera.prototype.distanceToBoundingSphere = function(boundingSphere) {
if (!defined_default(boundingSphere)) {
throw new DeveloperError_default("boundingSphere is required.");
}
const toCenter = Cartesian3_default.subtract(
this.positionWC,
boundingSphere.center,
scratchToCenter2
);
const proj2 = Cartesian3_default.multiplyByScalar(
this.directionWC,
Cartesian3_default.dot(toCenter, this.directionWC),
scratchProj
);
return Math.max(0, Cartesian3_default.magnitude(proj2) - boundingSphere.radius);
};
var scratchPixelSize = new Cartesian2_default();
Camera.prototype.getPixelSize = function(boundingSphere, drawingBufferWidth, drawingBufferHeight) {
if (!defined_default(boundingSphere)) {
throw new DeveloperError_default("boundingSphere is required.");
}
if (!defined_default(drawingBufferWidth)) {
throw new DeveloperError_default("drawingBufferWidth is required.");
}
if (!defined_default(drawingBufferHeight)) {
throw new DeveloperError_default("drawingBufferHeight is required.");
}
const distance2 = this.distanceToBoundingSphere(boundingSphere);
const pixelSize = this.frustum.getPixelDimensions(
drawingBufferWidth,
drawingBufferHeight,
distance2,
this._scene.pixelRatio,
scratchPixelSize
);
return Math.max(pixelSize.x, pixelSize.y);
};
function createAnimationTemplateCV(camera, position, center, maxX, maxY, duration) {
const newPosition = Cartesian3_default.clone(position);
if (center.y > maxX) {
newPosition.y -= center.y - maxX;
} else if (center.y < -maxX) {
newPosition.y += -maxX - center.y;
}
if (center.z > maxY) {
newPosition.z -= center.z - maxY;
} else if (center.z < -maxY) {
newPosition.z += -maxY - center.z;
}
function updateCV2(value) {
const interp = Cartesian3_default.lerp(
position,
newPosition,
value.time,
new Cartesian3_default()
);
camera.worldToCameraCoordinatesPoint(interp, camera.position);
}
return {
easingFunction: EasingFunction_default.EXPONENTIAL_OUT,
startObject: {
time: 0
},
stopObject: {
time: 1
},
duration,
update: updateCV2
};
}
var normalScratch6 = new Cartesian3_default();
var centerScratch6 = new Cartesian3_default();
var posScratch = new Cartesian3_default();
var scratchCartesian3Subtract = new Cartesian3_default();
function createAnimationCV(camera, duration) {
let position = camera.position;
const direction2 = camera.direction;
const normal2 = camera.worldToCameraCoordinatesVector(
Cartesian3_default.UNIT_X,
normalScratch6
);
const scalar = -Cartesian3_default.dot(normal2, position) / Cartesian3_default.dot(normal2, direction2);
const center = Cartesian3_default.add(
position,
Cartesian3_default.multiplyByScalar(direction2, scalar, centerScratch6),
centerScratch6
);
camera.cameraToWorldCoordinatesPoint(center, center);
position = camera.cameraToWorldCoordinatesPoint(camera.position, posScratch);
const tanPhi = Math.tan(camera.frustum.fovy * 0.5);
const tanTheta = camera.frustum.aspectRatio * tanPhi;
const distToC = Cartesian3_default.magnitude(
Cartesian3_default.subtract(position, center, scratchCartesian3Subtract)
);
const dWidth = tanTheta * distToC;
const dHeight = tanPhi * distToC;
const mapWidth = camera._maxCoord.x;
const mapHeight = camera._maxCoord.y;
const maxX = Math.max(dWidth - mapWidth, mapWidth);
const maxY = Math.max(dHeight - mapHeight, mapHeight);
if (position.z < -maxX || position.z > maxX || position.y < -maxY || position.y > maxY) {
const translateX = center.y < -maxX || center.y > maxX;
const translateY = center.z < -maxY || center.z > maxY;
if (translateX || translateY) {
return createAnimationTemplateCV(
camera,
position,
center,
maxX,
maxY,
duration
);
}
}
return void 0;
}
Camera.prototype.createCorrectPositionTween = function(duration) {
if (!defined_default(duration)) {
throw new DeveloperError_default("duration is required.");
}
if (this._mode === SceneMode_default.COLUMBUS_VIEW) {
return createAnimationCV(this, duration);
}
return void 0;
};
var scratchFlyToDestination = new Cartesian3_default();
var newOptions = {
destination: void 0,
heading: void 0,
pitch: void 0,
roll: void 0,
duration: void 0,
complete: void 0,
cancel: void 0,
endTransform: void 0,
maximumHeight: void 0,
easingFunction: void 0
};
Camera.prototype.cancelFlight = function() {
if (defined_default(this._currentFlight)) {
this._currentFlight.cancelTween();
this._currentFlight = void 0;
}
};
Camera.prototype.completeFlight = function() {
if (defined_default(this._currentFlight)) {
this._currentFlight.cancelTween();
const options = {
destination: void 0,
orientation: {
heading: void 0,
pitch: void 0,
roll: void 0
}
};
options.destination = newOptions.destination;
options.orientation.heading = newOptions.heading;
options.orientation.pitch = newOptions.pitch;
options.orientation.roll = newOptions.roll;
this.setView(options);
if (defined_default(this._currentFlight.complete)) {
this._currentFlight.complete();
}
this._currentFlight = void 0;
}
};
Camera.prototype.flyTo = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
let destination = options.destination;
if (!defined_default(destination)) {
throw new DeveloperError_default("destination is required.");
}
const mode2 = this._mode;
if (mode2 === SceneMode_default.MORPHING) {
return;
}
this.cancelFlight();
const isRectangle = destination instanceof Rectangle_default;
if (isRectangle) {
destination = this.getRectangleCameraCoordinates(
destination,
scratchFlyToDestination
);
}
let orientation = defaultValue_default(
options.orientation,
defaultValue_default.EMPTY_OBJECT
);
if (defined_default(orientation.direction)) {
orientation = directionUpToHeadingPitchRoll(
this,
destination,
orientation,
scratchSetViewOptions.orientation
);
}
if (defined_default(options.duration) && options.duration <= 0) {
const setViewOptions = scratchSetViewOptions;
setViewOptions.destination = options.destination;
setViewOptions.orientation.heading = orientation.heading;
setViewOptions.orientation.pitch = orientation.pitch;
setViewOptions.orientation.roll = orientation.roll;
setViewOptions.convert = options.convert;
setViewOptions.endTransform = options.endTransform;
this.setView(setViewOptions);
if (typeof options.complete === "function") {
options.complete();
}
return;
}
const that = this;
let flightTween;
newOptions.destination = destination;
newOptions.heading = orientation.heading;
newOptions.pitch = orientation.pitch;
newOptions.roll = orientation.roll;
newOptions.duration = options.duration;
newOptions.complete = function() {
if (flightTween === that._currentFlight) {
that._currentFlight = void 0;
}
if (defined_default(options.complete)) {
options.complete();
}
};
newOptions.cancel = options.cancel;
newOptions.endTransform = options.endTransform;
newOptions.convert = isRectangle ? false : options.convert;
newOptions.maximumHeight = options.maximumHeight;
newOptions.pitchAdjustHeight = options.pitchAdjustHeight;
newOptions.flyOverLongitude = options.flyOverLongitude;
newOptions.flyOverLongitudeWeight = options.flyOverLongitudeWeight;
newOptions.easingFunction = options.easingFunction;
const scene = this._scene;
const tweenOptions = CameraFlightPath_default.createTween(scene, newOptions);
if (tweenOptions.duration === 0) {
if (typeof tweenOptions.complete === "function") {
tweenOptions.complete();
}
return;
}
flightTween = scene.tweens.add(tweenOptions);
this._currentFlight = flightTween;
let preloadFlightCamera = this._scene.preloadFlightCamera;
if (this._mode !== SceneMode_default.SCENE2D) {
if (!defined_default(preloadFlightCamera)) {
preloadFlightCamera = Camera.clone(this);
}
preloadFlightCamera.setView({
destination,
orientation
});
this._scene.preloadFlightCullingVolume = preloadFlightCamera.frustum.computeCullingVolume(
preloadFlightCamera.positionWC,
preloadFlightCamera.directionWC,
preloadFlightCamera.upWC
);
}
};
function distanceToBoundingSphere3D(camera, radius) {
const frustum = camera.frustum;
const tanPhi = Math.tan(frustum.fovy * 0.5);
const tanTheta = frustum.aspectRatio * tanPhi;
return Math.max(radius / tanTheta, radius / tanPhi);
}
function distanceToBoundingSphere2D(camera, radius) {
let frustum = camera.frustum;
const offCenterFrustum = frustum.offCenterFrustum;
if (defined_default(offCenterFrustum)) {
frustum = offCenterFrustum;
}
let right, top;
const ratio = frustum.right / frustum.top;
const heightRatio = radius * ratio;
if (radius > heightRatio) {
right = radius;
top = right / ratio;
} else {
top = radius;
right = heightRatio;
}
return Math.max(right, top) * 1.5;
}
var MINIMUM_ZOOM = 100;
function adjustBoundingSphereOffset(camera, boundingSphere, offset2) {
offset2 = HeadingPitchRange_default.clone(
defined_default(offset2) ? offset2 : Camera.DEFAULT_OFFSET
);
const minimumZoom = camera._scene.screenSpaceCameraController.minimumZoomDistance;
const maximumZoom = camera._scene.screenSpaceCameraController.maximumZoomDistance;
const range = offset2.range;
if (!defined_default(range) || range === 0) {
const radius = boundingSphere.radius;
if (radius === 0) {
offset2.range = MINIMUM_ZOOM;
} else if (camera.frustum instanceof OrthographicFrustum_default || camera._mode === SceneMode_default.SCENE2D) {
offset2.range = distanceToBoundingSphere2D(camera, radius);
} else {
offset2.range = distanceToBoundingSphere3D(camera, radius);
}
offset2.range = Math_default.clamp(offset2.range, minimumZoom, maximumZoom);
}
return offset2;
}
Camera.prototype.viewBoundingSphere = function(boundingSphere, offset2) {
if (!defined_default(boundingSphere)) {
throw new DeveloperError_default("boundingSphere is required.");
}
if (this._mode === SceneMode_default.MORPHING) {
throw new DeveloperError_default(
"viewBoundingSphere is not supported while morphing."
);
}
offset2 = adjustBoundingSphereOffset(this, boundingSphere, offset2);
this.lookAt(boundingSphere.center, offset2);
};
var scratchflyToBoundingSphereTransform = new Matrix4_default();
var scratchflyToBoundingSphereDestination = new Cartesian3_default();
var scratchflyToBoundingSphereDirection = new Cartesian3_default();
var scratchflyToBoundingSphereUp = new Cartesian3_default();
var scratchflyToBoundingSphereRight = new Cartesian3_default();
var scratchFlyToBoundingSphereCart4 = new Cartesian4_default();
var scratchFlyToBoundingSphereQuaternion = new Quaternion_default();
var scratchFlyToBoundingSphereMatrix3 = new Matrix3_default();
Camera.prototype.flyToBoundingSphere = function(boundingSphere, options) {
if (!defined_default(boundingSphere)) {
throw new DeveloperError_default("boundingSphere is required.");
}
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const scene2D = this._mode === SceneMode_default.SCENE2D || this._mode === SceneMode_default.COLUMBUS_VIEW;
this._setTransform(Matrix4_default.IDENTITY);
const offset2 = adjustBoundingSphereOffset(
this,
boundingSphere,
options.offset
);
let position;
if (scene2D) {
position = Cartesian3_default.multiplyByScalar(
Cartesian3_default.UNIT_Z,
offset2.range,
scratchflyToBoundingSphereDestination
);
} else {
position = offsetFromHeadingPitchRange(
offset2.heading,
offset2.pitch,
offset2.range
);
}
const transform3 = Transforms_default.eastNorthUpToFixedFrame(
boundingSphere.center,
Ellipsoid_default.WGS84,
scratchflyToBoundingSphereTransform
);
Matrix4_default.multiplyByPoint(transform3, position, position);
let direction2;
let up;
if (!scene2D) {
direction2 = Cartesian3_default.subtract(
boundingSphere.center,
position,
scratchflyToBoundingSphereDirection
);
Cartesian3_default.normalize(direction2, direction2);
up = Matrix4_default.multiplyByPointAsVector(
transform3,
Cartesian3_default.UNIT_Z,
scratchflyToBoundingSphereUp
);
if (1 - Math.abs(Cartesian3_default.dot(direction2, up)) < Math_default.EPSILON6) {
const rotateQuat = Quaternion_default.fromAxisAngle(
direction2,
offset2.heading,
scratchFlyToBoundingSphereQuaternion
);
const rotation = Matrix3_default.fromQuaternion(
rotateQuat,
scratchFlyToBoundingSphereMatrix3
);
Cartesian3_default.fromCartesian4(
Matrix4_default.getColumn(transform3, 1, scratchFlyToBoundingSphereCart4),
up
);
Matrix3_default.multiplyByVector(rotation, up, up);
}
const right = Cartesian3_default.cross(
direction2,
up,
scratchflyToBoundingSphereRight
);
Cartesian3_default.cross(right, direction2, up);
Cartesian3_default.normalize(up, up);
}
this.flyTo({
destination: position,
orientation: {
direction: direction2,
up
},
duration: options.duration,
complete: options.complete,
cancel: options.cancel,
endTransform: options.endTransform,
maximumHeight: options.maximumHeight,
easingFunction: options.easingFunction,
flyOverLongitude: options.flyOverLongitude,
flyOverLongitudeWeight: options.flyOverLongitudeWeight,
pitchAdjustHeight: options.pitchAdjustHeight
});
};
var scratchCartesian3_1 = new Cartesian3_default();
var scratchCartesian3_2 = new Cartesian3_default();
var scratchCartesian3_3 = new Cartesian3_default();
var scratchCartesian3_4 = new Cartesian3_default();
var horizonPoints = [
new Cartesian3_default(),
new Cartesian3_default(),
new Cartesian3_default(),
new Cartesian3_default()
];
function computeHorizonQuad(camera, ellipsoid) {
const radii = ellipsoid.radii;
const p = camera.positionWC;
const q = Cartesian3_default.multiplyComponents(
ellipsoid.oneOverRadii,
p,
scratchCartesian3_1
);
const qMagnitude = Cartesian3_default.magnitude(q);
const qUnit = Cartesian3_default.normalize(q, scratchCartesian3_2);
let eUnit;
let nUnit;
if (Cartesian3_default.equalsEpsilon(qUnit, Cartesian3_default.UNIT_Z, Math_default.EPSILON10)) {
eUnit = new Cartesian3_default(0, 1, 0);
nUnit = new Cartesian3_default(0, 0, 1);
} else {
eUnit = Cartesian3_default.normalize(
Cartesian3_default.cross(Cartesian3_default.UNIT_Z, qUnit, scratchCartesian3_3),
scratchCartesian3_3
);
nUnit = Cartesian3_default.normalize(
Cartesian3_default.cross(qUnit, eUnit, scratchCartesian3_4),
scratchCartesian3_4
);
}
const wMagnitude = Math.sqrt(Cartesian3_default.magnitudeSquared(q) - 1);
const center = Cartesian3_default.multiplyByScalar(
qUnit,
1 / qMagnitude,
scratchCartesian3_1
);
const scalar = wMagnitude / qMagnitude;
const eastOffset = Cartesian3_default.multiplyByScalar(
eUnit,
scalar,
scratchCartesian3_2
);
const northOffset = Cartesian3_default.multiplyByScalar(
nUnit,
scalar,
scratchCartesian3_3
);
const upperLeft = Cartesian3_default.add(center, northOffset, horizonPoints[0]);
Cartesian3_default.subtract(upperLeft, eastOffset, upperLeft);
Cartesian3_default.multiplyComponents(radii, upperLeft, upperLeft);
const lowerLeft = Cartesian3_default.subtract(center, northOffset, horizonPoints[1]);
Cartesian3_default.subtract(lowerLeft, eastOffset, lowerLeft);
Cartesian3_default.multiplyComponents(radii, lowerLeft, lowerLeft);
const lowerRight = Cartesian3_default.subtract(center, northOffset, horizonPoints[2]);
Cartesian3_default.add(lowerRight, eastOffset, lowerRight);
Cartesian3_default.multiplyComponents(radii, lowerRight, lowerRight);
const upperRight = Cartesian3_default.add(center, northOffset, horizonPoints[3]);
Cartesian3_default.add(upperRight, eastOffset, upperRight);
Cartesian3_default.multiplyComponents(radii, upperRight, upperRight);
return horizonPoints;
}
var scratchPickCartesian2 = new Cartesian2_default();
var scratchRectCartesian = new Cartesian3_default();
var cartoArray = [
new Cartographic_default(),
new Cartographic_default(),
new Cartographic_default(),
new Cartographic_default()
];
function addToResult(x, y, index, camera, ellipsoid, computedHorizonQuad) {
scratchPickCartesian2.x = x;
scratchPickCartesian2.y = y;
const r = camera.pickEllipsoid(
scratchPickCartesian2,
ellipsoid,
scratchRectCartesian
);
if (defined_default(r)) {
cartoArray[index] = ellipsoid.cartesianToCartographic(r, cartoArray[index]);
return 1;
}
cartoArray[index] = ellipsoid.cartesianToCartographic(
computedHorizonQuad[index],
cartoArray[index]
);
return 0;
}
Camera.prototype.computeViewRectangle = function(ellipsoid, result) {
ellipsoid = defaultValue_default(ellipsoid, Ellipsoid_default.WGS84);
const cullingVolume = this.frustum.computeCullingVolume(
this.positionWC,
this.directionWC,
this.upWC
);
const boundingSphere = new BoundingSphere_default(
Cartesian3_default.ZERO,
ellipsoid.maximumRadius
);
const visibility = cullingVolume.computeVisibility(boundingSphere);
if (visibility === Intersect_default.OUTSIDE) {
return void 0;
}
const canvas = this._scene.canvas;
const width = canvas.clientWidth;
const height = canvas.clientHeight;
let successfulPickCount = 0;
const computedHorizonQuad = computeHorizonQuad(this, ellipsoid);
successfulPickCount += addToResult(
0,
0,
0,
this,
ellipsoid,
computedHorizonQuad
);
successfulPickCount += addToResult(
0,
height,
1,
this,
ellipsoid,
computedHorizonQuad
);
successfulPickCount += addToResult(
width,
height,
2,
this,
ellipsoid,
computedHorizonQuad
);
successfulPickCount += addToResult(
width,
0,
3,
this,
ellipsoid,
computedHorizonQuad
);
if (successfulPickCount < 2) {
return Rectangle_default.MAX_VALUE;
}
result = Rectangle_default.fromCartographicArray(cartoArray, result);
let distance2 = 0;
let lastLon = cartoArray[3].longitude;
for (let i = 0; i < 4; ++i) {
const lon = cartoArray[i].longitude;
const diff = Math.abs(lon - lastLon);
if (diff > Math_default.PI) {
distance2 += Math_default.TWO_PI - diff;
} else {
distance2 += diff;
}
lastLon = lon;
}
if (Math_default.equalsEpsilon(
Math.abs(distance2),
Math_default.TWO_PI,
Math_default.EPSILON9
)) {
result.west = -Math_default.PI;
result.east = Math_default.PI;
if (cartoArray[0].latitude >= 0) {
result.north = Math_default.PI_OVER_TWO;
} else {
result.south = -Math_default.PI_OVER_TWO;
}
}
return result;
};
Camera.prototype.switchToPerspectiveFrustum = function() {
if (this._mode === SceneMode_default.SCENE2D || this.frustum instanceof PerspectiveFrustum_default) {
return;
}
const scene = this._scene;
this.frustum = new PerspectiveFrustum_default();
this.frustum.aspectRatio = scene.drawingBufferWidth / scene.drawingBufferHeight;
this.frustum.fov = Math_default.toRadians(60);
};
Camera.prototype.switchToOrthographicFrustum = function() {
if (this._mode === SceneMode_default.SCENE2D || this.frustum instanceof OrthographicFrustum_default) {
return;
}
const frustumWidth = calculateOrthographicFrustumWidth(this);
const scene = this._scene;
this.frustum = new OrthographicFrustum_default();
this.frustum.aspectRatio = scene.drawingBufferWidth / scene.drawingBufferHeight;
this.frustum.width = frustumWidth;
};
Camera.clone = function(camera, result) {
if (!defined_default(result)) {
result = new Camera(camera._scene);
}
Cartesian3_default.clone(camera.position, result.position);
Cartesian3_default.clone(camera.direction, result.direction);
Cartesian3_default.clone(camera.up, result.up);
Cartesian3_default.clone(camera.right, result.right);
Matrix4_default.clone(camera._transform, result.transform);
result._transformChanged = true;
result.frustum = camera.frustum.clone();
return result;
};
var Camera_default = Camera;
// packages/engine/Source/Scene/Cesium3DTilePassState.js
function Cesium3DTilePassState(options) {
Check_default.typeOf.object("options", options);
Check_default.typeOf.number("options.pass", options.pass);
this.pass = options.pass;
this.commandList = options.commandList;
this.camera = options.camera;
this.cullingVolume = options.cullingVolume;
this.ready = false;
}
var Cesium3DTilePassState_default = Cesium3DTilePassState;
// packages/engine/Source/Scene/CreditDisplay.js
var import_urijs12 = __toESM(require_URI(), 1);
var mobileWidth = 576;
var lightboxHeight = 100;
var textColor = "#ffffff";
var highlightColor = "#48b";
function CreditDisplayElement(credit, count) {
this.credit = credit;
this.count = defaultValue_default(count, 1);
}
function contains(credits, credit) {
const len = credits.length;
for (let i = 0; i < len; i++) {
const existingCredit = credits[i];
if (Credit_default.equals(existingCredit, credit)) {
return true;
}
}
return false;
}
function swapCesiumCredit(creditDisplay) {
const previousCredit = creditDisplay._previousCesiumCredit;
const currentCredit = creditDisplay._currentCesiumCredit;
if (Credit_default.equals(currentCredit, previousCredit)) {
return;
}
if (defined_default(previousCredit)) {
creditDisplay._cesiumCreditContainer.removeChild(previousCredit.element);
}
if (defined_default(currentCredit)) {
creditDisplay._cesiumCreditContainer.appendChild(currentCredit.element);
}
creditDisplay._previousCesiumCredit = currentCredit;
}
var delimiterClassName = "cesium-credit-delimiter";
function createDelimiterElement(delimiter) {
const delimiterElement = document.createElement("span");
delimiterElement.textContent = delimiter;
delimiterElement.className = delimiterClassName;
return delimiterElement;
}
function createCreditElement(element, elementWrapperTagName) {
if (defined_default(elementWrapperTagName)) {
const wrapper = document.createElement(elementWrapperTagName);
wrapper._creditId = element._creditId;
wrapper.appendChild(element);
element = wrapper;
}
return element;
}
function displayCredits(container, credits, delimiter, elementWrapperTagName) {
const childNodes = container.childNodes;
let domIndex = -1;
credits.sort(function(credit1, credit2) {
return credit2.count - credit1.count;
});
for (let creditIndex = 0; creditIndex < credits.length; ++creditIndex) {
const credit = credits[creditIndex].credit;
if (defined_default(credit)) {
domIndex = creditIndex;
if (defined_default(delimiter)) {
domIndex *= 2;
if (creditIndex > 0) {
const delimiterDomIndex = domIndex - 1;
if (childNodes.length <= delimiterDomIndex) {
container.appendChild(createDelimiterElement(delimiter));
} else {
const existingDelimiter = childNodes[delimiterDomIndex];
if (existingDelimiter.className !== delimiterClassName) {
container.replaceChild(
createDelimiterElement(delimiter),
existingDelimiter
);
}
}
}
}
const element = credit.element;
if (childNodes.length <= domIndex) {
container.appendChild(
createCreditElement(element, elementWrapperTagName)
);
} else {
const existingElement = childNodes[domIndex];
if (existingElement._creditId !== credit._id) {
container.replaceChild(
createCreditElement(element, elementWrapperTagName),
existingElement
);
}
}
}
}
++domIndex;
while (domIndex < childNodes.length) {
container.removeChild(childNodes[domIndex]);
}
}
function styleLightboxContainer(that) {
const lightboxCredits = that._lightboxCredits;
const width = that.viewport.clientWidth;
const height = that.viewport.clientHeight;
if (width !== that._lastViewportWidth) {
if (width < mobileWidth) {
lightboxCredits.className = "cesium-credit-lightbox cesium-credit-lightbox-mobile";
lightboxCredits.style.marginTop = "0";
} else {
lightboxCredits.className = "cesium-credit-lightbox cesium-credit-lightbox-expanded";
lightboxCredits.style.marginTop = `${Math.floor(
(height - lightboxCredits.clientHeight) * 0.5
)}px`;
}
that._lastViewportWidth = width;
}
if (width >= mobileWidth && height !== that._lastViewportHeight) {
lightboxCredits.style.marginTop = `${Math.floor(
(height - lightboxCredits.clientHeight) * 0.5
)}px`;
that._lastViewportHeight = height;
}
}
function addStyle(selector, styles) {
let style = `${selector} {`;
for (const attribute in styles) {
if (styles.hasOwnProperty(attribute)) {
style += `${attribute}: ${styles[attribute]}; `;
}
}
style += " }\n";
return style;
}
function appendCss(container) {
let style = "";
style += addStyle(".cesium-credit-lightbox-overlay", {
display: "none",
"z-index": "1",
//must be at least 1 to draw over top other Cesium widgets
position: "absolute",
top: "0",
left: "0",
width: "100%",
height: "100%",
"background-color": "rgba(80, 80, 80, 0.8)"
});
style += addStyle(".cesium-credit-lightbox", {
"background-color": "#303336",
color: textColor,
position: "relative",
"min-height": `${lightboxHeight}px`,
margin: "auto"
});
style += addStyle(
".cesium-credit-lightbox > ul > li a, .cesium-credit-lightbox > ul > li a:visited",
{
color: textColor
}
);
style += addStyle(".cesium-credit-lightbox > ul > li a:hover", {
color: highlightColor
});
style += addStyle(".cesium-credit-lightbox.cesium-credit-lightbox-expanded", {
border: "1px solid #444",
"border-radius": "5px",
"max-width": "370px"
});
style += addStyle(".cesium-credit-lightbox.cesium-credit-lightbox-mobile", {
height: "100%",
width: "100%"
});
style += addStyle(".cesium-credit-lightbox-title", {
padding: "20px 20px 0 20px"
});
style += addStyle(".cesium-credit-lightbox-close", {
"font-size": "18pt",
cursor: "pointer",
position: "absolute",
top: "0",
right: "6px",
color: textColor
});
style += addStyle(".cesium-credit-lightbox-close:hover", {
color: highlightColor
});
style += addStyle(".cesium-credit-lightbox > ul", {
margin: "0",
padding: "12px 20px 12px 40px",
"font-size": "13px"
});
style += addStyle(".cesium-credit-lightbox > ul > li", {
"padding-bottom": "6px"
});
style += addStyle(".cesium-credit-lightbox > ul > li *", {
padding: "0",
margin: "0"
});
style += addStyle(".cesium-credit-expand-link", {
"padding-left": "5px",
cursor: "pointer",
"text-decoration": "underline",
color: textColor
});
style += addStyle(".cesium-credit-expand-link:hover", {
color: highlightColor
});
style += addStyle(".cesium-credit-text", {
color: textColor
});
style += addStyle(
".cesium-credit-textContainer *, .cesium-credit-logoContainer *",
{
display: "inline"
}
);
function getShadowRoot(container2) {
if (container2.shadowRoot) {
return container2.shadowRoot;
}
if (container2.getRootNode) {
const root = container2.getRootNode();
if (root instanceof ShadowRoot) {
return root;
}
}
return void 0;
}
const shadowRootOrDocumentHead = defaultValue_default(
getShadowRoot(container),
document.head
);
const css = document.createElement("style");
css.innerHTML = style;
shadowRootOrDocumentHead.appendChild(css);
}
function CreditDisplay(container, delimiter, viewport) {
Check_default.defined("container", container);
const that = this;
viewport = defaultValue_default(viewport, document.body);
const lightbox = document.createElement("div");
lightbox.className = "cesium-credit-lightbox-overlay";
viewport.appendChild(lightbox);
const lightboxCredits = document.createElement("div");
lightboxCredits.className = "cesium-credit-lightbox";
lightbox.appendChild(lightboxCredits);
function hideLightbox(event) {
if (lightboxCredits.contains(event.target)) {
return;
}
that.hideLightbox();
}
lightbox.addEventListener("click", hideLightbox, false);
const title = document.createElement("div");
title.className = "cesium-credit-lightbox-title";
title.textContent = "Data provided by:";
lightboxCredits.appendChild(title);
const closeButton = document.createElement("a");
closeButton.onclick = this.hideLightbox.bind(this);
closeButton.innerHTML = "×";
closeButton.className = "cesium-credit-lightbox-close";
lightboxCredits.appendChild(closeButton);
const creditList = document.createElement("ul");
lightboxCredits.appendChild(creditList);
const cesiumCreditContainer = document.createElement("div");
cesiumCreditContainer.className = "cesium-credit-logoContainer";
cesiumCreditContainer.style.display = "inline";
container.appendChild(cesiumCreditContainer);
const screenContainer = document.createElement("div");
screenContainer.className = "cesium-credit-textContainer";
screenContainer.style.display = "inline";
container.appendChild(screenContainer);
const expandLink = document.createElement("a");
expandLink.className = "cesium-credit-expand-link";
expandLink.onclick = this.showLightbox.bind(this);
expandLink.textContent = "Data attribution";
container.appendChild(expandLink);
appendCss(container);
const cesiumCredit = Credit_default.clone(CreditDisplay.cesiumCredit);
this._delimiter = defaultValue_default(delimiter, " \u2022 ");
this._screenContainer = screenContainer;
this._cesiumCreditContainer = cesiumCreditContainer;
this._lastViewportHeight = void 0;
this._lastViewportWidth = void 0;
this._lightboxCredits = lightboxCredits;
this._creditList = creditList;
this._lightbox = lightbox;
this._hideLightbox = hideLightbox;
this._expandLink = expandLink;
this._expanded = false;
this._staticCredits = [];
this._cesiumCredit = cesiumCredit;
this._previousCesiumCredit = void 0;
this._currentCesiumCredit = cesiumCredit;
this._creditDisplayElementPool = [];
this._creditDisplayElementIndex = 0;
this._currentFrameCredits = {
screenCredits: new AssociativeArray_default(),
lightboxCredits: new AssociativeArray_default()
};
this._defaultCredit = void 0;
this.viewport = viewport;
this.container = container;
}
function setCredit(creditDisplay, credits, credit, count) {
count = defaultValue_default(count, 1);
let creditDisplayElement = credits.get(credit.id);
if (!defined_default(creditDisplayElement)) {
const pool2 = creditDisplay._creditDisplayElementPool;
const poolIndex = creditDisplay._creditDisplayElementPoolIndex;
if (poolIndex < pool2.length) {
creditDisplayElement = pool2[poolIndex];
creditDisplayElement.credit = credit;
creditDisplayElement.count = count;
} else {
creditDisplayElement = new CreditDisplayElement(credit, count);
pool2.push(creditDisplayElement);
}
++creditDisplay._creditDisplayElementPoolIndex;
credits.set(credit.id, creditDisplayElement);
} else if (creditDisplayElement.count < Number.MAX_VALUE) {
creditDisplayElement.count += count;
}
}
CreditDisplay.prototype.addCredit = function(credit) {
deprecationWarning_default(
"CreditDisplay.addCredit",
"CreditDisplay.addCredit was deprecated in CesiumJS 1.105. It will be removed in CesiumJS 1.107. Use CreditDisplay.addCreditToNextFrame instead."
);
this.addCreditToNextFrame(credit);
};
CreditDisplay.prototype.addCreditToNextFrame = function(credit) {
Check_default.defined("credit", credit);
if (credit._isIon) {
if (!defined_default(this._defaultCredit)) {
this._defaultCredit = Credit_default.clone(getDefaultCredit());
}
this._currentCesiumCredit = this._defaultCredit;
return;
}
let credits;
if (!credit.showOnScreen) {
credits = this._currentFrameCredits.lightboxCredits;
} else {
credits = this._currentFrameCredits.screenCredits;
}
setCredit(this, credits, credit);
};
CreditDisplay.prototype.addDefaultCredit = function(credit) {
Check_default.defined("credit", credit);
deprecationWarning_default(
"CreditDisplay.addDefaultCredit",
"CreditDisplay.addDefaultCredit was deprecated in CesiumJS 1.105. It will be removed in CesiumJS 1.107. Use CreditDisplay.addStaticCredit instead."
);
const defaultCredits = this._staticCredits;
if (!contains(defaultCredits, credit)) {
credit.showOnScreen = true;
defaultCredits.push(credit);
}
};
CreditDisplay.prototype.addStaticCredit = function(credit) {
Check_default.defined("credit", credit);
const staticCredits = this._staticCredits;
if (!contains(staticCredits, credit)) {
staticCredits.push(credit);
}
};
CreditDisplay.prototype.removeStaticCredit = function(credit) {
Check_default.defined("credit", credit);
const staticCredits = this._staticCredits;
const index = staticCredits.indexOf(credit);
if (index !== -1) {
staticCredits.splice(index, 1);
}
};
CreditDisplay.prototype.removeDefaultCredit = function(credit) {
deprecationWarning_default(
"CreditDisplay.removeDefaultCredit",
"CreditDisplay.removeDefaultCredit was deprecated in CesiumJS 1.105. It will be removed in CesiumJS 1.107. Use CreditDisplay.addStaticCredit instead."
);
this.removeStaticCredit(credit);
};
CreditDisplay.prototype.showLightbox = function() {
this._lightbox.style.display = "block";
this._expanded = true;
};
CreditDisplay.prototype.hideLightbox = function() {
this._lightbox.style.display = "none";
this._expanded = false;
};
CreditDisplay.prototype.update = function() {
if (this._expanded) {
styleLightboxContainer(this);
}
};
CreditDisplay.prototype.beginFrame = function() {
const currentFrameCredits = this._currentFrameCredits;
this._creditDisplayElementPoolIndex = 0;
const screenCredits = currentFrameCredits.screenCredits;
const lightboxCredits = currentFrameCredits.lightboxCredits;
screenCredits.removeAll();
lightboxCredits.removeAll();
const staticCredits = this._staticCredits;
for (let i = 0; i < staticCredits.length; ++i) {
const staticCredit = staticCredits[i];
const creditCollection = staticCredit.showOnScreen ? screenCredits : lightboxCredits;
if (staticCredit._isIon && Credit_default.equals(CreditDisplay.cesiumCredit, this._cesiumCredit)) {
continue;
}
setCredit(this, creditCollection, staticCredit, Number.MAX_VALUE);
}
if (!Credit_default.equals(CreditDisplay.cesiumCredit, this._cesiumCredit)) {
this._cesiumCredit = Credit_default.clone(CreditDisplay.cesiumCredit);
}
this._currentCesiumCredit = this._cesiumCredit;
};
CreditDisplay.prototype.endFrame = function() {
const screenCredits = this._currentFrameCredits.screenCredits.values;
displayCredits(
this._screenContainer,
screenCredits,
this._delimiter,
void 0
);
const lightboxCredits = this._currentFrameCredits.lightboxCredits.values;
this._expandLink.style.display = lightboxCredits.length > 0 ? "inline" : "none";
displayCredits(this._creditList, lightboxCredits, void 0, "li");
swapCesiumCredit(this);
};
CreditDisplay.prototype.destroy = function() {
this._lightbox.removeEventListener("click", this._hideLightbox, false);
this.container.removeChild(this._cesiumCreditContainer);
this.container.removeChild(this._screenContainer);
this.container.removeChild(this._expandLink);
this.viewport.removeChild(this._lightbox);
return destroyObject_default(this);
};
CreditDisplay.prototype.isDestroyed = function() {
return false;
};
CreditDisplay._cesiumCredit = void 0;
CreditDisplay._cesiumCreditInitialized = false;
var defaultCredit2;
function getDefaultCredit() {
if (!defined_default(defaultCredit2)) {
let logo = buildModuleUrl_default("Assets/Images/ion-credit.png");
if (logo.indexOf("http://") !== 0 && logo.indexOf("https://") !== 0 && logo.indexOf("data:") !== 0) {
const logoUrl = new import_urijs12.default(logo);
logo = logoUrl.path();
}
defaultCredit2 = new Credit_default(
`ready
* and {@link AutoExposure#enabled} are true
. A stage will not be ready while it is waiting on textures
* to load.
*
* @memberof AutoExposure.prototype
* @type {boolean}
* @readonly
*/
ready: {
get: function() {
return this._ready;
}
},
/**
* The unique name of this post-process stage for reference by other stages.
*
* @memberof AutoExposure.prototype
* @type {string}
* @readonly
*/
name: {
get: function() {
return this._name;
}
},
/**
* A reference to the texture written to when executing this post process stage.
*
* @memberof AutoExposure.prototype
* @type {Texture}
* @readonly
* @private
*/
outputTexture: {
get: function() {
const framebuffers = this._framebuffers;
if (!defined_default(framebuffers)) {
return void 0;
}
return framebuffers[framebuffers.length - 1].getColorTexture(0);
}
}
});
function destroyFramebuffers4(autoexposure) {
const framebuffers = autoexposure._framebuffers;
if (!defined_default(framebuffers)) {
return;
}
const length3 = framebuffers.length;
for (let i = 0; i < length3; ++i) {
framebuffers[i].destroy();
}
autoexposure._framebuffers = void 0;
autoexposure._previousLuminance.destroy();
autoexposure._previousLuminance = void 0;
}
function createFramebuffers(autoexposure, context) {
destroyFramebuffers4(autoexposure);
let width = autoexposure._width;
let height = autoexposure._height;
const pixelDatatype = context.halfFloatingPointTexture ? PixelDatatype_default.HALF_FLOAT : PixelDatatype_default.FLOAT;
const length3 = Math.ceil(Math.log(Math.max(width, height)) / Math.log(3));
const framebuffers = new Array(length3);
for (let i = 0; i < length3; ++i) {
width = Math.max(Math.ceil(width / 3), 1);
height = Math.max(Math.ceil(height / 3), 1);
framebuffers[i] = new FramebufferManager_default();
framebuffers[i].update(context, width, height, 1, pixelDatatype);
}
const lastTexture = framebuffers[length3 - 1].getColorTexture(0);
autoexposure._previousLuminance.update(
context,
lastTexture.width,
lastTexture.height,
1,
pixelDatatype
);
autoexposure._framebuffers = framebuffers;
}
function destroyCommands(autoexposure) {
const commands = autoexposure._commands;
if (!defined_default(commands)) {
return;
}
const length3 = commands.length;
for (let i = 0; i < length3; ++i) {
commands[i].shaderProgram.destroy();
}
autoexposure._commands = void 0;
}
function createUniformMap4(autoexposure, index) {
let uniforms;
if (index === 0) {
uniforms = {
colorTexture: function() {
return autoexposure._colorTexture;
},
colorTextureDimensions: function() {
return autoexposure._colorTexture.dimensions;
}
};
} else {
const texture = autoexposure._framebuffers[index - 1].getColorTexture(0);
uniforms = {
colorTexture: function() {
return texture;
},
colorTextureDimensions: function() {
return texture.dimensions;
}
};
}
uniforms.minMaxLuminance = function() {
return autoexposure._minMaxLuminance;
};
uniforms.previousLuminance = function() {
return autoexposure._previousLuminance.getColorTexture(0);
};
return uniforms;
}
function getShaderSource(index, length3) {
let source = "uniform sampler2D colorTexture; \nin vec2 v_textureCoordinates; \nfloat sampleTexture(vec2 offset) { \n";
if (index === 0) {
source += " vec4 color = texture(colorTexture, v_textureCoordinates + offset); \n return czm_luminance(color.rgb); \n";
} else {
source += " return texture(colorTexture, v_textureCoordinates + offset).r; \n";
}
source += "}\n\n";
source += "uniform vec2 colorTextureDimensions; \nuniform vec2 minMaxLuminance; \nuniform sampler2D previousLuminance; \nvoid main() { \n float color = 0.0; \n float xStep = 1.0 / colorTextureDimensions.x; \n float yStep = 1.0 / colorTextureDimensions.y; \n int count = 0; \n for (int i = 0; i < 3; ++i) { \n for (int j = 0; j < 3; ++j) { \n vec2 offset; \n offset.x = -xStep + float(i) * xStep; \n offset.y = -yStep + float(j) * yStep; \n if (offset.x < 0.0 || offset.x > 1.0 || offset.y < 0.0 || offset.y > 1.0) { \n continue; \n } \n color += sampleTexture(offset); \n ++count; \n } \n } \n if (count > 0) { \n color /= float(count); \n } \n";
if (index === length3 - 1) {
source += " float previous = texture(previousLuminance, vec2(0.5)).r; \n color = clamp(color, minMaxLuminance.x, minMaxLuminance.y); \n color = previous + (color - previous) / (60.0 * 1.5); \n color = clamp(color, minMaxLuminance.x, minMaxLuminance.y); \n";
}
source += " out_FragColor = vec4(color); \n} \n";
return source;
}
function createCommands5(autoexposure, context) {
destroyCommands(autoexposure);
const framebuffers = autoexposure._framebuffers;
const length3 = framebuffers.length;
const commands = new Array(length3);
for (let i = 0; i < length3; ++i) {
commands[i] = context.createViewportQuadCommand(
getShaderSource(i, length3),
{
framebuffer: framebuffers[i].framebuffer,
uniformMap: createUniformMap4(autoexposure, i)
}
);
}
autoexposure._commands = commands;
}
AutoExposure.prototype.clear = function(context) {
const framebuffers = this._framebuffers;
if (!defined_default(framebuffers)) {
return;
}
let clearCommand = this._clearCommand;
if (!defined_default(clearCommand)) {
clearCommand = this._clearCommand = new ClearCommand_default({
color: new Color_default(0, 0, 0, 0),
framebuffer: void 0
});
}
const length3 = framebuffers.length;
for (let i = 0; i < length3; ++i) {
framebuffers[i].clear(context, clearCommand);
}
};
AutoExposure.prototype.update = function(context) {
const width = context.drawingBufferWidth;
const height = context.drawingBufferHeight;
if (width !== this._width || height !== this._height) {
this._width = width;
this._height = height;
createFramebuffers(this, context);
createCommands5(this, context);
if (!this._ready) {
this._ready = true;
}
}
this._minMaxLuminance.x = this.minimumLuminance;
this._minMaxLuminance.y = this.maximumLuminance;
const framebuffers = this._framebuffers;
const temp = framebuffers[framebuffers.length - 1];
framebuffers[framebuffers.length - 1] = this._previousLuminance;
this._commands[this._commands.length - 1].framebuffer = this._previousLuminance.framebuffer;
this._previousLuminance = temp;
};
AutoExposure.prototype.execute = function(context, colorTexture) {
this._colorTexture = colorTexture;
const commands = this._commands;
if (!defined_default(commands)) {
return;
}
const length3 = commands.length;
for (let i = 0; i < length3; ++i) {
commands[i].execute(context);
}
};
AutoExposure.prototype.isDestroyed = function() {
return false;
};
AutoExposure.prototype.destroy = function() {
destroyFramebuffers4(this);
destroyCommands(this);
return destroyObject_default(this);
};
var AutoExposure_default = AutoExposure;
// packages/engine/Source/Scene/PostProcessStageSampleMode.js
var PostProcessStageSampleMode = {
/**
* Samples the texture by returning the closest texel.
*
* @type {number}
* @constant
*/
NEAREST: 0,
/**
* Samples the texture through bi-linear interpolation of the four nearest texels.
*
* @type {number}
* @constant
*/
LINEAR: 1
};
var PostProcessStageSampleMode_default = PostProcessStageSampleMode;
// packages/engine/Source/Scene/PostProcessStage.js
function PostProcessStage(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const fragmentShader = options.fragmentShader;
const textureScale = defaultValue_default(options.textureScale, 1);
const pixelFormat = defaultValue_default(options.pixelFormat, PixelFormat_default.RGBA);
Check_default.typeOf.string("options.fragmentShader", fragmentShader);
Check_default.typeOf.number.greaterThan("options.textureScale", textureScale, 0);
Check_default.typeOf.number.lessThanOrEquals(
"options.textureScale",
textureScale,
1
);
if (!PixelFormat_default.isColorFormat(pixelFormat)) {
throw new DeveloperError_default("options.pixelFormat must be a color format.");
}
this._fragmentShader = fragmentShader;
this._uniforms = options.uniforms;
this._textureScale = textureScale;
this._forcePowerOfTwo = defaultValue_default(options.forcePowerOfTwo, false);
this._sampleMode = defaultValue_default(
options.sampleMode,
PostProcessStageSampleMode_default.NEAREST
);
this._pixelFormat = pixelFormat;
this._pixelDatatype = defaultValue_default(
options.pixelDatatype,
PixelDatatype_default.UNSIGNED_BYTE
);
this._clearColor = defaultValue_default(options.clearColor, Color_default.BLACK);
this._uniformMap = void 0;
this._command = void 0;
this._colorTexture = void 0;
this._depthTexture = void 0;
this._idTexture = void 0;
this._actualUniforms = {};
this._dirtyUniforms = [];
this._texturesToRelease = [];
this._texturesToCreate = [];
this._texturePromise = void 0;
const passState = new PassState_default();
passState.scissorTest = {
enabled: true,
rectangle: defined_default(options.scissorRectangle) ? BoundingRectangle_default.clone(options.scissorRectangle) : new BoundingRectangle_default()
};
this._passState = passState;
this._ready = false;
let name = options.name;
if (!defined_default(name)) {
name = createGuid_default();
}
this._name = name;
this._logDepthChanged = void 0;
this._useLogDepth = void 0;
this._selectedIdTexture = void 0;
this._selected = void 0;
this._selectedShadow = void 0;
this._parentSelected = void 0;
this._parentSelectedShadow = void 0;
this._combinedSelected = void 0;
this._combinedSelectedShadow = void 0;
this._selectedLength = 0;
this._parentSelectedLength = 0;
this._selectedDirty = true;
this._textureCache = void 0;
this._index = void 0;
this.enabled = true;
this._enabled = true;
}
Object.defineProperties(PostProcessStage.prototype, {
/**
* Determines if this post-process stage is ready to be executed. A stage is only executed when both ready
* and {@link PostProcessStage#enabled} are true
. A stage will not be ready while it is waiting on textures
* to load.
*
* @memberof PostProcessStage.prototype
* @type {boolean}
* @readonly
*/
ready: {
get: function() {
return this._ready;
}
},
/**
* The unique name of this post-process stage for reference by other stages in a {@link PostProcessStageComposite}.
*
* @memberof PostProcessStage.prototype
* @type {string}
* @readonly
*/
name: {
get: function() {
return this._name;
}
},
/**
* The fragment shader to use when execute this post-process stage.
*
* The shader must contain a sampler uniform declaration for colorTexture
, depthTexture
,
* or both.
*
* The shader must contain a vec2
varying declaration for v_textureCoordinates
for sampling
* the texture uniforms.
*
* The object property values can be either a constant or a function. The function will be called * each frame before the post-process stage is executed. *
** A constant value can also be a URI to an image, a data URI, or an HTML element that can be used as a texture, such as HTMLImageElement or HTMLCanvasElement. *
** If this post-process stage is part of a {@link PostProcessStageComposite} that does not execute in series, the constant value can also be * the name of another stage in a composite. This will set the uniform to the output texture the stage with that name. *
* * @memberof PostProcessStage.prototype * @type {object} * @readonly */ uniforms: { get: function() { return this._uniforms; } }, /** * A number in the range (0.0, 1.0] used to scale the output texture dimensions. A scale of 1.0 will render this post-process stage to a texture the size of the viewport. * * @memberof PostProcessStage.prototype * @type {number} * @readonly */ textureScale: { get: function() { return this._textureScale; } }, /** * Whether or not to force the output texture dimensions to be both equal powers of two. The power of two will be the next power of two of the minimum of the dimensions. * * @memberof PostProcessStage.prototype * @type {number} * @readonly */ forcePowerOfTwo: { get: function() { return this._forcePowerOfTwo; } }, /** * How to sample the input color texture. * * @memberof PostProcessStage.prototype * @type {PostProcessStageSampleMode} * @readonly */ sampleMode: { get: function() { return this._sampleMode; } }, /** * The color pixel format of the output texture. * * @memberof PostProcessStage.prototype * @type {PixelFormat} * @readonly */ pixelFormat: { get: function() { return this._pixelFormat; } }, /** * The pixel data type of the output texture. * * @memberof PostProcessStage.prototype * @type {PixelDatatype} * @readonly */ pixelDatatype: { get: function() { return this._pixelDatatype; } }, /** * The color to clear the output texture to. * * @memberof PostProcessStage.prototype * @type {Color} * @readonly */ clearColor: { get: function() { return this._clearColor; } }, /** * The {@link BoundingRectangle} to use for the scissor test. A default bounding rectangle will disable the scissor test. * * @memberof PostProcessStage.prototype * @type {BoundingRectangle} * @readonly */ scissorRectangle: { get: function() { return this._passState.scissorTest.rectangle; } }, /** * A reference to the texture written to when executing this post process stage. * * @memberof PostProcessStage.prototype * @type {Texture} * @readonly * @private */ outputTexture: { get: function() { if (defined_default(this._textureCache)) { const framebuffer = this._textureCache.getFramebuffer(this._name); if (defined_default(framebuffer)) { return framebuffer.getColorTexture(0); } } return void 0; } }, /** * The features selected for applying the post-process. *
* In the fragment shader, use czm_selected
to determine whether or not to apply the post-process
* stage to that fragment. For example:
*
* if (czm_selected(v_textureCoordinates)) {
* // apply post-process stage
* } else {
* out_FragColor = texture(colorTexture, v_textureCoordinates);
* }
*
*
undefined
; in which case, get each stage to set uniform values.
* @memberof PostProcessStageComposite.prototype
* @type {object}
*/
uniforms: {
get: function() {
return this._uniforms;
}
},
/**
* All post-process stages are executed in the order of the array. The input texture changes based on the value of inputPreviousStageTexture
.
* If inputPreviousStageTexture
is true
, the input to each stage is the output texture rendered to by the scene or of the stage that executed before it.
* If inputPreviousStageTexture
is false
, the input texture is the same for each stage in the composite. The input texture is the texture rendered to by the scene
* or the output texture of the previous stage.
*
* @memberof PostProcessStageComposite.prototype
* @type {boolean}
* @readonly
*/
inputPreviousStageTexture: {
get: function() {
return this._inputPreviousStageTexture;
}
},
/**
* The number of post-process stages in this composite.
*
* @memberof PostProcessStageComposite.prototype
* @type {number}
* @readonly
*/
length: {
get: function() {
return this._stages.length;
}
},
/**
* The features selected for applying the post-process.
*
* @memberof PostProcessStageComposite.prototype
* @type {Array}
*/
selected: {
get: function() {
return this._selected;
},
set: function(value) {
this._selected = value;
}
},
/**
* @private
*/
parentSelected: {
get: function() {
return this._parentSelected;
},
set: function(value) {
this._parentSelected = value;
}
}
});
PostProcessStageComposite.prototype._isSupported = function(context) {
const stages = this._stages;
const length3 = stages.length;
for (let i = 0; i < length3; ++i) {
if (!stages[i]._isSupported(context)) {
return false;
}
}
return true;
};
PostProcessStageComposite.prototype.get = function(index) {
Check_default.typeOf.number.greaterThanOrEquals("index", index, 0);
Check_default.typeOf.number.lessThan("index", index, this.length);
return this._stages[index];
};
function isSelectedTextureDirty2(stage) {
let length3 = defined_default(stage._selected) ? stage._selected.length : 0;
const parentLength = defined_default(stage._parentSelected) ? stage._parentSelected : 0;
let dirty = stage._selected !== stage._selectedShadow || length3 !== stage._selectedLength;
dirty = dirty || stage._parentSelected !== stage._parentSelectedShadow || parentLength !== stage._parentSelectedLength;
if (defined_default(stage._selected) && defined_default(stage._parentSelected)) {
stage._combinedSelected = stage._selected.concat(stage._parentSelected);
} else if (defined_default(stage._parentSelected)) {
stage._combinedSelected = stage._parentSelected;
} else {
stage._combinedSelected = stage._selected;
}
if (!dirty && defined_default(stage._combinedSelected)) {
if (!defined_default(stage._combinedSelectedShadow)) {
return true;
}
length3 = stage._combinedSelected.length;
for (let i = 0; i < length3; ++i) {
if (stage._combinedSelected[i] !== stage._combinedSelectedShadow[i]) {
return true;
}
}
}
return dirty;
}
PostProcessStageComposite.prototype.update = function(context, useLogDepth) {
this._selectedDirty = isSelectedTextureDirty2(this);
this._selectedShadow = this._selected;
this._parentSelectedShadow = this._parentSelected;
this._combinedSelectedShadow = this._combinedSelected;
this._selectedLength = defined_default(this._selected) ? this._selected.length : 0;
this._parentSelectedLength = defined_default(this._parentSelected) ? this._parentSelected.length : 0;
const stages = this._stages;
const length3 = stages.length;
for (let i = 0; i < length3; ++i) {
const stage = stages[i];
if (this._selectedDirty) {
stage.parentSelected = this._combinedSelected;
}
stage.update(context, useLogDepth);
}
};
PostProcessStageComposite.prototype.isDestroyed = function() {
return false;
};
PostProcessStageComposite.prototype.destroy = function() {
const stages = this._stages;
const length3 = stages.length;
for (let i = 0; i < length3; ++i) {
stages[i].destroy();
}
return destroyObject_default(this);
};
var PostProcessStageComposite_default = PostProcessStageComposite;
// packages/engine/Source/Scene/PostProcessStageLibrary.js
var PostProcessStageLibrary = {};
function createBlur(name) {
const delta = 1;
const sigma = 2;
const stepSize = 1;
const blurShader = `#define USE_STEP_SIZE
${GaussianBlur1D_default}`;
const blurX = new PostProcessStage_default({
name: `${name}_x_direction`,
fragmentShader: blurShader,
uniforms: {
delta,
sigma,
stepSize,
direction: 0
},
sampleMode: PostProcessStageSampleMode_default.LINEAR
});
const blurY = new PostProcessStage_default({
name: `${name}_y_direction`,
fragmentShader: blurShader,
uniforms: {
delta,
sigma,
stepSize,
direction: 1
},
sampleMode: PostProcessStageSampleMode_default.LINEAR
});
const uniforms = {};
Object.defineProperties(uniforms, {
delta: {
get: function() {
return blurX.uniforms.delta;
},
set: function(value) {
const blurXUniforms = blurX.uniforms;
const blurYUniforms = blurY.uniforms;
blurXUniforms.delta = blurYUniforms.delta = value;
}
},
sigma: {
get: function() {
return blurX.uniforms.sigma;
},
set: function(value) {
const blurXUniforms = blurX.uniforms;
const blurYUniforms = blurY.uniforms;
blurXUniforms.sigma = blurYUniforms.sigma = value;
}
},
stepSize: {
get: function() {
return blurX.uniforms.stepSize;
},
set: function(value) {
const blurXUniforms = blurX.uniforms;
const blurYUniforms = blurY.uniforms;
blurXUniforms.stepSize = blurYUniforms.stepSize = value;
}
}
});
return new PostProcessStageComposite_default({
name,
stages: [blurX, blurY],
uniforms
});
}
PostProcessStageLibrary.createBlurStage = function() {
return createBlur("czm_blur");
};
PostProcessStageLibrary.createDepthOfFieldStage = function() {
const blur = createBlur("czm_depth_of_field_blur");
const dof = new PostProcessStage_default({
name: "czm_depth_of_field_composite",
fragmentShader: DepthOfField_default,
uniforms: {
focalDistance: 5,
blurTexture: blur.name
}
});
const uniforms = {};
Object.defineProperties(uniforms, {
focalDistance: {
get: function() {
return dof.uniforms.focalDistance;
},
set: function(value) {
dof.uniforms.focalDistance = value;
}
},
delta: {
get: function() {
return blur.uniforms.delta;
},
set: function(value) {
blur.uniforms.delta = value;
}
},
sigma: {
get: function() {
return blur.uniforms.sigma;
},
set: function(value) {
blur.uniforms.sigma = value;
}
},
stepSize: {
get: function() {
return blur.uniforms.stepSize;
},
set: function(value) {
blur.uniforms.stepSize = value;
}
}
});
return new PostProcessStageComposite_default({
name: "czm_depth_of_field",
stages: [blur, dof],
inputPreviousStageTexture: false,
uniforms
});
};
PostProcessStageLibrary.isDepthOfFieldSupported = function(scene) {
return scene.context.depthTexture;
};
PostProcessStageLibrary.createEdgeDetectionStage = function() {
const name = createGuid_default();
return new PostProcessStage_default({
name: `czm_edge_detection_${name}`,
fragmentShader: EdgeDetection_default,
uniforms: {
length: 0.25,
color: Color_default.clone(Color_default.BLACK)
}
});
};
PostProcessStageLibrary.isEdgeDetectionSupported = function(scene) {
return scene.context.depthTexture;
};
function getSilhouetteEdgeDetection(edgeDetectionStages) {
if (!defined_default(edgeDetectionStages)) {
return PostProcessStageLibrary.createEdgeDetectionStage();
}
const edgeDetection = new PostProcessStageComposite_default({
name: "czm_edge_detection_multiple",
stages: edgeDetectionStages,
inputPreviousStageTexture: false
});
const compositeUniforms = {};
let fsDecl = "";
let fsLoop = "";
for (let i = 0; i < edgeDetectionStages.length; ++i) {
fsDecl += `uniform sampler2D edgeTexture${i};
`;
fsLoop += ` vec4 edge${i} = texture(edgeTexture${i}, v_textureCoordinates);
if (edge${i}.a > 0.0)
{
color = edge${i};
break;
}
`;
compositeUniforms[`edgeTexture${i}`] = edgeDetectionStages[i].name;
}
const fs = `${fsDecl}in vec2 v_textureCoordinates;
void main() {
vec4 color = vec4(0.0);
for (int i = 0; i < ${edgeDetectionStages.length}; i++)
{
${fsLoop} }
out_FragColor = color;
}
`;
const edgeComposite = new PostProcessStage_default({
name: "czm_edge_detection_combine",
fragmentShader: fs,
uniforms: compositeUniforms
});
return new PostProcessStageComposite_default({
name: "czm_edge_detection_composite",
stages: [edgeDetection, edgeComposite]
});
}
PostProcessStageLibrary.createSilhouetteStage = function(edgeDetectionStages) {
const edgeDetection = getSilhouetteEdgeDetection(edgeDetectionStages);
const silhouetteProcess = new PostProcessStage_default({
name: "czm_silhouette_color_edges",
fragmentShader: Silhouette_default,
uniforms: {
silhouetteTexture: edgeDetection.name
}
});
return new PostProcessStageComposite_default({
name: "czm_silhouette",
stages: [edgeDetection, silhouetteProcess],
inputPreviousStageTexture: false,
uniforms: edgeDetection.uniforms
});
};
PostProcessStageLibrary.isSilhouetteSupported = function(scene) {
return scene.context.depthTexture;
};
PostProcessStageLibrary.createBloomStage = function() {
const contrastBias = new PostProcessStage_default({
name: "czm_bloom_contrast_bias",
fragmentShader: ContrastBias_default,
uniforms: {
contrast: 128,
brightness: -0.3
}
});
const blur = createBlur("czm_bloom_blur");
const generateComposite = new PostProcessStageComposite_default({
name: "czm_bloom_contrast_bias_blur",
stages: [contrastBias, blur]
});
const bloomComposite = new PostProcessStage_default({
name: "czm_bloom_generate_composite",
fragmentShader: BloomComposite_default,
uniforms: {
glowOnly: false,
bloomTexture: generateComposite.name
}
});
const uniforms = {};
Object.defineProperties(uniforms, {
glowOnly: {
get: function() {
return bloomComposite.uniforms.glowOnly;
},
set: function(value) {
bloomComposite.uniforms.glowOnly = value;
}
},
contrast: {
get: function() {
return contrastBias.uniforms.contrast;
},
set: function(value) {
contrastBias.uniforms.contrast = value;
}
},
brightness: {
get: function() {
return contrastBias.uniforms.brightness;
},
set: function(value) {
contrastBias.uniforms.brightness = value;
}
},
delta: {
get: function() {
return blur.uniforms.delta;
},
set: function(value) {
blur.uniforms.delta = value;
}
},
sigma: {
get: function() {
return blur.uniforms.sigma;
},
set: function(value) {
blur.uniforms.sigma = value;
}
},
stepSize: {
get: function() {
return blur.uniforms.stepSize;
},
set: function(value) {
blur.uniforms.stepSize = value;
}
}
});
return new PostProcessStageComposite_default({
name: "czm_bloom",
stages: [generateComposite, bloomComposite],
inputPreviousStageTexture: false,
uniforms
});
};
PostProcessStageLibrary.createAmbientOcclusionStage = function() {
const generate = new PostProcessStage_default({
name: "czm_ambient_occlusion_generate",
fragmentShader: AmbientOcclusionGenerate_default,
uniforms: {
intensity: 3,
bias: 0.1,
lengthCap: 0.26,
stepSize: 1.95,
frustumLength: 1e3,
randomTexture: void 0
}
});
const blur = createBlur("czm_ambient_occlusion_blur");
blur.uniforms.stepSize = 0.86;
const generateAndBlur = new PostProcessStageComposite_default({
name: "czm_ambient_occlusion_generate_blur",
stages: [generate, blur]
});
const ambientOcclusionModulate = new PostProcessStage_default({
name: "czm_ambient_occlusion_composite",
fragmentShader: AmbientOcclusionModulate_default,
uniforms: {
ambientOcclusionOnly: false,
ambientOcclusionTexture: generateAndBlur.name
}
});
const uniforms = {};
Object.defineProperties(uniforms, {
intensity: {
get: function() {
return generate.uniforms.intensity;
},
set: function(value) {
generate.uniforms.intensity = value;
}
},
bias: {
get: function() {
return generate.uniforms.bias;
},
set: function(value) {
generate.uniforms.bias = value;
}
},
lengthCap: {
get: function() {
return generate.uniforms.lengthCap;
},
set: function(value) {
generate.uniforms.lengthCap = value;
}
},
stepSize: {
get: function() {
return generate.uniforms.stepSize;
},
set: function(value) {
generate.uniforms.stepSize = value;
}
},
frustumLength: {
get: function() {
return generate.uniforms.frustumLength;
},
set: function(value) {
generate.uniforms.frustumLength = value;
}
},
randomTexture: {
get: function() {
return generate.uniforms.randomTexture;
},
set: function(value) {
generate.uniforms.randomTexture = value;
}
},
delta: {
get: function() {
return blur.uniforms.delta;
},
set: function(value) {
blur.uniforms.delta = value;
}
},
sigma: {
get: function() {
return blur.uniforms.sigma;
},
set: function(value) {
blur.uniforms.sigma = value;
}
},
blurStepSize: {
get: function() {
return blur.uniforms.stepSize;
},
set: function(value) {
blur.uniforms.stepSize = value;
}
},
ambientOcclusionOnly: {
get: function() {
return ambientOcclusionModulate.uniforms.ambientOcclusionOnly;
},
set: function(value) {
ambientOcclusionModulate.uniforms.ambientOcclusionOnly = value;
}
}
});
return new PostProcessStageComposite_default({
name: "czm_ambient_occlusion",
stages: [generateAndBlur, ambientOcclusionModulate],
inputPreviousStageTexture: false,
uniforms
});
};
PostProcessStageLibrary.isAmbientOcclusionSupported = function(scene) {
return scene.context.depthTexture;
};
var fxaaFS = `#define FXAA_QUALITY_PRESET 39
${FXAA3_11_default}
${FXAA_default}`;
PostProcessStageLibrary.createFXAAStage = function() {
return new PostProcessStage_default({
name: "czm_FXAA",
fragmentShader: fxaaFS,
sampleMode: PostProcessStageSampleMode_default.LINEAR
});
};
PostProcessStageLibrary.createAcesTonemappingStage = function(useAutoExposure) {
let fs = useAutoExposure ? "#define AUTO_EXPOSURE\n" : "";
fs += AcesTonemappingStage_default;
return new PostProcessStage_default({
name: "czm_aces",
fragmentShader: fs,
uniforms: {
autoExposure: void 0
}
});
};
PostProcessStageLibrary.createFilmicTonemappingStage = function(useAutoExposure) {
let fs = useAutoExposure ? "#define AUTO_EXPOSURE\n" : "";
fs += FilmicTonemapping_default;
return new PostProcessStage_default({
name: "czm_filmic",
fragmentShader: fs,
uniforms: {
autoExposure: void 0
}
});
};
PostProcessStageLibrary.createReinhardTonemappingStage = function(useAutoExposure) {
let fs = useAutoExposure ? "#define AUTO_EXPOSURE\n" : "";
fs += ReinhardTonemapping_default;
return new PostProcessStage_default({
name: "czm_reinhard",
fragmentShader: fs,
uniforms: {
autoExposure: void 0
}
});
};
PostProcessStageLibrary.createModifiedReinhardTonemappingStage = function(useAutoExposure) {
let fs = useAutoExposure ? "#define AUTO_EXPOSURE\n" : "";
fs += ModifiedReinhardTonemapping_default;
return new PostProcessStage_default({
name: "czm_modified_reinhard",
fragmentShader: fs,
uniforms: {
white: Color_default.WHITE,
autoExposure: void 0
}
});
};
PostProcessStageLibrary.createAutoExposureStage = function() {
return new AutoExposure_default();
};
PostProcessStageLibrary.createBlackAndWhiteStage = function() {
return new PostProcessStage_default({
name: "czm_black_and_white",
fragmentShader: BlackAndWhite_default,
uniforms: {
gradations: 5
}
});
};
PostProcessStageLibrary.createBrightnessStage = function() {
return new PostProcessStage_default({
name: "czm_brightness",
fragmentShader: Brightness_default,
uniforms: {
brightness: 0.5
}
});
};
PostProcessStageLibrary.createNightVisionStage = function() {
return new PostProcessStage_default({
name: "czm_night_vision",
fragmentShader: NightVision_default
});
};
PostProcessStageLibrary.createDepthViewStage = function() {
return new PostProcessStage_default({
name: "czm_depth_view",
fragmentShader: DepthView_default
});
};
PostProcessStageLibrary.createLensFlareStage = function() {
return new PostProcessStage_default({
name: "czm_lens_flare",
fragmentShader: LensFlare_default,
uniforms: {
dirtTexture: buildModuleUrl_default("Assets/Textures/LensFlare/DirtMask.jpg"),
starTexture: buildModuleUrl_default("Assets/Textures/LensFlare/StarBurst.jpg"),
intensity: 2,
distortion: 10,
ghostDispersal: 0.4,
haloWidth: 0.4,
dirtAmount: 0.4,
earthRadius: Ellipsoid_default.WGS84.maximumRadius
}
});
};
var PostProcessStageLibrary_default = PostProcessStageLibrary;
// packages/engine/Source/Scene/PostProcessStageTextureCache.js
function PostProcessStageTextureCache(postProcessStageCollection) {
this._collection = postProcessStageCollection;
this._framebuffers = [];
this._stageNameToFramebuffer = {};
this._width = void 0;
this._height = void 0;
this._updateDependencies = false;
}
function getLastStageName(stage) {
while (defined_default(stage.length)) {
stage = stage.get(stage.length - 1);
}
return stage.name;
}
function getStageDependencies(collection, context, dependencies, stage, previousName) {
if (!stage.enabled || !stage._isSupported(context)) {
return previousName;
}
const stageDependencies = dependencies[stage.name] = {};
if (defined_default(previousName)) {
const previous = collection.getStageByName(previousName);
stageDependencies[getLastStageName(previous)] = true;
}
const uniforms = stage.uniforms;
if (defined_default(uniforms)) {
const uniformNames = Object.getOwnPropertyNames(uniforms);
const uniformNamesLength = uniformNames.length;
for (let i = 0; i < uniformNamesLength; ++i) {
const value = uniforms[uniformNames[i]];
if (typeof value === "string") {
const dependent = collection.getStageByName(value);
if (defined_default(dependent)) {
stageDependencies[getLastStageName(dependent)] = true;
}
}
}
}
return stage.name;
}
function getCompositeDependencies(collection, context, dependencies, composite, previousName) {
if (defined_default(composite.enabled) && !composite.enabled || defined_default(composite._isSupported) && !composite._isSupported(context)) {
return previousName;
}
const originalDependency = previousName;
const inSeries = !defined_default(composite.inputPreviousStageTexture) || composite.inputPreviousStageTexture;
let currentName = previousName;
const length3 = composite.length;
for (let i = 0; i < length3; ++i) {
const stage = composite.get(i);
if (defined_default(stage.length)) {
currentName = getCompositeDependencies(
collection,
context,
dependencies,
stage,
previousName
);
} else {
currentName = getStageDependencies(
collection,
context,
dependencies,
stage,
previousName
);
}
if (inSeries) {
previousName = currentName;
}
}
let j;
let name;
if (!inSeries) {
for (j = 1; j < length3; ++j) {
name = getLastStageName(composite.get(j));
const currentDependencies = dependencies[name];
for (let k = 0; k < j; ++k) {
currentDependencies[getLastStageName(composite.get(k))] = true;
}
}
} else {
for (j = 1; j < length3; ++j) {
name = getLastStageName(composite.get(j));
if (!defined_default(dependencies[name])) {
dependencies[name] = {};
}
dependencies[name][originalDependency] = true;
}
}
return currentName;
}
function getDependencies(collection, context) {
const dependencies = {};
if (defined_default(collection.ambientOcclusion)) {
const ao = collection.ambientOcclusion;
const bloom = collection.bloom;
const tonemapping = collection._tonemapping;
const fxaa = collection.fxaa;
let previousName = getCompositeDependencies(
collection,
context,
dependencies,
ao,
void 0
);
previousName = getCompositeDependencies(
collection,
context,
dependencies,
bloom,
previousName
);
previousName = getStageDependencies(
collection,
context,
dependencies,
tonemapping,
previousName
);
previousName = getCompositeDependencies(
collection,
context,
dependencies,
collection,
previousName
);
getStageDependencies(collection, context, dependencies, fxaa, previousName);
} else {
getCompositeDependencies(
collection,
context,
dependencies,
collection,
void 0
);
}
return dependencies;
}
function getFramebuffer(cache, stageName, dependencies) {
const collection = cache._collection;
const stage = collection.getStageByName(stageName);
const textureScale = stage._textureScale;
const forcePowerOfTwo = stage._forcePowerOfTwo;
const pixelFormat = stage._pixelFormat;
const pixelDatatype = stage._pixelDatatype;
const clearColor = stage._clearColor;
let i;
let framebuffer;
const framebuffers = cache._framebuffers;
const length3 = framebuffers.length;
for (i = 0; i < length3; ++i) {
framebuffer = framebuffers[i];
if (textureScale !== framebuffer.textureScale || forcePowerOfTwo !== framebuffer.forcePowerOfTwo || pixelFormat !== framebuffer.pixelFormat || pixelDatatype !== framebuffer.pixelDatatype || !Color_default.equals(clearColor, framebuffer.clearColor)) {
continue;
}
const stageNames = framebuffer.stages;
const stagesLength = stageNames.length;
let foundConflict = false;
for (let j = 0; j < stagesLength; ++j) {
if (dependencies[stageNames[j]]) {
foundConflict = true;
break;
}
}
if (!foundConflict) {
break;
}
}
if (defined_default(framebuffer) && i < length3) {
framebuffer.stages.push(stageName);
return framebuffer;
}
framebuffer = {
textureScale,
forcePowerOfTwo,
pixelFormat,
pixelDatatype,
clearColor,
stages: [stageName],
buffer: new FramebufferManager_default({
pixelFormat,
pixelDatatype
}),
clear: void 0
};
framebuffers.push(framebuffer);
return framebuffer;
}
function createFramebuffers2(cache, context) {
const dependencies = getDependencies(cache._collection, context);
for (const stageName in dependencies) {
if (dependencies.hasOwnProperty(stageName)) {
cache._stageNameToFramebuffer[stageName] = getFramebuffer(
cache,
stageName,
dependencies[stageName]
);
}
}
}
function releaseResources2(cache) {
const framebuffers = cache._framebuffers;
const length3 = framebuffers.length;
for (let i = 0; i < length3; ++i) {
const framebuffer = framebuffers[i];
framebuffer.buffer.destroy();
}
}
function updateFramebuffers4(cache, context) {
const width = cache._width;
const height = cache._height;
const framebuffers = cache._framebuffers;
const length3 = framebuffers.length;
for (let i = 0; i < length3; ++i) {
const framebuffer = framebuffers[i];
const scale = framebuffer.textureScale;
let textureWidth = Math.ceil(width * scale);
let textureHeight = Math.ceil(height * scale);
let size = Math.min(textureWidth, textureHeight);
if (framebuffer.forcePowerOfTwo) {
if (!Math_default.isPowerOfTwo(size)) {
size = Math_default.nextPowerOfTwo(size);
}
textureWidth = size;
textureHeight = size;
}
framebuffer.buffer.update(context, textureWidth, textureHeight);
framebuffer.clear = new ClearCommand_default({
color: framebuffer.clearColor,
framebuffer: framebuffer.buffer.framebuffer
});
}
}
PostProcessStageTextureCache.prototype.updateDependencies = function() {
this._updateDependencies = true;
};
PostProcessStageTextureCache.prototype.update = function(context) {
const collection = this._collection;
const updateDependencies = this._updateDependencies;
const aoEnabled = defined_default(collection.ambientOcclusion) && collection.ambientOcclusion.enabled && collection.ambientOcclusion._isSupported(context);
const bloomEnabled = defined_default(collection.bloom) && collection.bloom.enabled && collection.bloom._isSupported(context);
const tonemappingEnabled = defined_default(collection._tonemapping) && collection._tonemapping.enabled && collection._tonemapping._isSupported(context);
const fxaaEnabled = defined_default(collection.fxaa) && collection.fxaa.enabled && collection.fxaa._isSupported(context);
const needsCheckDimensionsUpdate = !defined_default(collection._activeStages) || collection._activeStages.length > 0 || aoEnabled || bloomEnabled || tonemappingEnabled || fxaaEnabled;
if (updateDependencies || !needsCheckDimensionsUpdate && this._framebuffers.length > 0) {
releaseResources2(this);
this._framebuffers.length = 0;
this._stageNameToFramebuffer = {};
this._width = void 0;
this._height = void 0;
}
if (!updateDependencies && !needsCheckDimensionsUpdate) {
return;
}
if (this._framebuffers.length === 0) {
createFramebuffers2(this, context);
}
const width = context.drawingBufferWidth;
const height = context.drawingBufferHeight;
const dimensionsChanged = this._width !== width || this._height !== height;
if (!updateDependencies && !dimensionsChanged) {
return;
}
this._width = width;
this._height = height;
this._updateDependencies = false;
releaseResources2(this);
updateFramebuffers4(this, context);
};
PostProcessStageTextureCache.prototype.clear = function(context) {
const framebuffers = this._framebuffers;
for (let i = 0; i < framebuffers.length; ++i) {
framebuffers[i].clear.execute(context);
}
};
PostProcessStageTextureCache.prototype.getStageByName = function(name) {
return this._collection.getStageByName(name);
};
PostProcessStageTextureCache.prototype.getOutputTexture = function(name) {
return this._collection.getOutputTexture(name);
};
PostProcessStageTextureCache.prototype.getFramebuffer = function(name) {
const framebuffer = this._stageNameToFramebuffer[name];
if (!defined_default(framebuffer)) {
return void 0;
}
return framebuffer.buffer.framebuffer;
};
PostProcessStageTextureCache.prototype.isDestroyed = function() {
return false;
};
PostProcessStageTextureCache.prototype.destroy = function() {
releaseResources2(this);
return destroyObject_default(this);
};
var PostProcessStageTextureCache_default = PostProcessStageTextureCache;
// packages/engine/Source/Scene/Tonemapper.js
var Tonemapper = {
/**
* Use the Reinhard tonemapping operator.
*
* @type {number}
* @constant
*/
REINHARD: 0,
/**
* Use the modified Reinhard tonemapping operator.
*
* @type {number}
* @constant
*/
MODIFIED_REINHARD: 1,
/**
* Use the Filmic tonemapping operator.
*
* @type {number}
* @constant
*/
FILMIC: 2,
/**
* Use the ACES tonemapping operator.
*
* @type {number}
* @constant
*/
ACES: 3,
/**
* @private
*/
validate: function(tonemapper) {
return tonemapper === Tonemapper.REINHARD || tonemapper === Tonemapper.MODIFIED_REINHARD || tonemapper === Tonemapper.FILMIC || tonemapper === Tonemapper.ACES;
}
};
var Tonemapper_default = Object.freeze(Tonemapper);
// packages/engine/Source/Scene/PostProcessStageCollection.js
var stackScratch = [];
function PostProcessStageCollection() {
const fxaa = PostProcessStageLibrary_default.createFXAAStage();
const ao = PostProcessStageLibrary_default.createAmbientOcclusionStage();
const bloom = PostProcessStageLibrary_default.createBloomStage();
this._autoExposureEnabled = false;
this._autoExposure = PostProcessStageLibrary_default.createAutoExposureStage();
this._tonemapping = void 0;
this._tonemapper = void 0;
this.tonemapper = Tonemapper_default.ACES;
const tonemapping = this._tonemapping;
fxaa.enabled = false;
ao.enabled = false;
bloom.enabled = false;
tonemapping.enabled = false;
const textureCache = new PostProcessStageTextureCache_default(this);
const stageNames = {};
const stack = stackScratch;
stack.push(fxaa, ao, bloom, tonemapping);
while (stack.length > 0) {
const stage = stack.pop();
stageNames[stage.name] = stage;
stage._textureCache = textureCache;
const length3 = stage.length;
if (defined_default(length3)) {
for (let i = 0; i < length3; ++i) {
stack.push(stage.get(i));
}
}
}
this._stages = [];
this._activeStages = [];
this._previousActiveStages = [];
this._randomTexture = void 0;
const that = this;
ao.uniforms.randomTexture = function() {
return that._randomTexture;
};
this._ao = ao;
this._bloom = bloom;
this._fxaa = fxaa;
this._aoEnabled = void 0;
this._bloomEnabled = void 0;
this._tonemappingEnabled = void 0;
this._fxaaEnabled = void 0;
this._activeStagesChanged = false;
this._stagesRemoved = false;
this._textureCacheDirty = false;
this._stageNames = stageNames;
this._textureCache = textureCache;
}
Object.defineProperties(PostProcessStageCollection.prototype, {
/**
* Determines if all of the post-process stages in the collection are ready to be executed.
*
* @memberof PostProcessStageCollection.prototype
* @type {boolean}
* @readonly
*/
ready: {
get: function() {
let readyAndEnabled = false;
const stages = this._stages;
const length3 = stages.length;
for (let i = length3 - 1; i >= 0; --i) {
const stage = stages[i];
readyAndEnabled = readyAndEnabled || stage.ready && stage.enabled;
}
const fxaa = this._fxaa;
const ao = this._ao;
const bloom = this._bloom;
const tonemapping = this._tonemapping;
readyAndEnabled = readyAndEnabled || fxaa.ready && fxaa.enabled;
readyAndEnabled = readyAndEnabled || ao.ready && ao.enabled;
readyAndEnabled = readyAndEnabled || bloom.ready && bloom.enabled;
readyAndEnabled = readyAndEnabled || tonemapping.ready && tonemapping.enabled;
return readyAndEnabled;
}
},
/**
* A post-process stage for Fast Approximate Anti-aliasing.
* * When enabled, this stage will execute after all others. *
* * @memberof PostProcessStageCollection.prototype * @type {PostProcessStage} * @readonly */ fxaa: { get: function() { return this._fxaa; } }, /** * A post-process stage that applies Horizon-based Ambient Occlusion (HBAO) to the input texture. ** Ambient occlusion simulates shadows from ambient light. These shadows would always be present when the * surface receives light and regardless of the light's position. *
*
* The uniforms have the following properties: intensity
, bias
, lengthCap
,
* stepSize
, frustumLength
, ambientOcclusionOnly
,
* delta
, sigma
, and blurStepSize
.
*
intensity
is a scalar value used to lighten or darken the shadows exponentially. Higher values make the shadows darker. The default value is 3.0
.bias
is a scalar value representing an angle in radians. If the dot product between the normal of the sample and the vector to the camera is less than this value,
* sampling stops in the current direction. This is used to remove shadows from near planar edges. The default value is 0.1
.lengthCap
is a scalar value representing a length in meters. If the distance from the current sample to first sample is greater than this value,
* sampling stops in the current direction. The default value is 0.26
.stepSize
is a scalar value indicating the distance to the next texel sample in the current direction. The default value is 1.95
.frustumLength
is a scalar value in meters. If the current fragment has a distance from the camera greater than this value, ambient occlusion is not computed for the fragment.
* The default value is 1000.0
.ambientOcclusionOnly
is a boolean value. When true
, only the shadows generated are written to the output. When false
, the input texture is modulated
* with the ambient occlusion. This is a useful debug option for seeing the effects of changing the uniform values. The default value is false
.
* delta
, sigma
, and blurStepSize
are the same properties as {@link PostProcessStageLibrary#createBlurStage}.
* The blur is applied to the shadows generated from the image to make them smoother.
*
* When enabled, this stage will execute before all others. *
* * @memberof PostProcessStageCollection.prototype * @type {PostProcessStageComposite} * @readonly */ ambientOcclusion: { get: function() { return this._ao; } }, /** * A post-process stage for a bloom effect. ** A bloom effect adds glow effect, makes bright areas brighter, and dark areas darker. *
*
* This stage has the following uniforms: contrast
, brightness
, glowOnly
,
* delta
, sigma
, and stepSize
.
*
contrast
is a scalar value in the range [-255.0, 255.0] and affects the contract of the effect. The default value is 128.0
.brightness
is a scalar value. The input texture RGB value is converted to hue, saturation, and brightness (HSB) then this value is
* added to the brightness. The default value is -0.3
.glowOnly
is a boolean value. When true
, only the glow effect will be shown. When false
, the glow will be added to the input texture.
* The default value is false
. This is a debug option for viewing the effects when changing the other uniform values.
* delta
, sigma
, and stepSize
are the same properties as {@link PostProcessStageLibrary#createBlurStage}.
* The blur is applied to the shadows generated from the image to make them smoother.
*
* When enabled, this stage will execute before all others. *
* * @memberOf PostProcessStageCollection.prototype * @type {PostProcessStageComposite} * @readonly */ bloom: { get: function() { return this._bloom; } }, /** * The number of post-process stages in this collection. * * @memberof PostProcessStageCollection.prototype * @type {number} * @readonly */ length: { get: function() { removeStages(this); return this._stages.length; } }, /** * A reference to the last texture written to when executing the post-process stages in this collection. * * @memberof PostProcessStageCollection.prototype * @type {Texture} * @readonly * @private */ outputTexture: { get: function() { const fxaa = this._fxaa; if (fxaa.enabled && fxaa.ready) { return this.getOutputTexture(fxaa.name); } const stages = this._stages; const length3 = stages.length; for (let i = length3 - 1; i >= 0; --i) { const stage = stages[i]; if (defined_default(stage) && stage.ready && stage.enabled) { return this.getOutputTexture(stage.name); } } const tonemapping = this._tonemapping; if (tonemapping.enabled && tonemapping.ready) { return this.getOutputTexture(tonemapping.name); } const bloom = this._bloom; if (bloom.enabled && bloom.ready) { return this.getOutputTexture(bloom.name); } const ao = this._ao; if (ao.enabled && ao.ready) { return this.getOutputTexture(ao.name); } return void 0; } }, /** * Whether the collection has a stage that has selected features. * * @memberof PostProcessStageCollection.prototype * @type {boolean} * @readonly * @private */ hasSelected: { get: function() { const stages = this._stages.slice(); while (stages.length > 0) { const stage = stages.pop(); if (!defined_default(stage)) { continue; } if (defined_default(stage.selected)) { return true; } const length3 = stage.length; if (defined_default(length3)) { for (let i = 0; i < length3; ++i) { stages.push(stage.get(i)); } } } return false; } }, /** * Gets and sets the tonemapping algorithm used when rendering with high dynamic range. * * @memberof PostProcessStageCollection.prototype * @type {Tonemapper} * @private */ tonemapper: { get: function() { return this._tonemapper; }, set: function(value) { if (this._tonemapper === value) { return; } if (!Tonemapper_default.validate(value)) { throw new DeveloperError_default("tonemapper was set to an invalid value."); } if (defined_default(this._tonemapping)) { delete this._stageNames[this._tonemapping.name]; this._tonemapping.destroy(); } const useAutoExposure = this._autoExposureEnabled; let tonemapper; switch (value) { case Tonemapper_default.REINHARD: tonemapper = PostProcessStageLibrary_default.createReinhardTonemappingStage( useAutoExposure ); break; case Tonemapper_default.MODIFIED_REINHARD: tonemapper = PostProcessStageLibrary_default.createModifiedReinhardTonemappingStage( useAutoExposure ); break; case Tonemapper_default.FILMIC: tonemapper = PostProcessStageLibrary_default.createFilmicTonemappingStage( useAutoExposure ); break; default: tonemapper = PostProcessStageLibrary_default.createAcesTonemappingStage( useAutoExposure ); break; } if (useAutoExposure) { const autoexposure = this._autoExposure; tonemapper.uniforms.autoExposure = function() { return autoexposure.outputTexture; }; } this._tonemapper = value; this._tonemapping = tonemapper; if (defined_default(this._stageNames)) { this._stageNames[tonemapper.name] = tonemapper; tonemapper._textureCache = this._textureCache; } this._textureCacheDirty = true; } } }); function removeStages(collection) { if (!collection._stagesRemoved) { return; } collection._stagesRemoved = false; const newStages = []; const stages = collection._stages; const length3 = stages.length; for (let i = 0, j = 0; i < length3; ++i) { const stage = stages[i]; if (stage) { stage._index = j++; newStages.push(stage); } } collection._stages = newStages; } PostProcessStageCollection.prototype.add = function(stage) { Check_default.typeOf.object("stage", stage); const stageNames = this._stageNames; const stack = stackScratch; stack.push(stage); while (stack.length > 0) { const currentStage = stack.pop(); if (defined_default(stageNames[currentStage.name])) { throw new DeveloperError_default( `${currentStage.name} has already been added to the collection or does not have a unique name.` ); } stageNames[currentStage.name] = currentStage; currentStage._textureCache = this._textureCache; const length3 = currentStage.length; if (defined_default(length3)) { for (let i = 0; i < length3; ++i) { stack.push(currentStage.get(i)); } } } const stages = this._stages; stage._index = stages.length; stages.push(stage); this._textureCacheDirty = true; return stage; }; PostProcessStageCollection.prototype.remove = function(stage) { if (!this.contains(stage)) { return false; } const stageNames = this._stageNames; const stack = stackScratch; stack.push(stage); while (stack.length > 0) { const currentStage = stack.pop(); delete stageNames[currentStage.name]; const length3 = currentStage.length; if (defined_default(length3)) { for (let i = 0; i < length3; ++i) { stack.push(currentStage.get(i)); } } } this._stages[stage._index] = void 0; this._stagesRemoved = true; this._textureCacheDirty = true; stage._index = void 0; stage._textureCache = void 0; stage.destroy(); return true; }; PostProcessStageCollection.prototype.contains = function(stage) { return defined_default(stage) && defined_default(stage._index) && stage._textureCache === this._textureCache; }; PostProcessStageCollection.prototype.get = function(index) { removeStages(this); const stages = this._stages; const length3 = stages.length; Check_default.typeOf.number.greaterThanOrEquals("stages length", length3, 0); Check_default.typeOf.number.greaterThanOrEquals("index", index, 0); Check_default.typeOf.number.lessThan("index", index, length3); return stages[index]; }; PostProcessStageCollection.prototype.removeAll = function() { const stages = this._stages; const length3 = stages.length; for (let i = 0; i < length3; ++i) { this.remove(stages[i]); } stages.length = 0; }; PostProcessStageCollection.prototype.getStageByName = function(name) { return this._stageNames[name]; }; PostProcessStageCollection.prototype.update = function(context, useLogDepth, useHdr) { removeStages(this); const previousActiveStages = this._activeStages; const activeStages = this._activeStages = this._previousActiveStages; this._previousActiveStages = previousActiveStages; const stages = this._stages; let length3 = activeStages.length = stages.length; let i; let stage; let count = 0; for (i = 0; i < length3; ++i) { stage = stages[i]; if (stage.ready && stage.enabled && stage._isSupported(context)) { activeStages[count++] = stage; } } activeStages.length = count; let activeStagesChanged = count !== previousActiveStages.length; if (!activeStagesChanged) { for (i = 0; i < count; ++i) { if (activeStages[i] !== previousActiveStages[i]) { activeStagesChanged = true; break; } } } const ao = this._ao; const bloom = this._bloom; const autoexposure = this._autoExposure; const tonemapping = this._tonemapping; const fxaa = this._fxaa; tonemapping.enabled = useHdr; const aoEnabled = ao.enabled && ao._isSupported(context); const bloomEnabled = bloom.enabled && bloom._isSupported(context); const tonemappingEnabled = tonemapping.enabled && tonemapping._isSupported(context); const fxaaEnabled = fxaa.enabled && fxaa._isSupported(context); if (activeStagesChanged || this._textureCacheDirty || aoEnabled !== this._aoEnabled || bloomEnabled !== this._bloomEnabled || tonemappingEnabled !== this._tonemappingEnabled || fxaaEnabled !== this._fxaaEnabled) { this._textureCache.updateDependencies(); this._aoEnabled = aoEnabled; this._bloomEnabled = bloomEnabled; this._tonemappingEnabled = tonemappingEnabled; this._fxaaEnabled = fxaaEnabled; this._textureCacheDirty = false; } if (defined_default(this._randomTexture) && !aoEnabled) { this._randomTexture.destroy(); this._randomTexture = void 0; } if (!defined_default(this._randomTexture) && aoEnabled) { length3 = 256 * 256 * 3; const random2 = new Uint8Array(length3); for (i = 0; i < length3; i += 3) { random2[i] = Math.floor(Math.random() * 255); } this._randomTexture = new Texture_default({ context, pixelFormat: PixelFormat_default.RGB, pixelDatatype: PixelDatatype_default.UNSIGNED_BYTE, source: { arrayBufferView: random2, width: 256, height: 256 }, sampler: new Sampler_default({ wrapS: TextureWrap_default.REPEAT, wrapT: TextureWrap_default.REPEAT, minificationFilter: TextureMinificationFilter_default.NEAREST, magnificationFilter: TextureMagnificationFilter_default.NEAREST }) }); } this._textureCache.update(context); fxaa.update(context, useLogDepth); ao.update(context, useLogDepth); bloom.update(context, useLogDepth); tonemapping.update(context, useLogDepth); if (this._autoExposureEnabled) { autoexposure.update(context, useLogDepth); } length3 = stages.length; for (i = 0; i < length3; ++i) { stages[i].update(context, useLogDepth); } count = 0; for (i = 0; i < length3; ++i) { stage = stages[i]; if (stage.ready && stage.enabled && stage._isSupported(context)) { count++; } } activeStagesChanged = count !== activeStages.length; if (activeStagesChanged) { this.update(context, useLogDepth, useHdr); } }; PostProcessStageCollection.prototype.clear = function(context) { this._textureCache.clear(context); if (this._autoExposureEnabled) { this._autoExposure.clear(context); } }; function getOutputTexture(stage) { while (defined_default(stage.length)) { stage = stage.get(stage.length - 1); } return stage.outputTexture; } PostProcessStageCollection.prototype.getOutputTexture = function(stageName) { const stage = this.getStageByName(stageName); if (!defined_default(stage)) { return void 0; } return getOutputTexture(stage); }; function execute(stage, context, colorTexture, depthTexture, idTexture) { if (defined_default(stage.execute)) { stage.execute(context, colorTexture, depthTexture, idTexture); return; } const length3 = stage.length; let i; if (stage.inputPreviousStageTexture) { execute(stage.get(0), context, colorTexture, depthTexture, idTexture); for (i = 1; i < length3; ++i) { execute( stage.get(i), context, getOutputTexture(stage.get(i - 1)), depthTexture, idTexture ); } } else { for (i = 0; i < length3; ++i) { execute(stage.get(i), context, colorTexture, depthTexture, idTexture); } } } PostProcessStageCollection.prototype.execute = function(context, colorTexture, depthTexture, idTexture) { const activeStages = this._activeStages; const length3 = activeStages.length; const fxaa = this._fxaa; const ao = this._ao; const bloom = this._bloom; const autoexposure = this._autoExposure; const tonemapping = this._tonemapping; const aoEnabled = ao.enabled && ao._isSupported(context); const bloomEnabled = bloom.enabled && bloom._isSupported(context); const autoExposureEnabled = this._autoExposureEnabled; const tonemappingEnabled = tonemapping.enabled && tonemapping._isSupported(context); const fxaaEnabled = fxaa.enabled && fxaa._isSupported(context); if (!fxaaEnabled && !aoEnabled && !bloomEnabled && !tonemappingEnabled && length3 === 0) { return; } let initialTexture = colorTexture; if (aoEnabled && ao.ready) { execute(ao, context, initialTexture, depthTexture, idTexture); initialTexture = getOutputTexture(ao); } if (bloomEnabled && bloom.ready) { execute(bloom, context, initialTexture, depthTexture, idTexture); initialTexture = getOutputTexture(bloom); } if (autoExposureEnabled && autoexposure.ready) { execute(autoexposure, context, initialTexture, depthTexture, idTexture); } if (tonemappingEnabled && tonemapping.ready) { execute(tonemapping, context, initialTexture, depthTexture, idTexture); initialTexture = getOutputTexture(tonemapping); } let lastTexture = initialTexture; if (length3 > 0) { execute(activeStages[0], context, initialTexture, depthTexture, idTexture); for (let i = 1; i < length3; ++i) { execute( activeStages[i], context, getOutputTexture(activeStages[i - 1]), depthTexture, idTexture ); } lastTexture = getOutputTexture(activeStages[length3 - 1]); } if (fxaaEnabled && fxaa.ready) { execute(fxaa, context, lastTexture, depthTexture, idTexture); } }; PostProcessStageCollection.prototype.copy = function(context, framebuffer) { if (!defined_default(this._copyColorCommand)) { const that = this; this._copyColorCommand = context.createViewportQuadCommand(PassThrough_default, { uniformMap: { colorTexture: function() { return that.outputTexture; } }, owner: this }); } this._copyColorCommand.framebuffer = framebuffer; this._copyColorCommand.execute(context); }; PostProcessStageCollection.prototype.isDestroyed = function() { return false; }; PostProcessStageCollection.prototype.destroy = function() { this._fxaa.destroy(); this._ao.destroy(); this._bloom.destroy(); this._autoExposure.destroy(); this._tonemapping.destroy(); this.removeAll(); this._textureCache = this._textureCache && this._textureCache.destroy(); return destroyObject_default(this); }; var PostProcessStageCollection_default = PostProcessStageCollection; // packages/engine/Source/Core/KeyboardEventModifier.js var KeyboardEventModifier = { /** * Represents the shift key being held down. * * @type {number} * @constant */ SHIFT: 0, /** * Represents the control key being held down. * * @type {number} * @constant */ CTRL: 1, /** * Represents the alt key being held down. * * @type {number} * @constant */ ALT: 2 }; var KeyboardEventModifier_default = Object.freeze(KeyboardEventModifier); // packages/engine/Source/Core/ScreenSpaceEventType.js var ScreenSpaceEventType = { /** * Represents a mouse left button down event. * * @type {number} * @constant */ LEFT_DOWN: 0, /** * Represents a mouse left button up event. * * @type {number} * @constant */ LEFT_UP: 1, /** * Represents a mouse left click event. * * @type {number} * @constant */ LEFT_CLICK: 2, /** * Represents a mouse left double click event. * * @type {number} * @constant */ LEFT_DOUBLE_CLICK: 3, /** * Represents a mouse left button down event. * * @type {number} * @constant */ RIGHT_DOWN: 5, /** * Represents a mouse right button up event. * * @type {number} * @constant */ RIGHT_UP: 6, /** * Represents a mouse right click event. * * @type {number} * @constant */ RIGHT_CLICK: 7, /** * Represents a mouse middle button down event. * * @type {number} * @constant */ MIDDLE_DOWN: 10, /** * Represents a mouse middle button up event. * * @type {number} * @constant */ MIDDLE_UP: 11, /** * Represents a mouse middle click event. * * @type {number} * @constant */ MIDDLE_CLICK: 12, /** * Represents a mouse move event. * * @type {number} * @constant */ MOUSE_MOVE: 15, /** * Represents a mouse wheel event. * * @type {number} * @constant */ WHEEL: 16, /** * Represents the start of a two-finger event on a touch surface. * * @type {number} * @constant */ PINCH_START: 17, /** * Represents the end of a two-finger event on a touch surface. * * @type {number} * @constant */ PINCH_END: 18, /** * Represents a change of a two-finger event on a touch surface. * * @type {number} * @constant */ PINCH_MOVE: 19 }; var ScreenSpaceEventType_default = Object.freeze(ScreenSpaceEventType); // packages/engine/Source/Core/ScreenSpaceEventHandler.js function getPosition3(screenSpaceEventHandler, event, result) { const element = screenSpaceEventHandler._element; if (element === document) { result.x = event.clientX; result.y = event.clientY; return result; } const rect = element.getBoundingClientRect(); result.x = event.clientX - rect.left; result.y = event.clientY - rect.top; return result; } function getInputEventKey(type, modifier) { let key = type; if (defined_default(modifier)) { key += `+${modifier}`; } return key; } function getModifier(event) { if (event.shiftKey) { return KeyboardEventModifier_default.SHIFT; } else if (event.ctrlKey) { return KeyboardEventModifier_default.CTRL; } else if (event.altKey) { return KeyboardEventModifier_default.ALT; } return void 0; } var MouseButton = { LEFT: 0, MIDDLE: 1, RIGHT: 2 }; function registerListener(screenSpaceEventHandler, domType, element, callback) { function listener(e) { callback(screenSpaceEventHandler, e); } if (FeatureDetection_default.isInternetExplorer()) { element.addEventListener(domType, listener, false); } else { element.addEventListener(domType, listener, { capture: false, passive: false }); } screenSpaceEventHandler._removalFunctions.push(function() { element.removeEventListener(domType, listener, false); }); } function registerListeners(screenSpaceEventHandler) { const element = screenSpaceEventHandler._element; const alternateElement = !defined_default(element.disableRootEvents) ? document : element; if (FeatureDetection_default.supportsPointerEvents()) { registerListener( screenSpaceEventHandler, "pointerdown", element, handlePointerDown ); registerListener( screenSpaceEventHandler, "pointerup", element, handlePointerUp ); registerListener( screenSpaceEventHandler, "pointermove", element, handlePointerMove ); registerListener( screenSpaceEventHandler, "pointercancel", element, handlePointerUp ); } else { registerListener( screenSpaceEventHandler, "mousedown", element, handleMouseDown ); registerListener( screenSpaceEventHandler, "mouseup", alternateElement, handleMouseUp ); registerListener( screenSpaceEventHandler, "mousemove", alternateElement, handleMouseMove ); registerListener( screenSpaceEventHandler, "touchstart", element, handleTouchStart ); registerListener( screenSpaceEventHandler, "touchend", alternateElement, handleTouchEnd ); registerListener( screenSpaceEventHandler, "touchmove", alternateElement, handleTouchMove ); registerListener( screenSpaceEventHandler, "touchcancel", alternateElement, handleTouchEnd ); } registerListener( screenSpaceEventHandler, "dblclick", element, handleDblClick ); let wheelEvent; if ("onwheel" in element) { wheelEvent = "wheel"; } else if (document.onmousewheel !== void 0) { wheelEvent = "mousewheel"; } else { wheelEvent = "DOMMouseScroll"; } registerListener(screenSpaceEventHandler, wheelEvent, element, handleWheel); } function unregisterListeners(screenSpaceEventHandler) { const removalFunctions = screenSpaceEventHandler._removalFunctions; for (let i = 0; i < removalFunctions.length; ++i) { removalFunctions[i](); } } var mouseDownEvent = { position: new Cartesian2_default() }; function gotTouchEvent(screenSpaceEventHandler) { screenSpaceEventHandler._lastSeenTouchEvent = getTimestamp_default(); } function canProcessMouseEvent(screenSpaceEventHandler) { return getTimestamp_default() - screenSpaceEventHandler._lastSeenTouchEvent > ScreenSpaceEventHandler.mouseEmulationIgnoreMilliseconds; } function checkPixelTolerance(startPosition, endPosition, pixelTolerance) { const xDiff = startPosition.x - endPosition.x; const yDiff = startPosition.y - endPosition.y; const totalPixels = Math.sqrt(xDiff * xDiff + yDiff * yDiff); return totalPixels < pixelTolerance; } function handleMouseDown(screenSpaceEventHandler, event) { if (!canProcessMouseEvent(screenSpaceEventHandler)) { return; } const button = event.button; screenSpaceEventHandler._buttonDown[button] = true; let screenSpaceEventType; if (button === MouseButton.LEFT) { screenSpaceEventType = ScreenSpaceEventType_default.LEFT_DOWN; } else if (button === MouseButton.MIDDLE) { screenSpaceEventType = ScreenSpaceEventType_default.MIDDLE_DOWN; } else if (button === MouseButton.RIGHT) { screenSpaceEventType = ScreenSpaceEventType_default.RIGHT_DOWN; } else { return; } const position = getPosition3( screenSpaceEventHandler, event, screenSpaceEventHandler._primaryPosition ); Cartesian2_default.clone(position, screenSpaceEventHandler._primaryStartPosition); Cartesian2_default.clone(position, screenSpaceEventHandler._primaryPreviousPosition); const modifier = getModifier(event); const action = screenSpaceEventHandler.getInputAction( screenSpaceEventType, modifier ); if (defined_default(action)) { Cartesian2_default.clone(position, mouseDownEvent.position); action(mouseDownEvent); event.preventDefault(); } } var mouseUpEvent = { position: new Cartesian2_default() }; var mouseClickEvent = { position: new Cartesian2_default() }; function cancelMouseEvent(screenSpaceEventHandler, screenSpaceEventType, clickScreenSpaceEventType, event) { const modifier = getModifier(event); const action = screenSpaceEventHandler.getInputAction( screenSpaceEventType, modifier ); const clickAction = screenSpaceEventHandler.getInputAction( clickScreenSpaceEventType, modifier ); if (defined_default(action) || defined_default(clickAction)) { const position = getPosition3( screenSpaceEventHandler, event, screenSpaceEventHandler._primaryPosition ); if (defined_default(action)) { Cartesian2_default.clone(position, mouseUpEvent.position); action(mouseUpEvent); } if (defined_default(clickAction)) { const startPosition = screenSpaceEventHandler._primaryStartPosition; if (checkPixelTolerance( startPosition, position, screenSpaceEventHandler._clickPixelTolerance )) { Cartesian2_default.clone(position, mouseClickEvent.position); clickAction(mouseClickEvent); } } } } function handleMouseUp(screenSpaceEventHandler, event) { if (!canProcessMouseEvent(screenSpaceEventHandler)) { return; } const button = event.button; if (button !== MouseButton.LEFT && button !== MouseButton.MIDDLE && button !== MouseButton.RIGHT) { return; } if (screenSpaceEventHandler._buttonDown[MouseButton.LEFT]) { cancelMouseEvent( screenSpaceEventHandler, ScreenSpaceEventType_default.LEFT_UP, ScreenSpaceEventType_default.LEFT_CLICK, event ); screenSpaceEventHandler._buttonDown[MouseButton.LEFT] = false; } if (screenSpaceEventHandler._buttonDown[MouseButton.MIDDLE]) { cancelMouseEvent( screenSpaceEventHandler, ScreenSpaceEventType_default.MIDDLE_UP, ScreenSpaceEventType_default.MIDDLE_CLICK, event ); screenSpaceEventHandler._buttonDown[MouseButton.MIDDLE] = false; } if (screenSpaceEventHandler._buttonDown[MouseButton.RIGHT]) { cancelMouseEvent( screenSpaceEventHandler, ScreenSpaceEventType_default.RIGHT_UP, ScreenSpaceEventType_default.RIGHT_CLICK, event ); screenSpaceEventHandler._buttonDown[MouseButton.RIGHT] = false; } } var mouseMoveEvent = { startPosition: new Cartesian2_default(), endPosition: new Cartesian2_default() }; function handleMouseMove(screenSpaceEventHandler, event) { if (!canProcessMouseEvent(screenSpaceEventHandler)) { return; } const modifier = getModifier(event); const position = getPosition3( screenSpaceEventHandler, event, screenSpaceEventHandler._primaryPosition ); const previousPosition = screenSpaceEventHandler._primaryPreviousPosition; const action = screenSpaceEventHandler.getInputAction( ScreenSpaceEventType_default.MOUSE_MOVE, modifier ); if (defined_default(action)) { Cartesian2_default.clone(previousPosition, mouseMoveEvent.startPosition); Cartesian2_default.clone(position, mouseMoveEvent.endPosition); action(mouseMoveEvent); } Cartesian2_default.clone(position, previousPosition); if (screenSpaceEventHandler._buttonDown[MouseButton.LEFT] || screenSpaceEventHandler._buttonDown[MouseButton.MIDDLE] || screenSpaceEventHandler._buttonDown[MouseButton.RIGHT]) { event.preventDefault(); } } var mouseDblClickEvent = { position: new Cartesian2_default() }; function handleDblClick(screenSpaceEventHandler, event) { const button = event.button; let screenSpaceEventType; if (button === MouseButton.LEFT) { screenSpaceEventType = ScreenSpaceEventType_default.LEFT_DOUBLE_CLICK; } else { return; } const modifier = getModifier(event); const action = screenSpaceEventHandler.getInputAction( screenSpaceEventType, modifier ); if (defined_default(action)) { getPosition3(screenSpaceEventHandler, event, mouseDblClickEvent.position); action(mouseDblClickEvent); } } function handleWheel(screenSpaceEventHandler, event) { let delta; if (defined_default(event.deltaY)) { const deltaMode = event.deltaMode; if (deltaMode === event.DOM_DELTA_PIXEL) { delta = -event.deltaY; } else if (deltaMode === event.DOM_DELTA_LINE) { delta = -event.deltaY * 40; } else { delta = -event.deltaY * 120; } } else if (event.detail > 0) { delta = event.detail * -120; } else { delta = event.wheelDelta; } if (!defined_default(delta)) { return; } const modifier = getModifier(event); const action = screenSpaceEventHandler.getInputAction( ScreenSpaceEventType_default.WHEEL, modifier ); if (defined_default(action)) { action(delta); event.preventDefault(); } } function handleTouchStart(screenSpaceEventHandler, event) { gotTouchEvent(screenSpaceEventHandler); const changedTouches = event.changedTouches; let i; const length3 = changedTouches.length; let touch; let identifier; const positions = screenSpaceEventHandler._positions; for (i = 0; i < length3; ++i) { touch = changedTouches[i]; identifier = touch.identifier; positions.set( identifier, getPosition3(screenSpaceEventHandler, touch, new Cartesian2_default()) ); } fireTouchEvents(screenSpaceEventHandler, event); const previousPositions = screenSpaceEventHandler._previousPositions; for (i = 0; i < length3; ++i) { touch = changedTouches[i]; identifier = touch.identifier; previousPositions.set( identifier, Cartesian2_default.clone(positions.get(identifier)) ); } } function handleTouchEnd(screenSpaceEventHandler, event) { gotTouchEvent(screenSpaceEventHandler); const changedTouches = event.changedTouches; let i; const length3 = changedTouches.length; let touch; let identifier; const positions = screenSpaceEventHandler._positions; for (i = 0; i < length3; ++i) { touch = changedTouches[i]; identifier = touch.identifier; positions.remove(identifier); } fireTouchEvents(screenSpaceEventHandler, event); const previousPositions = screenSpaceEventHandler._previousPositions; for (i = 0; i < length3; ++i) { touch = changedTouches[i]; identifier = touch.identifier; previousPositions.remove(identifier); } } var touchStartEvent = { position: new Cartesian2_default() }; var touch2StartEvent = { position1: new Cartesian2_default(), position2: new Cartesian2_default() }; var touchEndEvent = { position: new Cartesian2_default() }; var touchClickEvent = { position: new Cartesian2_default() }; var touchHoldEvent = { position: new Cartesian2_default() }; function fireTouchEvents(screenSpaceEventHandler, event) { const modifier = getModifier(event); const positions = screenSpaceEventHandler._positions; const numberOfTouches = positions.length; let action; let clickAction; const pinching = screenSpaceEventHandler._isPinching; if (numberOfTouches !== 1 && screenSpaceEventHandler._buttonDown[MouseButton.LEFT]) { screenSpaceEventHandler._buttonDown[MouseButton.LEFT] = false; if (defined_default(screenSpaceEventHandler._touchHoldTimer)) { clearTimeout(screenSpaceEventHandler._touchHoldTimer); screenSpaceEventHandler._touchHoldTimer = void 0; } action = screenSpaceEventHandler.getInputAction( ScreenSpaceEventType_default.LEFT_UP, modifier ); if (defined_default(action)) { Cartesian2_default.clone( screenSpaceEventHandler._primaryPosition, touchEndEvent.position ); action(touchEndEvent); } if (numberOfTouches === 0 && !screenSpaceEventHandler._isTouchHolding) { clickAction = screenSpaceEventHandler.getInputAction( ScreenSpaceEventType_default.LEFT_CLICK, modifier ); if (defined_default(clickAction)) { const startPosition = screenSpaceEventHandler._primaryStartPosition; const endPosition = screenSpaceEventHandler._previousPositions.values[0]; if (checkPixelTolerance( startPosition, endPosition, screenSpaceEventHandler._clickPixelTolerance )) { Cartesian2_default.clone( screenSpaceEventHandler._primaryPosition, touchClickEvent.position ); clickAction(touchClickEvent); } } } screenSpaceEventHandler._isTouchHolding = false; } if (numberOfTouches === 0 && pinching) { screenSpaceEventHandler._isPinching = false; action = screenSpaceEventHandler.getInputAction( ScreenSpaceEventType_default.PINCH_END, modifier ); if (defined_default(action)) { action(); } } if (numberOfTouches === 1 && !pinching) { const position = positions.values[0]; Cartesian2_default.clone(position, screenSpaceEventHandler._primaryPosition); Cartesian2_default.clone(position, screenSpaceEventHandler._primaryStartPosition); Cartesian2_default.clone( position, screenSpaceEventHandler._primaryPreviousPosition ); screenSpaceEventHandler._buttonDown[MouseButton.LEFT] = true; action = screenSpaceEventHandler.getInputAction( ScreenSpaceEventType_default.LEFT_DOWN, modifier ); if (defined_default(action)) { Cartesian2_default.clone(position, touchStartEvent.position); action(touchStartEvent); } screenSpaceEventHandler._touchHoldTimer = setTimeout(function() { if (!screenSpaceEventHandler.isDestroyed()) { screenSpaceEventHandler._touchHoldTimer = void 0; screenSpaceEventHandler._isTouchHolding = true; clickAction = screenSpaceEventHandler.getInputAction( ScreenSpaceEventType_default.RIGHT_CLICK, modifier ); if (defined_default(clickAction)) { const startPosition = screenSpaceEventHandler._primaryStartPosition; const endPosition = screenSpaceEventHandler._previousPositions.values[0]; if (checkPixelTolerance( startPosition, endPosition, screenSpaceEventHandler._holdPixelTolerance )) { Cartesian2_default.clone( screenSpaceEventHandler._primaryPosition, touchHoldEvent.position ); clickAction(touchHoldEvent); } } } }, ScreenSpaceEventHandler.touchHoldDelayMilliseconds); event.preventDefault(); } if (numberOfTouches === 2 && !pinching) { screenSpaceEventHandler._isPinching = true; action = screenSpaceEventHandler.getInputAction( ScreenSpaceEventType_default.PINCH_START, modifier ); if (defined_default(action)) { Cartesian2_default.clone(positions.values[0], touch2StartEvent.position1); Cartesian2_default.clone(positions.values[1], touch2StartEvent.position2); action(touch2StartEvent); event.preventDefault(); } } } function handleTouchMove(screenSpaceEventHandler, event) { gotTouchEvent(screenSpaceEventHandler); const changedTouches = event.changedTouches; let i; const length3 = changedTouches.length; let touch; let identifier; const positions = screenSpaceEventHandler._positions; for (i = 0; i < length3; ++i) { touch = changedTouches[i]; identifier = touch.identifier; const position = positions.get(identifier); if (defined_default(position)) { getPosition3(screenSpaceEventHandler, touch, position); } } fireTouchMoveEvents(screenSpaceEventHandler, event); const previousPositions = screenSpaceEventHandler._previousPositions; for (i = 0; i < length3; ++i) { touch = changedTouches[i]; identifier = touch.identifier; Cartesian2_default.clone( positions.get(identifier), previousPositions.get(identifier) ); } } var touchMoveEvent = { startPosition: new Cartesian2_default(), endPosition: new Cartesian2_default() }; var touchPinchMovementEvent = { distance: { startPosition: new Cartesian2_default(), endPosition: new Cartesian2_default() }, angleAndHeight: { startPosition: new Cartesian2_default(), endPosition: new Cartesian2_default() } }; function fireTouchMoveEvents(screenSpaceEventHandler, event) { const modifier = getModifier(event); const positions = screenSpaceEventHandler._positions; const previousPositions = screenSpaceEventHandler._previousPositions; const numberOfTouches = positions.length; let action; if (numberOfTouches === 1 && screenSpaceEventHandler._buttonDown[MouseButton.LEFT]) { const position = positions.values[0]; Cartesian2_default.clone(position, screenSpaceEventHandler._primaryPosition); const previousPosition = screenSpaceEventHandler._primaryPreviousPosition; action = screenSpaceEventHandler.getInputAction( ScreenSpaceEventType_default.MOUSE_MOVE, modifier ); if (defined_default(action)) { Cartesian2_default.clone(previousPosition, touchMoveEvent.startPosition); Cartesian2_default.clone(position, touchMoveEvent.endPosition); action(touchMoveEvent); } Cartesian2_default.clone(position, previousPosition); event.preventDefault(); } else if (numberOfTouches === 2 && screenSpaceEventHandler._isPinching) { action = screenSpaceEventHandler.getInputAction( ScreenSpaceEventType_default.PINCH_MOVE, modifier ); if (defined_default(action)) { const position1 = positions.values[0]; const position2 = positions.values[1]; const previousPosition1 = previousPositions.values[0]; const previousPosition2 = previousPositions.values[1]; const dX = position2.x - position1.x; const dY = position2.y - position1.y; const dist = Math.sqrt(dX * dX + dY * dY) * 0.25; const prevDX = previousPosition2.x - previousPosition1.x; const prevDY = previousPosition2.y - previousPosition1.y; const prevDist = Math.sqrt(prevDX * prevDX + prevDY * prevDY) * 0.25; const cY = (position2.y + position1.y) * 0.125; const prevCY = (previousPosition2.y + previousPosition1.y) * 0.125; const angle = Math.atan2(dY, dX); const prevAngle = Math.atan2(prevDY, prevDX); Cartesian2_default.fromElements( 0, prevDist, touchPinchMovementEvent.distance.startPosition ); Cartesian2_default.fromElements( 0, dist, touchPinchMovementEvent.distance.endPosition ); Cartesian2_default.fromElements( prevAngle, prevCY, touchPinchMovementEvent.angleAndHeight.startPosition ); Cartesian2_default.fromElements( angle, cY, touchPinchMovementEvent.angleAndHeight.endPosition ); action(touchPinchMovementEvent); } } } function handlePointerDown(screenSpaceEventHandler, event) { event.target.setPointerCapture(event.pointerId); if (event.pointerType === "touch") { const positions = screenSpaceEventHandler._positions; const identifier = event.pointerId; positions.set( identifier, getPosition3(screenSpaceEventHandler, event, new Cartesian2_default()) ); fireTouchEvents(screenSpaceEventHandler, event); const previousPositions = screenSpaceEventHandler._previousPositions; previousPositions.set( identifier, Cartesian2_default.clone(positions.get(identifier)) ); } else { handleMouseDown(screenSpaceEventHandler, event); } } function handlePointerUp(screenSpaceEventHandler, event) { if (event.pointerType === "touch") { const positions = screenSpaceEventHandler._positions; const identifier = event.pointerId; positions.remove(identifier); fireTouchEvents(screenSpaceEventHandler, event); const previousPositions = screenSpaceEventHandler._previousPositions; previousPositions.remove(identifier); } else { handleMouseUp(screenSpaceEventHandler, event); } } function handlePointerMove(screenSpaceEventHandler, event) { if (event.pointerType === "touch") { const positions = screenSpaceEventHandler._positions; const identifier = event.pointerId; const position = positions.get(identifier); if (!defined_default(position)) { return; } getPosition3(screenSpaceEventHandler, event, position); fireTouchMoveEvents(screenSpaceEventHandler, event); const previousPositions = screenSpaceEventHandler._previousPositions; Cartesian2_default.clone( positions.get(identifier), previousPositions.get(identifier) ); } else { handleMouseMove(screenSpaceEventHandler, event); } } function ScreenSpaceEventHandler(element) { this._inputEvents = {}; this._buttonDown = { LEFT: false, MIDDLE: false, RIGHT: false }; this._isPinching = false; this._isTouchHolding = false; this._lastSeenTouchEvent = -ScreenSpaceEventHandler.mouseEmulationIgnoreMilliseconds; this._primaryStartPosition = new Cartesian2_default(); this._primaryPosition = new Cartesian2_default(); this._primaryPreviousPosition = new Cartesian2_default(); this._positions = new AssociativeArray_default(); this._previousPositions = new AssociativeArray_default(); this._removalFunctions = []; this._touchHoldTimer = void 0; this._clickPixelTolerance = 5; this._holdPixelTolerance = 25; this._element = defaultValue_default(element, document); registerListeners(this); } ScreenSpaceEventHandler.prototype.setInputAction = function(action, type, modifier) { if (!defined_default(action)) { throw new DeveloperError_default("action is required."); } if (!defined_default(type)) { throw new DeveloperError_default("type is required."); } const key = getInputEventKey(type, modifier); this._inputEvents[key] = action; }; ScreenSpaceEventHandler.prototype.getInputAction = function(type, modifier) { if (!defined_default(type)) { throw new DeveloperError_default("type is required."); } const key = getInputEventKey(type, modifier); return this._inputEvents[key]; }; ScreenSpaceEventHandler.prototype.removeInputAction = function(type, modifier) { if (!defined_default(type)) { throw new DeveloperError_default("type is required."); } const key = getInputEventKey(type, modifier); delete this._inputEvents[key]; }; ScreenSpaceEventHandler.prototype.isDestroyed = function() { return false; }; ScreenSpaceEventHandler.prototype.destroy = function() { unregisterListeners(this); return destroyObject_default(this); }; ScreenSpaceEventHandler.mouseEmulationIgnoreMilliseconds = 800; ScreenSpaceEventHandler.touchHoldDelayMilliseconds = 1500; var ScreenSpaceEventHandler_default = ScreenSpaceEventHandler; // packages/engine/Source/Scene/SceneTransitioner.js function SceneTransitioner(scene) { Check_default.typeOf.object("scene", scene); this._scene = scene; this._currentTweens = []; this._morphHandler = void 0; this._morphCancelled = false; this._completeMorph = void 0; this._morphToOrthographic = false; } SceneTransitioner.prototype.completeMorph = function() { if (defined_default(this._completeMorph)) { this._completeMorph(); } }; SceneTransitioner.prototype.morphTo2D = function(duration, ellipsoid) { if (defined_default(this._completeMorph)) { this._completeMorph(); } const scene = this._scene; this._previousMode = scene.mode; this._morphToOrthographic = scene.camera.frustum instanceof OrthographicFrustum_default; if (this._previousMode === SceneMode_default.SCENE2D || this._previousMode === SceneMode_default.MORPHING) { return; } this._scene.morphStart.raiseEvent( this, this._previousMode, SceneMode_default.SCENE2D, true ); scene._mode = SceneMode_default.MORPHING; scene.camera._setTransform(Matrix4_default.IDENTITY); if (this._previousMode === SceneMode_default.COLUMBUS_VIEW) { morphFromColumbusViewTo2D(this, duration); } else { morphFrom3DTo2D(this, duration, ellipsoid); } if (duration === 0 && defined_default(this._completeMorph)) { this._completeMorph(); } }; var scratchToCVPosition = new Cartesian3_default(); var scratchToCVDirection = new Cartesian3_default(); var scratchToCVUp = new Cartesian3_default(); var scratchToCVPosition2D = new Cartesian3_default(); var scratchToCVDirection2D = new Cartesian3_default(); var scratchToCVUp2D = new Cartesian3_default(); var scratchToCVSurfacePosition = new Cartesian3_default(); var scratchToCVCartographic = new Cartographic_default(); var scratchToCVToENU = new Matrix4_default(); var scratchToCVFrustumPerspective = new PerspectiveFrustum_default(); var scratchToCVFrustumOrthographic = new OrthographicFrustum_default(); var scratchToCVCamera = { position: void 0, direction: void 0, up: void 0, position2D: void 0, direction2D: void 0, up2D: void 0, frustum: void 0 }; SceneTransitioner.prototype.morphToColumbusView = function(duration, ellipsoid) { if (defined_default(this._completeMorph)) { this._completeMorph(); } const scene = this._scene; this._previousMode = scene.mode; if (this._previousMode === SceneMode_default.COLUMBUS_VIEW || this._previousMode === SceneMode_default.MORPHING) { return; } this._scene.morphStart.raiseEvent( this, this._previousMode, SceneMode_default.COLUMBUS_VIEW, true ); scene.camera._setTransform(Matrix4_default.IDENTITY); let position = scratchToCVPosition; const direction2 = scratchToCVDirection; const up = scratchToCVUp; if (duration > 0) { position.x = 0; position.y = -1; position.z = 1; position = Cartesian3_default.multiplyByScalar( Cartesian3_default.normalize(position, position), 5 * ellipsoid.maximumRadius, position ); Cartesian3_default.negate(Cartesian3_default.normalize(position, direction2), direction2); Cartesian3_default.cross(Cartesian3_default.UNIT_X, direction2, up); } else { const camera = scene.camera; if (this._previousMode === SceneMode_default.SCENE2D) { Cartesian3_default.clone(camera.position, position); position.z = camera.frustum.right - camera.frustum.left; Cartesian3_default.negate(Cartesian3_default.UNIT_Z, direction2); Cartesian3_default.clone(Cartesian3_default.UNIT_Y, up); } else { Cartesian3_default.clone(camera.positionWC, position); Cartesian3_default.clone(camera.directionWC, direction2); Cartesian3_default.clone(camera.upWC, up); const surfacePoint = ellipsoid.scaleToGeodeticSurface( position, scratchToCVSurfacePosition ); const toENU = Transforms_default.eastNorthUpToFixedFrame( surfacePoint, ellipsoid, scratchToCVToENU ); Matrix4_default.inverseTransformation(toENU, toENU); scene.mapProjection.project( ellipsoid.cartesianToCartographic(position, scratchToCVCartographic), position ); Matrix4_default.multiplyByPointAsVector(toENU, direction2, direction2); Matrix4_default.multiplyByPointAsVector(toENU, up, up); } } let frustum; if (this._morphToOrthographic) { frustum = scratchToCVFrustumOrthographic; frustum.width = scene.camera.frustum.right - scene.camera.frustum.left; frustum.aspectRatio = scene.drawingBufferWidth / scene.drawingBufferHeight; } else { frustum = scratchToCVFrustumPerspective; frustum.aspectRatio = scene.drawingBufferWidth / scene.drawingBufferHeight; frustum.fov = Math_default.toRadians(60); } const cameraCV = scratchToCVCamera; cameraCV.position = position; cameraCV.direction = direction2; cameraCV.up = up; cameraCV.frustum = frustum; const complete = completeColumbusViewCallback(cameraCV); createMorphHandler(this, complete); if (this._previousMode === SceneMode_default.SCENE2D) { morphFrom2DToColumbusView(this, duration, cameraCV, complete); } else { cameraCV.position2D = Matrix4_default.multiplyByPoint( Camera_default.TRANSFORM_2D, position, scratchToCVPosition2D ); cameraCV.direction2D = Matrix4_default.multiplyByPointAsVector( Camera_default.TRANSFORM_2D, direction2, scratchToCVDirection2D ); cameraCV.up2D = Matrix4_default.multiplyByPointAsVector( Camera_default.TRANSFORM_2D, up, scratchToCVUp2D ); scene._mode = SceneMode_default.MORPHING; morphFrom3DToColumbusView(this, duration, cameraCV, complete); } if (duration === 0 && defined_default(this._completeMorph)) { this._completeMorph(); } }; var scratchCVTo3DCamera = { position: new Cartesian3_default(), direction: new Cartesian3_default(), up: new Cartesian3_default(), frustum: void 0 }; var scratch2DTo3DFrustumPersp = new PerspectiveFrustum_default(); SceneTransitioner.prototype.morphTo3D = function(duration, ellipsoid) { if (defined_default(this._completeMorph)) { this._completeMorph(); } const scene = this._scene; this._previousMode = scene.mode; if (this._previousMode === SceneMode_default.SCENE3D || this._previousMode === SceneMode_default.MORPHING) { return; } this._scene.morphStart.raiseEvent( this, this._previousMode, SceneMode_default.SCENE3D, true ); scene._mode = SceneMode_default.MORPHING; scene.camera._setTransform(Matrix4_default.IDENTITY); if (this._previousMode === SceneMode_default.SCENE2D) { morphFrom2DTo3D(this, duration, ellipsoid); } else { let camera3D; if (duration > 0) { camera3D = scratchCVTo3DCamera; Cartesian3_default.fromDegrees( 0, 0, 5 * ellipsoid.maximumRadius, ellipsoid, camera3D.position ); Cartesian3_default.negate(camera3D.position, camera3D.direction); Cartesian3_default.normalize(camera3D.direction, camera3D.direction); Cartesian3_default.clone(Cartesian3_default.UNIT_Z, camera3D.up); } else { camera3D = getColumbusViewTo3DCamera(this, ellipsoid); } let frustum; const camera = scene.camera; if (camera.frustum instanceof OrthographicFrustum_default) { frustum = camera.frustum.clone(); } else { frustum = scratch2DTo3DFrustumPersp; frustum.aspectRatio = scene.drawingBufferWidth / scene.drawingBufferHeight; frustum.fov = Math_default.toRadians(60); } camera3D.frustum = frustum; const complete = complete3DCallback(camera3D); createMorphHandler(this, complete); morphFromColumbusViewTo3D(this, duration, camera3D, complete); } if (duration === 0 && defined_default(this._completeMorph)) { this._completeMorph(); } }; SceneTransitioner.prototype.isDestroyed = function() { return false; }; SceneTransitioner.prototype.destroy = function() { destroyMorphHandler(this); return destroyObject_default(this); }; function createMorphHandler(transitioner, completeMorphFunction) { if (transitioner._scene.completeMorphOnUserInput) { transitioner._morphHandler = new ScreenSpaceEventHandler_default( transitioner._scene.canvas ); const completeMorph = function() { transitioner._morphCancelled = true; transitioner._scene.camera.cancelFlight(); completeMorphFunction(transitioner); }; transitioner._completeMorph = completeMorph; transitioner._morphHandler.setInputAction( completeMorph, ScreenSpaceEventType_default.LEFT_DOWN ); transitioner._morphHandler.setInputAction( completeMorph, ScreenSpaceEventType_default.MIDDLE_DOWN ); transitioner._morphHandler.setInputAction( completeMorph, ScreenSpaceEventType_default.RIGHT_DOWN ); transitioner._morphHandler.setInputAction( completeMorph, ScreenSpaceEventType_default.WHEEL ); } } function destroyMorphHandler(transitioner) { const tweens = transitioner._currentTweens; for (let i = 0; i < tweens.length; ++i) { tweens[i].cancelTween(); } transitioner._currentTweens.length = 0; transitioner._morphHandler = transitioner._morphHandler && transitioner._morphHandler.destroy(); } var scratchCVTo3DCartographic = new Cartographic_default(); var scratchCVTo3DSurfacePoint = new Cartesian3_default(); var scratchCVTo3DFromENU = new Matrix4_default(); function getColumbusViewTo3DCamera(transitioner, ellipsoid) { const scene = transitioner._scene; const camera = scene.camera; const camera3D = scratchCVTo3DCamera; const position = camera3D.position; const direction2 = camera3D.direction; const up = camera3D.up; const positionCarto = scene.mapProjection.unproject( camera.position, scratchCVTo3DCartographic ); ellipsoid.cartographicToCartesian(positionCarto, position); const surfacePoint = ellipsoid.scaleToGeodeticSurface( position, scratchCVTo3DSurfacePoint ); const fromENU = Transforms_default.eastNorthUpToFixedFrame( surfacePoint, ellipsoid, scratchCVTo3DFromENU ); Matrix4_default.multiplyByPointAsVector(fromENU, camera.direction, direction2); Matrix4_default.multiplyByPointAsVector(fromENU, camera.up, up); return camera3D; } var scratchCVTo3DStartPos = new Cartesian3_default(); var scratchCVTo3DStartDir = new Cartesian3_default(); var scratchCVTo3DStartUp = new Cartesian3_default(); var scratchCVTo3DEndPos = new Cartesian3_default(); var scratchCVTo3DEndDir = new Cartesian3_default(); var scratchCVTo3DEndUp = new Cartesian3_default(); function morphFromColumbusViewTo3D(transitioner, duration, endCamera, complete) { duration *= 0.5; const scene = transitioner._scene; const camera = scene.camera; const startPos = Cartesian3_default.clone(camera.position, scratchCVTo3DStartPos); const startDir = Cartesian3_default.clone(camera.direction, scratchCVTo3DStartDir); const startUp = Cartesian3_default.clone(camera.up, scratchCVTo3DStartUp); const endPos = Matrix4_default.multiplyByPoint( Camera_default.TRANSFORM_2D_INVERSE, endCamera.position, scratchCVTo3DEndPos ); const endDir = Matrix4_default.multiplyByPointAsVector( Camera_default.TRANSFORM_2D_INVERSE, endCamera.direction, scratchCVTo3DEndDir ); const endUp = Matrix4_default.multiplyByPointAsVector( Camera_default.TRANSFORM_2D_INVERSE, endCamera.up, scratchCVTo3DEndUp ); function update8(value) { columbusViewMorph(startPos, endPos, value.time, camera.position); columbusViewMorph(startDir, endDir, value.time, camera.direction); columbusViewMorph(startUp, endUp, value.time, camera.up); Cartesian3_default.cross(camera.direction, camera.up, camera.right); Cartesian3_default.normalize(camera.right, camera.right); } const tween = scene.tweens.add({ duration, easingFunction: EasingFunction_default.QUARTIC_OUT, startObject: { time: 0 }, stopObject: { time: 1 }, update: update8, complete: function() { addMorphTimeAnimations(transitioner, scene, 0, 1, duration, complete); } }); transitioner._currentTweens.push(tween); } var scratch2DTo3DFrustumOrtho = new OrthographicFrustum_default(); var scratch3DToCVStartPos = new Cartesian3_default(); var scratch3DToCVStartDir = new Cartesian3_default(); var scratch3DToCVStartUp = new Cartesian3_default(); var scratch3DToCVEndPos = new Cartesian3_default(); var scratch3DToCVEndDir = new Cartesian3_default(); var scratch3DToCVEndUp = new Cartesian3_default(); function morphFrom2DTo3D(transitioner, duration, ellipsoid) { duration /= 3; const scene = transitioner._scene; const camera = scene.camera; let camera3D; if (duration > 0) { camera3D = scratchCVTo3DCamera; Cartesian3_default.fromDegrees( 0, 0, 5 * ellipsoid.maximumRadius, ellipsoid, camera3D.position ); Cartesian3_default.negate(camera3D.position, camera3D.direction); Cartesian3_default.normalize(camera3D.direction, camera3D.direction); Cartesian3_default.clone(Cartesian3_default.UNIT_Z, camera3D.up); } else { camera.position.z = camera.frustum.right - camera.frustum.left; camera3D = getColumbusViewTo3DCamera(transitioner, ellipsoid); } let frustum; if (transitioner._morphToOrthographic) { frustum = scratch2DTo3DFrustumOrtho; frustum.aspectRatio = scene.drawingBufferWidth / scene.drawingBufferHeight; frustum.width = camera.frustum.right - camera.frustum.left; } else { frustum = scratch2DTo3DFrustumPersp; frustum.aspectRatio = scene.drawingBufferWidth / scene.drawingBufferHeight; frustum.fov = Math_default.toRadians(60); } camera3D.frustum = frustum; const complete = complete3DCallback(camera3D); createMorphHandler(transitioner, complete); let morph; if (transitioner._morphToOrthographic) { morph = function() { morphFromColumbusViewTo3D(transitioner, duration, camera3D, complete); }; } else { morph = function() { morphOrthographicToPerspective( transitioner, duration, camera3D, function() { morphFromColumbusViewTo3D(transitioner, duration, camera3D, complete); } ); }; } if (duration > 0) { scene._mode = SceneMode_default.SCENE2D; camera.flyTo({ duration, destination: Cartesian3_default.fromDegrees( 0, 0, 5 * ellipsoid.maximumRadius, ellipsoid, scratch3DToCVEndPos ), complete: function() { scene._mode = SceneMode_default.MORPHING; morph(); } }); } else { morph(); } } function columbusViewMorph(startPosition, endPosition, time, result) { return Cartesian3_default.lerp(startPosition, endPosition, time, result); } function morphPerspectiveToOrthographic(transitioner, duration, endCamera, updateHeight, complete) { const scene = transitioner._scene; const camera = scene.camera; if (camera.frustum instanceof OrthographicFrustum_default) { return; } const startFOV = camera.frustum.fov; const endFOV = Math_default.RADIANS_PER_DEGREE * 0.5; const d = endCamera.position.z * Math.tan(startFOV * 0.5); camera.frustum.far = d / Math.tan(endFOV * 0.5) + 1e7; function update8(value) { camera.frustum.fov = Math_default.lerp(startFOV, endFOV, value.time); const height = d / Math.tan(camera.frustum.fov * 0.5); updateHeight(camera, height); } const tween = scene.tweens.add({ duration, easingFunction: EasingFunction_default.QUARTIC_OUT, startObject: { time: 0 }, stopObject: { time: 1 }, update: update8, complete: function() { camera.frustum = endCamera.frustum.clone(); complete(transitioner); } }); transitioner._currentTweens.push(tween); } var scratchCVTo2DStartPos = new Cartesian3_default(); var scratchCVTo2DStartDir = new Cartesian3_default(); var scratchCVTo2DStartUp = new Cartesian3_default(); var scratchCVTo2DEndPos = new Cartesian3_default(); var scratchCVTo2DEndDir = new Cartesian3_default(); var scratchCVTo2DEndUp = new Cartesian3_default(); var scratchCVTo2DFrustum = new OrthographicOffCenterFrustum_default(); var scratchCVTo2DRay = new Ray_default(); var scratchCVTo2DPickPos = new Cartesian3_default(); var scratchCVTo2DCamera = { position: void 0, direction: void 0, up: void 0, frustum: void 0 }; function morphFromColumbusViewTo2D(transitioner, duration) { duration *= 0.5; const scene = transitioner._scene; const camera = scene.camera; const startPos = Cartesian3_default.clone(camera.position, scratchCVTo2DStartPos); const startDir = Cartesian3_default.clone(camera.direction, scratchCVTo2DStartDir); const startUp = Cartesian3_default.clone(camera.up, scratchCVTo2DStartUp); const endDir = Cartesian3_default.negate(Cartesian3_default.UNIT_Z, scratchCVTo2DEndDir); const endUp = Cartesian3_default.clone(Cartesian3_default.UNIT_Y, scratchCVTo2DEndUp); const endPos = scratchCVTo2DEndPos; if (duration > 0) { Cartesian3_default.clone(Cartesian3_default.ZERO, scratchCVTo2DEndPos); endPos.z = 5 * scene.mapProjection.ellipsoid.maximumRadius; } else { Cartesian3_default.clone(startPos, scratchCVTo2DEndPos); const ray = scratchCVTo2DRay; Matrix4_default.multiplyByPoint(Camera_default.TRANSFORM_2D, startPos, ray.origin); Matrix4_default.multiplyByPointAsVector( Camera_default.TRANSFORM_2D, startDir, ray.direction ); const globe = scene.globe; if (defined_default(globe)) { const pickPos = globe.pickWorldCoordinates( ray, scene, true, scratchCVTo2DPickPos ); if (defined_default(pickPos)) { Matrix4_default.multiplyByPoint(Camera_default.TRANSFORM_2D_INVERSE, pickPos, endPos); endPos.z += Cartesian3_default.distance(startPos, endPos); } } } const frustum = scratchCVTo2DFrustum; frustum.right = endPos.z * 0.5; frustum.left = -frustum.right; frustum.top = frustum.right * (scene.drawingBufferHeight / scene.drawingBufferWidth); frustum.bottom = -frustum.top; const camera2D = scratchCVTo2DCamera; camera2D.position = endPos; camera2D.direction = endDir; camera2D.up = endUp; camera2D.frustum = frustum; const complete = complete2DCallback(camera2D); createMorphHandler(transitioner, complete); function updateCV2(value) { columbusViewMorph(startPos, endPos, value.time, camera.position); columbusViewMorph(startDir, endDir, value.time, camera.direction); columbusViewMorph(startUp, endUp, value.time, camera.up); Cartesian3_default.cross(camera.direction, camera.up, camera.right); Cartesian3_default.normalize(camera.right, camera.right); camera._adjustOrthographicFrustum(true); } function updateHeight(camera2, height) { camera2.position.z = height; } const tween = scene.tweens.add({ duration, easingFunction: EasingFunction_default.QUARTIC_OUT, startObject: { time: 0 }, stopObject: { time: 1 }, update: updateCV2, complete: function() { morphPerspectiveToOrthographic( transitioner, duration, camera2D, updateHeight, complete ); } }); transitioner._currentTweens.push(tween); } var scratch3DTo2DCartographic = new Cartographic_default(); var scratch3DTo2DCamera = { position: new Cartesian3_default(), direction: new Cartesian3_default(), up: new Cartesian3_default(), position2D: new Cartesian3_default(), direction2D: new Cartesian3_default(), up2D: new Cartesian3_default(), frustum: new OrthographicOffCenterFrustum_default() }; var scratch3DTo2DEndCamera = { position: new Cartesian3_default(), direction: new Cartesian3_default(), up: new Cartesian3_default(), frustum: void 0 }; var scratch3DTo2DPickPosition = new Cartesian3_default(); var scratch3DTo2DRay = new Ray_default(); var scratch3DTo2DToENU = new Matrix4_default(); var scratch3DTo2DSurfacePoint = new Cartesian3_default(); function morphFrom3DTo2D(transitioner, duration, ellipsoid) { duration *= 0.5; const scene = transitioner._scene; const camera = scene.camera; const camera2D = scratch3DTo2DCamera; if (duration > 0) { Cartesian3_default.clone(Cartesian3_default.ZERO, camera2D.position); camera2D.position.z = 5 * ellipsoid.maximumRadius; Cartesian3_default.negate(Cartesian3_default.UNIT_Z, camera2D.direction); Cartesian3_default.clone(Cartesian3_default.UNIT_Y, camera2D.up); } else { ellipsoid.cartesianToCartographic( camera.positionWC, scratch3DTo2DCartographic ); scene.mapProjection.project(scratch3DTo2DCartographic, camera2D.position); Cartesian3_default.negate(Cartesian3_default.UNIT_Z, camera2D.direction); Cartesian3_default.clone(Cartesian3_default.UNIT_Y, camera2D.up); const ray = scratch3DTo2DRay; Cartesian3_default.clone(camera2D.position2D, ray.origin); const rayDirection = Cartesian3_default.clone(camera.directionWC, ray.direction); const surfacePoint = ellipsoid.scaleToGeodeticSurface( camera.positionWC, scratch3DTo2DSurfacePoint ); const toENU = Transforms_default.eastNorthUpToFixedFrame( surfacePoint, ellipsoid, scratch3DTo2DToENU ); Matrix4_default.inverseTransformation(toENU, toENU); Matrix4_default.multiplyByPointAsVector(toENU, rayDirection, rayDirection); Matrix4_default.multiplyByPointAsVector( Camera_default.TRANSFORM_2D, rayDirection, rayDirection ); const globe = scene.globe; if (defined_default(globe)) { const pickedPos = globe.pickWorldCoordinates( ray, scene, true, scratch3DTo2DPickPosition ); if (defined_default(pickedPos)) { const height = Cartesian3_default.distance(camera2D.position2D, pickedPos); pickedPos.x += height; Cartesian3_default.clone(pickedPos, camera2D.position2D); } } } function updateHeight(camera2, height) { camera2.position.x = height; } Matrix4_default.multiplyByPoint( Camera_default.TRANSFORM_2D, camera2D.position, camera2D.position2D ); Matrix4_default.multiplyByPointAsVector( Camera_default.TRANSFORM_2D, camera2D.direction, camera2D.direction2D ); Matrix4_default.multiplyByPointAsVector( Camera_default.TRANSFORM_2D, camera2D.up, camera2D.up2D ); const frustum = camera2D.frustum; frustum.right = camera2D.position.z * 0.5; frustum.left = -frustum.right; frustum.top = frustum.right * (scene.drawingBufferHeight / scene.drawingBufferWidth); frustum.bottom = -frustum.top; const endCamera = scratch3DTo2DEndCamera; Matrix4_default.multiplyByPoint( Camera_default.TRANSFORM_2D_INVERSE, camera2D.position2D, endCamera.position ); Cartesian3_default.clone(camera2D.direction, endCamera.direction); Cartesian3_default.clone(camera2D.up, endCamera.up); endCamera.frustum = frustum; const complete = complete2DCallback(endCamera); createMorphHandler(transitioner, complete); function completeCallback() { morphPerspectiveToOrthographic( transitioner, duration, camera2D, updateHeight, complete ); } morphFrom3DToColumbusView(transitioner, duration, camera2D, completeCallback); } function morphOrthographicToPerspective(transitioner, duration, cameraCV, complete) { const scene = transitioner._scene; const camera = scene.camera; const height = camera.frustum.right - camera.frustum.left; camera.frustum = cameraCV.frustum.clone(); const endFOV = camera.frustum.fov; const startFOV = Math_default.RADIANS_PER_DEGREE * 0.5; const d = height * Math.tan(endFOV * 0.5); camera.frustum.far = d / Math.tan(startFOV * 0.5) + 1e7; camera.frustum.fov = startFOV; function update8(value) { camera.frustum.fov = Math_default.lerp(startFOV, endFOV, value.time); camera.position.z = d / Math.tan(camera.frustum.fov * 0.5); } const tween = scene.tweens.add({ duration, easingFunction: EasingFunction_default.QUARTIC_OUT, startObject: { time: 0 }, stopObject: { time: 1 }, update: update8, complete: function() { complete(transitioner); } }); transitioner._currentTweens.push(tween); } function morphFrom2DToColumbusView(transitioner, duration, cameraCV, complete) { duration *= 0.5; const scene = transitioner._scene; const camera = scene.camera; const endPos = Cartesian3_default.clone(cameraCV.position, scratch3DToCVEndPos); const endDir = Cartesian3_default.clone(cameraCV.direction, scratch3DToCVEndDir); const endUp = Cartesian3_default.clone(cameraCV.up, scratch3DToCVEndUp); scene._mode = SceneMode_default.MORPHING; function morph() { camera.frustum = cameraCV.frustum.clone(); const startPos = Cartesian3_default.clone(camera.position, scratch3DToCVStartPos); const startDir = Cartesian3_default.clone(camera.direction, scratch3DToCVStartDir); const startUp = Cartesian3_default.clone(camera.up, scratch3DToCVStartUp); startPos.z = endPos.z; function update8(value) { columbusViewMorph(startPos, endPos, value.time, camera.position); columbusViewMorph(startDir, endDir, value.time, camera.direction); columbusViewMorph(startUp, endUp, value.time, camera.up); Cartesian3_default.cross(camera.direction, camera.up, camera.right); Cartesian3_default.normalize(camera.right, camera.right); } const tween = scene.tweens.add({ duration, easingFunction: EasingFunction_default.QUARTIC_OUT, startObject: { time: 0 }, stopObject: { time: 1 }, update: update8, complete: function() { complete(transitioner); } }); transitioner._currentTweens.push(tween); } if (transitioner._morphToOrthographic) { morph(); } else { morphOrthographicToPerspective(transitioner, 0, cameraCV, morph); } } function morphFrom3DToColumbusView(transitioner, duration, endCamera, complete) { const scene = transitioner._scene; const camera = scene.camera; const startPos = Cartesian3_default.clone(camera.position, scratch3DToCVStartPos); const startDir = Cartesian3_default.clone(camera.direction, scratch3DToCVStartDir); const startUp = Cartesian3_default.clone(camera.up, scratch3DToCVStartUp); const endPos = Cartesian3_default.clone(endCamera.position2D, scratch3DToCVEndPos); const endDir = Cartesian3_default.clone(endCamera.direction2D, scratch3DToCVEndDir); const endUp = Cartesian3_default.clone(endCamera.up2D, scratch3DToCVEndUp); function update8(value) { columbusViewMorph(startPos, endPos, value.time, camera.position); columbusViewMorph(startDir, endDir, value.time, camera.direction); columbusViewMorph(startUp, endUp, value.time, camera.up); Cartesian3_default.cross(camera.direction, camera.up, camera.right); Cartesian3_default.normalize(camera.right, camera.right); camera._adjustOrthographicFrustum(true); } const tween = scene.tweens.add({ duration, easingFunction: EasingFunction_default.QUARTIC_OUT, startObject: { time: 0 }, stopObject: { time: 1 }, update: update8, complete: function() { addMorphTimeAnimations(transitioner, scene, 1, 0, duration, complete); } }); transitioner._currentTweens.push(tween); } function addMorphTimeAnimations(transitioner, scene, start, stop2, duration, complete) { const options = { object: scene, property: "morphTime", startValue: start, stopValue: stop2, duration, easingFunction: EasingFunction_default.QUARTIC_OUT }; if (defined_default(complete)) { options.complete = function() { complete(transitioner); }; } const tween = scene.tweens.addProperty(options); transitioner._currentTweens.push(tween); } function complete3DCallback(camera3D) { return function(transitioner) { const scene = transitioner._scene; scene._mode = SceneMode_default.SCENE3D; scene.morphTime = SceneMode_default.getMorphTime(SceneMode_default.SCENE3D); destroyMorphHandler(transitioner); const camera = scene.camera; if (transitioner._previousMode !== SceneMode_default.MORPHING || transitioner._morphCancelled) { transitioner._morphCancelled = false; Cartesian3_default.clone(camera3D.position, camera.position); Cartesian3_default.clone(camera3D.direction, camera.direction); Cartesian3_default.clone(camera3D.up, camera.up); Cartesian3_default.cross(camera.direction, camera.up, camera.right); Cartesian3_default.normalize(camera.right, camera.right); camera.frustum = camera3D.frustum.clone(); } const frustum = camera.frustum; if (scene.frameState.useLogDepth) { frustum.near = 0.1; frustum.far = 1e10; } const wasMorphing = defined_default(transitioner._completeMorph); transitioner._completeMorph = void 0; scene.camera.update(scene.mode); transitioner._scene.morphComplete.raiseEvent( transitioner, transitioner._previousMode, SceneMode_default.SCENE3D, wasMorphing ); }; } function complete2DCallback(camera2D) { return function(transitioner) { const scene = transitioner._scene; scene._mode = SceneMode_default.SCENE2D; scene.morphTime = SceneMode_default.getMorphTime(SceneMode_default.SCENE2D); destroyMorphHandler(transitioner); const camera = scene.camera; Cartesian3_default.clone(camera2D.position, camera.position); camera.position.z = scene.mapProjection.ellipsoid.maximumRadius * 2; Cartesian3_default.clone(camera2D.direction, camera.direction); Cartesian3_default.clone(camera2D.up, camera.up); Cartesian3_default.cross(camera.direction, camera.up, camera.right); Cartesian3_default.normalize(camera.right, camera.right); camera.frustum = camera2D.frustum.clone(); const wasMorphing = defined_default(transitioner._completeMorph); transitioner._completeMorph = void 0; scene.camera.update(scene.mode); transitioner._scene.morphComplete.raiseEvent( transitioner, transitioner._previousMode, SceneMode_default.SCENE2D, wasMorphing ); }; } function completeColumbusViewCallback(cameraCV) { return function(transitioner) { const scene = transitioner._scene; scene._mode = SceneMode_default.COLUMBUS_VIEW; scene.morphTime = SceneMode_default.getMorphTime(SceneMode_default.COLUMBUS_VIEW); destroyMorphHandler(transitioner); const camera = scene.camera; if (transitioner._previousModeMode !== SceneMode_default.MORPHING || transitioner._morphCancelled) { transitioner._morphCancelled = false; Cartesian3_default.clone(cameraCV.position, camera.position); Cartesian3_default.clone(cameraCV.direction, camera.direction); Cartesian3_default.clone(cameraCV.up, camera.up); Cartesian3_default.cross(camera.direction, camera.up, camera.right); Cartesian3_default.normalize(camera.right, camera.right); } const frustum = camera.frustum; if (scene.frameState.useLogDepth) { frustum.near = 0.1; frustum.far = 1e10; } const wasMorphing = defined_default(transitioner._completeMorph); transitioner._completeMorph = void 0; scene.camera.update(scene.mode); transitioner._scene.morphComplete.raiseEvent( transitioner, transitioner._previousMode, SceneMode_default.COLUMBUS_VIEW, wasMorphing ); }; } var SceneTransitioner_default = SceneTransitioner; // packages/engine/Source/Scene/CameraEventType.js var CameraEventType = { /** * A left mouse button press followed by moving the mouse and releasing the button. * * @type {number} * @constant */ LEFT_DRAG: 0, /** * A right mouse button press followed by moving the mouse and releasing the button. * * @type {number} * @constant */ RIGHT_DRAG: 1, /** * A middle mouse button press followed by moving the mouse and releasing the button. * * @type {number} * @constant */ MIDDLE_DRAG: 2, /** * Scrolling the middle mouse button. * * @type {number} * @constant */ WHEEL: 3, /** * A two-finger touch on a touch surface. * * @type {number} * @constant */ PINCH: 4 }; var CameraEventType_default = Object.freeze(CameraEventType); // packages/engine/Source/Scene/CameraEventAggregator.js function getKey2(type, modifier) { let key = type; if (defined_default(modifier)) { key += `+${modifier}`; } return key; } function clonePinchMovement(pinchMovement, result) { Cartesian2_default.clone( pinchMovement.distance.startPosition, result.distance.startPosition ); Cartesian2_default.clone( pinchMovement.distance.endPosition, result.distance.endPosition ); Cartesian2_default.clone( pinchMovement.angleAndHeight.startPosition, result.angleAndHeight.startPosition ); Cartesian2_default.clone( pinchMovement.angleAndHeight.endPosition, result.angleAndHeight.endPosition ); } function listenToPinch(aggregator, modifier, canvas) { const key = getKey2(CameraEventType_default.PINCH, modifier); const update8 = aggregator._update; const isDown = aggregator._isDown; const eventStartPosition = aggregator._eventStartPosition; const pressTime = aggregator._pressTime; const releaseTime = aggregator._releaseTime; update8[key] = true; isDown[key] = false; eventStartPosition[key] = new Cartesian2_default(); let movement = aggregator._movement[key]; if (!defined_default(movement)) { movement = aggregator._movement[key] = {}; } movement.distance = { startPosition: new Cartesian2_default(), endPosition: new Cartesian2_default() }; movement.angleAndHeight = { startPosition: new Cartesian2_default(), endPosition: new Cartesian2_default() }; movement.prevAngle = 0; aggregator._eventHandler.setInputAction( function(event) { aggregator._buttonsDown++; isDown[key] = true; pressTime[key] = /* @__PURE__ */ new Date(); Cartesian2_default.lerp( event.position1, event.position2, 0.5, eventStartPosition[key] ); }, ScreenSpaceEventType_default.PINCH_START, modifier ); aggregator._eventHandler.setInputAction( function() { aggregator._buttonsDown = Math.max(aggregator._buttonsDown - 1, 0); isDown[key] = false; releaseTime[key] = /* @__PURE__ */ new Date(); }, ScreenSpaceEventType_default.PINCH_END, modifier ); aggregator._eventHandler.setInputAction( function(mouseMovement) { if (isDown[key]) { if (!update8[key]) { Cartesian2_default.clone( mouseMovement.distance.endPosition, movement.distance.endPosition ); Cartesian2_default.clone( mouseMovement.angleAndHeight.endPosition, movement.angleAndHeight.endPosition ); } else { clonePinchMovement(mouseMovement, movement); update8[key] = false; movement.prevAngle = movement.angleAndHeight.startPosition.x; } let angle = movement.angleAndHeight.endPosition.x; const prevAngle = movement.prevAngle; const TwoPI = Math.PI * 2; while (angle >= prevAngle + Math.PI) { angle -= TwoPI; } while (angle < prevAngle - Math.PI) { angle += TwoPI; } movement.angleAndHeight.endPosition.x = -angle * canvas.clientWidth / 12; movement.angleAndHeight.startPosition.x = -prevAngle * canvas.clientWidth / 12; } }, ScreenSpaceEventType_default.PINCH_MOVE, modifier ); } function listenToWheel(aggregator, modifier) { const key = getKey2(CameraEventType_default.WHEEL, modifier); const pressTime = aggregator._pressTime; const releaseTime = aggregator._releaseTime; const update8 = aggregator._update; update8[key] = true; let movement = aggregator._movement[key]; if (!defined_default(movement)) { movement = aggregator._movement[key] = {}; } let lastMovement = aggregator._lastMovement[key]; if (!defined_default(lastMovement)) { lastMovement = aggregator._lastMovement[key] = { startPosition: new Cartesian2_default(), endPosition: new Cartesian2_default(), valid: false }; } movement.startPosition = new Cartesian2_default(); Cartesian2_default.clone(Cartesian2_default.ZERO, movement.startPosition); movement.endPosition = new Cartesian2_default(); aggregator._eventHandler.setInputAction( function(delta) { const arcLength = 7.5 * Math_default.toRadians(delta); pressTime[key] = releaseTime[key] = /* @__PURE__ */ new Date(); movement.endPosition.x = 0; movement.endPosition.y = arcLength; Cartesian2_default.clone(movement.endPosition, lastMovement.endPosition); lastMovement.valid = true; update8[key] = false; }, ScreenSpaceEventType_default.WHEEL, modifier ); } function listenMouseButtonDownUp(aggregator, modifier, type) { const key = getKey2(type, modifier); const isDown = aggregator._isDown; const eventStartPosition = aggregator._eventStartPosition; const pressTime = aggregator._pressTime; const releaseTime = aggregator._releaseTime; isDown[key] = false; eventStartPosition[key] = new Cartesian2_default(); let lastMovement = aggregator._lastMovement[key]; if (!defined_default(lastMovement)) { lastMovement = aggregator._lastMovement[key] = { startPosition: new Cartesian2_default(), endPosition: new Cartesian2_default(), valid: false }; } let down; let up; if (type === CameraEventType_default.LEFT_DRAG) { down = ScreenSpaceEventType_default.LEFT_DOWN; up = ScreenSpaceEventType_default.LEFT_UP; } else if (type === CameraEventType_default.RIGHT_DRAG) { down = ScreenSpaceEventType_default.RIGHT_DOWN; up = ScreenSpaceEventType_default.RIGHT_UP; } else if (type === CameraEventType_default.MIDDLE_DRAG) { down = ScreenSpaceEventType_default.MIDDLE_DOWN; up = ScreenSpaceEventType_default.MIDDLE_UP; } aggregator._eventHandler.setInputAction( function(event) { aggregator._buttonsDown++; lastMovement.valid = false; isDown[key] = true; pressTime[key] = /* @__PURE__ */ new Date(); Cartesian2_default.clone(event.position, eventStartPosition[key]); }, down, modifier ); aggregator._eventHandler.setInputAction( function() { aggregator._buttonsDown = Math.max(aggregator._buttonsDown - 1, 0); isDown[key] = false; releaseTime[key] = /* @__PURE__ */ new Date(); }, up, modifier ); } function cloneMouseMovement(mouseMovement, result) { Cartesian2_default.clone(mouseMovement.startPosition, result.startPosition); Cartesian2_default.clone(mouseMovement.endPosition, result.endPosition); } function listenMouseMove(aggregator, modifier) { const update8 = aggregator._update; const movement = aggregator._movement; const lastMovement = aggregator._lastMovement; const isDown = aggregator._isDown; for (const typeName in CameraEventType_default) { if (CameraEventType_default.hasOwnProperty(typeName)) { const type = CameraEventType_default[typeName]; if (defined_default(type)) { const key = getKey2(type, modifier); update8[key] = true; if (!defined_default(aggregator._lastMovement[key])) { aggregator._lastMovement[key] = { startPosition: new Cartesian2_default(), endPosition: new Cartesian2_default(), valid: false }; } if (!defined_default(aggregator._movement[key])) { aggregator._movement[key] = { startPosition: new Cartesian2_default(), endPosition: new Cartesian2_default() }; } } } } aggregator._eventHandler.setInputAction( function(mouseMovement) { for (const typeName in CameraEventType_default) { if (CameraEventType_default.hasOwnProperty(typeName)) { const type = CameraEventType_default[typeName]; if (defined_default(type)) { const key = getKey2(type, modifier); if (isDown[key]) { if (!update8[key]) { Cartesian2_default.clone( mouseMovement.endPosition, movement[key].endPosition ); } else { cloneMouseMovement(movement[key], lastMovement[key]); lastMovement[key].valid = true; cloneMouseMovement(mouseMovement, movement[key]); update8[key] = false; } } } } } Cartesian2_default.clone( mouseMovement.endPosition, aggregator._currentMousePosition ); }, ScreenSpaceEventType_default.MOUSE_MOVE, modifier ); } function CameraEventAggregator(canvas) { if (!defined_default(canvas)) { throw new DeveloperError_default("canvas is required."); } this._eventHandler = new ScreenSpaceEventHandler_default(canvas); this._update = {}; this._movement = {}; this._lastMovement = {}; this._isDown = {}; this._eventStartPosition = {}; this._pressTime = {}; this._releaseTime = {}; this._buttonsDown = 0; this._currentMousePosition = new Cartesian2_default(); listenToWheel(this, void 0); listenToPinch(this, void 0, canvas); listenMouseButtonDownUp(this, void 0, CameraEventType_default.LEFT_DRAG); listenMouseButtonDownUp(this, void 0, CameraEventType_default.RIGHT_DRAG); listenMouseButtonDownUp(this, void 0, CameraEventType_default.MIDDLE_DRAG); listenMouseMove(this, void 0); for (const modifierName in KeyboardEventModifier_default) { if (KeyboardEventModifier_default.hasOwnProperty(modifierName)) { const modifier = KeyboardEventModifier_default[modifierName]; if (defined_default(modifier)) { listenToWheel(this, modifier); listenToPinch(this, modifier, canvas); listenMouseButtonDownUp(this, modifier, CameraEventType_default.LEFT_DRAG); listenMouseButtonDownUp(this, modifier, CameraEventType_default.RIGHT_DRAG); listenMouseButtonDownUp(this, modifier, CameraEventType_default.MIDDLE_DRAG); listenMouseMove(this, modifier); } } } } Object.defineProperties(CameraEventAggregator.prototype, { /** * Gets the current mouse position. * @memberof CameraEventAggregator.prototype * @type {Cartesian2} */ currentMousePosition: { get: function() { return this._currentMousePosition; } }, /** * Gets whether any mouse button is down, a touch has started, or the wheel has been moved. * @memberof CameraEventAggregator.prototype * @type {boolean} */ anyButtonDown: { get: function() { const wheelMoved = !this._update[getKey2(CameraEventType_default.WHEEL)] || !this._update[getKey2(CameraEventType_default.WHEEL, KeyboardEventModifier_default.SHIFT)] || !this._update[getKey2(CameraEventType_default.WHEEL, KeyboardEventModifier_default.CTRL)] || !this._update[getKey2(CameraEventType_default.WHEEL, KeyboardEventModifier_default.ALT)]; return this._buttonsDown > 0 || wheelMoved; } } }); CameraEventAggregator.prototype.isMoving = function(type, modifier) { if (!defined_default(type)) { throw new DeveloperError_default("type is required."); } const key = getKey2(type, modifier); return !this._update[key]; }; CameraEventAggregator.prototype.getMovement = function(type, modifier) { if (!defined_default(type)) { throw new DeveloperError_default("type is required."); } const key = getKey2(type, modifier); const movement = this._movement[key]; return movement; }; CameraEventAggregator.prototype.getLastMovement = function(type, modifier) { if (!defined_default(type)) { throw new DeveloperError_default("type is required."); } const key = getKey2(type, modifier); const lastMovement = this._lastMovement[key]; if (lastMovement.valid) { return lastMovement; } return void 0; }; CameraEventAggregator.prototype.isButtonDown = function(type, modifier) { if (!defined_default(type)) { throw new DeveloperError_default("type is required."); } const key = getKey2(type, modifier); return this._isDown[key]; }; CameraEventAggregator.prototype.getStartMousePosition = function(type, modifier) { if (!defined_default(type)) { throw new DeveloperError_default("type is required."); } if (type === CameraEventType_default.WHEEL) { return this._currentMousePosition; } const key = getKey2(type, modifier); return this._eventStartPosition[key]; }; CameraEventAggregator.prototype.getButtonPressTime = function(type, modifier) { if (!defined_default(type)) { throw new DeveloperError_default("type is required."); } const key = getKey2(type, modifier); return this._pressTime[key]; }; CameraEventAggregator.prototype.getButtonReleaseTime = function(type, modifier) { if (!defined_default(type)) { throw new DeveloperError_default("type is required."); } const key = getKey2(type, modifier); return this._releaseTime[key]; }; CameraEventAggregator.prototype.reset = function() { for (const name in this._update) { if (this._update.hasOwnProperty(name)) { this._update[name] = true; } } }; CameraEventAggregator.prototype.isDestroyed = function() { return false; }; CameraEventAggregator.prototype.destroy = function() { this._eventHandler = this._eventHandler && this._eventHandler.destroy(); return destroyObject_default(this); }; var CameraEventAggregator_default = CameraEventAggregator; // packages/engine/Source/Scene/TweenCollection.js function Tween2(tweens, tweenjs, startObject, stopObject, duration, delay2, easingFunction, update8, complete, cancel) { this._tweens = tweens; this._tweenjs = tweenjs; this._startObject = clone_default(startObject); this._stopObject = clone_default(stopObject); this._duration = duration; this._delay = delay2; this._easingFunction = easingFunction; this._update = update8; this._complete = complete; this.cancel = cancel; this.needsStart = true; } Object.defineProperties(Tween2.prototype, { /** * An object with properties for initial values of the tween. The properties of this object are changed during the tween's animation. * @memberof Tween.prototype * * @type {object} * @readonly */ startObject: { get: function() { return this._startObject; } }, /** * An object with properties for the final values of the tween. * @memberof Tween.prototype * * @type {object} * @readonly */ stopObject: { get: function() { return this._stopObject; } }, /** * The duration, in seconds, for the tween. The tween is automatically removed from the collection when it stops. * @memberof Tween.prototype * * @type {number} * @readonly */ duration: { get: function() { return this._duration; } }, /** * The delay, in seconds, before the tween starts animating. * @memberof Tween.prototype * * @type {number} * @readonly */ delay: { get: function() { return this._delay; } }, /** * Determines the curve for animtion. * @memberof Tween.prototype * * @type {EasingFunction} * @readonly */ easingFunction: { get: function() { return this._easingFunction; } }, /** * The callback to call at each animation update (usually tied to the a rendered frame). * @memberof Tween.prototype * * @type {TweenCollection.TweenUpdateCallback} * @readonly */ update: { get: function() { return this._update; } }, /** * The callback to call when the tween finishes animating. * @memberof Tween.prototype * * @type {TweenCollection.TweenCompleteCallback} * @readonly */ complete: { get: function() { return this._complete; } }, /** * @memberof Tween.prototype * * @private */ tweenjs: { get: function() { return this._tweenjs; } } }); Tween2.prototype.cancelTween = function() { this._tweens.remove(this); }; function TweenCollection() { this._tweens = []; } Object.defineProperties(TweenCollection.prototype, { /** * The number of tweens in the collection. * @memberof TweenCollection.prototype * * @type {number} * @readonly */ length: { get: function() { return this._tweens.length; } } }); TweenCollection.prototype.add = function(options) { options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT); if (!defined_default(options.startObject) || !defined_default(options.stopObject)) { throw new DeveloperError_default( "options.startObject and options.stopObject are required." ); } if (!defined_default(options.duration) || options.duration < 0) { throw new DeveloperError_default( "options.duration is required and must be positive." ); } if (options.duration === 0) { if (defined_default(options.complete)) { options.complete(); } return new Tween2(this); } const duration = options.duration / TimeConstants_default.SECONDS_PER_MILLISECOND; const delayInSeconds = defaultValue_default(options.delay, 0); const delay2 = delayInSeconds / TimeConstants_default.SECONDS_PER_MILLISECOND; const easingFunction = defaultValue_default( options.easingFunction, EasingFunction_default.LINEAR_NONE ); const value = options.startObject; const tweenjs = new Tween(value); tweenjs.to(clone_default(options.stopObject), duration); tweenjs.delay(delay2); tweenjs.easing(easingFunction); if (defined_default(options.update)) { tweenjs.onUpdate(function() { options.update(value); }); } tweenjs.onComplete(defaultValue_default(options.complete, null)); tweenjs.repeat(defaultValue_default(options._repeat, 0)); const tween = new Tween2( this, tweenjs, options.startObject, options.stopObject, options.duration, delayInSeconds, easingFunction, options.update, options.complete, options.cancel ); this._tweens.push(tween); return tween; }; TweenCollection.prototype.addProperty = function(options) { options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT); const object2 = options.object; const property = options.property; const startValue = options.startValue; const stopValue = options.stopValue; if (!defined_default(object2) || !defined_default(options.property)) { throw new DeveloperError_default( "options.object and options.property are required." ); } if (!defined_default(object2[property])) { throw new DeveloperError_default( "options.object must have the specified property." ); } if (!defined_default(startValue) || !defined_default(stopValue)) { throw new DeveloperError_default( "options.startValue and options.stopValue are required." ); } function update8(value) { object2[property] = value.value; } return this.add({ startObject: { value: startValue }, stopObject: { value: stopValue }, duration: defaultValue_default(options.duration, 3), delay: options.delay, easingFunction: options.easingFunction, update: update8, complete: options.complete, cancel: options.cancel, _repeat: options._repeat }); }; TweenCollection.prototype.addAlpha = function(options) { options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT); const material = options.material; if (!defined_default(material)) { throw new DeveloperError_default("options.material is required."); } const properties = []; for (const property in material.uniforms) { if (material.uniforms.hasOwnProperty(property) && defined_default(material.uniforms[property]) && defined_default(material.uniforms[property].alpha)) { properties.push(property); } } if (properties.length === 0) { throw new DeveloperError_default( "material has no properties with alpha components." ); } function update8(value) { const length3 = properties.length; for (let i = 0; i < length3; ++i) { material.uniforms[properties[i]].alpha = value.alpha; } } return this.add({ startObject: { alpha: defaultValue_default(options.startValue, 0) // Default to fade in }, stopObject: { alpha: defaultValue_default(options.stopValue, 1) }, duration: defaultValue_default(options.duration, 3), delay: options.delay, easingFunction: options.easingFunction, update: update8, complete: options.complete, cancel: options.cancel }); }; TweenCollection.prototype.addOffsetIncrement = function(options) { options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT); const material = options.material; if (!defined_default(material)) { throw new DeveloperError_default("material is required."); } if (!defined_default(material.uniforms.offset)) { throw new DeveloperError_default("material.uniforms must have an offset property."); } const uniforms = material.uniforms; return this.addProperty({ object: uniforms, property: "offset", startValue: uniforms.offset, stopValue: uniforms.offset + 1, duration: options.duration, delay: options.delay, easingFunction: options.easingFunction, update: options.update, cancel: options.cancel, _repeat: Infinity }); }; TweenCollection.prototype.remove = function(tween) { if (!defined_default(tween)) { return false; } const index = this._tweens.indexOf(tween); if (index !== -1) { tween.tweenjs.stop(); if (defined_default(tween.cancel)) { tween.cancel(); } this._tweens.splice(index, 1); return true; } return false; }; TweenCollection.prototype.removeAll = function() { const tweens = this._tweens; for (let i = 0; i < tweens.length; ++i) { const tween = tweens[i]; tween.tweenjs.stop(); if (defined_default(tween.cancel)) { tween.cancel(); } } tweens.length = 0; }; TweenCollection.prototype.contains = function(tween) { return defined_default(tween) && this._tweens.indexOf(tween) !== -1; }; TweenCollection.prototype.get = function(index) { if (!defined_default(index)) { throw new DeveloperError_default("index is required."); } return this._tweens[index]; }; TweenCollection.prototype.update = function(time) { const tweens = this._tweens; let i = 0; time = defined_default(time) ? time / TimeConstants_default.SECONDS_PER_MILLISECOND : getTimestamp_default(); while (i < tweens.length) { const tween = tweens[i]; const tweenjs = tween.tweenjs; if (tween.needsStart) { tween.needsStart = false; tweenjs.start(time); } else if (tweenjs.update(time)) { i++; } else { tweenjs.stop(); tweens.splice(i, 1); } } }; var TweenCollection_default = TweenCollection; // packages/engine/Source/Scene/ScreenSpaceCameraController.js function ScreenSpaceCameraController(scene) { if (!defined_default(scene)) { throw new DeveloperError_default("scene is required."); } this.enableInputs = true; this.enableTranslate = true; this.enableZoom = true; this.enableRotate = true; this.enableTilt = true; this.enableLook = true; this.inertiaSpin = 0.9; this.inertiaTranslate = 0.9; this.inertiaZoom = 0.8; this.maximumMovementRatio = 0.1; this.bounceAnimationTime = 3; this.minimumZoomDistance = 1; this.maximumZoomDistance = Number.POSITIVE_INFINITY; this.translateEventTypes = CameraEventType_default.LEFT_DRAG; this.zoomEventTypes = [ CameraEventType_default.RIGHT_DRAG, CameraEventType_default.WHEEL, CameraEventType_default.PINCH ]; this.rotateEventTypes = CameraEventType_default.LEFT_DRAG; this.tiltEventTypes = [ CameraEventType_default.MIDDLE_DRAG, CameraEventType_default.PINCH, { eventType: CameraEventType_default.LEFT_DRAG, modifier: KeyboardEventModifier_default.CTRL }, { eventType: CameraEventType_default.RIGHT_DRAG, modifier: KeyboardEventModifier_default.CTRL } ]; this.lookEventTypes = { eventType: CameraEventType_default.LEFT_DRAG, modifier: KeyboardEventModifier_default.SHIFT }; this.minimumPickingTerrainHeight = 15e4; this._minimumPickingTerrainHeight = this.minimumPickingTerrainHeight; this.minimumPickingTerrainDistanceWithInertia = 4e3; this.minimumCollisionTerrainHeight = 15e3; this._minimumCollisionTerrainHeight = this.minimumCollisionTerrainHeight; this.minimumTrackBallHeight = 75e5; this._minimumTrackBallHeight = this.minimumTrackBallHeight; this.enableCollisionDetection = true; this._scene = scene; this._globe = void 0; this._ellipsoid = void 0; this._aggregator = new CameraEventAggregator_default(scene.canvas); this._lastInertiaSpinMovement = void 0; this._lastInertiaZoomMovement = void 0; this._lastInertiaTranslateMovement = void 0; this._lastInertiaTiltMovement = void 0; this._inertiaDisablers = { _lastInertiaZoomMovement: [ "_lastInertiaSpinMovement", "_lastInertiaTranslateMovement", "_lastInertiaTiltMovement" ], _lastInertiaTiltMovement: [ "_lastInertiaSpinMovement", "_lastInertiaTranslateMovement" ] }; this._tweens = new TweenCollection_default(); this._tween = void 0; this._horizontalRotationAxis = void 0; this._tiltCenterMousePosition = new Cartesian2_default(-1, -1); this._tiltCenter = new Cartesian3_default(); this._rotateMousePosition = new Cartesian2_default(-1, -1); this._rotateStartPosition = new Cartesian3_default(); this._strafeStartPosition = new Cartesian3_default(); this._strafeMousePosition = new Cartesian2_default(); this._strafeEndMousePosition = new Cartesian2_default(); this._zoomMouseStart = new Cartesian2_default(-1, -1); this._zoomWorldPosition = new Cartesian3_default(); this._useZoomWorldPosition = false; this._tiltCVOffMap = false; this._looking = false; this._rotating = false; this._strafing = false; this._zoomingOnVector = false; this._zoomingUnderground = false; this._rotatingZoom = false; this._adjustedHeightForTerrain = false; this._cameraUnderground = false; const projection = scene.mapProjection; this._maxCoord = projection.project( new Cartographic_default(Math.PI, Math_default.PI_OVER_TWO) ); this._zoomFactor = 5; this._rotateFactor = void 0; this._rotateRateRangeAdjustment = void 0; this._maximumRotateRate = 1.77; this._minimumRotateRate = 1 / 5e3; this._minimumZoomRate = 20; this._maximumZoomRate = 5906376272e3; this._minimumUndergroundPickDistance = 2e3; this._maximumUndergroundPickDistance = 1e4; } function decay(time, coefficient) { if (time < 0) { return 0; } const tau = (1 - coefficient) * 25; return Math.exp(-tau * time); } function sameMousePosition(movement) { return Cartesian2_default.equalsEpsilon( movement.startPosition, movement.endPosition, Math_default.EPSILON14 ); } var inertiaMaxClickTimeThreshold = 0.4; function maintainInertia(aggregator, type, modifier, decayCoef, action, object2, lastMovementName) { let movementState = object2[lastMovementName]; if (!defined_default(movementState)) { movementState = object2[lastMovementName] = { startPosition: new Cartesian2_default(), endPosition: new Cartesian2_default(), motion: new Cartesian2_default(), inertiaEnabled: true }; } const ts = aggregator.getButtonPressTime(type, modifier); const tr = aggregator.getButtonReleaseTime(type, modifier); const threshold = ts && tr && (tr.getTime() - ts.getTime()) / 1e3; const now2 = /* @__PURE__ */ new Date(); const fromNow = tr && (now2.getTime() - tr.getTime()) / 1e3; if (ts && tr && threshold < inertiaMaxClickTimeThreshold) { const d = decay(fromNow, decayCoef); const lastMovement = aggregator.getLastMovement(type, modifier); if (!defined_default(lastMovement) || sameMousePosition(lastMovement) || !movementState.inertiaEnabled) { return; } movementState.motion.x = (lastMovement.endPosition.x - lastMovement.startPosition.x) * 0.5; movementState.motion.y = (lastMovement.endPosition.y - lastMovement.startPosition.y) * 0.5; movementState.startPosition = Cartesian2_default.clone( lastMovement.startPosition, movementState.startPosition ); movementState.endPosition = Cartesian2_default.multiplyByScalar( movementState.motion, d, movementState.endPosition ); movementState.endPosition = Cartesian2_default.add( movementState.startPosition, movementState.endPosition, movementState.endPosition ); if (isNaN(movementState.endPosition.x) || isNaN(movementState.endPosition.y) || Cartesian2_default.distance( movementState.startPosition, movementState.endPosition ) < 0.5) { return; } if (!aggregator.isButtonDown(type, modifier)) { const startPosition = aggregator.getStartMousePosition(type, modifier); action(object2, startPosition, movementState); } } } function activateInertia(controller, inertiaStateName) { if (defined_default(inertiaStateName)) { let movementState = controller[inertiaStateName]; if (defined_default(movementState)) { movementState.inertiaEnabled = true; } const inertiasToDisable = controller._inertiaDisablers[inertiaStateName]; if (defined_default(inertiasToDisable)) { const length3 = inertiasToDisable.length; for (let i = 0; i < length3; ++i) { movementState = controller[inertiasToDisable[i]]; if (defined_default(movementState)) { movementState.inertiaEnabled = false; } } } } } var scratchEventTypeArray = []; function reactToInput(controller, enabled, eventTypes, action, inertiaConstant, inertiaStateName) { if (!defined_default(eventTypes)) { return; } const aggregator = controller._aggregator; if (!Array.isArray(eventTypes)) { scratchEventTypeArray[0] = eventTypes; eventTypes = scratchEventTypeArray; } const length3 = eventTypes.length; for (let i = 0; i < length3; ++i) { const eventType = eventTypes[i]; const type = defined_default(eventType.eventType) ? eventType.eventType : eventType; const modifier = eventType.modifier; const movement = aggregator.isMoving(type, modifier) && aggregator.getMovement(type, modifier); const startPosition = aggregator.getStartMousePosition(type, modifier); if (controller.enableInputs && enabled) { if (movement) { action(controller, startPosition, movement); activateInertia(controller, inertiaStateName); } else if (inertiaConstant < 1) { maintainInertia( aggregator, type, modifier, inertiaConstant, action, controller, inertiaStateName ); } } } } var scratchZoomPickRay = new Ray_default(); var scratchPickCartesian = new Cartesian3_default(); var scratchZoomOffset = new Cartesian2_default(); var scratchZoomDirection = new Cartesian3_default(); var scratchCenterPixel = new Cartesian2_default(); var scratchCenterPosition = new Cartesian3_default(); var scratchPositionNormal3 = new Cartesian3_default(); var scratchPickNormal = new Cartesian3_default(); var scratchZoomAxis = new Cartesian3_default(); var scratchCameraPositionNormal = new Cartesian3_default(); var scratchTargetNormal = new Cartesian3_default(); var scratchCameraPosition2 = new Cartesian3_default(); var scratchCameraUpNormal = new Cartesian3_default(); var scratchCameraRightNormal = new Cartesian3_default(); var scratchForwardNormal = new Cartesian3_default(); var scratchPositionToTarget = new Cartesian3_default(); var scratchPositionToTargetNormal = new Cartesian3_default(); var scratchPan = new Cartesian3_default(); var scratchCenterMovement = new Cartesian3_default(); var scratchCenter10 = new Cartesian3_default(); var scratchCartesian30 = new Cartesian3_default(); var scratchCartesianTwo = new Cartesian3_default(); var scratchCartesianThree = new Cartesian3_default(); var scratchZoomViewOptions = { orientation: new HeadingPitchRoll_default() }; function handleZoom(object2, startPosition, movement, zoomFactor, distanceMeasure, unitPositionDotDirection) { let percentage = 1; if (defined_default(unitPositionDotDirection)) { percentage = Math_default.clamp( Math.abs(unitPositionDotDirection), 0.25, 1 ); } const diff = movement.endPosition.y - movement.startPosition.y; const approachingSurface = diff > 0; const minHeight = approachingSurface ? object2.minimumZoomDistance * percentage : 0; const maxHeight = object2.maximumZoomDistance; const minDistance = distanceMeasure - minHeight; let zoomRate = zoomFactor * minDistance; zoomRate = Math_default.clamp( zoomRate, object2._minimumZoomRate, object2._maximumZoomRate ); let rangeWindowRatio = diff / object2._scene.canvas.clientHeight; rangeWindowRatio = Math.min(rangeWindowRatio, object2.maximumMovementRatio); let distance2 = zoomRate * rangeWindowRatio; if (object2.enableCollisionDetection || object2.minimumZoomDistance === 0 || !defined_default(object2._globe)) { if (distance2 > 0 && Math.abs(distanceMeasure - minHeight) < 1) { return; } if (distance2 < 0 && Math.abs(distanceMeasure - maxHeight) < 1) { return; } if (distanceMeasure - distance2 < minHeight) { distance2 = distanceMeasure - minHeight - 1; } else if (distanceMeasure - distance2 > maxHeight) { distance2 = distanceMeasure - maxHeight; } } const scene = object2._scene; const camera = scene.camera; const mode2 = scene.mode; const orientation = scratchZoomViewOptions.orientation; orientation.heading = camera.heading; orientation.pitch = camera.pitch; orientation.roll = camera.roll; if (camera.frustum instanceof OrthographicFrustum_default) { if (Math.abs(distance2) > 0) { camera.zoomIn(distance2); camera._adjustOrthographicFrustum(true); } return; } const sameStartPosition = defaultValue_default( movement.inertiaEnabled, Cartesian2_default.equals(startPosition, object2._zoomMouseStart) ); let zoomingOnVector = object2._zoomingOnVector; let rotatingZoom = object2._rotatingZoom; let pickedPosition; if (!sameStartPosition) { object2._zoomMouseStart = Cartesian2_default.clone( startPosition, object2._zoomMouseStart ); if (defined_default(object2._globe)) { if (mode2 === SceneMode_default.SCENE2D) { pickedPosition = camera.getPickRay(startPosition, scratchZoomPickRay).origin; pickedPosition = Cartesian3_default.fromElements( pickedPosition.y, pickedPosition.z, pickedPosition.x ); } else { pickedPosition = pickGlobe(object2, startPosition, scratchPickCartesian); } } if (defined_default(pickedPosition)) { object2._useZoomWorldPosition = true; object2._zoomWorldPosition = Cartesian3_default.clone( pickedPosition, object2._zoomWorldPosition ); } else { object2._useZoomWorldPosition = false; } zoomingOnVector = object2._zoomingOnVector = false; rotatingZoom = object2._rotatingZoom = false; object2._zoomingUnderground = object2._cameraUnderground; } if (!object2._useZoomWorldPosition) { camera.zoomIn(distance2); return; } let zoomOnVector = mode2 === SceneMode_default.COLUMBUS_VIEW; if (camera.positionCartographic.height < 2e6) { rotatingZoom = true; } if (!sameStartPosition || rotatingZoom) { if (mode2 === SceneMode_default.SCENE2D) { const worldPosition = object2._zoomWorldPosition; const endPosition = camera.position; if (!Cartesian3_default.equals(worldPosition, endPosition) && camera.positionCartographic.height < object2._maxCoord.x * 2) { const savedX = camera.position.x; const direction2 = Cartesian3_default.subtract( worldPosition, endPosition, scratchZoomDirection ); Cartesian3_default.normalize(direction2, direction2); const d = Cartesian3_default.distance(worldPosition, endPosition) * distance2 / (camera.getMagnitude() * 0.5); camera.move(direction2, d * 0.5); if (camera.position.x < 0 && savedX > 0 || camera.position.x > 0 && savedX < 0) { pickedPosition = camera.getPickRay(startPosition, scratchZoomPickRay).origin; pickedPosition = Cartesian3_default.fromElements( pickedPosition.y, pickedPosition.z, pickedPosition.x ); object2._zoomWorldPosition = Cartesian3_default.clone( pickedPosition, object2._zoomWorldPosition ); } } } else if (mode2 === SceneMode_default.SCENE3D) { const cameraPositionNormal = Cartesian3_default.normalize( camera.position, scratchCameraPositionNormal ); if (object2._cameraUnderground || object2._zoomingUnderground || camera.positionCartographic.height < 3e3 && Math.abs(Cartesian3_default.dot(camera.direction, cameraPositionNormal)) < 0.6) { zoomOnVector = true; } else { const canvas = scene.canvas; const centerPixel = scratchCenterPixel; centerPixel.x = canvas.clientWidth / 2; centerPixel.y = canvas.clientHeight / 2; const centerPosition = pickGlobe( object2, centerPixel, scratchCenterPosition ); if (!defined_default(centerPosition)) { zoomOnVector = true; } else if (camera.positionCartographic.height < 1e6) { if (Cartesian3_default.dot(camera.direction, cameraPositionNormal) >= -0.5) { zoomOnVector = true; } else { const cameraPosition = scratchCameraPosition2; Cartesian3_default.clone(camera.position, cameraPosition); const target = object2._zoomWorldPosition; let targetNormal = scratchTargetNormal; targetNormal = Cartesian3_default.normalize(target, targetNormal); if (Cartesian3_default.dot(targetNormal, cameraPositionNormal) < 0) { return; } const center = scratchCenter10; const forward = scratchForwardNormal; Cartesian3_default.clone(camera.direction, forward); Cartesian3_default.add( cameraPosition, Cartesian3_default.multiplyByScalar(forward, 1e3, scratchCartesian30), center ); const positionToTarget = scratchPositionToTarget; const positionToTargetNormal = scratchPositionToTargetNormal; Cartesian3_default.subtract(target, cameraPosition, positionToTarget); Cartesian3_default.normalize(positionToTarget, positionToTargetNormal); const alphaDot = Cartesian3_default.dot( cameraPositionNormal, positionToTargetNormal ); if (alphaDot >= 0) { object2._zoomMouseStart.x = -1; return; } const alpha = Math.acos(-alphaDot); const cameraDistance = Cartesian3_default.magnitude(cameraPosition); const targetDistance = Cartesian3_default.magnitude(target); const remainingDistance = cameraDistance - distance2; const positionToTargetDistance = Cartesian3_default.magnitude( positionToTarget ); const gamma = Math.asin( Math_default.clamp( positionToTargetDistance / targetDistance * Math.sin(alpha), -1, 1 ) ); const delta = Math.asin( Math_default.clamp( remainingDistance / targetDistance * Math.sin(alpha), -1, 1 ) ); const beta = gamma - delta + alpha; const up = scratchCameraUpNormal; Cartesian3_default.normalize(cameraPosition, up); let right = scratchCameraRightNormal; right = Cartesian3_default.cross(positionToTargetNormal, up, right); right = Cartesian3_default.normalize(right, right); Cartesian3_default.normalize( Cartesian3_default.cross(up, right, scratchCartesian30), forward ); Cartesian3_default.multiplyByScalar( Cartesian3_default.normalize(center, scratchCartesian30), Cartesian3_default.magnitude(center) - distance2, center ); Cartesian3_default.normalize(cameraPosition, cameraPosition); Cartesian3_default.multiplyByScalar( cameraPosition, remainingDistance, cameraPosition ); const pMid = scratchPan; Cartesian3_default.multiplyByScalar( Cartesian3_default.add( Cartesian3_default.multiplyByScalar( up, Math.cos(beta) - 1, scratchCartesianTwo ), Cartesian3_default.multiplyByScalar( forward, Math.sin(beta), scratchCartesianThree ), scratchCartesian30 ), remainingDistance, pMid ); Cartesian3_default.add(cameraPosition, pMid, cameraPosition); Cartesian3_default.normalize(center, up); Cartesian3_default.normalize( Cartesian3_default.cross(up, right, scratchCartesian30), forward ); const cMid = scratchCenterMovement; Cartesian3_default.multiplyByScalar( Cartesian3_default.add( Cartesian3_default.multiplyByScalar( up, Math.cos(beta) - 1, scratchCartesianTwo ), Cartesian3_default.multiplyByScalar( forward, Math.sin(beta), scratchCartesianThree ), scratchCartesian30 ), Cartesian3_default.magnitude(center), cMid ); Cartesian3_default.add(center, cMid, center); Cartesian3_default.clone(cameraPosition, camera.position); Cartesian3_default.normalize( Cartesian3_default.subtract(center, cameraPosition, scratchCartesian30), camera.direction ); Cartesian3_default.clone(camera.direction, camera.direction); Cartesian3_default.cross(camera.direction, camera.up, camera.right); Cartesian3_default.cross(camera.right, camera.direction, camera.up); camera.setView(scratchZoomViewOptions); return; } } else { const positionNormal = Cartesian3_default.normalize( centerPosition, scratchPositionNormal3 ); const pickedNormal = Cartesian3_default.normalize( object2._zoomWorldPosition, scratchPickNormal ); const dotProduct = Cartesian3_default.dot(pickedNormal, positionNormal); if (dotProduct > 0 && dotProduct < 1) { const angle = Math_default.acosClamped(dotProduct); const axis = Cartesian3_default.cross( pickedNormal, positionNormal, scratchZoomAxis ); const denom = Math.abs(angle) > Math_default.toRadians(20) ? camera.positionCartographic.height * 0.75 : camera.positionCartographic.height - distance2; const scalar = distance2 / denom; camera.rotate(axis, angle * scalar); } } } } object2._rotatingZoom = !zoomOnVector; } if (!sameStartPosition && zoomOnVector || zoomingOnVector) { let ray; const zoomMouseStart = SceneTransforms_default.wgs84ToWindowCoordinates( scene, object2._zoomWorldPosition, scratchZoomOffset ); if (mode2 !== SceneMode_default.COLUMBUS_VIEW && Cartesian2_default.equals(startPosition, object2._zoomMouseStart) && defined_default(zoomMouseStart)) { ray = camera.getPickRay(zoomMouseStart, scratchZoomPickRay); } else { ray = camera.getPickRay(startPosition, scratchZoomPickRay); } const rayDirection = ray.direction; if (mode2 === SceneMode_default.COLUMBUS_VIEW || mode2 === SceneMode_default.SCENE2D) { Cartesian3_default.fromElements( rayDirection.y, rayDirection.z, rayDirection.x, rayDirection ); } camera.move(rayDirection, distance2); object2._zoomingOnVector = true; } else { camera.zoomIn(distance2); } if (!object2._cameraUnderground) { camera.setView(scratchZoomViewOptions); } } var translate2DStart = new Ray_default(); var translate2DEnd = new Ray_default(); var scratchTranslateP0 = new Cartesian3_default(); function translate2D(controller, startPosition, movement) { const scene = controller._scene; const camera = scene.camera; let start = camera.getPickRay(movement.startPosition, translate2DStart).origin; let end = camera.getPickRay(movement.endPosition, translate2DEnd).origin; start = Cartesian3_default.fromElements(start.y, start.z, start.x, start); end = Cartesian3_default.fromElements(end.y, end.z, end.x, end); const direction2 = Cartesian3_default.subtract(start, end, scratchTranslateP0); const distance2 = Cartesian3_default.magnitude(direction2); if (distance2 > 0) { Cartesian3_default.normalize(direction2, direction2); camera.move(direction2, distance2); } } function zoom2D2(controller, startPosition, movement) { if (defined_default(movement.distance)) { movement = movement.distance; } const scene = controller._scene; const camera = scene.camera; handleZoom( controller, startPosition, movement, controller._zoomFactor, camera.getMagnitude() ); } var twist2DStart = new Cartesian2_default(); var twist2DEnd = new Cartesian2_default(); function twist2D(controller, startPosition, movement) { if (defined_default(movement.angleAndHeight)) { singleAxisTwist2D(controller, startPosition, movement.angleAndHeight); return; } const scene = controller._scene; const camera = scene.camera; const canvas = scene.canvas; const width = canvas.clientWidth; const height = canvas.clientHeight; let start = twist2DStart; start.x = 2 / width * movement.startPosition.x - 1; start.y = 2 / height * (height - movement.startPosition.y) - 1; start = Cartesian2_default.normalize(start, start); let end = twist2DEnd; end.x = 2 / width * movement.endPosition.x - 1; end.y = 2 / height * (height - movement.endPosition.y) - 1; end = Cartesian2_default.normalize(end, end); let startTheta = Math_default.acosClamped(start.x); if (start.y < 0) { startTheta = Math_default.TWO_PI - startTheta; } let endTheta = Math_default.acosClamped(end.x); if (end.y < 0) { endTheta = Math_default.TWO_PI - endTheta; } const theta = endTheta - startTheta; camera.twistRight(theta); } function singleAxisTwist2D(controller, startPosition, movement) { let rotateRate = controller._rotateFactor * controller._rotateRateRangeAdjustment; if (rotateRate > controller._maximumRotateRate) { rotateRate = controller._maximumRotateRate; } if (rotateRate < controller._minimumRotateRate) { rotateRate = controller._minimumRotateRate; } const scene = controller._scene; const camera = scene.camera; const canvas = scene.canvas; let phiWindowRatio = (movement.endPosition.x - movement.startPosition.x) / canvas.clientWidth; phiWindowRatio = Math.min(phiWindowRatio, controller.maximumMovementRatio); const deltaPhi = rotateRate * phiWindowRatio * Math.PI * 4; camera.twistRight(deltaPhi); } function update2D(controller) { const rotatable2D = controller._scene.mapMode2D === MapMode2D_default.ROTATE; if (!Matrix4_default.equals(Matrix4_default.IDENTITY, controller._scene.camera.transform)) { reactToInput( controller, controller.enableZoom, controller.zoomEventTypes, zoom2D2, controller.inertiaZoom, "_lastInertiaZoomMovement" ); if (rotatable2D) { reactToInput( controller, controller.enableRotate, controller.translateEventTypes, twist2D, controller.inertiaSpin, "_lastInertiaSpinMovement" ); } } else { reactToInput( controller, controller.enableTranslate, controller.translateEventTypes, translate2D, controller.inertiaTranslate, "_lastInertiaTranslateMovement" ); reactToInput( controller, controller.enableZoom, controller.zoomEventTypes, zoom2D2, controller.inertiaZoom, "_lastInertiaZoomMovement" ); if (rotatable2D) { reactToInput( controller, controller.enableRotate, controller.tiltEventTypes, twist2D, controller.inertiaSpin, "_lastInertiaTiltMovement" ); } } } var pickGlobeScratchRay = new Ray_default(); var scratchDepthIntersection2 = new Cartesian3_default(); var scratchRayIntersection2 = new Cartesian3_default(); function pickGlobe(controller, mousePosition, result) { const scene = controller._scene; const globe = controller._globe; const camera = scene.camera; if (!defined_default(globe)) { return void 0; } const cullBackFaces = !controller._cameraUnderground; let depthIntersection; if (scene.pickPositionSupported) { depthIntersection = scene.pickPositionWorldCoordinates( mousePosition, scratchDepthIntersection2 ); } const ray = camera.getPickRay(mousePosition, pickGlobeScratchRay); const rayIntersection = globe.pickWorldCoordinates( ray, scene, cullBackFaces, scratchRayIntersection2 ); const pickDistance = defined_default(depthIntersection) ? Cartesian3_default.distance(depthIntersection, camera.positionWC) : Number.POSITIVE_INFINITY; const rayDistance = defined_default(rayIntersection) ? Cartesian3_default.distance(rayIntersection, camera.positionWC) : Number.POSITIVE_INFINITY; if (pickDistance < rayDistance) { return Cartesian3_default.clone(depthIntersection, result); } return Cartesian3_default.clone(rayIntersection, result); } var scratchDistanceCartographic = new Cartographic_default(); function getDistanceFromSurface(controller) { const ellipsoid = controller._ellipsoid; const scene = controller._scene; const camera = scene.camera; const mode2 = scene.mode; let height = 0; if (mode2 === SceneMode_default.SCENE3D) { const cartographic2 = ellipsoid.cartesianToCartographic( camera.position, scratchDistanceCartographic ); if (defined_default(cartographic2)) { height = cartographic2.height; } } else { height = camera.position.z; } const globeHeight = defaultValue_default(controller._scene.globeHeight, 0); const distanceFromSurface = Math.abs(globeHeight - height); return distanceFromSurface; } var scratchSurfaceNormal2 = new Cartesian3_default(); function getZoomDistanceUnderground(controller, ray) { const origin = ray.origin; const direction2 = ray.direction; const distanceFromSurface = getDistanceFromSurface(controller); const surfaceNormal = Cartesian3_default.normalize(origin, scratchSurfaceNormal2); let strength = Math.abs(Cartesian3_default.dot(surfaceNormal, direction2)); strength = Math.max(strength, 0.5) * 2; return distanceFromSurface * strength; } function getTiltCenterUnderground(controller, ray, pickedPosition, result) { let distance2 = Cartesian3_default.distance(ray.origin, pickedPosition); const distanceFromSurface = getDistanceFromSurface(controller); const maximumDistance = Math_default.clamp( distanceFromSurface * 5, controller._minimumUndergroundPickDistance, controller._maximumUndergroundPickDistance ); if (distance2 > maximumDistance) { distance2 = Math.min(distance2, distanceFromSurface / 5); distance2 = Math.max(distance2, 100); } return Ray_default.getPoint(ray, distance2, result); } function getStrafeStartPositionUnderground(controller, ray, pickedPosition, result) { let distance2; if (!defined_default(pickedPosition)) { distance2 = getDistanceFromSurface(controller); } else { distance2 = Cartesian3_default.distance(ray.origin, pickedPosition); if (distance2 > controller._maximumUndergroundPickDistance) { distance2 = getDistanceFromSurface(controller); } } return Ray_default.getPoint(ray, distance2, result); } var scratchInertialDelta = new Cartesian2_default(); function continueStrafing(controller, movement) { const originalEndPosition = movement.endPosition; const inertialDelta = Cartesian2_default.subtract( movement.endPosition, movement.startPosition, scratchInertialDelta ); const endPosition = controller._strafeEndMousePosition; Cartesian2_default.add(endPosition, inertialDelta, endPosition); movement.endPosition = endPosition; strafe(controller, movement, controller._strafeStartPosition); movement.endPosition = originalEndPosition; } var translateCVStartRay = new Ray_default(); var translateCVEndRay = new Ray_default(); var translateCVStartPos = new Cartesian3_default(); var translateCVEndPos = new Cartesian3_default(); var translateCVDifference = new Cartesian3_default(); var translateCVOrigin = new Cartesian3_default(); var translateCVPlane = new Plane_default(Cartesian3_default.UNIT_X, 0); var translateCVStartMouse = new Cartesian2_default(); var translateCVEndMouse = new Cartesian2_default(); function translateCV(controller, startPosition, movement) { if (!Cartesian3_default.equals(startPosition, controller._translateMousePosition)) { controller._looking = false; } if (!Cartesian3_default.equals(startPosition, controller._strafeMousePosition)) { controller._strafing = false; } if (controller._looking) { look3D(controller, startPosition, movement); return; } if (controller._strafing) { continueStrafing(controller, movement); return; } const scene = controller._scene; const camera = scene.camera; const cameraUnderground = controller._cameraUnderground; const startMouse = Cartesian2_default.clone( movement.startPosition, translateCVStartMouse ); const endMouse = Cartesian2_default.clone(movement.endPosition, translateCVEndMouse); let startRay = camera.getPickRay(startMouse, translateCVStartRay); const origin = Cartesian3_default.clone(Cartesian3_default.ZERO, translateCVOrigin); const normal2 = Cartesian3_default.UNIT_X; let globePos; if (camera.position.z < controller._minimumPickingTerrainHeight) { globePos = pickGlobe(controller, startMouse, translateCVStartPos); if (defined_default(globePos)) { origin.x = globePos.x; } } if (cameraUnderground || origin.x > camera.position.z && defined_default(globePos)) { let pickPosition = globePos; if (cameraUnderground) { pickPosition = getStrafeStartPositionUnderground( controller, startRay, globePos, translateCVStartPos ); } Cartesian2_default.clone(startPosition, controller._strafeMousePosition); Cartesian2_default.clone(startPosition, controller._strafeEndMousePosition); Cartesian3_default.clone(pickPosition, controller._strafeStartPosition); controller._strafing = true; strafe(controller, movement, controller._strafeStartPosition); return; } const plane = Plane_default.fromPointNormal(origin, normal2, translateCVPlane); startRay = camera.getPickRay(startMouse, translateCVStartRay); const startPlanePos = IntersectionTests_default.rayPlane( startRay, plane, translateCVStartPos ); const endRay = camera.getPickRay(endMouse, translateCVEndRay); const endPlanePos = IntersectionTests_default.rayPlane( endRay, plane, translateCVEndPos ); if (!defined_default(startPlanePos) || !defined_default(endPlanePos)) { controller._looking = true; look3D(controller, startPosition, movement); Cartesian2_default.clone(startPosition, controller._translateMousePosition); return; } const diff = Cartesian3_default.subtract( startPlanePos, endPlanePos, translateCVDifference ); const temp = diff.x; diff.x = diff.y; diff.y = diff.z; diff.z = temp; const mag = Cartesian3_default.magnitude(diff); if (mag > Math_default.EPSILON6) { Cartesian3_default.normalize(diff, diff); camera.move(diff, mag); } } var rotateCVWindowPos = new Cartesian2_default(); var rotateCVWindowRay = new Ray_default(); var rotateCVCenter = new Cartesian3_default(); var rotateCVVerticalCenter = new Cartesian3_default(); var rotateCVTransform = new Matrix4_default(); var rotateCVVerticalTransform = new Matrix4_default(); var rotateCVOrigin = new Cartesian3_default(); var rotateCVPlane = new Plane_default(Cartesian3_default.UNIT_X, 0); var rotateCVCartesian3 = new Cartesian3_default(); var rotateCVCart = new Cartographic_default(); var rotateCVOldTransform = new Matrix4_default(); var rotateCVQuaternion = new Quaternion_default(); var rotateCVMatrix = new Matrix3_default(); var tilt3DCartesian3 = new Cartesian3_default(); function rotateCV(controller, startPosition, movement) { if (defined_default(movement.angleAndHeight)) { movement = movement.angleAndHeight; } if (!Cartesian2_default.equals(startPosition, controller._tiltCenterMousePosition)) { controller._tiltCVOffMap = false; controller._looking = false; } if (controller._looking) { look3D(controller, startPosition, movement); return; } const scene = controller._scene; const camera = scene.camera; if (controller._tiltCVOffMap || !controller.onMap() || Math.abs(camera.position.z) > controller._minimumPickingTerrainHeight) { controller._tiltCVOffMap = true; rotateCVOnPlane(controller, startPosition, movement); } else { rotateCVOnTerrain(controller, startPosition, movement); } } function rotateCVOnPlane(controller, startPosition, movement) { const scene = controller._scene; const camera = scene.camera; const canvas = scene.canvas; const windowPosition = rotateCVWindowPos; windowPosition.x = canvas.clientWidth / 2; windowPosition.y = canvas.clientHeight / 2; const ray = camera.getPickRay(windowPosition, rotateCVWindowRay); const normal2 = Cartesian3_default.UNIT_X; const position = ray.origin; const direction2 = ray.direction; let scalar; const normalDotDirection = Cartesian3_default.dot(normal2, direction2); if (Math.abs(normalDotDirection) > Math_default.EPSILON6) { scalar = -Cartesian3_default.dot(normal2, position) / normalDotDirection; } if (!defined_default(scalar) || scalar <= 0) { controller._looking = true; look3D(controller, startPosition, movement); Cartesian2_default.clone(startPosition, controller._tiltCenterMousePosition); return; } const center = Cartesian3_default.multiplyByScalar(direction2, scalar, rotateCVCenter); Cartesian3_default.add(position, center, center); const projection = scene.mapProjection; const ellipsoid = projection.ellipsoid; Cartesian3_default.fromElements(center.y, center.z, center.x, center); const cart = projection.unproject(center, rotateCVCart); ellipsoid.cartographicToCartesian(cart, center); const transform3 = Transforms_default.eastNorthUpToFixedFrame( center, ellipsoid, rotateCVTransform ); const oldGlobe = controller._globe; const oldEllipsoid = controller._ellipsoid; controller._globe = void 0; controller._ellipsoid = Ellipsoid_default.UNIT_SPHERE; controller._rotateFactor = 1; controller._rotateRateRangeAdjustment = 1; const oldTransform = Matrix4_default.clone(camera.transform, rotateCVOldTransform); camera._setTransform(transform3); rotate3D(controller, startPosition, movement, Cartesian3_default.UNIT_Z); camera._setTransform(oldTransform); controller._globe = oldGlobe; controller._ellipsoid = oldEllipsoid; const radius = oldEllipsoid.maximumRadius; controller._rotateFactor = 1 / radius; controller._rotateRateRangeAdjustment = radius; } function rotateCVOnTerrain(controller, startPosition, movement) { const scene = controller._scene; const camera = scene.camera; const cameraUnderground = controller._cameraUnderground; let center; let ray; const normal2 = Cartesian3_default.UNIT_X; if (Cartesian2_default.equals(startPosition, controller._tiltCenterMousePosition)) { center = Cartesian3_default.clone(controller._tiltCenter, rotateCVCenter); } else { if (camera.position.z < controller._minimumPickingTerrainHeight) { center = pickGlobe(controller, startPosition, rotateCVCenter); } if (!defined_default(center)) { ray = camera.getPickRay(startPosition, rotateCVWindowRay); const position = ray.origin; const direction2 = ray.direction; let scalar; const normalDotDirection = Cartesian3_default.dot(normal2, direction2); if (Math.abs(normalDotDirection) > Math_default.EPSILON6) { scalar = -Cartesian3_default.dot(normal2, position) / normalDotDirection; } if (!defined_default(scalar) || scalar <= 0) { controller._looking = true; look3D(controller, startPosition, movement); Cartesian2_default.clone(startPosition, controller._tiltCenterMousePosition); return; } center = Cartesian3_default.multiplyByScalar(direction2, scalar, rotateCVCenter); Cartesian3_default.add(position, center, center); } if (cameraUnderground) { if (!defined_default(ray)) { ray = camera.getPickRay(startPosition, rotateCVWindowRay); } getTiltCenterUnderground(controller, ray, center, center); } Cartesian2_default.clone(startPosition, controller._tiltCenterMousePosition); Cartesian3_default.clone(center, controller._tiltCenter); } const canvas = scene.canvas; const windowPosition = rotateCVWindowPos; windowPosition.x = canvas.clientWidth / 2; windowPosition.y = controller._tiltCenterMousePosition.y; ray = camera.getPickRay(windowPosition, rotateCVWindowRay); const origin = Cartesian3_default.clone(Cartesian3_default.ZERO, rotateCVOrigin); origin.x = center.x; const plane = Plane_default.fromPointNormal(origin, normal2, rotateCVPlane); const verticalCenter = IntersectionTests_default.rayPlane( ray, plane, rotateCVVerticalCenter ); const projection = camera._projection; const ellipsoid = projection.ellipsoid; Cartesian3_default.fromElements(center.y, center.z, center.x, center); let cart = projection.unproject(center, rotateCVCart); ellipsoid.cartographicToCartesian(cart, center); const transform3 = Transforms_default.eastNorthUpToFixedFrame( center, ellipsoid, rotateCVTransform ); let verticalTransform; if (defined_default(verticalCenter)) { Cartesian3_default.fromElements( verticalCenter.y, verticalCenter.z, verticalCenter.x, verticalCenter ); cart = projection.unproject(verticalCenter, rotateCVCart); ellipsoid.cartographicToCartesian(cart, verticalCenter); verticalTransform = Transforms_default.eastNorthUpToFixedFrame( verticalCenter, ellipsoid, rotateCVVerticalTransform ); } else { verticalTransform = transform3; } const oldGlobe = controller._globe; const oldEllipsoid = controller._ellipsoid; controller._globe = void 0; controller._ellipsoid = Ellipsoid_default.UNIT_SPHERE; controller._rotateFactor = 1; controller._rotateRateRangeAdjustment = 1; let constrainedAxis = Cartesian3_default.UNIT_Z; const oldTransform = Matrix4_default.clone(camera.transform, rotateCVOldTransform); camera._setTransform(transform3); const tangent = Cartesian3_default.cross( Cartesian3_default.UNIT_Z, Cartesian3_default.normalize(camera.position, rotateCVCartesian3), rotateCVCartesian3 ); const dot2 = Cartesian3_default.dot(camera.right, tangent); rotate3D(controller, startPosition, movement, constrainedAxis, false, true); camera._setTransform(verticalTransform); if (dot2 < 0) { const movementDelta = movement.startPosition.y - movement.endPosition.y; if (cameraUnderground && movementDelta < 0 || !cameraUnderground && movementDelta > 0) { constrainedAxis = void 0; } const oldConstrainedAxis = camera.constrainedAxis; camera.constrainedAxis = void 0; rotate3D(controller, startPosition, movement, constrainedAxis, true, false); camera.constrainedAxis = oldConstrainedAxis; } else { rotate3D(controller, startPosition, movement, constrainedAxis, true, false); } if (defined_default(camera.constrainedAxis)) { const right = Cartesian3_default.cross( camera.direction, camera.constrainedAxis, tilt3DCartesian3 ); if (!Cartesian3_default.equalsEpsilon(right, Cartesian3_default.ZERO, Math_default.EPSILON6)) { if (Cartesian3_default.dot(right, camera.right) < 0) { Cartesian3_default.negate(right, right); } Cartesian3_default.cross(right, camera.direction, camera.up); Cartesian3_default.cross(camera.direction, camera.up, camera.right); Cartesian3_default.normalize(camera.up, camera.up); Cartesian3_default.normalize(camera.right, camera.right); } } camera._setTransform(oldTransform); controller._globe = oldGlobe; controller._ellipsoid = oldEllipsoid; const radius = oldEllipsoid.maximumRadius; controller._rotateFactor = 1 / radius; controller._rotateRateRangeAdjustment = radius; const originalPosition = Cartesian3_default.clone( camera.positionWC, rotateCVCartesian3 ); if (controller.enableCollisionDetection) { adjustHeightForTerrain(controller); } if (!Cartesian3_default.equals(camera.positionWC, originalPosition)) { camera._setTransform(verticalTransform); camera.worldToCameraCoordinatesPoint(originalPosition, originalPosition); const magSqrd = Cartesian3_default.magnitudeSquared(originalPosition); if (Cartesian3_default.magnitudeSquared(camera.position) > magSqrd) { Cartesian3_default.normalize(camera.position, camera.position); Cartesian3_default.multiplyByScalar( camera.position, Math.sqrt(magSqrd), camera.position ); } const angle = Cartesian3_default.angleBetween(originalPosition, camera.position); const axis = Cartesian3_default.cross( originalPosition, camera.position, originalPosition ); Cartesian3_default.normalize(axis, axis); const quaternion = Quaternion_default.fromAxisAngle( axis, angle, rotateCVQuaternion ); const rotation = Matrix3_default.fromQuaternion(quaternion, rotateCVMatrix); Matrix3_default.multiplyByVector(rotation, camera.direction, camera.direction); Matrix3_default.multiplyByVector(rotation, camera.up, camera.up); Cartesian3_default.cross(camera.direction, camera.up, camera.right); Cartesian3_default.cross(camera.right, camera.direction, camera.up); camera._setTransform(oldTransform); } } var zoomCVWindowPos = new Cartesian2_default(); var zoomCVWindowRay = new Ray_default(); var zoomCVIntersection = new Cartesian3_default(); function zoomCV(controller, startPosition, movement) { if (defined_default(movement.distance)) { movement = movement.distance; } const scene = controller._scene; const camera = scene.camera; const canvas = scene.canvas; const cameraUnderground = controller._cameraUnderground; let windowPosition; if (cameraUnderground) { windowPosition = startPosition; } else { windowPosition = zoomCVWindowPos; windowPosition.x = canvas.clientWidth / 2; windowPosition.y = canvas.clientHeight / 2; } const ray = camera.getPickRay(windowPosition, zoomCVWindowRay); const position = ray.origin; const direction2 = ray.direction; const height = camera.position.z; let intersection; if (height < controller._minimumPickingTerrainHeight) { intersection = pickGlobe(controller, windowPosition, zoomCVIntersection); } let distance2; if (defined_default(intersection)) { distance2 = Cartesian3_default.distance(position, intersection); } if (cameraUnderground) { const distanceUnderground = getZoomDistanceUnderground( controller, ray, height ); if (defined_default(distance2)) { distance2 = Math.min(distance2, distanceUnderground); } else { distance2 = distanceUnderground; } } if (!defined_default(distance2)) { const normal2 = Cartesian3_default.UNIT_X; distance2 = -Cartesian3_default.dot(normal2, position) / Cartesian3_default.dot(normal2, direction2); } handleZoom( controller, startPosition, movement, controller._zoomFactor, distance2 ); } function updateCV(controller) { const scene = controller._scene; const camera = scene.camera; if (!Matrix4_default.equals(Matrix4_default.IDENTITY, camera.transform)) { reactToInput( controller, controller.enableRotate, controller.rotateEventTypes, rotate3D, controller.inertiaSpin, "_lastInertiaSpinMovement" ); reactToInput( controller, controller.enableZoom, controller.zoomEventTypes, zoom3D2, controller.inertiaZoom, "_lastInertiaZoomMovement" ); } else { const tweens = controller._tweens; if (controller._aggregator.anyButtonDown) { tweens.removeAll(); } reactToInput( controller, controller.enableTilt, controller.tiltEventTypes, rotateCV, controller.inertiaSpin, "_lastInertiaTiltMovement" ); reactToInput( controller, controller.enableTranslate, controller.translateEventTypes, translateCV, controller.inertiaTranslate, "_lastInertiaTranslateMovement" ); reactToInput( controller, controller.enableZoom, controller.zoomEventTypes, zoomCV, controller.inertiaZoom, "_lastInertiaZoomMovement" ); reactToInput( controller, controller.enableLook, controller.lookEventTypes, look3D ); if (!controller._aggregator.anyButtonDown && !tweens.contains(controller._tween)) { const tween = camera.createCorrectPositionTween( controller.bounceAnimationTime ); if (defined_default(tween)) { controller._tween = tweens.add(tween); } } tweens.update(); } } var scratchStrafeRay = new Ray_default(); var scratchStrafePlane = new Plane_default(Cartesian3_default.UNIT_X, 0); var scratchStrafeIntersection = new Cartesian3_default(); var scratchStrafeDirection = new Cartesian3_default(); var scratchMousePos = new Cartesian3_default(); function strafe(controller, movement, strafeStartPosition) { const scene = controller._scene; const camera = scene.camera; const ray = camera.getPickRay(movement.endPosition, scratchStrafeRay); let direction2 = Cartesian3_default.clone(camera.direction, scratchStrafeDirection); if (scene.mode === SceneMode_default.COLUMBUS_VIEW) { Cartesian3_default.fromElements(direction2.z, direction2.x, direction2.y, direction2); } const plane = Plane_default.fromPointNormal( strafeStartPosition, direction2, scratchStrafePlane ); const intersection = IntersectionTests_default.rayPlane( ray, plane, scratchStrafeIntersection ); if (!defined_default(intersection)) { return; } direction2 = Cartesian3_default.subtract(strafeStartPosition, intersection, direction2); if (scene.mode === SceneMode_default.COLUMBUS_VIEW) { Cartesian3_default.fromElements(direction2.y, direction2.z, direction2.x, direction2); } Cartesian3_default.add(camera.position, direction2, camera.position); } var spin3DPick = new Cartesian3_default(); var scratchCartographic21 = new Cartographic_default(); var scratchRadii3 = new Cartesian3_default(); var scratchEllipsoid15 = new Ellipsoid_default(); var scratchLookUp = new Cartesian3_default(); var scratchNormal8 = new Cartesian3_default(); function spin3D(controller, startPosition, movement) { const scene = controller._scene; const camera = scene.camera; const cameraUnderground = controller._cameraUnderground; let ellipsoid = controller._ellipsoid; if (!Matrix4_default.equals(camera.transform, Matrix4_default.IDENTITY)) { rotate3D(controller, startPosition, movement); return; } let magnitude; let radii; const up = ellipsoid.geodeticSurfaceNormal(camera.position, scratchLookUp); if (Cartesian2_default.equals(startPosition, controller._rotateMousePosition)) { if (controller._looking) { look3D(controller, startPosition, movement, up); } else if (controller._rotating) { rotate3D(controller, startPosition, movement); } else if (controller._strafing) { continueStrafing(controller, movement); } else { if (Cartesian3_default.magnitude(camera.position) < Cartesian3_default.magnitude(controller._rotateStartPosition)) { return; } magnitude = Cartesian3_default.magnitude(controller._rotateStartPosition); radii = scratchRadii3; radii.x = radii.y = radii.z = magnitude; ellipsoid = Ellipsoid_default.fromCartesian3(radii, scratchEllipsoid15); pan3D(controller, startPosition, movement, ellipsoid); } return; } controller._looking = false; controller._rotating = false; controller._strafing = false; const height = ellipsoid.cartesianToCartographic( camera.positionWC, scratchCartographic21 ).height; const globe = controller._globe; if (defined_default(globe) && height < controller._minimumPickingTerrainHeight) { const mousePos = pickGlobe( controller, movement.startPosition, scratchMousePos ); if (defined_default(mousePos)) { let strafing = false; const ray = camera.getPickRay( movement.startPosition, pickGlobeScratchRay ); if (cameraUnderground) { strafing = true; getStrafeStartPositionUnderground(controller, ray, mousePos, mousePos); } else { const normal2 = ellipsoid.geodeticSurfaceNormal(mousePos, scratchNormal8); const tangentPick = Math.abs(Cartesian3_default.dot(ray.direction, normal2)) < 0.05; if (tangentPick) { strafing = true; } else { strafing = Cartesian3_default.magnitude(camera.position) < Cartesian3_default.magnitude(mousePos); } } if (strafing) { Cartesian2_default.clone(startPosition, controller._strafeEndMousePosition); Cartesian3_default.clone(mousePos, controller._strafeStartPosition); controller._strafing = true; strafe(controller, movement, controller._strafeStartPosition); } else { magnitude = Cartesian3_default.magnitude(mousePos); radii = scratchRadii3; radii.x = radii.y = radii.z = magnitude; ellipsoid = Ellipsoid_default.fromCartesian3(radii, scratchEllipsoid15); pan3D(controller, startPosition, movement, ellipsoid); Cartesian3_default.clone(mousePos, controller._rotateStartPosition); } } else { controller._looking = true; look3D(controller, startPosition, movement, up); } } else if (defined_default( camera.pickEllipsoid( movement.startPosition, controller._ellipsoid, spin3DPick ) )) { pan3D(controller, startPosition, movement, controller._ellipsoid); Cartesian3_default.clone(spin3DPick, controller._rotateStartPosition); } else if (height > controller._minimumTrackBallHeight) { controller._rotating = true; rotate3D(controller, startPosition, movement); } else { controller._looking = true; look3D(controller, startPosition, movement, up); } Cartesian2_default.clone(startPosition, controller._rotateMousePosition); } function rotate3D(controller, startPosition, movement, constrainedAxis, rotateOnlyVertical, rotateOnlyHorizontal) { rotateOnlyVertical = defaultValue_default(rotateOnlyVertical, false); rotateOnlyHorizontal = defaultValue_default(rotateOnlyHorizontal, false); const scene = controller._scene; const camera = scene.camera; const canvas = scene.canvas; const oldAxis = camera.constrainedAxis; if (defined_default(constrainedAxis)) { camera.constrainedAxis = constrainedAxis; } const rho = Cartesian3_default.magnitude(camera.position); let rotateRate = controller._rotateFactor * (rho - controller._rotateRateRangeAdjustment); if (rotateRate > controller._maximumRotateRate) { rotateRate = controller._maximumRotateRate; } if (rotateRate < controller._minimumRotateRate) { rotateRate = controller._minimumRotateRate; } let phiWindowRatio = (movement.startPosition.x - movement.endPosition.x) / canvas.clientWidth; let thetaWindowRatio = (movement.startPosition.y - movement.endPosition.y) / canvas.clientHeight; phiWindowRatio = Math.min(phiWindowRatio, controller.maximumMovementRatio); thetaWindowRatio = Math.min( thetaWindowRatio, controller.maximumMovementRatio ); const deltaPhi = rotateRate * phiWindowRatio * Math.PI * 2; const deltaTheta = rotateRate * thetaWindowRatio * Math.PI; if (!rotateOnlyVertical) { camera.rotateRight(deltaPhi); } if (!rotateOnlyHorizontal) { camera.rotateUp(deltaTheta); } camera.constrainedAxis = oldAxis; } var pan3DP0 = Cartesian4_default.clone(Cartesian4_default.UNIT_W); var pan3DP1 = Cartesian4_default.clone(Cartesian4_default.UNIT_W); var pan3DTemp0 = new Cartesian3_default(); var pan3DTemp1 = new Cartesian3_default(); var pan3DTemp2 = new Cartesian3_default(); var pan3DTemp3 = new Cartesian3_default(); var pan3DStartMousePosition = new Cartesian2_default(); var pan3DEndMousePosition = new Cartesian2_default(); function pan3D(controller, startPosition, movement, ellipsoid) { const scene = controller._scene; const camera = scene.camera; const startMousePosition = Cartesian2_default.clone( movement.startPosition, pan3DStartMousePosition ); const endMousePosition = Cartesian2_default.clone( movement.endPosition, pan3DEndMousePosition ); let p0 = camera.pickEllipsoid(startMousePosition, ellipsoid, pan3DP0); let p1 = camera.pickEllipsoid(endMousePosition, ellipsoid, pan3DP1); if (!defined_default(p0) || !defined_default(p1)) { controller._rotating = true; rotate3D(controller, startPosition, movement); return; } p0 = camera.worldToCameraCoordinates(p0, p0); p1 = camera.worldToCameraCoordinates(p1, p1); if (!defined_default(camera.constrainedAxis)) { Cartesian3_default.normalize(p0, p0); Cartesian3_default.normalize(p1, p1); const dot2 = Cartesian3_default.dot(p0, p1); const axis = Cartesian3_default.cross(p0, p1, pan3DTemp0); if (dot2 < 1 && !Cartesian3_default.equalsEpsilon(axis, Cartesian3_default.ZERO, Math_default.EPSILON14)) { const angle = Math.acos(dot2); camera.rotate(axis, angle); } } else { const basis0 = camera.constrainedAxis; const basis1 = Cartesian3_default.mostOrthogonalAxis(basis0, pan3DTemp0); Cartesian3_default.cross(basis1, basis0, basis1); Cartesian3_default.normalize(basis1, basis1); const basis2 = Cartesian3_default.cross(basis0, basis1, pan3DTemp1); const startRho = Cartesian3_default.magnitude(p0); const startDot = Cartesian3_default.dot(basis0, p0); const startTheta = Math.acos(startDot / startRho); const startRej = Cartesian3_default.multiplyByScalar(basis0, startDot, pan3DTemp2); Cartesian3_default.subtract(p0, startRej, startRej); Cartesian3_default.normalize(startRej, startRej); const endRho = Cartesian3_default.magnitude(p1); const endDot = Cartesian3_default.dot(basis0, p1); const endTheta = Math.acos(endDot / endRho); const endRej = Cartesian3_default.multiplyByScalar(basis0, endDot, pan3DTemp3); Cartesian3_default.subtract(p1, endRej, endRej); Cartesian3_default.normalize(endRej, endRej); let startPhi = Math.acos(Cartesian3_default.dot(startRej, basis1)); if (Cartesian3_default.dot(startRej, basis2) < 0) { startPhi = Math_default.TWO_PI - startPhi; } let endPhi = Math.acos(Cartesian3_default.dot(endRej, basis1)); if (Cartesian3_default.dot(endRej, basis2) < 0) { endPhi = Math_default.TWO_PI - endPhi; } const deltaPhi = startPhi - endPhi; let east; if (Cartesian3_default.equalsEpsilon(basis0, camera.position, Math_default.EPSILON2)) { east = camera.right; } else { east = Cartesian3_default.cross(basis0, camera.position, pan3DTemp0); } const planeNormal = Cartesian3_default.cross(basis0, east, pan3DTemp0); const side0 = Cartesian3_default.dot( planeNormal, Cartesian3_default.subtract(p0, basis0, pan3DTemp1) ); const side1 = Cartesian3_default.dot( planeNormal, Cartesian3_default.subtract(p1, basis0, pan3DTemp1) ); let deltaTheta; if (side0 > 0 && side1 > 0) { deltaTheta = endTheta - startTheta; } else if (side0 > 0 && side1 <= 0) { if (Cartesian3_default.dot(camera.position, basis0) > 0) { deltaTheta = -startTheta - endTheta; } else { deltaTheta = startTheta + endTheta; } } else { deltaTheta = startTheta - endTheta; } camera.rotateRight(deltaPhi); camera.rotateUp(deltaTheta); } } var zoom3DUnitPosition = new Cartesian3_default(); var zoom3DCartographic = new Cartographic_default(); var preIntersectionDistance = 0; function zoom3D2(controller, startPosition, movement) { if (defined_default(movement.distance)) { movement = movement.distance; } const inertiaMovement = movement.inertiaEnabled; const ellipsoid = controller._ellipsoid; const scene = controller._scene; const camera = scene.camera; const canvas = scene.canvas; const cameraUnderground = controller._cameraUnderground; let windowPosition; if (cameraUnderground) { windowPosition = startPosition; } else { windowPosition = zoomCVWindowPos; windowPosition.x = canvas.clientWidth / 2; windowPosition.y = canvas.clientHeight / 2; } const ray = camera.getPickRay(windowPosition, zoomCVWindowRay); let intersection; const height = ellipsoid.cartesianToCartographic( camera.position, zoom3DCartographic ).height; const approachingCollision = Math.abs(preIntersectionDistance) < controller.minimumPickingTerrainDistanceWithInertia; const needPickGlobe = inertiaMovement ? approachingCollision : height < controller._minimumPickingTerrainHeight; if (needPickGlobe) { intersection = pickGlobe(controller, windowPosition, zoomCVIntersection); } let distance2; if (defined_default(intersection)) { distance2 = Cartesian3_default.distance(ray.origin, intersection); preIntersectionDistance = distance2; } if (cameraUnderground) { const distanceUnderground = getZoomDistanceUnderground( controller, ray, height ); if (defined_default(distance2)) { distance2 = Math.min(distance2, distanceUnderground); } else { distance2 = distanceUnderground; } } if (!defined_default(distance2)) { distance2 = height; } const unitPosition = Cartesian3_default.normalize( camera.position, zoom3DUnitPosition ); handleZoom( controller, startPosition, movement, controller._zoomFactor, distance2, Cartesian3_default.dot(unitPosition, camera.direction) ); } var tilt3DWindowPos = new Cartesian2_default(); var tilt3DRay = new Ray_default(); var tilt3DCenter = new Cartesian3_default(); var tilt3DVerticalCenter = new Cartesian3_default(); var tilt3DTransform = new Matrix4_default(); var tilt3DVerticalTransform = new Matrix4_default(); var tilt3DOldTransform = new Matrix4_default(); var tilt3DQuaternion = new Quaternion_default(); var tilt3DMatrix = new Matrix3_default(); var tilt3DCart = new Cartographic_default(); var tilt3DLookUp = new Cartesian3_default(); function tilt3D(controller, startPosition, movement) { const scene = controller._scene; const camera = scene.camera; if (!Matrix4_default.equals(camera.transform, Matrix4_default.IDENTITY)) { return; } if (defined_default(movement.angleAndHeight)) { movement = movement.angleAndHeight; } if (!Cartesian2_default.equals(startPosition, controller._tiltCenterMousePosition)) { controller._tiltOnEllipsoid = false; controller._looking = false; } if (controller._looking) { const up = controller._ellipsoid.geodeticSurfaceNormal( camera.position, tilt3DLookUp ); look3D(controller, startPosition, movement, up); return; } const ellipsoid = controller._ellipsoid; const cartographic2 = ellipsoid.cartesianToCartographic( camera.position, tilt3DCart ); if (controller._tiltOnEllipsoid || cartographic2.height > controller._minimumCollisionTerrainHeight) { controller._tiltOnEllipsoid = true; tilt3DOnEllipsoid(controller, startPosition, movement); } else { tilt3DOnTerrain(controller, startPosition, movement); } } var tilt3DOnEllipsoidCartographic = new Cartographic_default(); function tilt3DOnEllipsoid(controller, startPosition, movement) { const ellipsoid = controller._ellipsoid; const scene = controller._scene; const camera = scene.camera; const minHeight = controller.minimumZoomDistance * 0.25; const height = ellipsoid.cartesianToCartographic( camera.positionWC, tilt3DOnEllipsoidCartographic ).height; if (height - minHeight - 1 < Math_default.EPSILON3 && movement.endPosition.y - movement.startPosition.y < 0) { return; } const canvas = scene.canvas; const windowPosition = tilt3DWindowPos; windowPosition.x = canvas.clientWidth / 2; windowPosition.y = canvas.clientHeight / 2; const ray = camera.getPickRay(windowPosition, tilt3DRay); let center; const intersection = IntersectionTests_default.rayEllipsoid(ray, ellipsoid); if (defined_default(intersection)) { center = Ray_default.getPoint(ray, intersection.start, tilt3DCenter); } else if (height > controller._minimumTrackBallHeight) { const grazingAltitudeLocation = IntersectionTests_default.grazingAltitudeLocation( ray, ellipsoid ); if (!defined_default(grazingAltitudeLocation)) { return; } const grazingAltitudeCart = ellipsoid.cartesianToCartographic( grazingAltitudeLocation, tilt3DCart ); grazingAltitudeCart.height = 0; center = ellipsoid.cartographicToCartesian( grazingAltitudeCart, tilt3DCenter ); } else { controller._looking = true; const up = controller._ellipsoid.geodeticSurfaceNormal( camera.position, tilt3DLookUp ); look3D(controller, startPosition, movement, up); Cartesian2_default.clone(startPosition, controller._tiltCenterMousePosition); return; } const transform3 = Transforms_default.eastNorthUpToFixedFrame( center, ellipsoid, tilt3DTransform ); const oldGlobe = controller._globe; const oldEllipsoid = controller._ellipsoid; controller._globe = void 0; controller._ellipsoid = Ellipsoid_default.UNIT_SPHERE; controller._rotateFactor = 1; controller._rotateRateRangeAdjustment = 1; const oldTransform = Matrix4_default.clone(camera.transform, tilt3DOldTransform); camera._setTransform(transform3); rotate3D(controller, startPosition, movement, Cartesian3_default.UNIT_Z); camera._setTransform(oldTransform); controller._globe = oldGlobe; controller._ellipsoid = oldEllipsoid; const radius = oldEllipsoid.maximumRadius; controller._rotateFactor = 1 / radius; controller._rotateRateRangeAdjustment = radius; } function tilt3DOnTerrain(controller, startPosition, movement) { const ellipsoid = controller._ellipsoid; const scene = controller._scene; const camera = scene.camera; const cameraUnderground = controller._cameraUnderground; let center; let ray; let intersection; if (Cartesian2_default.equals(startPosition, controller._tiltCenterMousePosition)) { center = Cartesian3_default.clone(controller._tiltCenter, tilt3DCenter); } else { center = pickGlobe(controller, startPosition, tilt3DCenter); if (!defined_default(center)) { ray = camera.getPickRay(startPosition, tilt3DRay); intersection = IntersectionTests_default.rayEllipsoid(ray, ellipsoid); if (!defined_default(intersection)) { const cartographic2 = ellipsoid.cartesianToCartographic( camera.position, tilt3DCart ); if (cartographic2.height <= controller._minimumTrackBallHeight) { controller._looking = true; const up = controller._ellipsoid.geodeticSurfaceNormal( camera.position, tilt3DLookUp ); look3D(controller, startPosition, movement, up); Cartesian2_default.clone(startPosition, controller._tiltCenterMousePosition); } return; } center = Ray_default.getPoint(ray, intersection.start, tilt3DCenter); } if (cameraUnderground) { if (!defined_default(ray)) { ray = camera.getPickRay(startPosition, tilt3DRay); } getTiltCenterUnderground(controller, ray, center, center); } Cartesian2_default.clone(startPosition, controller._tiltCenterMousePosition); Cartesian3_default.clone(center, controller._tiltCenter); } const canvas = scene.canvas; const windowPosition = tilt3DWindowPos; windowPosition.x = canvas.clientWidth / 2; windowPosition.y = controller._tiltCenterMousePosition.y; ray = camera.getPickRay(windowPosition, tilt3DRay); const mag = Cartesian3_default.magnitude(center); const radii = Cartesian3_default.fromElements(mag, mag, mag, scratchRadii3); const newEllipsoid = Ellipsoid_default.fromCartesian3(radii, scratchEllipsoid15); intersection = IntersectionTests_default.rayEllipsoid(ray, newEllipsoid); if (!defined_default(intersection)) { return; } const t = Cartesian3_default.magnitude(ray.origin) > mag ? intersection.start : intersection.stop; const verticalCenter = Ray_default.getPoint(ray, t, tilt3DVerticalCenter); const transform3 = Transforms_default.eastNorthUpToFixedFrame( center, ellipsoid, tilt3DTransform ); const verticalTransform = Transforms_default.eastNorthUpToFixedFrame( verticalCenter, newEllipsoid, tilt3DVerticalTransform ); const oldGlobe = controller._globe; const oldEllipsoid = controller._ellipsoid; controller._globe = void 0; controller._ellipsoid = Ellipsoid_default.UNIT_SPHERE; controller._rotateFactor = 1; controller._rotateRateRangeAdjustment = 1; let constrainedAxis = Cartesian3_default.UNIT_Z; const oldTransform = Matrix4_default.clone(camera.transform, tilt3DOldTransform); camera._setTransform(verticalTransform); const tangent = Cartesian3_default.cross( verticalCenter, camera.positionWC, tilt3DCartesian3 ); const dot2 = Cartesian3_default.dot(camera.rightWC, tangent); if (dot2 < 0) { const movementDelta = movement.startPosition.y - movement.endPosition.y; if (cameraUnderground && movementDelta < 0 || !cameraUnderground && movementDelta > 0) { constrainedAxis = void 0; } const oldConstrainedAxis = camera.constrainedAxis; camera.constrainedAxis = void 0; rotate3D(controller, startPosition, movement, constrainedAxis, true, false); camera.constrainedAxis = oldConstrainedAxis; } else { rotate3D(controller, startPosition, movement, constrainedAxis, true, false); } camera._setTransform(transform3); rotate3D(controller, startPosition, movement, constrainedAxis, false, true); if (defined_default(camera.constrainedAxis)) { const right = Cartesian3_default.cross( camera.direction, camera.constrainedAxis, tilt3DCartesian3 ); if (!Cartesian3_default.equalsEpsilon(right, Cartesian3_default.ZERO, Math_default.EPSILON6)) { if (Cartesian3_default.dot(right, camera.right) < 0) { Cartesian3_default.negate(right, right); } Cartesian3_default.cross(right, camera.direction, camera.up); Cartesian3_default.cross(camera.direction, camera.up, camera.right); Cartesian3_default.normalize(camera.up, camera.up); Cartesian3_default.normalize(camera.right, camera.right); } } camera._setTransform(oldTransform); controller._globe = oldGlobe; controller._ellipsoid = oldEllipsoid; const radius = oldEllipsoid.maximumRadius; controller._rotateFactor = 1 / radius; controller._rotateRateRangeAdjustment = radius; const originalPosition = Cartesian3_default.clone( camera.positionWC, tilt3DCartesian3 ); if (controller.enableCollisionDetection) { adjustHeightForTerrain(controller); } if (!Cartesian3_default.equals(camera.positionWC, originalPosition)) { camera._setTransform(verticalTransform); camera.worldToCameraCoordinatesPoint(originalPosition, originalPosition); const magSqrd = Cartesian3_default.magnitudeSquared(originalPosition); if (Cartesian3_default.magnitudeSquared(camera.position) > magSqrd) { Cartesian3_default.normalize(camera.position, camera.position); Cartesian3_default.multiplyByScalar( camera.position, Math.sqrt(magSqrd), camera.position ); } const angle = Cartesian3_default.angleBetween(originalPosition, camera.position); const axis = Cartesian3_default.cross( originalPosition, camera.position, originalPosition ); Cartesian3_default.normalize(axis, axis); const quaternion = Quaternion_default.fromAxisAngle(axis, angle, tilt3DQuaternion); const rotation = Matrix3_default.fromQuaternion(quaternion, tilt3DMatrix); Matrix3_default.multiplyByVector(rotation, camera.direction, camera.direction); Matrix3_default.multiplyByVector(rotation, camera.up, camera.up); Cartesian3_default.cross(camera.direction, camera.up, camera.right); Cartesian3_default.cross(camera.right, camera.direction, camera.up); camera._setTransform(oldTransform); } } var look3DStartPos = new Cartesian2_default(); var look3DEndPos = new Cartesian2_default(); var look3DStartRay = new Ray_default(); var look3DEndRay = new Ray_default(); var look3DNegativeRot = new Cartesian3_default(); var look3DTan = new Cartesian3_default(); function look3D(controller, startPosition, movement, rotationAxis) { const scene = controller._scene; const camera = scene.camera; const startPos = look3DStartPos; startPos.x = movement.startPosition.x; startPos.y = 0; const endPos = look3DEndPos; endPos.x = movement.endPosition.x; endPos.y = 0; let startRay = camera.getPickRay(startPos, look3DStartRay); let endRay = camera.getPickRay(endPos, look3DEndRay); let angle = 0; let start; let end; if (camera.frustum instanceof OrthographicFrustum_default) { start = startRay.origin; end = endRay.origin; Cartesian3_default.add(camera.direction, start, start); Cartesian3_default.add(camera.direction, end, end); Cartesian3_default.subtract(start, camera.position, start); Cartesian3_default.subtract(end, camera.position, end); Cartesian3_default.normalize(start, start); Cartesian3_default.normalize(end, end); } else { start = startRay.direction; end = endRay.direction; } let dot2 = Cartesian3_default.dot(start, end); if (dot2 < 1) { angle = Math.acos(dot2); } angle = movement.startPosition.x > movement.endPosition.x ? -angle : angle; const horizontalRotationAxis = controller._horizontalRotationAxis; if (defined_default(rotationAxis)) { camera.look(rotationAxis, -angle); } else if (defined_default(horizontalRotationAxis)) { camera.look(horizontalRotationAxis, -angle); } else { camera.lookLeft(angle); } startPos.x = 0; startPos.y = movement.startPosition.y; endPos.x = 0; endPos.y = movement.endPosition.y; startRay = camera.getPickRay(startPos, look3DStartRay); endRay = camera.getPickRay(endPos, look3DEndRay); angle = 0; if (camera.frustum instanceof OrthographicFrustum_default) { start = startRay.origin; end = endRay.origin; Cartesian3_default.add(camera.direction, start, start); Cartesian3_default.add(camera.direction, end, end); Cartesian3_default.subtract(start, camera.position, start); Cartesian3_default.subtract(end, camera.position, end); Cartesian3_default.normalize(start, start); Cartesian3_default.normalize(end, end); } else { start = startRay.direction; end = endRay.direction; } dot2 = Cartesian3_default.dot(start, end); if (dot2 < 1) { angle = Math.acos(dot2); } angle = movement.startPosition.y > movement.endPosition.y ? -angle : angle; rotationAxis = defaultValue_default(rotationAxis, horizontalRotationAxis); if (defined_default(rotationAxis)) { const direction2 = camera.direction; const negativeRotationAxis = Cartesian3_default.negate( rotationAxis, look3DNegativeRot ); const northParallel = Cartesian3_default.equalsEpsilon( direction2, rotationAxis, Math_default.EPSILON2 ); const southParallel = Cartesian3_default.equalsEpsilon( direction2, negativeRotationAxis, Math_default.EPSILON2 ); if (!northParallel && !southParallel) { dot2 = Cartesian3_default.dot(direction2, rotationAxis); let angleToAxis = Math_default.acosClamped(dot2); if (angle > 0 && angle > angleToAxis) { angle = angleToAxis - Math_default.EPSILON4; } dot2 = Cartesian3_default.dot(direction2, negativeRotationAxis); angleToAxis = Math_default.acosClamped(dot2); if (angle < 0 && -angle > angleToAxis) { angle = -angleToAxis + Math_default.EPSILON4; } const tangent = Cartesian3_default.cross(rotationAxis, direction2, look3DTan); camera.look(tangent, angle); } else if (northParallel && angle < 0 || southParallel && angle > 0) { camera.look(camera.right, -angle); } } else { camera.lookUp(angle); } } function update3D(controller) { reactToInput( controller, controller.enableRotate, controller.rotateEventTypes, spin3D, controller.inertiaSpin, "_lastInertiaSpinMovement" ); reactToInput( controller, controller.enableZoom, controller.zoomEventTypes, zoom3D2, controller.inertiaZoom, "_lastInertiaZoomMovement" ); reactToInput( controller, controller.enableTilt, controller.tiltEventTypes, tilt3D, controller.inertiaSpin, "_lastInertiaTiltMovement" ); reactToInput( controller, controller.enableLook, controller.lookEventTypes, look3D ); } var scratchAdjustHeightTransform = new Matrix4_default(); var scratchAdjustHeightCartographic = new Cartographic_default(); function adjustHeightForTerrain(controller) { controller._adjustedHeightForTerrain = true; const scene = controller._scene; const mode2 = scene.mode; const globe = scene.globe; if (!defined_default(globe) || mode2 === SceneMode_default.SCENE2D || mode2 === SceneMode_default.MORPHING) { return; } const camera = scene.camera; const ellipsoid = globe.ellipsoid; const projection = scene.mapProjection; let transform3; let mag; if (!Matrix4_default.equals(camera.transform, Matrix4_default.IDENTITY)) { transform3 = Matrix4_default.clone(camera.transform, scratchAdjustHeightTransform); mag = Cartesian3_default.magnitude(camera.position); camera._setTransform(Matrix4_default.IDENTITY); } const cartographic2 = scratchAdjustHeightCartographic; if (mode2 === SceneMode_default.SCENE3D) { ellipsoid.cartesianToCartographic(camera.position, cartographic2); } else { projection.unproject(camera.position, cartographic2); } let heightUpdated = false; if (cartographic2.height < controller._minimumCollisionTerrainHeight) { const globeHeight = controller._scene.globeHeight; if (defined_default(globeHeight)) { const height = globeHeight + controller.minimumZoomDistance; if (cartographic2.height < height) { cartographic2.height = height; if (mode2 === SceneMode_default.SCENE3D) { ellipsoid.cartographicToCartesian(cartographic2, camera.position); } else { projection.project(cartographic2, camera.position); } heightUpdated = true; } } } if (defined_default(transform3)) { camera._setTransform(transform3); if (heightUpdated) { Cartesian3_default.normalize(camera.position, camera.position); Cartesian3_default.negate(camera.position, camera.direction); Cartesian3_default.multiplyByScalar( camera.position, Math.max(mag, controller.minimumZoomDistance), camera.position ); Cartesian3_default.normalize(camera.direction, camera.direction); Cartesian3_default.cross(camera.direction, camera.up, camera.right); Cartesian3_default.cross(camera.right, camera.direction, camera.up); } } } ScreenSpaceCameraController.prototype.onMap = function() { const scene = this._scene; const mode2 = scene.mode; const camera = scene.camera; if (mode2 === SceneMode_default.COLUMBUS_VIEW) { return Math.abs(camera.position.x) - this._maxCoord.x < 0 && Math.abs(camera.position.y) - this._maxCoord.y < 0; } return true; }; var scratchPreviousPosition = new Cartesian3_default(); var scratchPreviousDirection = new Cartesian3_default(); ScreenSpaceCameraController.prototype.update = function() { const scene = this._scene; const camera = scene.camera; const globe = scene.globe; const mode2 = scene.mode; if (!Matrix4_default.equals(camera.transform, Matrix4_default.IDENTITY)) { this._globe = void 0; this._ellipsoid = Ellipsoid_default.UNIT_SPHERE; } else { this._globe = globe; this._ellipsoid = defined_default(this._globe) ? this._globe.ellipsoid : scene.mapProjection.ellipsoid; } const exaggeration = defined_default(this._globe) ? this._globe.terrainExaggeration : 1; const exaggerationRelativeHeight = defined_default(this._globe) ? this._globe.terrainExaggerationRelativeHeight : 0; this._minimumCollisionTerrainHeight = TerrainExaggeration_default.getHeight( this.minimumCollisionTerrainHeight, exaggeration, exaggerationRelativeHeight ); this._minimumPickingTerrainHeight = TerrainExaggeration_default.getHeight( this.minimumPickingTerrainHeight, exaggeration, exaggerationRelativeHeight ); this._minimumTrackBallHeight = TerrainExaggeration_default.getHeight( this.minimumTrackBallHeight, exaggeration, exaggerationRelativeHeight ); this._cameraUnderground = scene.cameraUnderground && defined_default(this._globe); const radius = this._ellipsoid.maximumRadius; this._rotateFactor = 1 / radius; this._rotateRateRangeAdjustment = radius; this._adjustedHeightForTerrain = false; const previousPosition = Cartesian3_default.clone( camera.positionWC, scratchPreviousPosition ); const previousDirection = Cartesian3_default.clone( camera.directionWC, scratchPreviousDirection ); if (mode2 === SceneMode_default.SCENE2D) { update2D(this); } else if (mode2 === SceneMode_default.COLUMBUS_VIEW) { this._horizontalRotationAxis = Cartesian3_default.UNIT_Z; updateCV(this); } else if (mode2 === SceneMode_default.SCENE3D) { this._horizontalRotationAxis = void 0; update3D(this); } if (this.enableCollisionDetection && !this._adjustedHeightForTerrain) { const cameraChanged = !Cartesian3_default.equals(previousPosition, camera.positionWC) || !Cartesian3_default.equals(previousDirection, camera.directionWC); if (cameraChanged) { adjustHeightForTerrain(this); } } this._aggregator.reset(); }; ScreenSpaceCameraController.prototype.isDestroyed = function() { return false; }; ScreenSpaceCameraController.prototype.destroy = function() { this._tweens.removeAll(); this._aggregator = this._aggregator && this._aggregator.destroy(); return destroyObject_default(this); }; var ScreenSpaceCameraController_default = ScreenSpaceCameraController; // packages/engine/Source/Shaders/PostProcessStages/AdditiveBlend.js var AdditiveBlend_default = "uniform sampler2D colorTexture;\nuniform sampler2D colorTexture2;\n\nuniform vec2 center;\nuniform float radius;\n\nin vec2 v_textureCoordinates;\n\nvoid main()\n{\n vec4 color0 = texture(colorTexture, v_textureCoordinates);\n vec4 color1 = texture(colorTexture2, v_textureCoordinates);\n\n float x = length(gl_FragCoord.xy - center) / radius;\n float t = smoothstep(0.5, 0.8, x);\n out_FragColor = mix(color0 + color1, color1, t);\n}\n"; // packages/engine/Source/Shaders/PostProcessStages/BrightPass.js var BrightPass_default = 'uniform sampler2D colorTexture;\n\nuniform float avgLuminance;\nuniform float threshold;\nuniform float offset;\n\nin vec2 v_textureCoordinates;\n\nfloat key(float avg)\n{\n float guess = 1.5 - (1.5 / (avg * 0.1 + 1.0));\n return max(0.0, guess) + 0.1;\n}\n\n// See section 9. "The bright-pass filter" of Realtime HDR Rendering\n// http://www.cg.tuwien.ac.at/research/publications/2007/Luksch_2007_RHR/Luksch_2007_RHR-RealtimeHDR%20.pdf\n\nvoid main()\n{\n vec4 color = texture(colorTexture, v_textureCoordinates);\n vec3 xyz = czm_RGBToXYZ(color.rgb);\n float luminance = xyz.r;\n\n float scaledLum = key(avgLuminance) * luminance / avgLuminance;\n float brightLum = max(scaledLum - threshold, 0.0);\n float brightness = brightLum / (offset + brightLum);\n\n xyz.r = brightness;\n out_FragColor = vec4(czm_XYZToRGB(xyz), 1.0);\n}\n'; // packages/engine/Source/Scene/SunPostProcess.js function SunPostProcess() { this._sceneFramebuffer = new SceneFramebuffer_default(); const scale = 0.125; const stages = new Array(6); stages[0] = new PostProcessStage_default({ fragmentShader: PassThrough_default, textureScale: scale, forcePowerOfTwo: true, sampleMode: PostProcessStageSampleMode_default.LINEAR }); const brightPass = stages[1] = new PostProcessStage_default({ fragmentShader: BrightPass_default, uniforms: { avgLuminance: 0.5, // A guess at the average luminance across the entire scene threshold: 0.25, offset: 0.1 }, textureScale: scale, forcePowerOfTwo: true }); const that = this; this._delta = 1; this._sigma = 2; this._blurStep = new Cartesian2_default(); stages[2] = new PostProcessStage_default({ fragmentShader: GaussianBlur1D_default, uniforms: { step: function() { that._blurStep.x = that._blurStep.y = 1 / brightPass.outputTexture.width; return that._blurStep; }, delta: function() { return that._delta; }, sigma: function() { return that._sigma; }, direction: 0 }, textureScale: scale, forcePowerOfTwo: true }); stages[3] = new PostProcessStage_default({ fragmentShader: GaussianBlur1D_default, uniforms: { step: function() { that._blurStep.x = that._blurStep.y = 1 / brightPass.outputTexture.width; return that._blurStep; }, delta: function() { return that._delta; }, sigma: function() { return that._sigma; }, direction: 1 }, textureScale: scale, forcePowerOfTwo: true }); stages[4] = new PostProcessStage_default({ fragmentShader: PassThrough_default, sampleMode: PostProcessStageSampleMode_default.LINEAR }); this._uCenter = new Cartesian2_default(); this._uRadius = void 0; stages[5] = new PostProcessStage_default({ fragmentShader: AdditiveBlend_default, uniforms: { center: function() { return that._uCenter; }, radius: function() { return that._uRadius; }, colorTexture2: function() { return that._sceneFramebuffer.framebuffer.getColorTexture(0); } } }); this._stages = new PostProcessStageComposite_default({ stages }); const textureCache = new PostProcessStageTextureCache_default(this); const length3 = stages.length; for (let i = 0; i < length3; ++i) { stages[i]._textureCache = textureCache; } this._textureCache = textureCache; this.length = stages.length; } SunPostProcess.prototype.get = function(index) { return this._stages.get(index); }; SunPostProcess.prototype.getStageByName = function(name) { const length3 = this._stages.length; for (let i = 0; i < length3; ++i) { const stage = this._stages.get(i); if (stage.name === name) { return stage; } } return void 0; }; var sunPositionECScratch = new Cartesian4_default(); var sunPositionWCScratch = new Cartesian2_default(); var sizeScratch = new Cartesian2_default(); var postProcessMatrix4Scratch = new Matrix4_default(); function updateSunPosition(postProcess, context, viewport) { const us = context.uniformState; const sunPosition = us.sunPositionWC; const viewMatrix = us.view; const viewProjectionMatrix = us.viewProjection; const projectionMatrix = us.projection; let viewportTransformation = Matrix4_default.computeViewportTransformation( viewport, 0, 1, postProcessMatrix4Scratch ); const sunPositionEC = Matrix4_default.multiplyByPoint( viewMatrix, sunPosition, sunPositionECScratch ); let sunPositionWC = Transforms_default.pointToGLWindowCoordinates( viewProjectionMatrix, viewportTransformation, sunPosition, sunPositionWCScratch ); sunPositionEC.x += Math_default.SOLAR_RADIUS; const limbWC = Transforms_default.pointToGLWindowCoordinates( projectionMatrix, viewportTransformation, sunPositionEC, sunPositionEC ); const sunSize = Cartesian2_default.magnitude(Cartesian2_default.subtract(limbWC, sunPositionWC, limbWC)) * 30 * 2; const size = sizeScratch; size.x = sunSize; size.y = sunSize; postProcess._uCenter = Cartesian2_default.clone(sunPositionWC, postProcess._uCenter); postProcess._uRadius = Math.max(size.x, size.y) * 0.15; const width = context.drawingBufferWidth; const height = context.drawingBufferHeight; const stages = postProcess._stages; const firstStage = stages.get(0); const downSampleWidth = firstStage.outputTexture.width; const downSampleHeight = firstStage.outputTexture.height; const downSampleViewport = new BoundingRectangle_default(); downSampleViewport.width = downSampleWidth; downSampleViewport.height = downSampleHeight; viewportTransformation = Matrix4_default.computeViewportTransformation( downSampleViewport, 0, 1, postProcessMatrix4Scratch ); sunPositionWC = Transforms_default.pointToGLWindowCoordinates( viewProjectionMatrix, viewportTransformation, sunPosition, sunPositionWCScratch ); size.x *= downSampleWidth / width; size.y *= downSampleHeight / height; const scissorRectangle = firstStage.scissorRectangle; scissorRectangle.x = Math.max(sunPositionWC.x - size.x * 0.5, 0); scissorRectangle.y = Math.max(sunPositionWC.y - size.y * 0.5, 0); scissorRectangle.width = Math.min(size.x, width); scissorRectangle.height = Math.min(size.y, height); for (let i = 1; i < 4; ++i) { BoundingRectangle_default.clone(scissorRectangle, stages.get(i).scissorRectangle); } } SunPostProcess.prototype.clear = function(context, passState, clearColor) { this._sceneFramebuffer.clear(context, passState, clearColor); this._textureCache.clear(context); }; SunPostProcess.prototype.update = function(passState) { const context = passState.context; const viewport = passState.viewport; const sceneFramebuffer = this._sceneFramebuffer; sceneFramebuffer.update(context, viewport); const framebuffer = sceneFramebuffer.framebuffer; this._textureCache.update(context); this._stages.update(context, false); updateSunPosition(this, context, viewport); return framebuffer; }; SunPostProcess.prototype.execute = function(context) { const colorTexture = this._sceneFramebuffer.framebuffer.getColorTexture(0); const stages = this._stages; const length3 = stages.length; stages.get(0).execute(context, colorTexture); for (let i = 1; i < length3; ++i) { stages.get(i).execute(context, stages.get(i - 1).outputTexture); } }; SunPostProcess.prototype.copy = function(context, framebuffer) { if (!defined_default(this._copyColorCommand)) { const that = this; this._copyColorCommand = context.createViewportQuadCommand(PassThrough_default, { uniformMap: { colorTexture: function() { return that._stages.get(that._stages.length - 1).outputTexture; } }, owner: this }); } this._copyColorCommand.framebuffer = framebuffer; this._copyColorCommand.execute(context); }; SunPostProcess.prototype.isDestroyed = function() { return false; }; SunPostProcess.prototype.destroy = function() { this._textureCache.destroy(); this._stages.destroy(); return destroyObject_default(this); }; var SunPostProcess_default = SunPostProcess; // packages/engine/Source/Scene/DebugInspector.js function DebugInspector() { this._cachedShowFrustumsShaders = {}; } function getAttributeLocations(shaderProgram) { const attributeLocations8 = {}; const attributes = shaderProgram.vertexAttributes; for (const a3 in attributes) { if (attributes.hasOwnProperty(a3)) { attributeLocations8[a3] = attributes[a3].index; } } return attributeLocations8; } function createDebugShowFrustumsShaderProgram(scene, shaderProgram) { const context = scene.context; const sp = shaderProgram; const fs = sp.fragmentShaderSource.clone(); const targets = []; fs.sources = fs.sources.map(function(source) { source = ShaderSource_default.replaceMain(source, "czm_Debug_main"); const re = /out_FragData_(\d+)/g; let match; while ((match = re.exec(source)) !== null) { if (targets.indexOf(match[1]) === -1) { targets.push(match[1]); } } return source; }); const length3 = targets.length; let newMain = ""; newMain += "uniform vec3 debugShowCommandsColor;\n"; newMain += "uniform vec3 debugShowFrustumsColor;\n"; newMain += "void main() \n{ \n czm_Debug_main(); \n"; let i; if (length3 > 0) { for (i = 0; i < length3; ++i) { newMain += ` out_FragData_${targets[i]}.rgb *= debugShowCommandsColor; `; newMain += ` out_FragData_${targets[i]}.rgb *= debugShowFrustumsColor; `; } } else { newMain += " out_FragColor.rgb *= debugShowCommandsColor;\n"; newMain += " out_FragColor.rgb *= debugShowFrustumsColor;\n"; } newMain += "}"; fs.sources.push(newMain); const attributeLocations8 = getAttributeLocations(sp); return ShaderProgram_default.fromCache({ context, vertexShaderSource: sp.vertexShaderSource, fragmentShaderSource: fs, attributeLocations: attributeLocations8 }); } var scratchFrustumColor = new Color_default(); function createDebugShowFrustumsUniformMap(scene, command) { let debugUniformMap; if (!defined_default(command.uniformMap)) { debugUniformMap = {}; } else { debugUniformMap = command.uniformMap; } if (defined_default(debugUniformMap.debugShowCommandsColor) || defined_default(debugUniformMap.debugShowFrustumsColor)) { return debugUniformMap; } debugUniformMap.debugShowCommandsColor = function() { if (!scene.debugShowCommands) { return Color_default.WHITE; } if (!defined_default(command._debugColor)) { command._debugColor = Color_default.fromRandom(); } return command._debugColor; }; debugUniformMap.debugShowFrustumsColor = function() { if (!scene.debugShowFrustums) { return Color_default.WHITE; } scratchFrustumColor.red = command.debugOverlappingFrustums & 1 << 0 ? 1 : 0; scratchFrustumColor.green = command.debugOverlappingFrustums & 1 << 1 ? 1 : 0; scratchFrustumColor.blue = command.debugOverlappingFrustums & 1 << 2 ? 1 : 0; scratchFrustumColor.alpha = 1; return scratchFrustumColor; }; return debugUniformMap; } var scratchShowFrustumCommand = new DrawCommand_default(); DebugInspector.prototype.executeDebugShowFrustumsCommand = function(scene, command, passState) { const shaderProgramId = command.shaderProgram.id; let debugShaderProgram = this._cachedShowFrustumsShaders[shaderProgramId]; if (!defined_default(debugShaderProgram)) { debugShaderProgram = createDebugShowFrustumsShaderProgram( scene, command.shaderProgram ); this._cachedShowFrustumsShaders[shaderProgramId] = debugShaderProgram; } const debugCommand = DrawCommand_default.shallowClone( command, scratchShowFrustumCommand ); debugCommand.shaderProgram = debugShaderProgram; debugCommand.uniformMap = createDebugShowFrustumsUniformMap(scene, command); debugCommand.execute(scene.context, passState); }; var DebugInspector_default = DebugInspector; // packages/engine/Source/Scene/Scene.js var requestRenderAfterFrame = function(scene) { return function() { scene.frameState.afterRender.push(function() { scene.requestRender(); }); }; }; function Scene4(options) { options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT); const canvas = options.canvas; let creditContainer = options.creditContainer; let creditViewport = options.creditViewport; const contextOptions = clone_default(options.contextOptions); if (!defined_default(canvas)) { throw new DeveloperError_default("options and options.canvas are required."); } const hasCreditContainer = defined_default(creditContainer); const context = new Context_default(canvas, contextOptions); if (!hasCreditContainer) { creditContainer = document.createElement("div"); creditContainer.style.position = "absolute"; creditContainer.style.bottom = "0"; creditContainer.style["text-shadow"] = "0 0 2px #000000"; creditContainer.style.color = "#ffffff"; creditContainer.style["font-size"] = "10px"; creditContainer.style["padding-right"] = "5px"; canvas.parentNode.appendChild(creditContainer); } if (!defined_default(creditViewport)) { creditViewport = canvas.parentNode; } this._id = createGuid_default(); this._jobScheduler = new JobScheduler_default(); this._frameState = new FrameState_default( context, new CreditDisplay_default(creditContainer, " \u2022 ", creditViewport), this._jobScheduler ); this._frameState.scene3DOnly = defaultValue_default(options.scene3DOnly, false); this._removeCreditContainer = !hasCreditContainer; this._creditContainer = creditContainer; this._canvas = canvas; this._context = context; this._computeEngine = new ComputeEngine_default(context); this._globe = void 0; this._globeTranslucencyState = new GlobeTranslucencyState_default(); this._primitives = new PrimitiveCollection_default(); this._groundPrimitives = new PrimitiveCollection_default(); this._globeHeight = void 0; this._cameraUnderground = false; this._logDepthBuffer = context.fragmentDepth; this._logDepthBufferDirty = true; this._tweens = new TweenCollection_default(); this._shaderFrameCount = 0; this._sunPostProcess = void 0; this._computeCommandList = []; this._overlayCommandList = []; this._useOIT = defaultValue_default(options.orderIndependentTranslucency, true); this._executeOITFunction = void 0; this._depthPlane = new DepthPlane_default(options.depthPlaneEllipsoidOffset); this._clearColorCommand = new ClearCommand_default({ color: new Color_default(), stencil: 0, owner: this }); this._depthClearCommand = new ClearCommand_default({ depth: 1, owner: this }); this._stencilClearCommand = new ClearCommand_default({ stencil: 0 }); this._classificationStencilClearCommand = new ClearCommand_default({ stencil: 0, renderState: RenderState_default.fromCache({ stencilMask: StencilConstants_default.CLASSIFICATION_MASK }) }); this._depthOnlyRenderStateCache = {}; this._transitioner = new SceneTransitioner_default(this); this._preUpdate = new Event_default(); this._postUpdate = new Event_default(); this._renderError = new Event_default(); this._preRender = new Event_default(); this._postRender = new Event_default(); this._minimumDisableDepthTestDistance = 0; this._debugInspector = new DebugInspector_default(); this._msaaSamples = defaultValue_default(options.msaaSamples, 1); this.rethrowRenderErrors = false; this.completeMorphOnUserInput = true; this.morphStart = new Event_default(); this.morphComplete = new Event_default(); this.skyBox = void 0; this.skyAtmosphere = void 0; this.sun = void 0; this.sunBloom = true; this._sunBloom = void 0; this.moon = void 0; this.backgroundColor = Color_default.clone(Color_default.BLACK); this._mode = SceneMode_default.SCENE3D; this._mapProjection = defined_default(options.mapProjection) ? options.mapProjection : new GeographicProjection_default(); this.morphTime = 1; this.farToNearRatio = 1e3; this.logarithmicDepthFarToNearRatio = 1e9; this.nearToFarDistance2D = 175e4; this.debugCommandFilter = void 0; this.debugShowCommands = false; this.debugShowFrustums = false; this.debugShowFramesPerSecond = false; this.debugShowDepthFrustum = 1; this.debugShowFrustumPlanes = false; this._debugShowFrustumPlanes = false; this._debugFrustumPlanes = void 0; this.useDepthPicking = true; this.pickTranslucentDepth = false; this.cameraEventWaitTime = 500; this.fog = new Fog_default(); this._shadowMapCamera = new Camera_default(this); this.shadowMap = new ShadowMap_default({ context, lightCamera: this._shadowMapCamera, enabled: defaultValue_default(options.shadows, false) }); this.invertClassification = false; this.invertClassificationColor = Color_default.clone(Color_default.WHITE); this._actualInvertClassificationColor = Color_default.clone( this._invertClassificationColor ); this._invertClassification = new InvertClassification_default(); this.focalLength = void 0; this.eyeSeparation = void 0; this.postProcessStages = new PostProcessStageCollection_default(); this._brdfLutGenerator = new BrdfLutGenerator_default(); this._performanceDisplay = void 0; this._debugVolume = void 0; this._screenSpaceCameraController = new ScreenSpaceCameraController_default(this); this._cameraUnderground = false; this._mapMode2D = defaultValue_default(options.mapMode2D, MapMode2D_default.INFINITE_SCROLL); this._environmentState = { skyBoxCommand: void 0, skyAtmosphereCommand: void 0, sunDrawCommand: void 0, sunComputeCommand: void 0, moonCommand: void 0, isSunVisible: false, isMoonVisible: false, isReadyForAtmosphere: false, isSkyAtmosphereVisible: false, clearGlobeDepth: false, useDepthPlane: false, renderTranslucentDepthForPick: false, originalFramebuffer: void 0, useGlobeDepthFramebuffer: false, useOIT: false, useInvertClassification: false, usePostProcess: false, usePostProcessSelected: false, useWebVR: false }; this._useWebVR = false; this._cameraVR = void 0; this._aspectRatioVR = void 0; this.requestRenderMode = defaultValue_default(options.requestRenderMode, false); this._renderRequested = true; this.maximumRenderTimeChange = defaultValue_default( options.maximumRenderTimeChange, 0 ); this._lastRenderTime = void 0; this._frameRateMonitor = void 0; this._removeRequestListenerCallback = RequestScheduler_default.requestCompletedEvent.addEventListener( requestRenderAfterFrame(this) ); this._removeTaskProcessorListenerCallback = TaskProcessor_default.taskCompletedEvent.addEventListener( requestRenderAfterFrame(this) ); this._removeGlobeCallbacks = []; this._removeTerrainProviderReadyListener = void 0; const viewport = new BoundingRectangle_default( 0, 0, context.drawingBufferWidth, context.drawingBufferHeight ); const camera = new Camera_default(this); if (this._logDepthBuffer) { camera.frustum.near = 0.1; camera.frustum.far = 1e10; } this.preloadFlightCamera = new Camera_default(this); this.preloadFlightCullingVolume = void 0; this._picking = new Picking_default(this); this._defaultView = new View_default(this, camera, viewport); this._view = this._defaultView; this._hdr = void 0; this._hdrDirty = void 0; this.highDynamicRange = false; this.gamma = 2.2; this.sphericalHarmonicCoefficients = void 0; this.specularEnvironmentMaps = void 0; this._specularEnvironmentMapAtlas = void 0; this.light = new SunLight_default(); updateFrameNumber(this, 0, JulianDate_default.now()); this.updateFrameState(); this.initializeFrame(); } function updateGlobeListeners(scene, globe) { for (let i = 0; i < scene._removeGlobeCallbacks.length; ++i) { scene._removeGlobeCallbacks[i](); } scene._removeGlobeCallbacks.length = 0; const removeGlobeCallbacks = []; if (defined_default(globe)) { removeGlobeCallbacks.push( globe.imageryLayersUpdatedEvent.addEventListener( requestRenderAfterFrame(scene) ) ); removeGlobeCallbacks.push( globe.terrainProviderChanged.addEventListener( requestRenderAfterFrame(scene) ) ); } scene._removeGlobeCallbacks = removeGlobeCallbacks; } Object.defineProperties(Scene4.prototype, { /** * Gets the canvas element to which this scene is bound. * @memberof Scene.prototype * * @type {HTMLCanvasElement} * @readonly */ canvas: { get: function() { return this._canvas; } }, /** * The drawingBufferHeight of the underlying GL context. * @memberof Scene.prototype * * @type {number} * @readonly * * @see {@link https://www.khronos.org/registry/webgl/specs/1.0/#DOM-WebGLRenderingContext-drawingBufferHeight|drawingBufferHeight} */ drawingBufferHeight: { get: function() { return this._context.drawingBufferHeight; } }, /** * The drawingBufferHeight of the underlying GL context. * @memberof Scene.prototype * * @type {number} * @readonly * * @see {@link https://www.khronos.org/registry/webgl/specs/1.0/#DOM-WebGLRenderingContext-drawingBufferHeight|drawingBufferHeight} */ drawingBufferWidth: { get: function() { return this._context.drawingBufferWidth; } }, /** * The maximum aliased line width, in pixels, supported by this WebGL implementation. It will be at least one. * @memberof Scene.prototype * * @type {number} * @readonly * * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} withALIASED_LINE_WIDTH_RANGE
.
*/
maximumAliasedLineWidth: {
get: function() {
return ContextLimits_default.maximumAliasedLineWidth;
}
},
/**
* The maximum length in pixels of one edge of a cube map, supported by this WebGL implementation. It will be at least 16.
* @memberof Scene.prototype
*
* @type {number}
* @readonly
*
* @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with GL_MAX_CUBE_MAP_TEXTURE_SIZE
.
*/
maximumCubeMapSize: {
get: function() {
return ContextLimits_default.maximumCubeMapSize;
}
},
/**
* Returns true
if the {@link Scene#pickPosition} function is supported.
* @memberof Scene.prototype
*
* @type {boolean}
* @readonly
*
* @see Scene#pickPosition
*/
pickPositionSupported: {
get: function() {
return this._context.depthTexture;
}
},
/**
* Returns true
if the {@link Scene#sampleHeight} and {@link Scene#sampleHeightMostDetailed} functions are supported.
* @memberof Scene.prototype
*
* @type {boolean}
* @readonly
*
* @see Scene#sampleHeight
* @see Scene#sampleHeightMostDetailed
*/
sampleHeightSupported: {
get: function() {
return this._context.depthTexture;
}
},
/**
* Returns true
if the {@link Scene#clampToHeight} and {@link Scene#clampToHeightMostDetailed} functions are supported.
* @memberof Scene.prototype
*
* @type {boolean}
* @readonly
*
* @see Scene#clampToHeight
* @see Scene#clampToHeightMostDetailed
*/
clampToHeightSupported: {
get: function() {
return this._context.depthTexture;
}
},
/**
* Returns true
if the {@link Scene#invertClassification} is supported.
* @memberof Scene.prototype
*
* @type {boolean}
* @readonly
*
* @see Scene#invertClassification
*/
invertClassificationSupported: {
get: function() {
return this._context.depthTexture;
}
},
/**
* Returns true
if specular environment maps are supported.
* @memberof Scene.prototype
*
* @type {boolean}
* @readonly
*
* @see Scene#specularEnvironmentMaps
*/
specularEnvironmentMapsSupported: {
get: function() {
return OctahedralProjectedCubeMap_default.isSupported(this._context);
}
},
/**
* Gets or sets the depth-test ellipsoid.
* @memberof Scene.prototype
*
* @type {Globe}
*/
globe: {
get: function() {
return this._globe;
},
set: function(globe) {
this._globe = this._globe && this._globe.destroy();
this._globe = globe;
updateGlobeListeners(this, globe);
}
},
/**
* Gets the collection of primitives.
* @memberof Scene.prototype
*
* @type {PrimitiveCollection}
* @readonly
*/
primitives: {
get: function() {
return this._primitives;
}
},
/**
* Gets the collection of ground primitives.
* @memberof Scene.prototype
*
* @type {PrimitiveCollection}
* @readonly
*/
groundPrimitives: {
get: function() {
return this._groundPrimitives;
}
},
/**
* Gets or sets the camera.
* @memberof Scene.prototype
*
* @type {Camera}
* @readonly
*/
camera: {
get: function() {
return this._view.camera;
},
set: function(camera) {
this._view.camera = camera;
}
},
/**
* Gets or sets the view.
* @memberof Scene.prototype
*
* @type {View}
* @readonly
*
* @private
*/
view: {
get: function() {
return this._view;
},
set: function(view) {
this._view = view;
}
},
/**
* Gets the default view.
* @memberof Scene.prototype
*
* @type {View}
* @readonly
*
* @private
*/
defaultView: {
get: function() {
return this._defaultView;
}
},
/**
* Gets picking functions and state
* @memberof Scene.prototype
*
* @type {Picking}
* @readonly
*
* @private
*/
picking: {
get: function() {
return this._picking;
}
},
/**
* Gets the controller for camera input handling.
* @memberof Scene.prototype
*
* @type {ScreenSpaceCameraController}
* @readonly
*/
screenSpaceCameraController: {
get: function() {
return this._screenSpaceCameraController;
}
},
/**
* Get the map projection to use in 2D and Columbus View modes.
* @memberof Scene.prototype
*
* @type {MapProjection}
* @readonly
*
* @default new GeographicProjection()
*/
mapProjection: {
get: function() {
return this._mapProjection;
}
},
/**
* Gets the job scheduler
* @memberof Scene.prototype
* @type {JobScheduler}
* @readonly
*
* @private
*/
jobScheduler: {
get: function() {
return this._jobScheduler;
}
},
/**
* Gets state information about the current scene. If called outside of a primitive's update
* function, the previous frame's state is returned.
* @memberof Scene.prototype
*
* @type {FrameState}
* @readonly
*
* @private
*/
frameState: {
get: function() {
return this._frameState;
}
},
/**
* Gets the environment state.
* @memberof Scene.prototype
*
* @type {EnvironmentState}
* @readonly
*
* @private
*/
environmentState: {
get: function() {
return this._environmentState;
}
},
/**
* Gets the collection of tweens taking place in the scene.
* @memberof Scene.prototype
*
* @type {TweenCollection}
* @readonly
*
* @private
*/
tweens: {
get: function() {
return this._tweens;
}
},
/**
* Gets the collection of image layers that will be rendered on the globe.
* @memberof Scene.prototype
*
* @type {ImageryLayerCollection}
* @readonly
*/
imageryLayers: {
get: function() {
if (!defined_default(this.globe)) {
return void 0;
}
return this.globe.imageryLayers;
}
},
/**
* The terrain provider providing surface geometry for the globe.
* @memberof Scene.prototype
*
* @type {TerrainProvider}
*/
terrainProvider: {
get: function() {
if (!defined_default(this.globe)) {
return void 0;
}
return this.globe.terrainProvider;
},
set: function(terrainProvider) {
this._removeTerrainProviderReadyListener = this._removeTerrainProviderReadyListener && this._removeTerrainProviderReadyListener();
if (defined_default(this.globe)) {
this.globe.terrainProvider = terrainProvider;
}
}
},
/**
* Gets an event that's raised when the terrain provider is changed
* @memberof Scene.prototype
*
* @type {Event}
* @readonly
*/
terrainProviderChanged: {
get: function() {
if (!defined_default(this.globe)) {
return void 0;
}
return this.globe.terrainProviderChanged;
}
},
/**
* Gets the event that will be raised before the scene is updated or rendered. Subscribers to the event
* receive the Scene instance as the first parameter and the current time as the second parameter.
* @memberof Scene.prototype
*
* @see {@link https://cesium.com/blog/2018/01/24/cesium-scene-rendering-performance/|Improving Performance with Explicit Rendering}
* @see Scene#postUpdate
* @see Scene#preRender
* @see Scene#postRender
*
* @type {Event}
* @readonly
*/
preUpdate: {
get: function() {
return this._preUpdate;
}
},
/**
* Gets the event that will be raised immediately after the scene is updated and before the scene is rendered.
* Subscribers to the event receive the Scene instance as the first parameter and the current time as the second
* parameter.
* @memberof Scene.prototype
*
* @see {@link https://cesium.com/blog/2018/01/24/cesium-scene-rendering-performance/|Improving Performance with Explicit Rendering}
* @see Scene#preUpdate
* @see Scene#preRender
* @see Scene#postRender
*
* @type {Event}
* @readonly
*/
postUpdate: {
get: function() {
return this._postUpdate;
}
},
/**
* Gets the event that will be raised when an error is thrown inside the render
function.
* The Scene instance and the thrown error are the only two parameters passed to the event handler.
* By default, errors are not rethrown after this event is raised, but that can be changed by setting
* the rethrowRenderErrors
property.
* @memberof Scene.prototype
*
* @type {Event}
* @readonly
*/
renderError: {
get: function() {
return this._renderError;
}
},
/**
* Gets the event that will be raised after the scene is updated and immediately before the scene is rendered.
* Subscribers to the event receive the Scene instance as the first parameter and the current time as the second
* parameter.
* @memberof Scene.prototype
*
* @see {@link https://cesium.com/blog/2018/01/24/cesium-scene-rendering-performance/|Improving Performance with Explicit Rendering}
* @see Scene#preUpdate
* @see Scene#postUpdate
* @see Scene#postRender
*
* @type {Event}
* @readonly
*/
preRender: {
get: function() {
return this._preRender;
}
},
/**
* Gets the event that will be raised immediately after the scene is rendered. Subscribers to the event
* receive the Scene instance as the first parameter and the current time as the second parameter.
* @memberof Scene.prototype
*
* @see {@link https://cesium.com/blog/2018/01/24/cesium-scene-rendering-performance/|Improving Performance with Explicit Rendering}
* @see Scene#preUpdate
* @see Scene#postUpdate
* @see Scene#postRender
*
* @type {Event}
* @readonly
*/
postRender: {
get: function() {
return this._postRender;
}
},
/**
* Gets the simulation time when the scene was last rendered. Returns undefined if the scene has not yet been
* rendered.
* @memberof Scene.prototype
*
* @type {JulianDate}
* @readonly
*/
lastRenderTime: {
get: function() {
return this._lastRenderTime;
}
},
/**
* @memberof Scene.prototype
* @private
* @readonly
*/
context: {
get: function() {
return this._context;
}
},
/**
* This property is for debugging only; it is not for production use.
*
* When {@link Scene.debugShowFrustums} is true
, this contains
* properties with statistics about the number of command execute per frustum.
* totalCommands
is the total number of commands executed, ignoring
* overlap. commandsInFrustums
is an array with the number of times
* commands are executed redundantly, e.g., how many commands overlap two or
* three frustums.
*
true
, splits the scene into two viewports with steroscopic views for the left and right eyes.
* Used for cardboard and WebVR.
* @memberof Scene.prototype
* @type {boolean}
* @default false
*/
useWebVR: {
get: function() {
return this._useWebVR;
},
set: function(value) {
if (this.camera.frustum instanceof OrthographicFrustum_default) {
throw new DeveloperError_default(
"VR is unsupported with an orthographic projection."
);
}
this._useWebVR = value;
if (this._useWebVR) {
this._frameState.creditDisplay.container.style.visibility = "hidden";
this._cameraVR = new Camera_default(this);
if (!defined_default(this._deviceOrientationCameraController)) {
this._deviceOrientationCameraController = new DeviceOrientationCameraController_default(
this
);
}
this._aspectRatioVR = this.camera.frustum.aspectRatio;
} else {
this._frameState.creditDisplay.container.style.visibility = "visible";
this._cameraVR = void 0;
this._deviceOrientationCameraController = this._deviceOrientationCameraController && !this._deviceOrientationCameraController.isDestroyed() && this._deviceOrientationCameraController.destroy();
this.camera.frustum.aspectRatio = this._aspectRatioVR;
this.camera.frustum.xOffset = 0;
}
}
},
/**
* Determines if the 2D map is rotatable or can be scrolled infinitely in the horizontal direction.
* @memberof Scene.prototype
* @type {MapMode2D}
* @readonly
*/
mapMode2D: {
get: function() {
return this._mapMode2D;
}
},
/**
* Gets or sets the position of the splitter within the viewport. Valid values are between 0.0 and 1.0.
* @memberof Scene.prototype
*
* @type {number}
*/
splitPosition: {
get: function() {
return this._frameState.splitPosition;
},
set: function(value) {
this._frameState.splitPosition = value;
}
},
/**
* The distance from the camera at which to disable the depth test of billboards, labels and points
* to, for example, prevent clipping against terrain. When set to zero, the depth test should always
* be applied. When less than zero, the depth test should never be applied. Setting the disableDepthTestDistance
* property of a billboard, label or point will override this value.
* @memberof Scene.prototype
* @type {number}
* @default 0.0
*/
minimumDisableDepthTestDistance: {
get: function() {
return this._minimumDisableDepthTestDistance;
},
set: function(value) {
if (!defined_default(value) || value < 0) {
throw new DeveloperError_default(
"minimumDisableDepthTestDistance must be greater than or equal to 0.0."
);
}
this._minimumDisableDepthTestDistance = value;
}
},
/**
* Whether or not to use a logarithmic depth buffer. Enabling this option will allow for less frustums in the multi-frustum,
* increasing performance. This property relies on fragmentDepth being supported.
* @memberof Scene.prototype
* @type {boolean}
*/
logarithmicDepthBuffer: {
get: function() {
return this._logDepthBuffer;
},
set: function(value) {
value = this._context.fragmentDepth && value;
if (this._logDepthBuffer !== value) {
this._logDepthBuffer = value;
this._logDepthBufferDirty = true;
}
}
},
/**
* The value used for gamma correction. This is only used when rendering with high dynamic range.
* @memberof Scene.prototype
* @type {number}
* @default 2.2
*/
gamma: {
get: function() {
return this._context.uniformState.gamma;
},
set: function(value) {
this._context.uniformState.gamma = value;
}
},
/**
* Whether or not to use high dynamic range rendering.
* @memberof Scene.prototype
* @type {boolean}
* @default false
*/
highDynamicRange: {
get: function() {
return this._hdr;
},
set: function(value) {
const context = this._context;
const hdr = value && context.depthTexture && (context.colorBufferFloat || context.colorBufferHalfFloat);
this._hdrDirty = hdr !== this._hdr;
this._hdr = hdr;
}
},
/**
* Whether or not high dynamic range rendering is supported.
* @memberof Scene.prototype
* @type {boolean}
* @readonly
* @default true
*/
highDynamicRangeSupported: {
get: function() {
const context = this._context;
return context.depthTexture && (context.colorBufferFloat || context.colorBufferHalfFloat);
}
},
/**
* Whether or not the camera is underneath the globe.
* @memberof Scene.prototype
* @type {boolean}
* @readonly
* @default false
*/
cameraUnderground: {
get: function() {
return this._cameraUnderground;
}
},
/**
* The sample rate of multisample antialiasing (values greater than 1 enable MSAA).
* @memberof Scene.prototype
* @type {number}
* @default 1
*/
msaaSamples: {
get: function() {
return this._msaaSamples;
},
set: function(value) {
value = Math.min(value, ContextLimits_default.maximumSamples);
this._msaaSamples = value;
}
},
/**
* Returns true
if the Scene's context supports MSAA.
* @memberof Scene.prototype
* @type {boolean}
* @readonly
*/
msaaSupported: {
get: function() {
return this._context.msaa;
}
},
/**
* Ratio between a pixel and a density-independent pixel. Provides a standard unit of
* measure for real pixel measurements appropriate to a particular device.
*
* @memberof Scene.prototype
* @type {number}
* @default 1.0
* @private
*/
pixelRatio: {
get: function() {
return this._frameState.pixelRatio;
},
set: function(value) {
this._frameState.pixelRatio = value;
}
},
/**
* @private
*/
opaqueFrustumNearOffset: {
get: function() {
return 0.9999;
}
},
/**
* @private
*/
globeHeight: {
get: function() {
return this._globeHeight;
}
}
});
Scene4.prototype.getCompressedTextureFormatSupported = function(format) {
const context = this.context;
return (format === "WEBGL_compressed_texture_s3tc" || format === "s3tc") && context.s3tc || (format === "WEBGL_compressed_texture_pvrtc" || format === "pvrtc") && context.pvrtc || (format === "WEBGL_compressed_texture_etc" || format === "etc") && context.etc || (format === "WEBGL_compressed_texture_etc1" || format === "etc1") && context.etc1 || (format === "WEBGL_compressed_texture_astc" || format === "astc") && context.astc || (format === "EXT_texture_compression_bptc" || format === "bc7") && context.bc7;
};
function updateDerivedCommands2(scene, command, shadowsDirty) {
const frameState = scene._frameState;
const context = scene._context;
const oit = scene._view.oit;
const lightShadowMaps = frameState.shadowState.lightShadowMaps;
const lightShadowsEnabled = frameState.shadowState.lightShadowsEnabled;
let derivedCommands = command.derivedCommands;
if (defined_default(command.pickId)) {
derivedCommands.picking = DerivedCommand_default.createPickDerivedCommand(
scene,
command,
context,
derivedCommands.picking
);
}
if (!command.pickOnly) {
derivedCommands.depth = DerivedCommand_default.createDepthOnlyDerivedCommand(
scene,
command,
context,
derivedCommands.depth
);
}
derivedCommands.originalCommand = command;
if (scene._hdr) {
derivedCommands.hdr = DerivedCommand_default.createHdrCommand(
command,
context,
derivedCommands.hdr
);
command = derivedCommands.hdr.command;
derivedCommands = command.derivedCommands;
}
if (lightShadowsEnabled && command.receiveShadows) {
derivedCommands.shadows = ShadowMap_default.createReceiveDerivedCommand(
lightShadowMaps,
command,
shadowsDirty,
context,
derivedCommands.shadows
);
}
if (command.pass === Pass_default.TRANSLUCENT && defined_default(oit) && oit.isSupported()) {
if (lightShadowsEnabled && command.receiveShadows) {
derivedCommands.oit = defined_default(derivedCommands.oit) ? derivedCommands.oit : {};
derivedCommands.oit.shadows = oit.createDerivedCommands(
derivedCommands.shadows.receiveCommand,
context,
derivedCommands.oit.shadows
);
} else {
derivedCommands.oit = oit.createDerivedCommands(
command,
context,
derivedCommands.oit
);
}
}
}
Scene4.prototype.updateDerivedCommands = function(command) {
if (!defined_default(command.derivedCommands)) {
return;
}
const frameState = this._frameState;
const context = this._context;
let shadowsDirty = false;
const lastDirtyTime = frameState.shadowState.lastDirtyTime;
if (command.lastDirtyTime !== lastDirtyTime) {
command.lastDirtyTime = lastDirtyTime;
command.dirty = true;
shadowsDirty = true;
}
const useLogDepth = frameState.useLogDepth;
const useHdr = this._hdr;
const derivedCommands = command.derivedCommands;
const hasLogDepthDerivedCommands = defined_default(derivedCommands.logDepth);
const hasHdrCommands = defined_default(derivedCommands.hdr);
const hasDerivedCommands = defined_default(derivedCommands.originalCommand);
const needsLogDepthDerivedCommands = useLogDepth && !hasLogDepthDerivedCommands;
const needsHdrCommands = useHdr && !hasHdrCommands;
const needsDerivedCommands = (!useLogDepth || !useHdr) && !hasDerivedCommands;
command.dirty = command.dirty || needsLogDepthDerivedCommands || needsHdrCommands || needsDerivedCommands;
if (command.dirty) {
command.dirty = false;
const shadowMaps = frameState.shadowState.shadowMaps;
const shadowsEnabled = frameState.shadowState.shadowsEnabled;
if (shadowsEnabled && command.castShadows) {
derivedCommands.shadows = ShadowMap_default.createCastDerivedCommand(
shadowMaps,
command,
shadowsDirty,
context,
derivedCommands.shadows
);
}
if (hasLogDepthDerivedCommands || needsLogDepthDerivedCommands) {
derivedCommands.logDepth = DerivedCommand_default.createLogDepthCommand(
command,
context,
derivedCommands.logDepth
);
updateDerivedCommands2(
this,
derivedCommands.logDepth.command,
shadowsDirty
);
}
if (hasDerivedCommands || needsDerivedCommands) {
updateDerivedCommands2(this, command, shadowsDirty);
}
}
};
var renderTilesetPassState = new Cesium3DTilePassState_default({
pass: Cesium3DTilePass_default.RENDER
});
var preloadTilesetPassState = new Cesium3DTilePassState_default({
pass: Cesium3DTilePass_default.PRELOAD
});
var preloadFlightTilesetPassState = new Cesium3DTilePassState_default({
pass: Cesium3DTilePass_default.PRELOAD_FLIGHT
});
var requestRenderModeDeferCheckPassState = new Cesium3DTilePassState_default({
pass: Cesium3DTilePass_default.REQUEST_RENDER_MODE_DEFER_CHECK
});
var scratchOccluderBoundingSphere = new BoundingSphere_default();
var scratchOccluder;
function getOccluder(scene) {
const globe = scene.globe;
if (scene._mode === SceneMode_default.SCENE3D && defined_default(globe) && globe.show && !scene._cameraUnderground && !scene._globeTranslucencyState.translucent) {
const ellipsoid = globe.ellipsoid;
const minimumTerrainHeight = scene.frameState.minimumTerrainHeight;
scratchOccluderBoundingSphere.radius = ellipsoid.minimumRadius + minimumTerrainHeight;
scratchOccluder = Occluder_default.fromBoundingSphere(
scratchOccluderBoundingSphere,
scene.camera.positionWC,
scratchOccluder
);
return scratchOccluder;
}
return void 0;
}
Scene4.prototype.clearPasses = function(passes) {
passes.render = false;
passes.pick = false;
passes.depth = false;
passes.postProcess = false;
passes.offscreen = false;
};
function updateFrameNumber(scene, frameNumber, time) {
const frameState = scene._frameState;
frameState.frameNumber = frameNumber;
frameState.time = JulianDate_default.clone(time, frameState.time);
}
Scene4.prototype.updateFrameState = function() {
const camera = this.camera;
const frameState = this._frameState;
frameState.commandList.length = 0;
frameState.shadowMaps.length = 0;
frameState.brdfLutGenerator = this._brdfLutGenerator;
frameState.environmentMap = this.skyBox && this.skyBox._cubeMap;
frameState.mode = this._mode;
frameState.morphTime = this.morphTime;
frameState.mapProjection = this.mapProjection;
frameState.camera = camera;
frameState.cullingVolume = camera.frustum.computeCullingVolume(
camera.positionWC,
camera.directionWC,
camera.upWC
);
frameState.occluder = getOccluder(this);
frameState.minimumTerrainHeight = 0;
frameState.minimumDisableDepthTestDistance = this._minimumDisableDepthTestDistance;
frameState.invertClassification = this.invertClassification;
frameState.useLogDepth = this._logDepthBuffer && !(this.camera.frustum instanceof OrthographicFrustum_default || this.camera.frustum instanceof OrthographicOffCenterFrustum_default);
frameState.light = this.light;
frameState.cameraUnderground = this._cameraUnderground;
frameState.globeTranslucencyState = this._globeTranslucencyState;
if (defined_default(this.globe)) {
frameState.terrainExaggeration = this.globe.terrainExaggeration;
frameState.terrainExaggerationRelativeHeight = this.globe.terrainExaggerationRelativeHeight;
}
if (defined_default(this._specularEnvironmentMapAtlas) && this._specularEnvironmentMapAtlas.ready) {
frameState.specularEnvironmentMaps = this._specularEnvironmentMapAtlas.texture;
frameState.specularEnvironmentMapsMaximumLOD = this._specularEnvironmentMapAtlas.maximumMipmapLevel;
} else {
frameState.specularEnvironmentMaps = void 0;
frameState.specularEnvironmentMapsMaximumLOD = void 0;
}
frameState.sphericalHarmonicCoefficients = this.sphericalHarmonicCoefficients;
this._actualInvertClassificationColor = Color_default.clone(
this.invertClassificationColor,
this._actualInvertClassificationColor
);
if (!InvertClassification_default.isTranslucencySupported(this._context)) {
this._actualInvertClassificationColor.alpha = 1;
}
frameState.invertClassificationColor = this._actualInvertClassificationColor;
if (defined_default(this.globe)) {
frameState.maximumScreenSpaceError = this.globe.maximumScreenSpaceError;
} else {
frameState.maximumScreenSpaceError = 2;
}
this.clearPasses(frameState.passes);
frameState.tilesetPassState = void 0;
};
Scene4.prototype.isVisible = function(command, cullingVolume, occluder) {
return defined_default(command) && (!defined_default(command.boundingVolume) || !command.cull || cullingVolume.computeVisibility(command.boundingVolume) !== Intersect_default.OUTSIDE && (!defined_default(occluder) || !command.occlude || !command.boundingVolume.isOccluded(occluder)));
};
var transformFrom2D = new Matrix4_default(
0,
0,
1,
0,
1,
0,
0,
0,
0,
1,
0,
0,
0,
0,
0,
1
);
transformFrom2D = Matrix4_default.inverseTransformation(
transformFrom2D,
transformFrom2D
);
function debugShowBoundingVolume(command, scene, passState, debugFramebuffer) {
const frameState = scene._frameState;
const context = frameState.context;
const boundingVolume = command.boundingVolume;
if (defined_default(scene._debugVolume)) {
scene._debugVolume.destroy();
}
let geometry;
let center = Cartesian3_default.clone(boundingVolume.center);
if (frameState.mode !== SceneMode_default.SCENE3D) {
center = Matrix4_default.multiplyByPoint(transformFrom2D, center, center);
const projection = frameState.mapProjection;
const centerCartographic = projection.unproject(center);
center = projection.ellipsoid.cartographicToCartesian(centerCartographic);
}
if (defined_default(boundingVolume.radius)) {
const radius = boundingVolume.radius;
geometry = GeometryPipeline_default.toWireframe(
EllipsoidGeometry_default.createGeometry(
new EllipsoidGeometry_default({
radii: new Cartesian3_default(radius, radius, radius),
vertexFormat: PerInstanceColorAppearance_default.FLAT_VERTEX_FORMAT
})
)
);
scene._debugVolume = new Primitive_default({
geometryInstances: new GeometryInstance_default({
geometry,
modelMatrix: Matrix4_default.fromTranslation(center),
attributes: {
color: new ColorGeometryInstanceAttribute_default(1, 0, 0, 1)
}
}),
appearance: new PerInstanceColorAppearance_default({
flat: true,
translucent: false
}),
asynchronous: false
});
} else {
const halfAxes = boundingVolume.halfAxes;
geometry = GeometryPipeline_default.toWireframe(
BoxGeometry_default.createGeometry(
BoxGeometry_default.fromDimensions({
dimensions: new Cartesian3_default(2, 2, 2),
vertexFormat: PerInstanceColorAppearance_default.FLAT_VERTEX_FORMAT
})
)
);
scene._debugVolume = new Primitive_default({
geometryInstances: new GeometryInstance_default({
geometry,
modelMatrix: Matrix4_default.fromRotationTranslation(
halfAxes,
center,
new Matrix4_default()
),
attributes: {
color: new ColorGeometryInstanceAttribute_default(1, 0, 0, 1)
}
}),
appearance: new PerInstanceColorAppearance_default({
flat: true,
translucent: false
}),
asynchronous: false
});
}
const savedCommandList = frameState.commandList;
const commandList = frameState.commandList = [];
scene._debugVolume.update(frameState);
command = commandList[0];
if (frameState.useLogDepth) {
const logDepth = DerivedCommand_default.createLogDepthCommand(command, context);
command = logDepth.command;
}
let framebuffer;
if (defined_default(debugFramebuffer)) {
framebuffer = passState.framebuffer;
passState.framebuffer = debugFramebuffer;
}
command.execute(context, passState);
if (defined_default(framebuffer)) {
passState.framebuffer = framebuffer;
}
frameState.commandList = savedCommandList;
}
function executeCommand(command, scene, context, passState, debugFramebuffer) {
const frameState = scene._frameState;
if (defined_default(scene.debugCommandFilter) && !scene.debugCommandFilter(command)) {
return;
}
if (command instanceof ClearCommand_default) {
command.execute(context, passState);
return;
}
if (command.debugShowBoundingVolume && defined_default(command.boundingVolume)) {
debugShowBoundingVolume(command, scene, passState, debugFramebuffer);
}
if (frameState.useLogDepth && defined_default(command.derivedCommands.logDepth)) {
command = command.derivedCommands.logDepth.command;
}
const passes = frameState.passes;
if (!passes.pick && !passes.depth && scene._hdr && defined_default(command.derivedCommands) && defined_default(command.derivedCommands.hdr)) {
command = command.derivedCommands.hdr.command;
}
if (passes.pick || passes.depth) {
if (passes.pick && !passes.depth && defined_default(command.derivedCommands.picking)) {
command = command.derivedCommands.picking.pickCommand;
command.execute(context, passState);
return;
} else if (defined_default(command.derivedCommands.depth)) {
command = command.derivedCommands.depth.depthOnlyCommand;
command.execute(context, passState);
return;
}
}
if (scene.debugShowCommands || scene.debugShowFrustums) {
scene._debugInspector.executeDebugShowFrustumsCommand(
scene,
command,
passState
);
return;
}
if (frameState.shadowState.lightShadowsEnabled && command.receiveShadows && defined_default(command.derivedCommands.shadows)) {
command.derivedCommands.shadows.receiveCommand.execute(context, passState);
} else {
command.execute(context, passState);
}
}
function executeIdCommand(command, scene, context, passState) {
const frameState = scene._frameState;
let derivedCommands = command.derivedCommands;
if (!defined_default(derivedCommands)) {
return;
}
if (frameState.useLogDepth && defined_default(derivedCommands.logDepth)) {
command = derivedCommands.logDepth.command;
}
derivedCommands = command.derivedCommands;
if (defined_default(derivedCommands.picking)) {
command = derivedCommands.picking.pickCommand;
command.execute(context, passState);
} else if (defined_default(derivedCommands.depth)) {
command = derivedCommands.depth.depthOnlyCommand;
command.execute(context, passState);
}
}
function backToFront(a3, b, position) {
return b.boundingVolume.distanceSquaredTo(position) - a3.boundingVolume.distanceSquaredTo(position);
}
function frontToBack(a3, b, position) {
return a3.boundingVolume.distanceSquaredTo(position) - b.boundingVolume.distanceSquaredTo(position) + Math_default.EPSILON12;
}
function executeTranslucentCommandsBackToFront(scene, executeFunction, passState, commands, invertClassification) {
const context = scene.context;
mergeSort_default(commands, backToFront, scene.camera.positionWC);
if (defined_default(invertClassification)) {
executeFunction(
invertClassification.unclassifiedCommand,
scene,
context,
passState
);
}
const length3 = commands.length;
for (let i = 0; i < length3; ++i) {
executeFunction(commands[i], scene, context, passState);
}
}
function executeTranslucentCommandsFrontToBack(scene, executeFunction, passState, commands, invertClassification) {
const context = scene.context;
mergeSort_default(commands, frontToBack, scene.camera.positionWC);
if (defined_default(invertClassification)) {
executeFunction(
invertClassification.unclassifiedCommand,
scene,
context,
passState
);
}
const length3 = commands.length;
for (let i = 0; i < length3; ++i) {
executeFunction(commands[i], scene, context, passState);
}
}
function executeVoxelCommands(scene, executeFunction, passState, commands) {
const context = scene.context;
mergeSort_default(commands, backToFront, scene.camera.positionWC);
const length3 = commands.length;
for (let i = 0; i < length3; ++i) {
executeFunction(commands[i], scene, context, passState);
}
}
var scratchPerspectiveFrustum2 = new PerspectiveFrustum_default();
var scratchPerspectiveOffCenterFrustum2 = new PerspectiveOffCenterFrustum_default();
var scratchOrthographicFrustum2 = new OrthographicFrustum_default();
var scratchOrthographicOffCenterFrustum2 = new OrthographicOffCenterFrustum_default();
function executeCommands2(scene, passState) {
const camera = scene.camera;
const context = scene.context;
const frameState = scene.frameState;
const us = context.uniformState;
us.updateCamera(camera);
let frustum;
if (defined_default(camera.frustum.fov)) {
frustum = camera.frustum.clone(scratchPerspectiveFrustum2);
} else if (defined_default(camera.frustum.infiniteProjectionMatrix)) {
frustum = camera.frustum.clone(scratchPerspectiveOffCenterFrustum2);
} else if (defined_default(camera.frustum.width)) {
frustum = camera.frustum.clone(scratchOrthographicFrustum2);
} else {
frustum = camera.frustum.clone(scratchOrthographicOffCenterFrustum2);
}
frustum.near = camera.frustum.near;
frustum.far = camera.frustum.far;
us.updateFrustum(frustum);
us.updatePass(Pass_default.ENVIRONMENT);
const passes = frameState.passes;
const picking = passes.pick;
const environmentState = scene._environmentState;
const view = scene._view;
const renderTranslucentDepthForPick2 = environmentState.renderTranslucentDepthForPick;
const useWebVR = environmentState.useWebVR;
if (!picking) {
const skyBoxCommand = environmentState.skyBoxCommand;
if (defined_default(skyBoxCommand)) {
executeCommand(skyBoxCommand, scene, context, passState);
}
if (environmentState.isSkyAtmosphereVisible) {
executeCommand(
environmentState.skyAtmosphereCommand,
scene,
context,
passState
);
}
if (environmentState.isSunVisible) {
environmentState.sunDrawCommand.execute(context, passState);
if (scene.sunBloom && !useWebVR) {
let framebuffer;
if (environmentState.useGlobeDepthFramebuffer) {
framebuffer = view.globeDepth.framebuffer;
} else if (environmentState.usePostProcess) {
framebuffer = view.sceneFramebuffer.framebuffer;
} else {
framebuffer = environmentState.originalFramebuffer;
}
scene._sunPostProcess.execute(context);
scene._sunPostProcess.copy(context, framebuffer);
passState.framebuffer = framebuffer;
}
}
if (environmentState.isMoonVisible) {
environmentState.moonCommand.execute(context, passState);
}
}
let executeTranslucentCommands;
if (environmentState.useOIT) {
if (!defined_default(scene._executeOITFunction)) {
scene._executeOITFunction = function(scene2, executeFunction, passState2, commands, invertClassification) {
view.globeDepth.prepareColorTextures(context);
view.oit.executeCommands(
scene2,
executeFunction,
passState2,
commands,
invertClassification
);
};
}
executeTranslucentCommands = scene._executeOITFunction;
} else if (passes.render) {
executeTranslucentCommands = executeTranslucentCommandsBackToFront;
} else {
executeTranslucentCommands = executeTranslucentCommandsFrontToBack;
}
const frustumCommandsList = view.frustumCommandsList;
const numFrustums = frustumCommandsList.length;
const clearGlobeDepth = environmentState.clearGlobeDepth;
const useDepthPlane2 = environmentState.useDepthPlane;
const globeTranslucencyState = scene._globeTranslucencyState;
const globeTranslucent = globeTranslucencyState.translucent;
const globeTranslucencyFramebuffer = scene._view.globeTranslucencyFramebuffer;
const clearDepth = scene._depthClearCommand;
const clearStencil = scene._stencilClearCommand;
const clearClassificationStencil = scene._classificationStencilClearCommand;
const depthPlane = scene._depthPlane;
const usePostProcessSelected = environmentState.usePostProcessSelected;
const height2D = camera.position.z;
let j;
for (let i = 0; i < numFrustums; ++i) {
const index = numFrustums - i - 1;
const frustumCommands = frustumCommandsList[index];
if (scene.mode === SceneMode_default.SCENE2D) {
camera.position.z = height2D - frustumCommands.near + 1;
frustum.far = Math.max(1, frustumCommands.far - frustumCommands.near);
frustum.near = 1;
us.update(frameState);
us.updateFrustum(frustum);
} else {
frustum.near = index !== 0 ? frustumCommands.near * scene.opaqueFrustumNearOffset : frustumCommands.near;
frustum.far = frustumCommands.far;
us.updateFrustum(frustum);
}
clearDepth.execute(context, passState);
if (context.stencilBuffer) {
clearStencil.execute(context, passState);
}
us.updatePass(Pass_default.GLOBE);
let commands = frustumCommands.commands[Pass_default.GLOBE];
let length3 = frustumCommands.indices[Pass_default.GLOBE];
if (globeTranslucent) {
globeTranslucencyState.executeGlobeCommands(
frustumCommands,
executeCommand,
globeTranslucencyFramebuffer,
scene,
passState
);
} else {
for (j = 0; j < length3; ++j) {
executeCommand(commands[j], scene, context, passState);
}
}
const globeDepth = view.globeDepth;
if (defined_default(globeDepth) && environmentState.useGlobeDepthFramebuffer) {
globeDepth.executeCopyDepth(context, passState);
}
if (!environmentState.renderTranslucentDepthForPick) {
us.updatePass(Pass_default.TERRAIN_CLASSIFICATION);
commands = frustumCommands.commands[Pass_default.TERRAIN_CLASSIFICATION];
length3 = frustumCommands.indices[Pass_default.TERRAIN_CLASSIFICATION];
if (globeTranslucent) {
globeTranslucencyState.executeGlobeClassificationCommands(
frustumCommands,
executeCommand,
globeTranslucencyFramebuffer,
scene,
passState
);
} else {
for (j = 0; j < length3; ++j) {
executeCommand(commands[j], scene, context, passState);
}
}
}
if (clearGlobeDepth) {
clearDepth.execute(context, passState);
if (useDepthPlane2) {
depthPlane.execute(context, passState);
}
}
if (!environmentState.useInvertClassification || picking || environmentState.renderTranslucentDepthForPick) {
us.updatePass(Pass_default.CESIUM_3D_TILE);
commands = frustumCommands.commands[Pass_default.CESIUM_3D_TILE];
length3 = frustumCommands.indices[Pass_default.CESIUM_3D_TILE];
for (j = 0; j < length3; ++j) {
executeCommand(commands[j], scene, context, passState);
}
if (length3 > 0) {
if (defined_default(globeDepth) && environmentState.useGlobeDepthFramebuffer) {
globeDepth.prepareColorTextures(context, clearGlobeDepth);
globeDepth.executeUpdateDepth(
context,
passState,
clearGlobeDepth,
globeDepth.depthStencilTexture
);
}
if (!environmentState.renderTranslucentDepthForPick) {
us.updatePass(Pass_default.CESIUM_3D_TILE_CLASSIFICATION);
commands = frustumCommands.commands[Pass_default.CESIUM_3D_TILE_CLASSIFICATION];
length3 = frustumCommands.indices[Pass_default.CESIUM_3D_TILE_CLASSIFICATION];
for (j = 0; j < length3; ++j) {
executeCommand(commands[j], scene, context, passState);
}
}
}
} else {
scene._invertClassification.clear(context, passState);
const opaqueClassificationFramebuffer = passState.framebuffer;
passState.framebuffer = scene._invertClassification._fbo.framebuffer;
us.updatePass(Pass_default.CESIUM_3D_TILE);
commands = frustumCommands.commands[Pass_default.CESIUM_3D_TILE];
length3 = frustumCommands.indices[Pass_default.CESIUM_3D_TILE];
for (j = 0; j < length3; ++j) {
executeCommand(commands[j], scene, context, passState);
}
if (defined_default(globeDepth) && environmentState.useGlobeDepthFramebuffer) {
scene._invertClassification.prepareTextures(context);
globeDepth.executeUpdateDepth(
context,
passState,
clearGlobeDepth,
scene._invertClassification._fbo.getDepthStencilTexture()
);
}
us.updatePass(Pass_default.CESIUM_3D_TILE_CLASSIFICATION_IGNORE_SHOW);
commands = frustumCommands.commands[Pass_default.CESIUM_3D_TILE_CLASSIFICATION_IGNORE_SHOW];
length3 = frustumCommands.indices[Pass_default.CESIUM_3D_TILE_CLASSIFICATION_IGNORE_SHOW];
for (j = 0; j < length3; ++j) {
executeCommand(commands[j], scene, context, passState);
}
passState.framebuffer = opaqueClassificationFramebuffer;
scene._invertClassification.executeClassified(context, passState);
if (frameState.invertClassificationColor.alpha === 1) {
scene._invertClassification.executeUnclassified(context, passState);
}
if (length3 > 0 && context.stencilBuffer) {
clearClassificationStencil.execute(context, passState);
}
us.updatePass(Pass_default.CESIUM_3D_TILE_CLASSIFICATION);
commands = frustumCommands.commands[Pass_default.CESIUM_3D_TILE_CLASSIFICATION];
length3 = frustumCommands.indices[Pass_default.CESIUM_3D_TILE_CLASSIFICATION];
for (j = 0; j < length3; ++j) {
executeCommand(commands[j], scene, context, passState);
}
}
if (length3 > 0 && context.stencilBuffer) {
clearStencil.execute(context, passState);
}
us.updatePass(Pass_default.VOXELS);
commands = frustumCommands.commands[Pass_default.VOXELS];
length3 = frustumCommands.indices[Pass_default.VOXELS];
commands.length = length3;
executeVoxelCommands(scene, executeCommand, passState, commands);
us.updatePass(Pass_default.OPAQUE);
commands = frustumCommands.commands[Pass_default.OPAQUE];
length3 = frustumCommands.indices[Pass_default.OPAQUE];
for (j = 0; j < length3; ++j) {
executeCommand(commands[j], scene, context, passState);
}
if (index !== 0 && scene.mode !== SceneMode_default.SCENE2D) {
frustum.near = frustumCommands.near;
us.updateFrustum(frustum);
}
let invertClassification;
if (!picking && environmentState.useInvertClassification && frameState.invertClassificationColor.alpha < 1) {
invertClassification = scene._invertClassification;
}
us.updatePass(Pass_default.TRANSLUCENT);
commands = frustumCommands.commands[Pass_default.TRANSLUCENT];
commands.length = frustumCommands.indices[Pass_default.TRANSLUCENT];
executeTranslucentCommands(
scene,
executeCommand,
passState,
commands,
invertClassification
);
const has3DTilesClassificationCommands = frustumCommands.indices[Pass_default.CESIUM_3D_TILE_CLASSIFICATION] > 0;
if (has3DTilesClassificationCommands && view.translucentTileClassification.isSupported()) {
view.translucentTileClassification.executeTranslucentCommands(
scene,
executeCommand,
passState,
commands,
globeDepth.depthStencilTexture
);
view.translucentTileClassification.executeClassificationCommands(
scene,
executeCommand,
passState,
frustumCommands
);
}
if (context.depthTexture && scene.useDepthPicking && (environmentState.useGlobeDepthFramebuffer || renderTranslucentDepthForPick2)) {
const depthStencilTexture = globeDepth.depthStencilTexture;
const pickDepth = scene._picking.getPickDepth(scene, index);
pickDepth.update(context, depthStencilTexture);
pickDepth.executeCopyDepth(context, passState);
}
if (picking || !usePostProcessSelected) {
continue;
}
const originalFramebuffer = passState.framebuffer;
passState.framebuffer = view.sceneFramebuffer.getIdFramebuffer();
frustum.near = index !== 0 ? frustumCommands.near * scene.opaqueFrustumNearOffset : frustumCommands.near;
frustum.far = frustumCommands.far;
us.updateFrustum(frustum);
us.updatePass(Pass_default.GLOBE);
commands = frustumCommands.commands[Pass_default.GLOBE];
length3 = frustumCommands.indices[Pass_default.GLOBE];
if (globeTranslucent) {
globeTranslucencyState.executeGlobeCommands(
frustumCommands,
executeIdCommand,
globeTranslucencyFramebuffer,
scene,
passState
);
} else {
for (j = 0; j < length3; ++j) {
executeIdCommand(commands[j], scene, context, passState);
}
}
if (clearGlobeDepth) {
clearDepth.framebuffer = passState.framebuffer;
clearDepth.execute(context, passState);
clearDepth.framebuffer = void 0;
}
if (clearGlobeDepth && useDepthPlane2) {
depthPlane.execute(context, passState);
}
us.updatePass(Pass_default.CESIUM_3D_TILE);
commands = frustumCommands.commands[Pass_default.CESIUM_3D_TILE];
length3 = frustumCommands.indices[Pass_default.CESIUM_3D_TILE];
for (j = 0; j < length3; ++j) {
executeIdCommand(commands[j], scene, context, passState);
}
us.updatePass(Pass_default.OPAQUE);
commands = frustumCommands.commands[Pass_default.OPAQUE];
length3 = frustumCommands.indices[Pass_default.OPAQUE];
for (j = 0; j < length3; ++j) {
executeIdCommand(commands[j], scene, context, passState);
}
us.updatePass(Pass_default.TRANSLUCENT);
commands = frustumCommands.commands[Pass_default.TRANSLUCENT];
length3 = frustumCommands.indices[Pass_default.TRANSLUCENT];
for (j = 0; j < length3; ++j) {
executeIdCommand(commands[j], scene, context, passState);
}
passState.framebuffer = originalFramebuffer;
}
}
function executeComputeCommands(scene) {
const us = scene.context.uniformState;
us.updatePass(Pass_default.COMPUTE);
const sunComputeCommand = scene._environmentState.sunComputeCommand;
if (defined_default(sunComputeCommand)) {
sunComputeCommand.execute(scene._computeEngine);
}
const commandList = scene._computeCommandList;
const length3 = commandList.length;
for (let i = 0; i < length3; ++i) {
commandList[i].execute(scene._computeEngine);
}
}
function executeOverlayCommands(scene, passState) {
const us = scene.context.uniformState;
us.updatePass(Pass_default.OVERLAY);
const context = scene.context;
const commandList = scene._overlayCommandList;
const length3 = commandList.length;
for (let i = 0; i < length3; ++i) {
commandList[i].execute(context, passState);
}
}
function insertShadowCastCommands(scene, commandList, shadowMap) {
const shadowVolume = shadowMap.shadowMapCullingVolume;
const isPointLight = shadowMap.isPointLight;
const passes = shadowMap.passes;
const numberOfPasses = passes.length;
const length3 = commandList.length;
for (let i = 0; i < length3; ++i) {
const command = commandList[i];
scene.updateDerivedCommands(command);
if (command.castShadows && (command.pass === Pass_default.GLOBE || command.pass === Pass_default.CESIUM_3D_TILE || command.pass === Pass_default.OPAQUE || command.pass === Pass_default.TRANSLUCENT)) {
if (scene.isVisible(command, shadowVolume)) {
if (isPointLight) {
for (let k = 0; k < numberOfPasses; ++k) {
passes[k].commandList.push(command);
}
} else if (numberOfPasses === 1) {
passes[0].commandList.push(command);
} else {
let wasVisible = false;
for (let j = numberOfPasses - 1; j >= 0; --j) {
const cascadeVolume = passes[j].cullingVolume;
if (scene.isVisible(command, cascadeVolume)) {
passes[j].commandList.push(command);
wasVisible = true;
} else if (wasVisible) {
break;
}
}
}
}
}
}
}
function executeShadowMapCastCommands(scene) {
const frameState = scene.frameState;
const shadowMaps = frameState.shadowState.shadowMaps;
const shadowMapLength = shadowMaps.length;
if (!frameState.shadowState.shadowsEnabled) {
return;
}
const context = scene.context;
const uniformState = context.uniformState;
for (let i = 0; i < shadowMapLength; ++i) {
const shadowMap = shadowMaps[i];
if (shadowMap.outOfView) {
continue;
}
const passes = shadowMap.passes;
const numberOfPasses = passes.length;
for (let j = 0; j < numberOfPasses; ++j) {
passes[j].commandList.length = 0;
}
const sceneCommands = scene.frameState.commandList;
insertShadowCastCommands(scene, sceneCommands, shadowMap);
for (let j = 0; j < numberOfPasses; ++j) {
const pass = shadowMap.passes[j];
uniformState.updateCamera(pass.camera);
shadowMap.updatePass(context, j);
const numberOfCommands = pass.commandList.length;
for (let k = 0; k < numberOfCommands; ++k) {
const command = pass.commandList[k];
uniformState.updatePass(command.pass);
executeCommand(
command.derivedCommands.shadows.castCommands[i],
scene,
context,
pass.passState
);
}
}
}
}
var scratchEyeTranslation = new Cartesian3_default();
Scene4.prototype.updateAndExecuteCommands = function(passState, backgroundColor) {
const frameState = this._frameState;
const mode2 = frameState.mode;
const useWebVR = this._environmentState.useWebVR;
if (useWebVR) {
executeWebVRCommands(this, passState, backgroundColor);
} else if (mode2 !== SceneMode_default.SCENE2D || this._mapMode2D === MapMode2D_default.ROTATE) {
executeCommandsInViewport(true, this, passState, backgroundColor);
} else {
updateAndClearFramebuffers(this, passState, backgroundColor);
execute2DViewportCommands(this, passState);
}
};
function executeWebVRCommands(scene, passState, backgroundColor) {
const view = scene._view;
const camera = view.camera;
const environmentState = scene._environmentState;
const renderTranslucentDepthForPick2 = environmentState.renderTranslucentDepthForPick;
updateAndClearFramebuffers(scene, passState, backgroundColor);
updateAndRenderPrimitives(scene);
view.createPotentiallyVisibleSet(scene);
executeComputeCommands(scene);
if (!renderTranslucentDepthForPick2) {
executeShadowMapCastCommands(scene);
}
const viewport = passState.viewport;
viewport.x = 0;
viewport.y = 0;
viewport.width = viewport.width * 0.5;
const savedCamera = Camera_default.clone(camera, scene._cameraVR);
savedCamera.frustum = camera.frustum;
const near = camera.frustum.near;
const fo = near * defaultValue_default(scene.focalLength, 5);
const eyeSeparation = defaultValue_default(scene.eyeSeparation, fo / 30);
const eyeTranslation = Cartesian3_default.multiplyByScalar(
savedCamera.right,
eyeSeparation * 0.5,
scratchEyeTranslation
);
camera.frustum.aspectRatio = viewport.width / viewport.height;
const offset2 = 0.5 * eyeSeparation * near / fo;
Cartesian3_default.add(savedCamera.position, eyeTranslation, camera.position);
camera.frustum.xOffset = offset2;
executeCommands2(scene, passState);
viewport.x = viewport.width;
Cartesian3_default.subtract(savedCamera.position, eyeTranslation, camera.position);
camera.frustum.xOffset = -offset2;
executeCommands2(scene, passState);
Camera_default.clone(savedCamera, camera);
}
var scratch2DViewportCartographic = new Cartographic_default(
Math.PI,
Math_default.PI_OVER_TWO
);
var scratch2DViewportMaxCoord = new Cartesian3_default();
var scratch2DViewportSavedPosition = new Cartesian3_default();
var scratch2DViewportTransform = new Matrix4_default();
var scratch2DViewportCameraTransform = new Matrix4_default();
var scratch2DViewportEyePoint = new Cartesian3_default();
var scratch2DViewportWindowCoords = new Cartesian3_default();
var scratch2DViewport = new BoundingRectangle_default();
function execute2DViewportCommands(scene, passState) {
const context = scene.context;
const frameState = scene.frameState;
const camera = scene.camera;
const originalViewport = passState.viewport;
const viewport = BoundingRectangle_default.clone(originalViewport, scratch2DViewport);
passState.viewport = viewport;
const maxCartographic = scratch2DViewportCartographic;
const maxCoord = scratch2DViewportMaxCoord;
const projection = scene.mapProjection;
projection.project(maxCartographic, maxCoord);
const position = Cartesian3_default.clone(
camera.position,
scratch2DViewportSavedPosition
);
const transform3 = Matrix4_default.clone(
camera.transform,
scratch2DViewportCameraTransform
);
const frustum = camera.frustum.clone();
camera._setTransform(Matrix4_default.IDENTITY);
const viewportTransformation = Matrix4_default.computeViewportTransformation(
viewport,
0,
1,
scratch2DViewportTransform
);
const projectionMatrix = camera.frustum.projectionMatrix;
const x = camera.positionWC.y;
const eyePoint = Cartesian3_default.fromElements(
Math_default.sign(x) * maxCoord.x - x,
0,
-camera.positionWC.x,
scratch2DViewportEyePoint
);
const windowCoordinates = Transforms_default.pointToGLWindowCoordinates(
projectionMatrix,
viewportTransformation,
eyePoint,
scratch2DViewportWindowCoords
);
windowCoordinates.x = Math.floor(windowCoordinates.x);
const viewportX = viewport.x;
const viewportWidth = viewport.width;
if (x === 0 || windowCoordinates.x <= viewportX || windowCoordinates.x >= viewportX + viewportWidth) {
executeCommandsInViewport(true, scene, passState);
} else if (Math.abs(viewportX + viewportWidth * 0.5 - windowCoordinates.x) < 1) {
viewport.width = windowCoordinates.x - viewport.x;
camera.position.x *= Math_default.sign(camera.position.x);
camera.frustum.right = 0;
frameState.cullingVolume = camera.frustum.computeCullingVolume(
camera.positionWC,
camera.directionWC,
camera.upWC
);
context.uniformState.update(frameState);
executeCommandsInViewport(true, scene, passState);
viewport.x = windowCoordinates.x;
camera.position.x = -camera.position.x;
camera.frustum.right = -camera.frustum.left;
camera.frustum.left = 0;
frameState.cullingVolume = camera.frustum.computeCullingVolume(
camera.positionWC,
camera.directionWC,
camera.upWC
);
context.uniformState.update(frameState);
executeCommandsInViewport(false, scene, passState);
} else if (windowCoordinates.x > viewportX + viewportWidth * 0.5) {
viewport.width = windowCoordinates.x - viewportX;
const right = camera.frustum.right;
camera.frustum.right = maxCoord.x - x;
frameState.cullingVolume = camera.frustum.computeCullingVolume(
camera.positionWC,
camera.directionWC,
camera.upWC
);
context.uniformState.update(frameState);
executeCommandsInViewport(true, scene, passState);
viewport.x = windowCoordinates.x;
viewport.width = viewportX + viewportWidth - windowCoordinates.x;
camera.position.x = -camera.position.x;
camera.frustum.left = -camera.frustum.right;
camera.frustum.right = right - camera.frustum.right * 2;
frameState.cullingVolume = camera.frustum.computeCullingVolume(
camera.positionWC,
camera.directionWC,
camera.upWC
);
context.uniformState.update(frameState);
executeCommandsInViewport(false, scene, passState);
} else {
viewport.x = windowCoordinates.x;
viewport.width = viewportX + viewportWidth - windowCoordinates.x;
const left = camera.frustum.left;
camera.frustum.left = -maxCoord.x - x;
frameState.cullingVolume = camera.frustum.computeCullingVolume(
camera.positionWC,
camera.directionWC,
camera.upWC
);
context.uniformState.update(frameState);
executeCommandsInViewport(true, scene, passState);
viewport.x = viewportX;
viewport.width = windowCoordinates.x - viewportX;
camera.position.x = -camera.position.x;
camera.frustum.right = -camera.frustum.left;
camera.frustum.left = left - camera.frustum.left * 2;
frameState.cullingVolume = camera.frustum.computeCullingVolume(
camera.positionWC,
camera.directionWC,
camera.upWC
);
context.uniformState.update(frameState);
executeCommandsInViewport(false, scene, passState);
}
camera._setTransform(transform3);
Cartesian3_default.clone(position, camera.position);
camera.frustum = frustum.clone();
passState.viewport = originalViewport;
}
function executeCommandsInViewport(firstViewport, scene, passState, backgroundColor) {
const environmentState = scene._environmentState;
const view = scene._view;
const renderTranslucentDepthForPick2 = environmentState.renderTranslucentDepthForPick;
if (!firstViewport) {
scene.frameState.commandList.length = 0;
}
updateAndRenderPrimitives(scene);
view.createPotentiallyVisibleSet(scene);
if (firstViewport) {
if (defined_default(backgroundColor)) {
updateAndClearFramebuffers(scene, passState, backgroundColor);
}
executeComputeCommands(scene);
if (!renderTranslucentDepthForPick2) {
executeShadowMapCastCommands(scene);
}
}
executeCommands2(scene, passState);
}
var scratchCullingVolume2 = new CullingVolume_default();
Scene4.prototype.updateEnvironment = function() {
const frameState = this._frameState;
const view = this._view;
const environmentState = this._environmentState;
const renderPass = frameState.passes.render;
const offscreenPass = frameState.passes.offscreen;
const skyAtmosphere = this.skyAtmosphere;
const globe = this.globe;
const globeTranslucencyState = this._globeTranslucencyState;
if (!renderPass || this._mode !== SceneMode_default.SCENE2D && view.camera.frustum instanceof OrthographicFrustum_default || !globeTranslucencyState.environmentVisible) {
environmentState.skyAtmosphereCommand = void 0;
environmentState.skyBoxCommand = void 0;
environmentState.sunDrawCommand = void 0;
environmentState.sunComputeCommand = void 0;
environmentState.moonCommand = void 0;
} else {
if (defined_default(skyAtmosphere)) {
if (defined_default(globe)) {
skyAtmosphere.setDynamicAtmosphereColor(
globe.enableLighting && globe.dynamicAtmosphereLighting,
globe.dynamicAtmosphereLightingFromSun
);
environmentState.isReadyForAtmosphere = environmentState.isReadyForAtmosphere || globe._surface._tilesToRender.length > 0;
}
environmentState.skyAtmosphereCommand = skyAtmosphere.update(
frameState,
globe
);
if (defined_default(environmentState.skyAtmosphereCommand)) {
this.updateDerivedCommands(environmentState.skyAtmosphereCommand);
}
} else {
environmentState.skyAtmosphereCommand = void 0;
}
environmentState.skyBoxCommand = defined_default(this.skyBox) ? this.skyBox.update(frameState, this._hdr) : void 0;
const sunCommands = defined_default(this.sun) ? this.sun.update(frameState, view.passState, this._hdr) : void 0;
environmentState.sunDrawCommand = defined_default(sunCommands) ? sunCommands.drawCommand : void 0;
environmentState.sunComputeCommand = defined_default(sunCommands) ? sunCommands.computeCommand : void 0;
environmentState.moonCommand = defined_default(this.moon) ? this.moon.update(frameState) : void 0;
}
const clearGlobeDepth = environmentState.clearGlobeDepth = defined_default(globe) && globe.show && (!globe.depthTestAgainstTerrain || this.mode === SceneMode_default.SCENE2D);
const useDepthPlane2 = environmentState.useDepthPlane = clearGlobeDepth && this.mode === SceneMode_default.SCENE3D && globeTranslucencyState.useDepthPlane;
if (useDepthPlane2) {
this._depthPlane.update(frameState);
}
environmentState.renderTranslucentDepthForPick = false;
environmentState.useWebVR = this._useWebVR && this.mode !== SceneMode_default.SCENE2D && !offscreenPass;
const occluder = frameState.mode === SceneMode_default.SCENE3D && !globeTranslucencyState.sunVisibleThroughGlobe ? frameState.occluder : void 0;
let cullingVolume = frameState.cullingVolume;
const planes = scratchCullingVolume2.planes;
for (let k = 0; k < 5; ++k) {
planes[k] = cullingVolume.planes[k];
}
cullingVolume = scratchCullingVolume2;
environmentState.isSkyAtmosphereVisible = defined_default(environmentState.skyAtmosphereCommand) && environmentState.isReadyForAtmosphere;
environmentState.isSunVisible = this.isVisible(
environmentState.sunDrawCommand,
cullingVolume,
occluder
);
environmentState.isMoonVisible = this.isVisible(
environmentState.moonCommand,
cullingVolume,
occluder
);
const envMaps = this.specularEnvironmentMaps;
let envMapAtlas = this._specularEnvironmentMapAtlas;
if (defined_default(envMaps) && (!defined_default(envMapAtlas) || envMapAtlas.url !== envMaps)) {
envMapAtlas = envMapAtlas && envMapAtlas.destroy();
this._specularEnvironmentMapAtlas = new OctahedralProjectedCubeMap_default(envMaps);
} else if (!defined_default(envMaps) && defined_default(envMapAtlas)) {
envMapAtlas.destroy();
this._specularEnvironmentMapAtlas = void 0;
}
if (defined_default(this._specularEnvironmentMapAtlas)) {
this._specularEnvironmentMapAtlas.update(frameState);
}
};
function updateDebugFrustumPlanes(scene) {
const frameState = scene._frameState;
if (scene.debugShowFrustumPlanes !== scene._debugShowFrustumPlanes) {
if (scene.debugShowFrustumPlanes) {
scene._debugFrustumPlanes = new DebugCameraPrimitive_default({
camera: scene.camera,
updateOnChange: false,
frustumSplits: frameState.frustumSplits
});
} else {
scene._debugFrustumPlanes = scene._debugFrustumPlanes && scene._debugFrustumPlanes.destroy();
}
scene._debugShowFrustumPlanes = scene.debugShowFrustumPlanes;
}
if (defined_default(scene._debugFrustumPlanes)) {
scene._debugFrustumPlanes.update(frameState);
}
}
function updateShadowMaps(scene) {
const frameState = scene._frameState;
const shadowMaps = frameState.shadowMaps;
const length3 = shadowMaps.length;
const shadowsEnabled = length3 > 0 && !frameState.passes.pick && scene.mode === SceneMode_default.SCENE3D;
if (shadowsEnabled !== frameState.shadowState.shadowsEnabled) {
++frameState.shadowState.lastDirtyTime;
frameState.shadowState.shadowsEnabled = shadowsEnabled;
}
frameState.shadowState.lightShadowsEnabled = false;
if (!shadowsEnabled) {
return;
}
for (let j = 0; j < length3; ++j) {
if (shadowMaps[j] !== frameState.shadowState.shadowMaps[j]) {
++frameState.shadowState.lastDirtyTime;
break;
}
}
frameState.shadowState.shadowMaps.length = 0;
frameState.shadowState.lightShadowMaps.length = 0;
for (let i = 0; i < length3; ++i) {
const shadowMap = shadowMaps[i];
shadowMap.update(frameState);
frameState.shadowState.shadowMaps.push(shadowMap);
if (shadowMap.fromLightSource) {
frameState.shadowState.lightShadowMaps.push(shadowMap);
frameState.shadowState.lightShadowsEnabled = true;
}
if (shadowMap.dirty) {
++frameState.shadowState.lastDirtyTime;
shadowMap.dirty = false;
}
}
}
function updateAndRenderPrimitives(scene) {
const frameState = scene._frameState;
scene._groundPrimitives.update(frameState);
scene._primitives.update(frameState);
updateDebugFrustumPlanes(scene);
updateShadowMaps(scene);
if (scene._globe) {
scene._globe.render(frameState);
}
}
function updateAndClearFramebuffers(scene, passState, clearColor) {
const context = scene._context;
const frameState = scene._frameState;
const environmentState = scene._environmentState;
const view = scene._view;
const passes = scene._frameState.passes;
const picking = passes.pick;
if (defined_default(view.globeDepth)) {
view.globeDepth.picking = picking;
}
const useWebVR = environmentState.useWebVR;
environmentState.originalFramebuffer = passState.framebuffer;
if (defined_default(scene.sun) && scene.sunBloom !== scene._sunBloom) {
if (scene.sunBloom && !useWebVR) {
scene._sunPostProcess = new SunPostProcess_default();
} else if (defined_default(scene._sunPostProcess)) {
scene._sunPostProcess = scene._sunPostProcess.destroy();
}
scene._sunBloom = scene.sunBloom;
} else if (!defined_default(scene.sun) && defined_default(scene._sunPostProcess)) {
scene._sunPostProcess = scene._sunPostProcess.destroy();
scene._sunBloom = false;
}
const clear2 = scene._clearColorCommand;
Color_default.clone(clearColor, clear2.color);
clear2.execute(context, passState);
const useGlobeDepthFramebuffer = environmentState.useGlobeDepthFramebuffer = defined_default(
view.globeDepth
);
if (useGlobeDepthFramebuffer) {
view.globeDepth.update(
context,
passState,
view.viewport,
scene.msaaSamples,
scene._hdr,
environmentState.clearGlobeDepth
);
view.globeDepth.clear(context, passState, clearColor);
}
const oit = view.oit;
const useOIT = environmentState.useOIT = !picking && defined_default(oit) && oit.isSupported();
if (useOIT) {
oit.update(
context,
passState,
view.globeDepth.colorFramebufferManager,
scene._hdr,
scene.msaaSamples
);
oit.clear(context, passState, clearColor);
environmentState.useOIT = oit.isSupported();
}
const postProcess = scene.postProcessStages;
let usePostProcess = environmentState.usePostProcess = !picking && (scene._hdr || postProcess.length > 0 || postProcess.ambientOcclusion.enabled || postProcess.fxaa.enabled || postProcess.bloom.enabled);
environmentState.usePostProcessSelected = false;
if (usePostProcess) {
view.sceneFramebuffer.update(
context,
view.viewport,
scene._hdr,
scene.msaaSamples
);
view.sceneFramebuffer.clear(context, passState, clearColor);
postProcess.update(context, frameState.useLogDepth, scene._hdr);
postProcess.clear(context);
usePostProcess = environmentState.usePostProcess = postProcess.ready;
environmentState.usePostProcessSelected = usePostProcess && postProcess.hasSelected;
}
if (environmentState.isSunVisible && scene.sunBloom && !useWebVR) {
passState.framebuffer = scene._sunPostProcess.update(passState);
scene._sunPostProcess.clear(context, passState, clearColor);
} else if (useGlobeDepthFramebuffer) {
passState.framebuffer = view.globeDepth.framebuffer;
} else if (usePostProcess) {
passState.framebuffer = view.sceneFramebuffer.framebuffer;
}
if (defined_default(passState.framebuffer)) {
clear2.execute(context, passState);
}
const useInvertClassification = environmentState.useInvertClassification = !picking && defined_default(passState.framebuffer) && scene.invertClassification;
if (useInvertClassification) {
let depthFramebuffer;
if (scene.frameState.invertClassificationColor.alpha === 1) {
if (environmentState.useGlobeDepthFramebuffer) {
depthFramebuffer = view.globeDepth.framebuffer;
}
}
if (defined_default(depthFramebuffer) || context.depthTexture) {
scene._invertClassification.previousFramebuffer = depthFramebuffer;
scene._invertClassification.update(
context,
scene.msaaSamples,
view.globeDepth.colorFramebufferManager
);
scene._invertClassification.clear(context, passState);
if (scene.frameState.invertClassificationColor.alpha < 1 && useOIT) {
const command = scene._invertClassification.unclassifiedCommand;
const derivedCommands = command.derivedCommands;
derivedCommands.oit = oit.createDerivedCommands(
command,
context,
derivedCommands.oit
);
}
} else {
environmentState.useInvertClassification = false;
}
}
if (scene._globeTranslucencyState.translucent) {
view.globeTranslucencyFramebuffer.updateAndClear(
scene._hdr,
view.viewport,
context,
passState
);
}
}
Scene4.prototype.resolveFramebuffers = function(passState) {
const context = this._context;
const environmentState = this._environmentState;
const view = this._view;
const globeDepth = view.globeDepth;
if (defined_default(globeDepth)) {
globeDepth.prepareColorTextures(context);
}
const useOIT = environmentState.useOIT;
const useGlobeDepthFramebuffer = environmentState.useGlobeDepthFramebuffer;
const usePostProcess = environmentState.usePostProcess;
const defaultFramebuffer = environmentState.originalFramebuffer;
const globeFramebuffer = useGlobeDepthFramebuffer ? globeDepth.colorFramebufferManager : void 0;
const sceneFramebuffer = view.sceneFramebuffer._colorFramebuffer;
const idFramebuffer = view.sceneFramebuffer.idFramebuffer;
if (useOIT) {
passState.framebuffer = usePostProcess ? sceneFramebuffer.framebuffer : defaultFramebuffer;
view.oit.execute(context, passState);
}
const translucentTileClassification = view.translucentTileClassification;
if (translucentTileClassification.hasTranslucentDepth && translucentTileClassification.isSupported()) {
translucentTileClassification.execute(this, passState);
}
if (usePostProcess) {
view.sceneFramebuffer.prepareColorTextures(context);
let inputFramebuffer = sceneFramebuffer;
if (useGlobeDepthFramebuffer && !useOIT) {
inputFramebuffer = globeFramebuffer;
}
const postProcess = this.postProcessStages;
const colorTexture = inputFramebuffer.getColorTexture(0);
const idTexture = idFramebuffer.getColorTexture(0);
const depthTexture = defaultValue_default(
globeFramebuffer,
sceneFramebuffer
).getDepthStencilTexture();
postProcess.execute(context, colorTexture, depthTexture, idTexture);
postProcess.copy(context, defaultFramebuffer);
}
if (!useOIT && !usePostProcess && useGlobeDepthFramebuffer) {
passState.framebuffer = defaultFramebuffer;
globeDepth.executeCopyColor(context, passState);
}
};
function callAfterRenderFunctions(scene) {
const functions = scene._frameState.afterRender;
for (let i = 0, length3 = functions.length; i < length3; ++i) {
const shouldRequestRender = functions[i]();
if (shouldRequestRender) {
scene.requestRender();
}
}
functions.length = 0;
}
function getGlobeHeight(scene) {
const globe = scene._globe;
const camera = scene.camera;
const cartographic2 = camera.positionCartographic;
if (defined_default(globe) && globe.show && defined_default(cartographic2)) {
return globe.getHeight(cartographic2);
}
return void 0;
}
function isCameraUnderground(scene) {
const camera = scene.camera;
const mode2 = scene._mode;
const globe = scene.globe;
const cameraController = scene._screenSpaceCameraController;
const cartographic2 = camera.positionCartographic;
if (!defined_default(cartographic2)) {
return false;
}
if (!cameraController.onMap() && cartographic2.height < 0) {
return true;
}
if (!defined_default(globe) || !globe.show || mode2 === SceneMode_default.SCENE2D || mode2 === SceneMode_default.MORPHING) {
return false;
}
const globeHeight = scene._globeHeight;
return defined_default(globeHeight) && cartographic2.height < globeHeight;
}
Scene4.prototype.initializeFrame = function() {
if (this._shaderFrameCount++ === 120) {
this._shaderFrameCount = 0;
this._context.shaderCache.destroyReleasedShaderPrograms();
this._context.textureCache.destroyReleasedTextures();
}
this._tweens.update();
this._globeHeight = getGlobeHeight(this);
this._cameraUnderground = isCameraUnderground(this);
this._globeTranslucencyState.update(this);
this._screenSpaceCameraController.update();
if (defined_default(this._deviceOrientationCameraController)) {
this._deviceOrientationCameraController.update();
}
this.camera.update(this._mode);
this.camera._updateCameraChanged();
};
function updateDebugShowFramesPerSecond(scene, renderedThisFrame) {
if (scene.debugShowFramesPerSecond) {
if (!defined_default(scene._performanceDisplay)) {
const performanceContainer = document.createElement("div");
performanceContainer.className = "cesium-performanceDisplay-defaultContainer";
const container = scene._canvas.parentNode;
container.appendChild(performanceContainer);
const performanceDisplay = new PerformanceDisplay_default({
container: performanceContainer
});
scene._performanceDisplay = performanceDisplay;
scene._performanceContainer = performanceContainer;
}
scene._performanceDisplay.throttled = scene.requestRenderMode;
scene._performanceDisplay.update(renderedThisFrame);
} else if (defined_default(scene._performanceDisplay)) {
scene._performanceDisplay = scene._performanceDisplay && scene._performanceDisplay.destroy();
scene._performanceContainer.parentNode.removeChild(
scene._performanceContainer
);
}
}
function prePassesUpdate(scene) {
scene._jobScheduler.resetBudgets();
const frameState = scene._frameState;
const primitives = scene.primitives;
primitives.prePassesUpdate(frameState);
if (defined_default(scene.globe)) {
scene.globe.update(frameState);
}
scene._picking.update();
frameState.creditDisplay.update();
}
function postPassesUpdate(scene) {
const frameState = scene._frameState;
const primitives = scene.primitives;
primitives.postPassesUpdate(frameState);
RequestScheduler_default.update();
}
var scratchBackgroundColor = new Color_default();
function render(scene) {
const frameState = scene._frameState;
const context = scene.context;
const us = context.uniformState;
const view = scene._defaultView;
scene._view = view;
scene.updateFrameState();
frameState.passes.render = true;
frameState.passes.postProcess = scene.postProcessStages.hasSelected;
frameState.tilesetPassState = renderTilesetPassState;
let backgroundColor = defaultValue_default(scene.backgroundColor, Color_default.BLACK);
if (scene._hdr) {
backgroundColor = Color_default.clone(backgroundColor, scratchBackgroundColor);
backgroundColor.red = Math.pow(backgroundColor.red, scene.gamma);
backgroundColor.green = Math.pow(backgroundColor.green, scene.gamma);
backgroundColor.blue = Math.pow(backgroundColor.blue, scene.gamma);
}
frameState.backgroundColor = backgroundColor;
scene.fog.update(frameState);
us.update(frameState);
const shadowMap = scene.shadowMap;
if (defined_default(shadowMap) && shadowMap.enabled) {
if (!defined_default(scene.light) || scene.light instanceof SunLight_default) {
Cartesian3_default.negate(us.sunDirectionWC, scene._shadowMapCamera.direction);
} else {
Cartesian3_default.clone(scene.light.direction, scene._shadowMapCamera.direction);
}
frameState.shadowMaps.push(shadowMap);
}
scene._computeCommandList.length = 0;
scene._overlayCommandList.length = 0;
const viewport = view.viewport;
viewport.x = 0;
viewport.y = 0;
viewport.width = context.drawingBufferWidth;
viewport.height = context.drawingBufferHeight;
const passState = view.passState;
passState.framebuffer = void 0;
passState.blendingEnabled = void 0;
passState.scissorTest = void 0;
passState.viewport = BoundingRectangle_default.clone(viewport, passState.viewport);
if (defined_default(scene.globe)) {
scene.globe.beginFrame(frameState);
}
scene.updateEnvironment();
scene.updateAndExecuteCommands(passState, backgroundColor);
scene.resolveFramebuffers(passState);
passState.framebuffer = void 0;
executeOverlayCommands(scene, passState);
if (defined_default(scene.globe)) {
scene.globe.endFrame(frameState);
if (!scene.globe.tilesLoaded) {
scene._renderRequested = true;
}
}
context.endFrame();
}
function tryAndCatchError(scene, functionToExecute) {
try {
functionToExecute(scene);
} catch (error) {
scene._renderError.raiseEvent(scene, error);
if (scene.rethrowRenderErrors) {
throw error;
}
}
}
function updateMostDetailedRayPicks(scene) {
return scene._picking.updateMostDetailedRayPicks(scene);
}
Scene4.prototype.render = function(time) {
this._preUpdate.raiseEvent(this, time);
const frameState = this._frameState;
frameState.newFrame = false;
if (!defined_default(time)) {
time = JulianDate_default.now();
}
const cameraChanged = this._view.checkForCameraUpdates(this);
let shouldRender = !this.requestRenderMode || this._renderRequested || cameraChanged || this._logDepthBufferDirty || this._hdrDirty || this.mode === SceneMode_default.MORPHING;
if (!shouldRender && defined_default(this.maximumRenderTimeChange) && defined_default(this._lastRenderTime)) {
const difference = Math.abs(
JulianDate_default.secondsDifference(this._lastRenderTime, time)
);
shouldRender = shouldRender || difference > this.maximumRenderTimeChange;
}
if (shouldRender) {
this._lastRenderTime = JulianDate_default.clone(time, this._lastRenderTime);
this._renderRequested = false;
this._logDepthBufferDirty = false;
this._hdrDirty = false;
const frameNumber = Math_default.incrementWrap(
frameState.frameNumber,
15e6,
1
);
updateFrameNumber(this, frameNumber, time);
frameState.newFrame = true;
}
tryAndCatchError(this, prePassesUpdate);
if (this.primitives.show) {
tryAndCatchError(this, updateMostDetailedRayPicks);
tryAndCatchError(this, updatePreloadPass);
tryAndCatchError(this, updatePreloadFlightPass);
if (!shouldRender) {
tryAndCatchError(this, updateRequestRenderModeDeferCheckPass);
}
}
this._postUpdate.raiseEvent(this, time);
if (shouldRender) {
this._preRender.raiseEvent(this, time);
frameState.creditDisplay.beginFrame();
tryAndCatchError(this, render);
}
updateDebugShowFramesPerSecond(this, shouldRender);
tryAndCatchError(this, postPassesUpdate);
callAfterRenderFunctions(this);
if (shouldRender) {
this._postRender.raiseEvent(this, time);
frameState.creditDisplay.endFrame();
}
};
Scene4.prototype.forceRender = function(time) {
this._renderRequested = true;
this.render(time);
};
Scene4.prototype.requestRender = function() {
this._renderRequested = true;
};
Scene4.prototype.clampLineWidth = function(width) {
return Math.max(
ContextLimits_default.minimumAliasedLineWidth,
Math.min(width, ContextLimits_default.maximumAliasedLineWidth)
);
};
Scene4.prototype.pick = function(windowPosition, width, height) {
return this._picking.pick(this, windowPosition, width, height);
};
Scene4.prototype.pickPositionWorldCoordinates = function(windowPosition, result) {
return this._picking.pickPositionWorldCoordinates(
this,
windowPosition,
result
);
};
Scene4.prototype.pickPosition = function(windowPosition, result) {
return this._picking.pickPosition(this, windowPosition, result);
};
Scene4.prototype.drillPick = function(windowPosition, limit, width, height) {
return this._picking.drillPick(this, windowPosition, limit, width, height);
};
function updatePreloadPass(scene) {
const frameState = scene._frameState;
preloadTilesetPassState.camera = frameState.camera;
preloadTilesetPassState.cullingVolume = frameState.cullingVolume;
const primitives = scene.primitives;
primitives.updateForPass(frameState, preloadTilesetPassState);
}
function updatePreloadFlightPass(scene) {
const frameState = scene._frameState;
const camera = frameState.camera;
if (!camera.canPreloadFlight()) {
return;
}
preloadFlightTilesetPassState.camera = scene.preloadFlightCamera;
preloadFlightTilesetPassState.cullingVolume = scene.preloadFlightCullingVolume;
const primitives = scene.primitives;
primitives.updateForPass(frameState, preloadFlightTilesetPassState);
}
function updateRequestRenderModeDeferCheckPass(scene) {
scene.primitives.updateForPass(
scene._frameState,
requestRenderModeDeferCheckPassState
);
}
Scene4.prototype.pickFromRay = function(ray, objectsToExclude, width) {
return this._picking.pickFromRay(this, ray, objectsToExclude, width);
};
Scene4.prototype.drillPickFromRay = function(ray, limit, objectsToExclude, width) {
return this._picking.drillPickFromRay(
this,
ray,
limit,
objectsToExclude,
width
);
};
Scene4.prototype.pickFromRayMostDetailed = function(ray, objectsToExclude, width) {
return this._picking.pickFromRayMostDetailed(
this,
ray,
objectsToExclude,
width
);
};
Scene4.prototype.drillPickFromRayMostDetailed = function(ray, limit, objectsToExclude, width) {
return this._picking.drillPickFromRayMostDetailed(
this,
ray,
limit,
objectsToExclude,
width
);
};
Scene4.prototype.sampleHeight = function(position, objectsToExclude, width) {
return this._picking.sampleHeight(this, position, objectsToExclude, width);
};
Scene4.prototype.clampToHeight = function(cartesian11, objectsToExclude, width, result) {
return this._picking.clampToHeight(
this,
cartesian11,
objectsToExclude,
width,
result
);
};
Scene4.prototype.sampleHeightMostDetailed = function(positions, objectsToExclude, width) {
return this._picking.sampleHeightMostDetailed(
this,
positions,
objectsToExclude,
width
);
};
Scene4.prototype.clampToHeightMostDetailed = function(cartesians, objectsToExclude, width) {
return this._picking.clampToHeightMostDetailed(
this,
cartesians,
objectsToExclude,
width
);
};
Scene4.prototype.cartesianToCanvasCoordinates = function(position, result) {
return SceneTransforms_default.wgs84ToWindowCoordinates(this, position, result);
};
Scene4.prototype.completeMorph = function() {
this._transitioner.completeMorph();
};
Scene4.prototype.morphTo2D = function(duration) {
let ellipsoid;
const globe = this.globe;
if (defined_default(globe)) {
ellipsoid = globe.ellipsoid;
} else {
ellipsoid = this.mapProjection.ellipsoid;
}
duration = defaultValue_default(duration, 2);
this._transitioner.morphTo2D(duration, ellipsoid);
};
Scene4.prototype.morphToColumbusView = function(duration) {
let ellipsoid;
const globe = this.globe;
if (defined_default(globe)) {
ellipsoid = globe.ellipsoid;
} else {
ellipsoid = this.mapProjection.ellipsoid;
}
duration = defaultValue_default(duration, 2);
this._transitioner.morphToColumbusView(duration, ellipsoid);
};
Scene4.prototype.morphTo3D = function(duration) {
let ellipsoid;
const globe = this.globe;
if (defined_default(globe)) {
ellipsoid = globe.ellipsoid;
} else {
ellipsoid = this.mapProjection.ellipsoid;
}
duration = defaultValue_default(duration, 2);
this._transitioner.morphTo3D(duration, ellipsoid);
};
function setTerrain(scene, terrain) {
scene._removeTerrainProviderReadyListener = scene._removeTerrainProviderReadyListener && scene._removeTerrainProviderReadyListener();
if (terrain.ready) {
if (defined_default(scene.globe)) {
scene.globe.terrainProvider = terrain.provider;
}
return;
}
scene.globe.terrainProvider = void 0;
scene._removeTerrainProviderReadyListener = terrain.readyEvent.addEventListener(
(provider) => {
if (defined_default(scene) && defined_default(scene.globe)) {
scene.globe.terrainProvider = provider;
}
scene._removeTerrainProviderReadyListener();
}
);
}
Scene4.prototype.setTerrain = function(terrain) {
Check_default.typeOf.object("terrain", terrain);
setTerrain(this, terrain);
return terrain;
};
Scene4.prototype.isDestroyed = function() {
return false;
};
Scene4.prototype.destroy = function() {
this._tweens.removeAll();
this._computeEngine = this._computeEngine && this._computeEngine.destroy();
this._screenSpaceCameraController = this._screenSpaceCameraController && this._screenSpaceCameraController.destroy();
this._deviceOrientationCameraController = this._deviceOrientationCameraController && !this._deviceOrientationCameraController.isDestroyed() && this._deviceOrientationCameraController.destroy();
this._primitives = this._primitives && this._primitives.destroy();
this._groundPrimitives = this._groundPrimitives && this._groundPrimitives.destroy();
this._globe = this._globe && this._globe.destroy();
this._removeTerrainProviderReadyListener = this._removeTerrainProviderReadyListener && this._removeTerrainProviderReadyListener();
this.skyBox = this.skyBox && this.skyBox.destroy();
this.skyAtmosphere = this.skyAtmosphere && this.skyAtmosphere.destroy();
this._debugSphere = this._debugSphere && this._debugSphere.destroy();
this.sun = this.sun && this.sun.destroy();
this._sunPostProcess = this._sunPostProcess && this._sunPostProcess.destroy();
this._depthPlane = this._depthPlane && this._depthPlane.destroy();
this._transitioner = this._transitioner && this._transitioner.destroy();
this._debugFrustumPlanes = this._debugFrustumPlanes && this._debugFrustumPlanes.destroy();
this._brdfLutGenerator = this._brdfLutGenerator && this._brdfLutGenerator.destroy();
this._picking = this._picking && this._picking.destroy();
this._defaultView = this._defaultView && this._defaultView.destroy();
this._view = void 0;
if (this._removeCreditContainer) {
this._canvas.parentNode.removeChild(this._creditContainer);
}
this.postProcessStages = this.postProcessStages && this.postProcessStages.destroy();
this._context = this._context && this._context.destroy();
this._frameState.creditDisplay = this._frameState.creditDisplay && this._frameState.creditDisplay.destroy();
if (defined_default(this._performanceDisplay)) {
this._performanceDisplay = this._performanceDisplay && this._performanceDisplay.destroy();
this._performanceContainer.parentNode.removeChild(
this._performanceContainer
);
}
this._removeRequestListenerCallback();
this._removeTaskProcessorListenerCallback();
for (let i = 0; i < this._removeGlobeCallbacks.length; ++i) {
this._removeGlobeCallbacks[i]();
}
this._removeGlobeCallbacks.length = 0;
return destroyObject_default(this);
};
var Scene_default = Scene4;
// packages/engine/Source/Shaders/SkyAtmosphereCommon.js
var SkyAtmosphereCommon_default = "float interpolateByDistance(vec4 nearFarScalar, float distance)\n{\n float startDistance = nearFarScalar.x;\n float startValue = nearFarScalar.y;\n float endDistance = nearFarScalar.z;\n float endValue = nearFarScalar.w;\n float t = clamp((distance - startDistance) / (endDistance - startDistance), 0.0, 1.0);\n return mix(startValue, endValue, t);\n}\n\nvec3 getLightDirection(vec3 positionWC)\n{\n float lightEnum = u_radiiAndDynamicAtmosphereColor.z;\n vec3 lightDirection =\n positionWC * float(lightEnum == 0.0) +\n czm_lightDirectionWC * float(lightEnum == 1.0) +\n czm_sunDirectionWC * float(lightEnum == 2.0);\n return normalize(lightDirection);\n}\n\nvoid computeAtmosphereScattering(vec3 positionWC, vec3 lightDirection, out vec3 rayleighColor, out vec3 mieColor, out float opacity, out float underTranslucentGlobe)\n{\n float ellipsoidRadiiDifference = czm_ellipsoidRadii.x - czm_ellipsoidRadii.z;\n\n // Adjustment to the atmosphere radius applied based on the camera height.\n float distanceAdjustMin = czm_ellipsoidRadii.x / 4.0;\n float distanceAdjustMax = czm_ellipsoidRadii.x;\n float distanceAdjustModifier = ellipsoidRadiiDifference / 2.0;\n float distanceAdjust = distanceAdjustModifier * clamp((czm_eyeHeight - distanceAdjustMin) / (distanceAdjustMax - distanceAdjustMin), 0.0, 1.0);\n\n // Since atmosphere scattering assumes the atmosphere is a spherical shell, we compute an inner radius of the atmosphere best fit \n // for the position on the ellipsoid.\n float radiusAdjust = (ellipsoidRadiiDifference / 4.0) + distanceAdjust;\n float atmosphereInnerRadius = (length(czm_viewerPositionWC) - czm_eyeHeight) - radiusAdjust;\n\n // Setup the primary ray: from the camera position to the vertex position.\n vec3 cameraToPositionWC = positionWC - czm_viewerPositionWC;\n vec3 cameraToPositionWCDirection = normalize(cameraToPositionWC);\n czm_ray primaryRay = czm_ray(czm_viewerPositionWC, cameraToPositionWCDirection);\n\n underTranslucentGlobe = 0.0;\n\n // Brighten the sky atmosphere under the Earth's atmosphere when translucency is enabled.\n #if defined(GLOBE_TRANSLUCENT)\n\n // Check for intersection with the inner radius of the atmopshere.\n czm_raySegment primaryRayEarthIntersect = czm_raySphereIntersectionInterval(primaryRay, vec3(0.0), atmosphereInnerRadius + radiusAdjust);\n if (primaryRayEarthIntersect.start > 0.0 && primaryRayEarthIntersect.stop > 0.0) {\n \n // Compute position on globe.\n vec3 direction = normalize(positionWC);\n czm_ray ellipsoidRay = czm_ray(positionWC, -direction);\n czm_raySegment ellipsoidIntersection = czm_rayEllipsoidIntersectionInterval(ellipsoidRay, vec3(0.0), czm_ellipsoidInverseRadii);\n vec3 onEarth = positionWC - (direction * ellipsoidIntersection.start);\n\n // Control the color using the camera angle.\n float angle = dot(normalize(czm_viewerPositionWC), normalize(onEarth));\n\n // Control the opacity using the distance from Earth.\n opacity = interpolateByDistance(vec4(0.0, 1.0, czm_ellipsoidRadii.x, 0.0), length(czm_viewerPositionWC - onEarth));\n vec3 horizonColor = vec3(0.1, 0.2, 0.3);\n vec3 nearColor = vec3(0.0);\n\n rayleighColor = mix(nearColor, horizonColor, exp(-angle) * opacity);\n \n // Set the traslucent flag to avoid alpha adjustment in computeFinalColor funciton.\n underTranslucentGlobe = 1.0;\n return;\n }\n #endif\n\n computeScattering(\n primaryRay,\n length(cameraToPositionWC),\n lightDirection,\n atmosphereInnerRadius,\n rayleighColor,\n mieColor,\n opacity\n );\n\n // Alter the opacity based on how close the viewer is to the ground.\n // (0.0 = At edge of atmosphere, 1.0 = On ground)\n float cameraHeight = czm_eyeHeight + atmosphereInnerRadius;\n float atmosphereOuterRadius = atmosphereInnerRadius + ATMOSPHERE_THICKNESS;\n opacity = clamp((atmosphereOuterRadius - cameraHeight) / (atmosphereOuterRadius - atmosphereInnerRadius), 0.0, 1.0);\n\n // Alter alpha based on time of day (0.0 = night , 1.0 = day)\n float nightAlpha = (u_radiiAndDynamicAtmosphereColor.z != 0.0) ? clamp(dot(normalize(positionWC), lightDirection), 0.0, 1.0) : 1.0;\n opacity *= pow(nightAlpha, 0.5);\n}\n";
// packages/engine/Source/Shaders/SkyAtmosphereFS.js
var SkyAtmosphereFS_default = "in vec3 v_outerPositionWC;\n\nuniform vec3 u_hsbShift;\n\n#ifndef PER_FRAGMENT_ATMOSPHERE\nin vec3 v_mieColor;\nin vec3 v_rayleighColor;\nin float v_opacity;\nin float v_translucent;\n#endif\n\nvoid main (void)\n{\n vec3 lightDirection = getLightDirection(v_outerPositionWC);\n \n vec3 mieColor;\n vec3 rayleighColor;\n float opacity;\n float translucent;\n\n #ifdef PER_FRAGMENT_ATMOSPHERE\n computeAtmosphereScattering(\n v_outerPositionWC,\n lightDirection,\n rayleighColor,\n mieColor,\n opacity,\n translucent\n );\n #else\n mieColor = v_mieColor;\n rayleighColor = v_rayleighColor;\n opacity = v_opacity;\n translucent = v_translucent;\n #endif\n\n vec4 color = computeAtmosphereColor(v_outerPositionWC, lightDirection, rayleighColor, mieColor, opacity);\n\n #ifndef HDR\n color.rgb = czm_acesTonemapping(color.rgb);\n color.rgb = czm_inverseGamma(color.rgb);\n #endif\n\n #ifdef COLOR_CORRECT\n // Convert rgb color to hsb\n vec3 hsb = czm_RGBToHSB(color.rgb);\n // Perform hsb shift\n hsb.x += u_hsbShift.x; // hue\n hsb.y = clamp(hsb.y + u_hsbShift.y, 0.0, 1.0); // saturation\n hsb.z = hsb.z > czm_epsilon7 ? hsb.z + u_hsbShift.z : 0.0; // brightness\n // Convert shifted hsb back to rgb\n color.rgb = czm_HSBToRGB(hsb);\n #endif\n\n // For the parts of the sky atmosphere that are not behind a translucent globe,\n // we mix in the default opacity so that the sky atmosphere still appears at distance.\n // This is needed because the opacity in the sky atmosphere is initially adjusted based\n // on the camera height.\n if (translucent == 0.0) {\n color.a = mix(color.b, 1.0, color.a) * smoothstep(0.0, 1.0, czm_morphTime);\n }\n\n out_FragColor = color;\n}\n";
// packages/engine/Source/Shaders/SkyAtmosphereVS.js
var SkyAtmosphereVS_default = "in vec4 position;\n\nout vec3 v_outerPositionWC;\n\n#ifndef PER_FRAGMENT_ATMOSPHERE\nout vec3 v_mieColor;\nout vec3 v_rayleighColor;\nout float v_opacity;\nout float v_translucent;\n#endif\n\nvoid main(void)\n{\n vec4 positionWC = czm_model * position;\n vec3 lightDirection = getLightDirection(positionWC.xyz);\n\n #ifndef PER_FRAGMENT_ATMOSPHERE\n computeAtmosphereScattering(\n positionWC.xyz,\n lightDirection,\n v_rayleighColor,\n v_mieColor,\n v_opacity,\n v_translucent\n );\n #endif\n \n v_outerPositionWC = positionWC.xyz;\n gl_Position = czm_modelViewProjection * position;\n}\n";
// packages/engine/Source/Scene/SkyAtmosphere.js
function SkyAtmosphere(ellipsoid) {
ellipsoid = defaultValue_default(ellipsoid, Ellipsoid_default.WGS84);
this.show = true;
this.perFragmentAtmosphere = false;
this._ellipsoid = ellipsoid;
const outerEllipsoidScale = 1.025;
const scaleVector = Cartesian3_default.multiplyByScalar(
ellipsoid.radii,
outerEllipsoidScale,
new Cartesian3_default()
);
this._scaleMatrix = Matrix4_default.fromScale(scaleVector);
this._modelMatrix = new Matrix4_default();
this._command = new DrawCommand_default({
owner: this,
modelMatrix: this._modelMatrix
});
this._spSkyFromSpace = void 0;
this._spSkyFromAtmosphere = void 0;
this._flags = void 0;
this.atmosphereLightIntensity = 50;
this.atmosphereRayleighCoefficient = new Cartesian3_default(55e-7, 13e-6, 284e-7);
this.atmosphereMieCoefficient = new Cartesian3_default(21e-6, 21e-6, 21e-6);
this.atmosphereRayleighScaleHeight = 1e4;
this.atmosphereMieScaleHeight = 3200;
this.atmosphereMieAnisotropy = 0.9;
this.hueShift = 0;
this.saturationShift = 0;
this.brightnessShift = 0;
this._hueSaturationBrightness = new Cartesian3_default();
const radiiAndDynamicAtmosphereColor = new Cartesian3_default();
radiiAndDynamicAtmosphereColor.x = ellipsoid.maximumRadius * outerEllipsoidScale;
radiiAndDynamicAtmosphereColor.y = ellipsoid.maximumRadius;
radiiAndDynamicAtmosphereColor.z = 0;
this._radiiAndDynamicAtmosphereColor = radiiAndDynamicAtmosphereColor;
const that = this;
this._command.uniformMap = {
u_radiiAndDynamicAtmosphereColor: function() {
return that._radiiAndDynamicAtmosphereColor;
},
u_hsbShift: function() {
that._hueSaturationBrightness.x = that.hueShift;
that._hueSaturationBrightness.y = that.saturationShift;
that._hueSaturationBrightness.z = that.brightnessShift;
return that._hueSaturationBrightness;
},
u_atmosphereLightIntensity: function() {
return that.atmosphereLightIntensity;
},
u_atmosphereRayleighCoefficient: function() {
return that.atmosphereRayleighCoefficient;
},
u_atmosphereMieCoefficient: function() {
return that.atmosphereMieCoefficient;
},
u_atmosphereRayleighScaleHeight: function() {
return that.atmosphereRayleighScaleHeight;
},
u_atmosphereMieScaleHeight: function() {
return that.atmosphereMieScaleHeight;
},
u_atmosphereMieAnisotropy: function() {
return that.atmosphereMieAnisotropy;
}
};
}
Object.defineProperties(SkyAtmosphere.prototype, {
/**
* Gets the ellipsoid the atmosphere is drawn around.
* @memberof SkyAtmosphere.prototype
*
* @type {Ellipsoid}
* @readonly
*/
ellipsoid: {
get: function() {
return this._ellipsoid;
}
}
});
SkyAtmosphere.prototype.setDynamicAtmosphereColor = function(enableLighting, useSunDirection) {
const lightEnum = enableLighting ? useSunDirection ? 2 : 1 : 0;
this._radiiAndDynamicAtmosphereColor.z = lightEnum;
};
var scratchModelMatrix2 = new Matrix4_default();
SkyAtmosphere.prototype.update = function(frameState, globe) {
if (!this.show) {
return void 0;
}
const mode2 = frameState.mode;
if (mode2 !== SceneMode_default.SCENE3D && mode2 !== SceneMode_default.MORPHING) {
return void 0;
}
if (!frameState.passes.render) {
return void 0;
}
const rotationMatrix = Matrix4_default.fromRotationTranslation(
frameState.context.uniformState.inverseViewRotation,
Cartesian3_default.ZERO,
scratchModelMatrix2
);
const rotationOffsetMatrix = Matrix4_default.multiplyTransformation(
rotationMatrix,
Axis_default.Y_UP_TO_Z_UP,
scratchModelMatrix2
);
const modelMatrix = Matrix4_default.multiply(
this._scaleMatrix,
rotationOffsetMatrix,
scratchModelMatrix2
);
Matrix4_default.clone(modelMatrix, this._modelMatrix);
const context = frameState.context;
const colorCorrect = hasColorCorrection(this);
const translucent = frameState.globeTranslucencyState.translucent;
const perFragmentAtmosphere = this.perFragmentAtmosphere || translucent || !defined_default(globe) || !globe.show;
const command = this._command;
if (!defined_default(command.vertexArray)) {
const geometry = EllipsoidGeometry_default.createGeometry(
new EllipsoidGeometry_default({
radii: new Cartesian3_default(1, 1, 1),
slicePartitions: 256,
stackPartitions: 256,
vertexFormat: VertexFormat_default.POSITION_ONLY
})
);
command.vertexArray = VertexArray_default.fromGeometry({
context,
geometry,
attributeLocations: GeometryPipeline_default.createAttributeLocations(geometry),
bufferUsage: BufferUsage_default.STATIC_DRAW
});
command.renderState = RenderState_default.fromCache({
cull: {
enabled: true,
face: CullFace_default.FRONT
},
blending: BlendingState_default.ALPHA_BLEND,
depthMask: false
});
}
const flags = colorCorrect | perFragmentAtmosphere << 2 | translucent << 3;
if (flags !== this._flags) {
this._flags = flags;
const defines = [];
if (colorCorrect) {
defines.push("COLOR_CORRECT");
}
if (perFragmentAtmosphere) {
defines.push("PER_FRAGMENT_ATMOSPHERE");
}
if (translucent) {
defines.push("GLOBE_TRANSLUCENT");
}
const vs = new ShaderSource_default({
defines,
sources: [AtmosphereCommon_default, SkyAtmosphereCommon_default, SkyAtmosphereVS_default]
});
const fs = new ShaderSource_default({
defines,
sources: [AtmosphereCommon_default, SkyAtmosphereCommon_default, SkyAtmosphereFS_default]
});
this._spSkyAtmosphere = ShaderProgram_default.fromCache({
context,
vertexShaderSource: vs,
fragmentShaderSource: fs
});
command.shaderProgram = this._spSkyAtmosphere;
}
return command;
};
function hasColorCorrection(skyAtmosphere) {
return !(Math_default.equalsEpsilon(
skyAtmosphere.hueShift,
0,
Math_default.EPSILON7
) && Math_default.equalsEpsilon(
skyAtmosphere.saturationShift,
0,
Math_default.EPSILON7
) && Math_default.equalsEpsilon(
skyAtmosphere.brightnessShift,
0,
Math_default.EPSILON7
));
}
SkyAtmosphere.prototype.isDestroyed = function() {
return false;
};
SkyAtmosphere.prototype.destroy = function() {
const command = this._command;
command.vertexArray = command.vertexArray && command.vertexArray.destroy();
this._spSkyAtmosphere = this._spSkyAtmosphere && this._spSkyAtmosphere.destroy();
return destroyObject_default(this);
};
var SkyAtmosphere_default = SkyAtmosphere;
// packages/engine/Source/Shaders/SkyBoxFS.js
var SkyBoxFS_default = "uniform samplerCube u_cubeMap;\n\nin vec3 v_texCoord;\n\nvoid main()\n{\n vec4 color = czm_textureCube(u_cubeMap, normalize(v_texCoord));\n out_FragColor = vec4(czm_gammaCorrect(color).rgb, czm_morphTime);\n}\n";
// packages/engine/Source/Shaders/SkyBoxVS.js
var SkyBoxVS_default = "in vec3 position;\n\nout vec3 v_texCoord;\n\nvoid main()\n{\n vec3 p = czm_viewRotation * (czm_temeToPseudoFixed * (czm_entireFrustum.y * position));\n gl_Position = czm_projection * vec4(p, 1.0);\n v_texCoord = position.xyz;\n}\n";
// packages/engine/Source/Scene/SkyBox.js
function SkyBox(options) {
this.sources = options.sources;
this._sources = void 0;
this.show = defaultValue_default(options.show, true);
this._command = new DrawCommand_default({
modelMatrix: Matrix4_default.clone(Matrix4_default.IDENTITY),
owner: this
});
this._cubeMap = void 0;
this._attributeLocations = void 0;
this._useHdr = void 0;
}
SkyBox.prototype.update = function(frameState, useHdr) {
const that = this;
if (!this.show) {
return void 0;
}
if (frameState.mode !== SceneMode_default.SCENE3D && frameState.mode !== SceneMode_default.MORPHING) {
return void 0;
}
if (!frameState.passes.render) {
return void 0;
}
const context = frameState.context;
if (this._sources !== this.sources) {
this._sources = this.sources;
const sources = this.sources;
if (!defined_default(sources.positiveX) || !defined_default(sources.negativeX) || !defined_default(sources.positiveY) || !defined_default(sources.negativeY) || !defined_default(sources.positiveZ) || !defined_default(sources.negativeZ)) {
throw new DeveloperError_default(
"this.sources is required and must have positiveX, negativeX, positiveY, negativeY, positiveZ, and negativeZ properties."
);
}
if (typeof sources.positiveX !== typeof sources.negativeX || typeof sources.positiveX !== typeof sources.positiveY || typeof sources.positiveX !== typeof sources.negativeY || typeof sources.positiveX !== typeof sources.positiveZ || typeof sources.positiveX !== typeof sources.negativeZ) {
throw new DeveloperError_default(
"this.sources properties must all be the same type."
);
}
if (typeof sources.positiveX === "string") {
loadCubeMap_default(context, this._sources).then(function(cubeMap) {
that._cubeMap = that._cubeMap && that._cubeMap.destroy();
that._cubeMap = cubeMap;
});
} else {
this._cubeMap = this._cubeMap && this._cubeMap.destroy();
this._cubeMap = new CubeMap_default({
context,
source: sources
});
}
}
const command = this._command;
if (!defined_default(command.vertexArray)) {
command.uniformMap = {
u_cubeMap: function() {
return that._cubeMap;
}
};
const geometry = BoxGeometry_default.createGeometry(
BoxGeometry_default.fromDimensions({
dimensions: new Cartesian3_default(2, 2, 2),
vertexFormat: VertexFormat_default.POSITION_ONLY
})
);
const attributeLocations8 = this._attributeLocations = GeometryPipeline_default.createAttributeLocations(
geometry
);
command.vertexArray = VertexArray_default.fromGeometry({
context,
geometry,
attributeLocations: attributeLocations8,
bufferUsage: BufferUsage_default.STATIC_DRAW
});
command.renderState = RenderState_default.fromCache({
blending: BlendingState_default.ALPHA_BLEND
});
}
if (!defined_default(command.shaderProgram) || this._useHdr !== useHdr) {
const fs = new ShaderSource_default({
defines: [useHdr ? "HDR" : ""],
sources: [SkyBoxFS_default]
});
command.shaderProgram = ShaderProgram_default.fromCache({
context,
vertexShaderSource: SkyBoxVS_default,
fragmentShaderSource: fs,
attributeLocations: this._attributeLocations
});
this._useHdr = useHdr;
}
if (!defined_default(this._cubeMap)) {
return void 0;
}
return command;
};
SkyBox.prototype.isDestroyed = function() {
return false;
};
SkyBox.prototype.destroy = function() {
const command = this._command;
command.vertexArray = command.vertexArray && command.vertexArray.destroy();
command.shaderProgram = command.shaderProgram && command.shaderProgram.destroy();
this._cubeMap = this._cubeMap && this._cubeMap.destroy();
return destroyObject_default(this);
};
var SkyBox_default = SkyBox;
// packages/engine/Source/Shaders/SunFS.js
var SunFS_default = "uniform sampler2D u_texture;\n\nin vec2 v_textureCoordinates;\n\nvoid main()\n{\n vec4 color = texture(u_texture, v_textureCoordinates);\n out_FragColor = czm_gammaCorrect(color);\n}\n";
// packages/engine/Source/Shaders/SunTextureFS.js
var SunTextureFS_default = "uniform float u_radiusTS;\n\nin vec2 v_textureCoordinates;\n\nvec2 rotate(vec2 p, vec2 direction)\n{\n return vec2(p.x * direction.x - p.y * direction.y, p.x * direction.y + p.y * direction.x);\n}\n\nvec4 addBurst(vec2 position, vec2 direction, float lengthScalar)\n{\n vec2 rotatedPosition = rotate(position, direction) * vec2(25.0, 0.75);\n float radius = length(rotatedPosition) * lengthScalar;\n float burst = 1.0 - smoothstep(0.0, 0.55, radius);\n return vec4(burst);\n}\n\nvoid main()\n{\n float lengthScalar = 2.0 / sqrt(2.0);\n vec2 position = v_textureCoordinates - vec2(0.5);\n float radius = length(position) * lengthScalar;\n float surface = step(radius, u_radiusTS);\n vec4 color = vec4(vec2(1.0), surface + 0.2, surface);\n\n float glow = 1.0 - smoothstep(0.0, 0.55, radius);\n color.ba += mix(vec2(0.0), vec2(1.0), glow) * 0.75;\n\n vec4 burst = vec4(0.0);\n\n // The following loop has been manually unrolled for speed, to\n // avoid sin() and cos().\n //\n //for (float i = 0.4; i < 3.2; i += 1.047) {\n // vec2 direction = vec2(sin(i), cos(i));\n // burst += 0.4 * addBurst(position, direction, lengthScalar);\n //\n // direction = vec2(sin(i - 0.08), cos(i - 0.08));\n // burst += 0.3 * addBurst(position, direction, lengthScalar);\n //}\n\n burst += 0.4 * addBurst(position, vec2(0.38942, 0.92106), lengthScalar); // angle == 0.4\n burst += 0.4 * addBurst(position, vec2(0.99235, 0.12348), lengthScalar); // angle == 0.4 + 1.047\n burst += 0.4 * addBurst(position, vec2(0.60327, -0.79754), lengthScalar); // angle == 0.4 + 1.047 * 2.0\n\n burst += 0.3 * addBurst(position, vec2(0.31457, 0.94924), lengthScalar); // angle == 0.4 - 0.08\n burst += 0.3 * addBurst(position, vec2(0.97931, 0.20239), lengthScalar); // angle == 0.4 + 1.047 - 0.08\n burst += 0.3 * addBurst(position, vec2(0.66507, -0.74678), lengthScalar); // angle == 0.4 + 1.047 * 2.0 - 0.08\n\n // End of manual loop unrolling.\n\n color += clamp(burst, vec4(0.0), vec4(1.0)) * 0.15;\n\n out_FragColor = clamp(color, vec4(0.0), vec4(1.0));\n}\n";
// packages/engine/Source/Shaders/SunVS.js
var SunVS_default = "in vec2 direction;\n\nuniform float u_size;\n\nout vec2 v_textureCoordinates;\n\nvoid main() \n{\n vec4 position;\n if (czm_morphTime == 1.0)\n {\n position = vec4(czm_sunPositionWC, 1.0);\n }\n else\n {\n position = vec4(czm_sunPositionColumbusView.zxy, 1.0);\n }\n \n vec4 positionEC = czm_view * position;\n vec4 positionWC = czm_eyeToWindowCoordinates(positionEC);\n \n vec2 halfSize = vec2(u_size * 0.5);\n halfSize *= ((direction * 2.0) - 1.0);\n \n gl_Position = czm_viewportOrthographic * vec4(positionWC.xy + halfSize, -positionWC.z, 1.0);\n \n v_textureCoordinates = direction;\n}\n";
// packages/engine/Source/Scene/Sun.js
function Sun() {
this.show = true;
this._drawCommand = new DrawCommand_default({
primitiveType: PrimitiveType_default.TRIANGLES,
boundingVolume: new BoundingSphere_default(),
owner: this
});
this._commands = {
drawCommand: this._drawCommand,
computeCommand: void 0
};
this._boundingVolume = new BoundingSphere_default();
this._boundingVolume2D = new BoundingSphere_default();
this._texture = void 0;
this._drawingBufferWidth = void 0;
this._drawingBufferHeight = void 0;
this._radiusTS = void 0;
this._size = void 0;
this.glowFactor = 1;
this._glowFactorDirty = false;
this._useHdr = void 0;
const that = this;
this._uniformMap = {
u_texture: function() {
return that._texture;
},
u_size: function() {
return that._size;
}
};
}
Object.defineProperties(Sun.prototype, {
/**
* Gets or sets a number that controls how "bright" the Sun's lens flare appears
* to be. Zero shows just the Sun's disc without any flare.
* Use larger values for a more pronounced flare around the Sun.
*
* @memberof Sun.prototype
* @type {number}
* @default 1.0
*/
glowFactor: {
get: function() {
return this._glowFactor;
},
set: function(glowFactor) {
glowFactor = Math.max(glowFactor, 0);
this._glowFactor = glowFactor;
this._glowFactorDirty = true;
}
}
});
var scratchPositionWC = new Cartesian2_default();
var scratchLimbWC = new Cartesian2_default();
var scratchPositionEC = new Cartesian4_default();
var scratchCartesian47 = new Cartesian4_default();
Sun.prototype.update = function(frameState, passState, useHdr) {
if (!this.show) {
return void 0;
}
const mode2 = frameState.mode;
if (mode2 === SceneMode_default.SCENE2D || mode2 === SceneMode_default.MORPHING) {
return void 0;
}
if (!frameState.passes.render) {
return void 0;
}
const context = frameState.context;
const drawingBufferWidth = passState.viewport.width;
const drawingBufferHeight = passState.viewport.height;
if (!defined_default(this._texture) || drawingBufferWidth !== this._drawingBufferWidth || drawingBufferHeight !== this._drawingBufferHeight || this._glowFactorDirty || useHdr !== this._useHdr) {
this._texture = this._texture && this._texture.destroy();
this._drawingBufferWidth = drawingBufferWidth;
this._drawingBufferHeight = drawingBufferHeight;
this._glowFactorDirty = false;
this._useHdr = useHdr;
let size = Math.max(drawingBufferWidth, drawingBufferHeight);
size = Math.pow(2, Math.ceil(Math.log(size) / Math.log(2)) - 2);
size = Math.max(1, size);
const pixelDatatype = useHdr ? context.halfFloatingPointTexture ? PixelDatatype_default.HALF_FLOAT : PixelDatatype_default.FLOAT : PixelDatatype_default.UNSIGNED_BYTE;
this._texture = new Texture_default({
context,
width: size,
height: size,
pixelFormat: PixelFormat_default.RGBA,
pixelDatatype
});
this._glowLengthTS = this._glowFactor * 5;
this._radiusTS = 1 / (1 + 2 * this._glowLengthTS) * 0.5;
const that = this;
const uniformMap2 = {
u_radiusTS: function() {
return that._radiusTS;
}
};
this._commands.computeCommand = new ComputeCommand_default({
fragmentShaderSource: SunTextureFS_default,
outputTexture: this._texture,
uniformMap: uniformMap2,
persists: false,
owner: this,
postExecute: function() {
that._commands.computeCommand = void 0;
}
});
}
const drawCommand = this._drawCommand;
if (!defined_default(drawCommand.vertexArray)) {
const attributeLocations8 = {
direction: 0
};
const directions2 = new Uint8Array(4 * 2);
directions2[0] = 0;
directions2[1] = 0;
directions2[2] = 255;
directions2[3] = 0;
directions2[4] = 255;
directions2[5] = 255;
directions2[6] = 0;
directions2[7] = 255;
const vertexBuffer = Buffer_default.createVertexBuffer({
context,
typedArray: directions2,
usage: BufferUsage_default.STATIC_DRAW
});
const attributes = [
{
index: attributeLocations8.direction,
vertexBuffer,
componentsPerAttribute: 2,
normalize: true,
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE
}
];
const indexBuffer = Buffer_default.createIndexBuffer({
context,
typedArray: new Uint16Array([0, 1, 2, 0, 2, 3]),
usage: BufferUsage_default.STATIC_DRAW,
indexDatatype: IndexDatatype_default.UNSIGNED_SHORT
});
drawCommand.vertexArray = new VertexArray_default({
context,
attributes,
indexBuffer
});
drawCommand.shaderProgram = ShaderProgram_default.fromCache({
context,
vertexShaderSource: SunVS_default,
fragmentShaderSource: SunFS_default,
attributeLocations: attributeLocations8
});
drawCommand.renderState = RenderState_default.fromCache({
blending: BlendingState_default.ALPHA_BLEND
});
drawCommand.uniformMap = this._uniformMap;
}
const sunPosition = context.uniformState.sunPositionWC;
const sunPositionCV = context.uniformState.sunPositionColumbusView;
const boundingVolume = this._boundingVolume;
const boundingVolume2D = this._boundingVolume2D;
Cartesian3_default.clone(sunPosition, boundingVolume.center);
boundingVolume2D.center.x = sunPositionCV.z;
boundingVolume2D.center.y = sunPositionCV.x;
boundingVolume2D.center.z = sunPositionCV.y;
boundingVolume.radius = Math_default.SOLAR_RADIUS + Math_default.SOLAR_RADIUS * this._glowLengthTS;
boundingVolume2D.radius = boundingVolume.radius;
if (mode2 === SceneMode_default.SCENE3D) {
BoundingSphere_default.clone(boundingVolume, drawCommand.boundingVolume);
} else if (mode2 === SceneMode_default.COLUMBUS_VIEW) {
BoundingSphere_default.clone(boundingVolume2D, drawCommand.boundingVolume);
}
const position = SceneTransforms_default.computeActualWgs84Position(
frameState,
sunPosition,
scratchCartesian47
);
const dist = Cartesian3_default.magnitude(
Cartesian3_default.subtract(position, frameState.camera.position, scratchCartesian47)
);
const projMatrix = context.uniformState.projection;
const positionEC = scratchPositionEC;
positionEC.x = 0;
positionEC.y = 0;
positionEC.z = -dist;
positionEC.w = 1;
const positionCC2 = Matrix4_default.multiplyByVector(
projMatrix,
positionEC,
scratchCartesian47
);
const positionWC2 = SceneTransforms_default.clipToGLWindowCoordinates(
passState.viewport,
positionCC2,
scratchPositionWC
);
positionEC.x = Math_default.SOLAR_RADIUS;
const limbCC = Matrix4_default.multiplyByVector(
projMatrix,
positionEC,
scratchCartesian47
);
const limbWC = SceneTransforms_default.clipToGLWindowCoordinates(
passState.viewport,
limbCC,
scratchLimbWC
);
this._size = Cartesian2_default.magnitude(
Cartesian2_default.subtract(limbWC, positionWC2, scratchCartesian47)
);
this._size = 2 * this._size * (1 + 2 * this._glowLengthTS);
this._size = Math.ceil(this._size);
return this._commands;
};
Sun.prototype.isDestroyed = function() {
return false;
};
Sun.prototype.destroy = function() {
const command = this._drawCommand;
command.vertexArray = command.vertexArray && command.vertexArray.destroy();
command.shaderProgram = command.shaderProgram && command.shaderProgram.destroy();
this._texture = this._texture && this._texture.destroy();
return destroyObject_default(this);
};
var Sun_default = Sun;
// packages/engine/Source/Widget/CesiumWidget.js
function getDefaultSkyBoxUrl(suffix) {
return buildModuleUrl_default(`Assets/Textures/SkyBox/tycho2t3_80_${suffix}.jpg`);
}
function startRenderLoop(widget) {
widget._renderLoopRunning = true;
let lastFrameTime = 0;
function render2(frameTime) {
if (widget.isDestroyed()) {
return;
}
if (widget._useDefaultRenderLoop) {
try {
const targetFrameRate = widget._targetFrameRate;
if (!defined_default(targetFrameRate)) {
widget.resize();
widget.render();
requestAnimationFrame(render2);
} else {
const interval = 1e3 / targetFrameRate;
const delta = frameTime - lastFrameTime;
if (delta > interval) {
widget.resize();
widget.render();
lastFrameTime = frameTime - delta % interval;
}
requestAnimationFrame(render2);
}
} catch (error) {
widget._useDefaultRenderLoop = false;
widget._renderLoopRunning = false;
if (widget._showRenderLoopErrors) {
const title = "An error occurred while rendering. Rendering has stopped.";
widget.showErrorPanel(title, void 0, error);
}
}
} else {
widget._renderLoopRunning = false;
}
}
requestAnimationFrame(render2);
}
function configurePixelRatio(widget) {
let pixelRatio = widget._useBrowserRecommendedResolution ? 1 : window.devicePixelRatio;
pixelRatio *= widget._resolutionScale;
if (defined_default(widget._scene)) {
widget._scene.pixelRatio = pixelRatio;
}
return pixelRatio;
}
function configureCanvasSize(widget) {
const canvas = widget._canvas;
let width = canvas.clientWidth;
let height = canvas.clientHeight;
const pixelRatio = configurePixelRatio(widget);
widget._canvasClientWidth = width;
widget._canvasClientHeight = height;
width *= pixelRatio;
height *= pixelRatio;
canvas.width = width;
canvas.height = height;
widget._canRender = width !== 0 && height !== 0;
widget._lastDevicePixelRatio = window.devicePixelRatio;
}
function configureCameraFrustum(widget) {
const canvas = widget._canvas;
const width = canvas.width;
const height = canvas.height;
if (width !== 0 && height !== 0) {
const frustum = widget._scene.camera.frustum;
if (defined_default(frustum.aspectRatio)) {
frustum.aspectRatio = width / height;
} else {
frustum.top = frustum.right * (height / width);
frustum.bottom = -frustum.top;
}
}
}
function CesiumWidget(container, options) {
if (!defined_default(container)) {
throw new DeveloperError_default("container is required.");
}
container = getElement_default(container);
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const element = document.createElement("div");
element.className = "cesium-widget";
container.appendChild(element);
const canvas = document.createElement("canvas");
const supportsImageRenderingPixelated2 = FeatureDetection_default.supportsImageRenderingPixelated();
this._supportsImageRenderingPixelated = supportsImageRenderingPixelated2;
if (supportsImageRenderingPixelated2) {
canvas.style.imageRendering = FeatureDetection_default.imageRenderingValue();
}
canvas.oncontextmenu = function() {
return false;
};
canvas.onselectstart = function() {
return false;
};
function blurActiveElement() {
if (canvas !== canvas.ownerDocument.activeElement) {
canvas.ownerDocument.activeElement.blur();
}
}
const blurActiveElementOnCanvasFocus = defaultValue_default(
options.blurActiveElementOnCanvasFocus,
true
);
if (blurActiveElementOnCanvasFocus) {
canvas.addEventListener("mousedown", blurActiveElement);
canvas.addEventListener("pointerdown", blurActiveElement);
}
element.appendChild(canvas);
const innerCreditContainer = document.createElement("div");
innerCreditContainer.className = "cesium-widget-credits";
const creditContainer = defined_default(options.creditContainer) ? getElement_default(options.creditContainer) : element;
creditContainer.appendChild(innerCreditContainer);
const creditViewport = defined_default(options.creditViewport) ? getElement_default(options.creditViewport) : element;
const showRenderLoopErrors = defaultValue_default(options.showRenderLoopErrors, true);
const useBrowserRecommendedResolution = defaultValue_default(
options.useBrowserRecommendedResolution,
true
);
this._element = element;
this._container = container;
this._canvas = canvas;
this._canvasClientWidth = 0;
this._canvasClientHeight = 0;
this._lastDevicePixelRatio = 0;
this._creditViewport = creditViewport;
this._creditContainer = creditContainer;
this._innerCreditContainer = innerCreditContainer;
this._canRender = false;
this._renderLoopRunning = false;
this._showRenderLoopErrors = showRenderLoopErrors;
this._resolutionScale = 1;
this._useBrowserRecommendedResolution = useBrowserRecommendedResolution;
this._forceResize = false;
this._clock = defined_default(options.clock) ? options.clock : new Clock_default();
configureCanvasSize(this);
try {
const scene = new Scene_default({
canvas,
contextOptions: options.contextOptions,
creditContainer: innerCreditContainer,
creditViewport,
mapProjection: options.mapProjection,
orderIndependentTranslucency: options.orderIndependentTranslucency,
scene3DOnly: defaultValue_default(options.scene3DOnly, false),
shadows: options.shadows,
mapMode2D: options.mapMode2D,
requestRenderMode: options.requestRenderMode,
maximumRenderTimeChange: options.maximumRenderTimeChange,
depthPlaneEllipsoidOffset: options.depthPlaneEllipsoidOffset,
msaaSamples: options.msaaSamples
});
this._scene = scene;
scene.camera.constrainedAxis = Cartesian3_default.UNIT_Z;
configurePixelRatio(this);
configureCameraFrustum(this);
const ellipsoid = defaultValue_default(
scene.mapProjection.ellipsoid,
Ellipsoid_default.WGS84
);
let globe = options.globe;
if (!defined_default(globe)) {
globe = new Globe_default(ellipsoid);
}
if (globe !== false) {
scene.globe = globe;
scene.globe.shadows = defaultValue_default(
options.terrainShadows,
ShadowMode_default.RECEIVE_ONLY
);
}
let skyBox = options.skyBox;
if (!defined_default(skyBox)) {
skyBox = new SkyBox_default({
sources: {
positiveX: getDefaultSkyBoxUrl("px"),
negativeX: getDefaultSkyBoxUrl("mx"),
positiveY: getDefaultSkyBoxUrl("py"),
negativeY: getDefaultSkyBoxUrl("my"),
positiveZ: getDefaultSkyBoxUrl("pz"),
negativeZ: getDefaultSkyBoxUrl("mz")
}
});
}
if (skyBox !== false) {
scene.skyBox = skyBox;
scene.sun = new Sun_default();
scene.moon = new Moon_default();
}
let skyAtmosphere = options.skyAtmosphere;
if (!defined_default(skyAtmosphere)) {
skyAtmosphere = new SkyAtmosphere_default(ellipsoid);
}
if (skyAtmosphere !== false) {
scene.skyAtmosphere = skyAtmosphere;
}
if (defined_default(options.imageryProvider)) {
deprecationWarning_default(
"CesiumWidget options.imageryProvider",
"options.imageryProvider was deprecated in CesiumJS 1.104. It will be in CesiumJS 1.107. Use options.baseLayer instead."
);
}
let baseLayer = options.baseLayer;
if (options.globe !== false && baseLayer !== false && options.imageryProvider !== false) {
if (defined_default(options.imageryProvider) && !defined_default(baseLayer)) {
baseLayer = new ImageryLayer_default(options.imageryProvider);
}
if (!defined_default(baseLayer)) {
baseLayer = ImageryLayer_default.fromWorldImagery();
}
scene.imageryLayers.add(baseLayer);
}
if (defined_default(options.terrainProvider) && options.globe !== false) {
scene.terrainProvider = options.terrainProvider;
}
if (defined_default(options.terrain) && options.globe !== false) {
if (defined_default(options.terrainProvider)) {
throw new DeveloperError_default(
"Specify either options.terrainProvider or options.terrain."
);
}
scene.setTerrain(options.terrain);
}
this._screenSpaceEventHandler = new ScreenSpaceEventHandler_default(canvas);
if (defined_default(options.sceneMode)) {
if (options.sceneMode === SceneMode_default.SCENE2D) {
this._scene.morphTo2D(0);
}
if (options.sceneMode === SceneMode_default.COLUMBUS_VIEW) {
this._scene.morphToColumbusView(0);
}
}
this._useDefaultRenderLoop = void 0;
this.useDefaultRenderLoop = defaultValue_default(
options.useDefaultRenderLoop,
true
);
this._targetFrameRate = void 0;
this.targetFrameRate = options.targetFrameRate;
const that = this;
this._onRenderError = function(scene2, error) {
that._useDefaultRenderLoop = false;
that._renderLoopRunning = false;
if (that._showRenderLoopErrors) {
const title = "An error occurred while rendering. Rendering has stopped.";
that.showErrorPanel(title, void 0, error);
}
};
scene.renderError.addEventListener(this._onRenderError);
} catch (error) {
if (showRenderLoopErrors) {
const title = "Error constructing CesiumWidget.";
const message = 'Visit http://get.webgl.org to verify that your web browser and hardware support WebGL. Consider trying a different web browser or updating your video drivers. Detailed error information is below:';
this.showErrorPanel(title, message, error);
}
throw error;
}
}
Object.defineProperties(CesiumWidget.prototype, {
/**
* Gets the parent container.
* @memberof CesiumWidget.prototype
*
* @type {Element}
* @readonly
*/
container: {
get: function() {
return this._container;
}
},
/**
* Gets the canvas.
* @memberof CesiumWidget.prototype
*
* @type {HTMLCanvasElement}
* @readonly
*/
canvas: {
get: function() {
return this._canvas;
}
},
/**
* Gets the credit container.
* @memberof CesiumWidget.prototype
*
* @type {Element}
* @readonly
*/
creditContainer: {
get: function() {
return this._creditContainer;
}
},
/**
* Gets the credit viewport
* @memberof CesiumWidget.prototype
*
* @type {Element}
* @readonly
*/
creditViewport: {
get: function() {
return this._creditViewport;
}
},
/**
* Gets the scene.
* @memberof CesiumWidget.prototype
*
* @type {Scene}
* @readonly
*/
scene: {
get: function() {
return this._scene;
}
},
/**
* Gets the collection of image layers that will be rendered on the globe.
* @memberof CesiumWidget.prototype
*
* @type {ImageryLayerCollection}
* @readonly
*/
imageryLayers: {
get: function() {
return this._scene.imageryLayers;
}
},
/**
* The terrain provider providing surface geometry for the globe.
* @memberof CesiumWidget.prototype
*
* @type {TerrainProvider}
*/
terrainProvider: {
get: function() {
return this._scene.terrainProvider;
},
set: function(terrainProvider) {
this._scene.terrainProvider = terrainProvider;
}
},
/**
* Manages the list of credits to display on screen and in the lightbox.
* @memberof CesiumWidget.prototype
*
* @type {CreditDisplay}
*/
creditDisplay: {
get: function() {
return this._scene.frameState.creditDisplay;
}
},
/**
* Gets the camera.
* @memberof CesiumWidget.prototype
*
* @type {Camera}
* @readonly
*/
camera: {
get: function() {
return this._scene.camera;
}
},
/**
* Gets the clock.
* @memberof CesiumWidget.prototype
*
* @type {Clock}
* @readonly
*/
clock: {
get: function() {
return this._clock;
}
},
/**
* Gets the screen space event handler.
* @memberof CesiumWidget.prototype
*
* @type {ScreenSpaceEventHandler}
* @readonly
*/
screenSpaceEventHandler: {
get: function() {
return this._screenSpaceEventHandler;
}
},
/**
* Gets or sets the target frame rate of the widget when useDefaultRenderLoop
* is true. If undefined, the browser's requestAnimationFrame implementation
* determines the frame rate. If defined, this value must be greater than 0. A value higher
* than the underlying requestAnimationFrame implementation will have no effect.
* @memberof CesiumWidget.prototype
*
* @type {number}
*/
targetFrameRate: {
get: function() {
return this._targetFrameRate;
},
set: function(value) {
if (value <= 0) {
throw new DeveloperError_default(
"targetFrameRate must be greater than 0, or undefined."
);
}
this._targetFrameRate = value;
}
},
/**
* Gets or sets whether or not this widget should control the render loop.
* If true the widget will use requestAnimationFrame to
* perform rendering and resizing of the widget, as well as drive the
* simulation clock. If set to false, you must manually call the
* resize
, render
methods as part of a custom
* render loop. If an error occurs during rendering, {@link Scene}'s
* renderError
event will be raised and this property
* will be set to false. It must be set back to true to continue rendering
* after the error.
* @memberof CesiumWidget.prototype
*
* @type {boolean}
*/
useDefaultRenderLoop: {
get: function() {
return this._useDefaultRenderLoop;
},
set: function(value) {
if (this._useDefaultRenderLoop !== value) {
this._useDefaultRenderLoop = value;
if (value && !this._renderLoopRunning) {
startRenderLoop(this);
}
}
}
},
/**
* Gets or sets a scaling factor for rendering resolution. Values less than 1.0 can improve
* performance on less powerful devices while values greater than 1.0 will render at a higher
* resolution and then scale down, resulting in improved visual fidelity.
* For example, if the widget is laid out at a size of 640x480, setting this value to 0.5
* will cause the scene to be rendered at 320x240 and then scaled up while setting
* it to 2.0 will cause the scene to be rendered at 1280x960 and then scaled down.
* @memberof CesiumWidget.prototype
*
* @type {number}
* @default 1.0
*/
resolutionScale: {
get: function() {
return this._resolutionScale;
},
set: function(value) {
if (value <= 0) {
throw new DeveloperError_default("resolutionScale must be greater than 0.");
}
if (this._resolutionScale !== value) {
this._resolutionScale = value;
this._forceResize = true;
}
}
},
/**
* Boolean flag indicating if the browser's recommended resolution is used.
* If true, the browser's device pixel ratio is ignored and 1.0 is used instead,
* effectively rendering based on CSS pixels instead of device pixels. This can improve
* performance on less powerful devices that have high pixel density. When false, rendering
* will be in device pixels. {@link CesiumWidget#resolutionScale} will still take effect whether
* this flag is true or false.
* @memberof CesiumWidget.prototype
*
* @type {boolean}
* @default true
*/
useBrowserRecommendedResolution: {
get: function() {
return this._useBrowserRecommendedResolution;
},
set: function(value) {
if (this._useBrowserRecommendedResolution !== value) {
this._useBrowserRecommendedResolution = value;
this._forceResize = true;
}
}
}
});
CesiumWidget.prototype.showErrorPanel = function(title, message, error) {
const element = this._element;
const overlay = document.createElement("div");
overlay.className = "cesium-widget-errorPanel";
const content = document.createElement("div");
content.className = "cesium-widget-errorPanel-content";
overlay.appendChild(content);
const errorHeader = document.createElement("div");
errorHeader.className = "cesium-widget-errorPanel-header";
errorHeader.appendChild(document.createTextNode(title));
content.appendChild(errorHeader);
const errorPanelScroller = document.createElement("div");
errorPanelScroller.className = "cesium-widget-errorPanel-scroll";
content.appendChild(errorPanelScroller);
function resizeCallback() {
errorPanelScroller.style.maxHeight = `${Math.max(
Math.round(element.clientHeight * 0.9 - 100),
30
)}px`;
}
resizeCallback();
if (defined_default(window.addEventListener)) {
window.addEventListener("resize", resizeCallback, false);
}
const hasMessage = defined_default(message);
const hasError = defined_default(error);
if (hasMessage || hasError) {
const errorMessage = document.createElement("div");
errorMessage.className = "cesium-widget-errorPanel-message";
errorPanelScroller.appendChild(errorMessage);
if (hasError) {
let errorDetails = formatError_default(error);
if (!hasMessage) {
if (typeof error === "string") {
error = new Error(error);
}
message = formatError_default({
name: error.name,
message: error.message
});
errorDetails = error.stack;
}
if (typeof console !== "undefined") {
console.error(`${title}
${message}
${errorDetails}`);
}
const errorMessageDetails = document.createElement("div");
errorMessageDetails.className = "cesium-widget-errorPanel-message-details collapsed";
const moreDetails = document.createElement("span");
moreDetails.className = "cesium-widget-errorPanel-more-details";
moreDetails.appendChild(document.createTextNode("See more..."));
errorMessageDetails.appendChild(moreDetails);
errorMessageDetails.onclick = function(e) {
errorMessageDetails.removeChild(moreDetails);
errorMessageDetails.appendChild(document.createTextNode(errorDetails));
errorMessageDetails.className = "cesium-widget-errorPanel-message-details";
content.className = "cesium-widget-errorPanel-content expanded";
errorMessageDetails.onclick = void 0;
};
errorPanelScroller.appendChild(errorMessageDetails);
}
errorMessage.innerHTML = `${message}
`; } const buttonPanel = document.createElement("div"); buttonPanel.className = "cesium-widget-errorPanel-buttonPanel"; content.appendChild(buttonPanel); const okButton = document.createElement("button"); okButton.setAttribute("type", "button"); okButton.className = "cesium-button"; okButton.appendChild(document.createTextNode("OK")); okButton.onclick = function() { if (defined_default(resizeCallback) && defined_default(window.removeEventListener)) { window.removeEventListener("resize", resizeCallback, false); } element.removeChild(overlay); }; buttonPanel.appendChild(okButton); element.appendChild(overlay); }; CesiumWidget.prototype.isDestroyed = function() { return false; }; CesiumWidget.prototype.destroy = function() { if (defined_default(this._scene)) { this._scene.renderError.removeEventListener(this._onRenderError); this._scene = this._scene.destroy(); } this._container.removeChild(this._element); this._creditContainer.removeChild(this._innerCreditContainer); destroyObject_default(this); }; CesiumWidget.prototype.resize = function() { const canvas = this._canvas; if (!this._forceResize && this._canvasClientWidth === canvas.clientWidth && this._canvasClientHeight === canvas.clientHeight && this._lastDevicePixelRatio === window.devicePixelRatio) { return; } this._forceResize = false; configureCanvasSize(this); configureCameraFrustum(this); this._scene.requestRender(); }; CesiumWidget.prototype.render = function() { if (this._canRender) { this._scene.initializeFrame(); const currentTime = this._clock.tick(); this._scene.render(currentTime); } else { this._clock.tick(); } }; var CesiumWidget_default = CesiumWidget; // packages/engine/Source/Shaders/CloudCollectionFS.js var CloudCollectionFS_default = `uniform sampler2D u_noiseTexture; uniform vec3 u_noiseTextureDimensions; uniform float u_noiseDetail; in vec2 v_offset; in vec3 v_maximumSize; in vec4 v_color; in float v_slice; in float v_brightness; float wrap(float value, float rangeLength) { if(value < 0.0) { float absValue = abs(value); float modValue = mod(absValue, rangeLength); return mod(rangeLength - modValue, rangeLength); } return mod(value, rangeLength); } vec3 wrapVec(vec3 value, float rangeLength) { return vec3(wrap(value.x, rangeLength), wrap(value.y, rangeLength), wrap(value.z, rangeLength)); } vec2 voxelToUV(vec3 voxelIndex) { float textureSliceWidth = u_noiseTextureDimensions.x; float noiseTextureRows = u_noiseTextureDimensions.y; float inverseNoiseTextureRows = u_noiseTextureDimensions.z; float textureSliceWidthSquared = textureSliceWidth * textureSliceWidth; vec2 inverseNoiseTextureDimensions = vec2(noiseTextureRows / textureSliceWidthSquared, inverseNoiseTextureRows / textureSliceWidth); vec3 wrappedIndex = wrapVec(voxelIndex, textureSliceWidth); float column = mod(wrappedIndex.z, textureSliceWidth * inverseNoiseTextureRows); float row = floor(wrappedIndex.z / textureSliceWidth * noiseTextureRows); float xPixelCoord = wrappedIndex.x + column * textureSliceWidth; float yPixelCoord = wrappedIndex.y + row * textureSliceWidth; return vec2(xPixelCoord, yPixelCoord) * inverseNoiseTextureDimensions; } // Interpolate a voxel with its neighbor (along the positive X-axis) vec4 lerpSamplesX(vec3 voxelIndex, float x) { vec2 uv0 = voxelToUV(voxelIndex); vec2 uv1 = voxelToUV(voxelIndex + vec3(1.0, 0.0, 0.0)); vec4 sample0 = texture(u_noiseTexture, uv0); vec4 sample1 = texture(u_noiseTexture, uv1); return mix(sample0, sample1, x); } vec4 sampleNoiseTexture(vec3 position) { float textureSliceWidth = u_noiseTextureDimensions.x; vec3 recenteredPos = position + vec3(textureSliceWidth / 2.0); vec3 lerpValue = fract(recenteredPos); vec3 voxelIndex = floor(recenteredPos); vec4 xLerp00 = lerpSamplesX(voxelIndex, lerpValue.x); vec4 xLerp01 = lerpSamplesX(voxelIndex + vec3(0.0, 0.0, 1.0), lerpValue.x); vec4 xLerp10 = lerpSamplesX(voxelIndex + vec3(0.0, 1.0, 0.0), lerpValue.x); vec4 xLerp11 = lerpSamplesX(voxelIndex + vec3(0.0, 1.0, 1.0), lerpValue.x); vec4 yLerp0 = mix(xLerp00, xLerp10, lerpValue.y); vec4 yLerp1 = mix(xLerp01, xLerp11, lerpValue.y); return mix(yLerp0, yLerp1, lerpValue.z); } // Intersection with a unit sphere with radius 0.5 at center (0, 0, 0). bool intersectSphere(vec3 origin, vec3 dir, float slice, out vec3 point, out vec3 normal) { float A = dot(dir, dir); float B = dot(origin, dir); float C = dot(origin, origin) - 0.25; float discriminant = (B * B) - (A * C); if(discriminant < 0.0) { return false; } float root = sqrt(discriminant); float t = (-B - root) / A; if(t < 0.0) { t = (-B + root) / A; } point = origin + t * dir; if(slice >= 0.0) { point.z = (slice / 2.0) - 0.5; if(length(point) > 0.5) { return false; } } normal = normalize(point); point -= czm_epsilon2 * normal; return true; } // Transforms the ray origin and direction into unit sphere space, // then transforms the result back into the ellipsoid's space. bool intersectEllipsoid(vec3 origin, vec3 dir, vec3 center, vec3 scale, float slice, out vec3 point, out vec3 normal) { if(scale.x <= 0.01 || scale.y < 0.01 || scale.z < 0.01) { return false; } vec3 o = (origin - center) / scale; vec3 d = dir / scale; vec3 p, n; bool intersected = intersectSphere(o, d, slice, p, n); if(intersected) { point = (p * scale) + center; normal = n; } return intersected; } // Assume that if phase shift is being called for octave i, // the frequency is of i - 1. This saves us from doing extra // division / multiplication operations. vec2 phaseShift2D(vec2 p, vec2 freq) { return (czm_pi / 2.0) * sin(freq.yx * p.yx); } vec2 phaseShift3D(vec3 p, vec2 freq) { return phaseShift2D(p.xy, freq) + czm_pi * vec2(sin(freq.x * p.z)); } // The cloud texture function derived from Gardner's 1985 paper, // "Visual Simulation of Clouds." // https://www.cs.drexel.edu/~david/Classes/Papers/p297-gardner.pdf const float T0 = 0.6; // contrast of the texture pattern const float k = 0.1; // computed to produce a maximum value of 1 const float C0 = 0.8; // coefficient const float FX0 = 0.6; // frequency X const float FY0 = 0.6; // frequency Y const int octaves = 5; float T(vec3 point) { vec2 sum = vec2(0.0); float Ci = C0; vec2 FXY = vec2(FX0, FY0); vec2 PXY = vec2(0.0); for(int i = 1; i <= octaves; i++) { PXY = phaseShift3D(point, FXY); Ci *= 0.707; FXY *= 2.0; vec2 sinTerm = sin(FXY * point.xy + PXY); sum += Ci * sinTerm + vec2(T0); } return k * sum.x * sum.y; } const float a = 0.5; // fraction of surface reflection due to ambient or scattered light, const float t = 0.4; // fraction of texture shading const float s = 0.25; // fraction of specular reflection float I(float Id, float Is, float It) { return (1.0 - a) * ((1.0 - t) * ((1.0 - s) * Id + s * Is) + t * It) + a; } const vec3 lightDir = normalize(vec3(0.2, -1.0, 0.7)); vec4 drawCloud(vec3 rayOrigin, vec3 rayDir, vec3 cloudCenter, vec3 cloudScale, float cloudSlice, float brightness) { vec3 cloudPoint, cloudNormal; if(!intersectEllipsoid(rayOrigin, rayDir, cloudCenter, cloudScale, cloudSlice, cloudPoint, cloudNormal)) { return vec4(0.0); } float Id = clamp(dot(cloudNormal, -lightDir), 0.0, 1.0); // diffuse reflection float Is = max(pow(dot(-lightDir, -rayDir), 2.0), 0.0); // specular reflection float It = T(cloudPoint); // texture function float intensity = I(Id, Is, It); vec3 color = vec3(intensity * clamp(brightness, 0.1, 1.0)); vec4 noise = sampleNoiseTexture(u_noiseDetail * cloudPoint); float W = noise.x; float W2 = noise.y; float W3 = noise.z; // The dot product between the cloud's normal and the ray's direction is greatest // in the center of the ellipsoid's surface. It decreases towards the edge. // Thus, it is used to blur the areas leading to the edges of the ellipsoid, // so that no harsh lines appear. // The first (and biggest) layer of worley noise is then subtracted from this. // The final result is scaled up so that the base cloud is not too translucent. float ndDot = clamp(dot(cloudNormal, -rayDir), 0.0, 1.0); float TR = pow(ndDot, 3.0) - W; // translucency TR *= 1.3; // Subtracting the second and third layers of worley noise is more complicated. // If these layers of noise were simply subtracted from the current translucency, // the shape derived from the first layer of noise would be completely deleted. // The erosion of this noise should thus be constricted to the edges of the cloud. // However, because the edges of the ellipsoid were already blurred away, mapping // the noise to (1.0 - ndDot) will have no impact on most of the cloud's appearance. // The value of (0.5 - ndDot) provides the best compromise. float minusDot = 0.5 - ndDot; // Even with the previous calculation, subtracting the second layer of wnoise // erode too much of the cloud. The addition of it, however, will detailed // volume to the cloud. As long as the noise is only added and not subtracted, // the results are aesthetically pleasing. // The minusDot product is mapped in a way that it is larger at the edges of // the ellipsoid, so a subtraction and min operation are used instead of // an addition and max one. TR -= min(minusDot * W2, 0.0); // The third level of worley noise is subtracted from the result, with some // modifications. First, a scalar is added to minusDot so that the noise // starts affecting the shape farther away from the center of the ellipsoid's // surface. Then, it is scaled down so its impact is not too intense. TR -= 0.8 * (minusDot + 0.25) * W3; // The texture function's shading does not correlate with the shape of the cloud // produced by the layers of noise, so an extra shading scalar is calculated. // The darkest areas of the cloud are assigned to be where the noise erodes // the cloud the most. This is then interpolated based on the translucency // and the diffuse shading term of that point in the cloud. float shading = mix(1.0 - 0.8 * W * W, 1.0, Id * TR); // To avoid values that are too dark, this scalar is increased by a small amount // and clamped so it never goes to zero. shading = clamp(shading + 0.2, 0.3, 1.0); // Finally, the contrast of the cloud's color is increased. vec3 finalColor = mix(vec3(0.5), shading * color, 1.15); return vec4(finalColor, clamp(TR, 0.0, 1.0)) * v_color; } void main() { #ifdef DEBUG_BILLBOARDS out_FragColor = vec4(0.0, 0.5, 0.5, 1.0); #endif // To avoid calculations with high values, // we raycast from an arbitrarily smaller space. vec2 coordinate = v_maximumSize.xy * v_offset; vec3 ellipsoidScale = 0.82 * v_maximumSize; vec3 ellipsoidCenter = vec3(0.0); float zOffset = max(ellipsoidScale.z - 10.0, 0.0); vec3 eye = vec3(0, 0, -10.0 - zOffset); vec3 rayDir = normalize(vec3(coordinate, 1.0) - eye); vec3 rayOrigin = eye; #ifdef DEBUG_ELLIPSOIDS vec3 point, normal; if(intersectEllipsoid(rayOrigin, rayDir, ellipsoidCenter, ellipsoidScale, v_slice, point, normal)) { out_FragColor = v_brightness * v_color; } #else #ifndef DEBUG_BILLBOARDS vec4 cloud = drawCloud(rayOrigin, rayDir, ellipsoidCenter, ellipsoidScale, v_slice, v_brightness); if(cloud.w < 0.01) { discard; } out_FragColor = cloud; #endif #endif } `; // packages/engine/Source/Shaders/CloudCollectionVS.js var CloudCollectionVS_default = "#ifdef INSTANCED\nin vec2 direction;\n#endif\nin vec4 positionHighAndScaleX;\nin vec4 positionLowAndScaleY;\nin vec4 packedAttribute0;\nin vec4 packedAttribute1;\nin vec4 color;\n\nout vec2 v_offset;\nout vec3 v_maximumSize;\nout vec4 v_color;\nout float v_slice;\nout float v_brightness;\n\nvoid main() {\n // Unpack attributes.\n vec3 positionHigh = positionHighAndScaleX.xyz;\n vec3 positionLow = positionLowAndScaleY.xyz;\n vec2 scale = vec2(positionHighAndScaleX.w, positionLowAndScaleY.w);\n\n float show = packedAttribute0.x;\n float brightness = packedAttribute0.y;\n vec2 coordinates = packedAttribute0.wz;\n vec3 maximumSize = packedAttribute1.xyz;\n float slice = packedAttribute1.w;\n\n#ifdef INSTANCED\n vec2 dir = direction;\n#else\n vec2 dir = coordinates;\n#endif\n\n vec2 offset = dir - vec2(0.5, 0.5);\n vec2 scaledOffset = scale * offset;\n vec4 p = czm_translateRelativeToEye(positionHigh, positionLow);\n vec4 positionEC = czm_modelViewRelativeToEye * p;\n positionEC.xy += scaledOffset;\n \n positionEC.xyz *= show;\n gl_Position = czm_projection * positionEC;\n\n v_offset = offset;\n v_maximumSize = maximumSize;\n v_color = color;\n v_slice = slice;\n v_brightness = brightness;\n}\n"; // packages/engine/Source/Shaders/CloudNoiseFS.js var CloudNoiseFS_default = "uniform vec3 u_noiseTextureDimensions;\nuniform float u_noiseDetail;\nuniform vec3 u_noiseOffset;\nin vec2 v_position;\n\nfloat wrap(float value, float rangeLength) {\n if(value < 0.0) {\n float absValue = abs(value);\n float modValue = mod(absValue, rangeLength);\n return mod(rangeLength - modValue, rangeLength);\n }\n return mod(value, rangeLength);\n}\n\nvec3 wrapVec(vec3 value, float rangeLength) {\n return vec3(wrap(value.x, rangeLength),\n wrap(value.y, rangeLength),\n wrap(value.z, rangeLength));\n}\n\nvec3 random3(vec3 p) {\n float dot1 = dot(p, vec3(127.1, 311.7, 932.8));\n float dot2 = dot(p, vec3(269.5, 183.3, 421.4));\n return fract(vec3(sin(dot1 - dot2), cos(dot1 * dot2), dot1 * dot2));\n}\n\n// Frequency corresponds to cell size.\n// The higher the frequency, the smaller the cell size.\nvec3 getWorleyCellPoint(vec3 centerCell, vec3 offset, float freq) {\n float textureSliceWidth = u_noiseTextureDimensions.x;\n vec3 cell = centerCell + offset;\n cell = wrapVec(cell, textureSliceWidth / u_noiseDetail);\n cell += floor(u_noiseOffset / u_noiseDetail);\n vec3 p = offset + random3(cell);\n return p;\n}\n\nfloat worleyNoise(vec3 p, float freq) {\n vec3 centerCell = floor(p * freq);\n vec3 pointInCell = fract(p * freq);\n float shortestDistance = 1000.0;\n\n for(float z = -1.0; z <= 1.0; z++) {\n for(float y = -1.0; y <= 1.0; y++) {\n for(float x = -1.0; x <= 1.0; x++) {\n vec3 offset = vec3(x, y, z);\n vec3 point = getWorleyCellPoint(centerCell, offset, freq);\n\n float distance = length(pointInCell - point);\n if(distance < shortestDistance) {\n shortestDistance = distance;\n }\n }\n }\n }\n\n return shortestDistance;\n}\n\nconst float MAX_FBM_ITERATIONS = 10.0;\n\nfloat worleyFBMNoise(vec3 p, float octaves, float scale) {\n float noise = 0.0;\n float freq = 1.0;\n float persistence = 0.625;\n for(float i = 0.0; i < MAX_FBM_ITERATIONS; i++) {\n if(i >= octaves) {\n break;\n }\n\n noise += worleyNoise(p * scale, freq * scale) * persistence;\n persistence *= 0.5;\n freq *= 2.0;\n }\n return noise;\n}\n\nvoid main() {\n float textureSliceWidth = u_noiseTextureDimensions.x;\n float inverseNoiseTextureRows = u_noiseTextureDimensions.z;\n float x = mod(v_position.x, textureSliceWidth);\n float y = mod(v_position.y, textureSliceWidth);\n float sliceRow = floor(v_position.y / textureSliceWidth);\n float z = floor(v_position.x / textureSliceWidth) + sliceRow * inverseNoiseTextureRows * textureSliceWidth;\n\n vec3 position = vec3(x, y, z);\n position /= u_noiseDetail;\n float worley0 = clamp(worleyFBMNoise(position, 3.0, 1.0), 0.0, 1.0);\n float worley1 = clamp(worleyFBMNoise(position, 3.0, 2.0), 0.0, 1.0);\n float worley2 = clamp(worleyFBMNoise(position, 3.0, 3.0), 0.0, 1.0);\n out_FragColor = vec4(worley0, worley1, worley2, 1.0);\n}\n"; // packages/engine/Source/Shaders/CloudNoiseVS.js var CloudNoiseVS_default = "uniform vec3 u_noiseTextureDimensions;\nin vec2 position;\n\nout vec2 v_position;\n\nvoid main()\n{\n gl_Position = vec4(position, 0.1, 1.0);\n\n float textureSliceWidth = u_noiseTextureDimensions.x;\n float noiseTextureRows = u_noiseTextureDimensions.y;\n float inverseNoiseTextureRows = u_noiseTextureDimensions.z;\n vec2 transformedPos = (position * 0.5) + vec2(0.5);\n transformedPos *= textureSliceWidth;\n transformedPos.x *= textureSliceWidth * inverseNoiseTextureRows;\n transformedPos.y *= noiseTextureRows;\n v_position = transformedPos;\n}\n"; // packages/engine/Source/Shaders/ViewportQuadFS.js var ViewportQuadFS_default = "\nin vec2 v_textureCoordinates;\n\nvoid main()\n{\n czm_materialInput materialInput;\n \n materialInput.s = v_textureCoordinates.s;\n materialInput.st = v_textureCoordinates;\n materialInput.str = vec3(v_textureCoordinates, 0.0);\n materialInput.normalEC = vec3(0.0, 0.0, -1.0);\n \n czm_material material = czm_getMaterial(materialInput);\n\n out_FragColor = vec4(material.diffuse + material.emission, material.alpha);\n}\n"; // packages/engine/Source/Scene/BoxEmitter.js var defaultDimensions = new Cartesian3_default(1, 1, 1); function BoxEmitter(dimensions) { dimensions = defaultValue_default(dimensions, defaultDimensions); Check_default.defined("dimensions", dimensions); Check_default.typeOf.number.greaterThanOrEquals("dimensions.x", dimensions.x, 0); Check_default.typeOf.number.greaterThanOrEquals("dimensions.y", dimensions.y, 0); Check_default.typeOf.number.greaterThanOrEquals("dimensions.z", dimensions.z, 0); this._dimensions = Cartesian3_default.clone(dimensions); } Object.defineProperties(BoxEmitter.prototype, { /** * The width, height and depth dimensions of the box in meters. * @memberof BoxEmitter.prototype * @type {Cartesian3} * @default new Cartesian3(1.0, 1.0, 1.0) */ dimensions: { get: function() { return this._dimensions; }, set: function(value) { Check_default.defined("value", value); Check_default.typeOf.number.greaterThanOrEquals("value.x", value.x, 0); Check_default.typeOf.number.greaterThanOrEquals("value.y", value.y, 0); Check_default.typeOf.number.greaterThanOrEquals("value.z", value.z, 0); Cartesian3_default.clone(value, this._dimensions); } } }); var scratchHalfDim = new Cartesian3_default(); BoxEmitter.prototype.emit = function(particle) { const dim = this._dimensions; const halfDim = Cartesian3_default.multiplyByScalar(dim, 0.5, scratchHalfDim); const x = Math_default.randomBetween(-halfDim.x, halfDim.x); const y = Math_default.randomBetween(-halfDim.y, halfDim.y); const z = Math_default.randomBetween(-halfDim.z, halfDim.z); particle.position = Cartesian3_default.fromElements(x, y, z, particle.position); particle.velocity = Cartesian3_default.normalize( particle.position, particle.velocity ); }; var BoxEmitter_default = BoxEmitter; // packages/engine/Source/Scene/Cesium3DTileContent.js function Cesium3DTileContent() { this.featurePropertiesDirty = false; } Object.defineProperties(Cesium3DTileContent.prototype, { /** * Gets the number of features in the tile. * * @memberof Cesium3DTileContent.prototype * * @type {number} * @readonly */ featuresLength: { // eslint-disable-next-line getter-return get: function() { DeveloperError_default.throwInstantiationError(); } }, /** * Gets the number of points in the tile. *
* Only applicable for tiles with Point Cloud content. This is different than {@link Cesium3DTileContent#featuresLength} which
* equals the number of groups of points as distinguished by the BATCH_ID
feature table semantic.
*
* This is used to implement the Cesium3DTileContent
interface, but is
* not part of the public Cesium API.
*
* This is used to implement the Cesium3DTileContent
interface, but is
* not part of the public Cesium API.
*
3DTILES_metadata
extension. If neither are present,
* this property should be undefined.
*
* This is used to implement the Cesium3DTileContent
interface, but is
* not part of the public Cesium API.
*
show
property. Alternatively a boolean, string, or object defining a show style can be used.
* The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
*
* The expression must return or convert to a Boolean
.
*
* This expression is applicable to all tile formats. *
* * @memberof Cesium3DTileStyle.prototype * * @type {StyleExpression} * * @example * const style = new Cesium3DTileStyle({ * show : '(regExp("^Chest").test(${County})) && (${YearBuilt} >= 1970)' * }); * style.show.evaluate(feature); // returns true or false depending on the feature's properties * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override show expression with a custom function * style.show = { * evaluate : function(feature) { * return true; * } * }; * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override show expression with a boolean * style.show = true; * }; * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override show expression with a string * style.show = '${Height} > 0'; * }; * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override show expression with a condition * style.show = { * conditions: [ * ['${height} > 2', 'false'], * ['true', 'true'] * ]; * }; */ show: { get: function() { return this._show; }, set: function(value) { this._show = getExpression(this, value); this._style.show = getJsonFromExpression(this._show); this._showShaderFunctionReady = false; } }, /** * Gets or sets the {@link StyleExpression} object used to evaluate the style'scolor
property. Alternatively a string or object defining a color style can be used.
* The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
*
* The expression must return a Color
.
*
* This expression is applicable to all tile formats. *
* * @memberof Cesium3DTileStyle.prototype * * @type {StyleExpression} * * @example * const style = new Cesium3DTileStyle({ * color : '(${Temperature} > 90) ? color("red") : color("white")' * }); * style.color.evaluateColor(feature, result); // returns a Cesium.Color object * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override color expression with a custom function * style.color = { * evaluateColor : function(feature, result) { * return Cesium.Color.clone(Cesium.Color.WHITE, result); * } * }; * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override color expression with a string * style.color = 'color("blue")'; * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override color expression with a condition * style.color = { * conditions : [ * ['${height} > 2', 'color("cyan")'], * ['true', 'color("blue")'] * ] * }; */ color: { get: function() { return this._color; }, set: function(value) { this._color = getExpression(this, value); this._style.color = getJsonFromExpression(this._color); this._colorShaderFunctionReady = false; } }, /** * Gets or sets the {@link StyleExpression} object used to evaluate the style'spointSize
property. Alternatively a string or object defining a point size style can be used.
* The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
*
* The expression must return a Number
.
*
* This expression is only applicable to point features in a Vector tile or a Point Cloud tile. *
* * @memberof Cesium3DTileStyle.prototype * * @type {StyleExpression} * * @example * const style = new Cesium3DTileStyle({ * pointSize : '(${Temperature} > 90) ? 2.0 : 1.0' * }); * style.pointSize.evaluate(feature); // returns a Number * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override pointSize expression with a custom function * style.pointSize = { * evaluate : function(feature) { * return 1.0; * } * }; * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override pointSize expression with a number * style.pointSize = 1.0; * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override pointSize expression with a string * style.pointSize = '${height} / 10'; * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override pointSize expression with a condition * style.pointSize = { * conditions : [ * ['${height} > 2', '1.0'], * ['true', '2.0'] * ] * }; */ pointSize: { get: function() { return this._pointSize; }, set: function(value) { this._pointSize = getExpression(this, value); this._style.pointSize = getJsonFromExpression(this._pointSize); this._pointSizeShaderFunctionReady = false; } }, /** * Gets or sets the {@link StyleExpression} object used to evaluate the style'spointOutlineColor
property. Alternatively a string or object defining a color style can be used.
* The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
*
* The expression must return a Color
.
*
* This expression is only applicable to point features in a Vector tile. *
* * @memberof Cesium3DTileStyle.prototype * * @type {StyleExpression} * * @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. * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override pointOutlineColor expression with a string * style.pointOutlineColor = 'color("blue")'; * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override pointOutlineColor expression with a condition * style.pointOutlineColor = { * conditions : [ * ['${height} > 2', 'color("cyan")'], * ['true', 'color("blue")'] * ] * }; */ pointOutlineColor: { get: function() { return this._pointOutlineColor; }, set: function(value) { this._pointOutlineColor = getExpression(this, value); this._style.pointOutlineColor = getJsonFromExpression( this._pointOutlineColor ); } }, /** * Gets or sets the {@link StyleExpression} object used to evaluate the style'spointOutlineWidth
property. Alternatively a string or object defining a number style can be used.
* The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
*
* The expression must return a Number
.
*
* This expression is only applicable to point features in a Vector tile. *
* * @memberof Cesium3DTileStyle.prototype * * @type {StyleExpression} * * @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. * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override pointOutlineWidth expression with a string * style.pointOutlineWidth = '5'; * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override pointOutlineWidth expression with a condition * style.pointOutlineWidth = { * conditions : [ * ['${height} > 2', '5'], * ['true', '0'] * ] * }; */ pointOutlineWidth: { get: function() { return this._pointOutlineWidth; }, set: function(value) { this._pointOutlineWidth = getExpression(this, value); this._style.pointOutlineWidth = getJsonFromExpression( this._pointOutlineWidth ); } }, /** * Gets or sets the {@link StyleExpression} object used to evaluate the style'slabelColor
property. Alternatively a string or object defining a color style can be used.
* The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
*
* The expression must return a Color
.
*
* This expression is only applicable to point features in a Vector tile. *
* * @memberof Cesium3DTileStyle.prototype * * @type {StyleExpression} * * @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. * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override labelColor expression with a string * style.labelColor = 'color("blue")'; * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override labelColor expression with a condition * style.labelColor = { * conditions : [ * ['${height} > 2', 'color("cyan")'], * ['true', 'color("blue")'] * ] * }; */ labelColor: { get: function() { return this._labelColor; }, set: function(value) { this._labelColor = getExpression(this, value); this._style.labelColor = getJsonFromExpression(this._labelColor); } }, /** * Gets or sets the {@link StyleExpression} object used to evaluate the style'slabelOutlineColor
property. Alternatively a string or object defining a color style can be used.
* The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
*
* The expression must return a Color
.
*
* This expression is only applicable to point features in a Vector tile. *
* * @memberof Cesium3DTileStyle.prototype * * @type {StyleExpression} * * @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. * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override labelOutlineColor expression with a string * style.labelOutlineColor = 'color("blue")'; * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override labelOutlineColor expression with a condition * style.labelOutlineColor = { * conditions : [ * ['${height} > 2', 'color("cyan")'], * ['true', 'color("blue")'] * ] * }; */ labelOutlineColor: { get: function() { return this._labelOutlineColor; }, set: function(value) { this._labelOutlineColor = getExpression(this, value); this._style.labelOutlineColor = getJsonFromExpression( this._labelOutlineColor ); } }, /** * Gets or sets the {@link StyleExpression} object used to evaluate the style'slabelOutlineWidth
property. Alternatively a string or object defining a number style can be used.
* The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
*
* The expression must return a Number
.
*
* This expression is only applicable to point features in a Vector tile. *
* * @memberof Cesium3DTileStyle.prototype * * @type {StyleExpression} * * @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. * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override labelOutlineWidth expression with a string * style.labelOutlineWidth = '5'; * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override labelOutlineWidth expression with a condition * style.labelOutlineWidth = { * conditions : [ * ['${height} > 2', '5'], * ['true', '0'] * ] * }; */ labelOutlineWidth: { get: function() { return this._labelOutlineWidth; }, set: function(value) { this._labelOutlineWidth = getExpression(this, value); this._style.labelOutlineWidth = getJsonFromExpression( this._labelOutlineWidth ); } }, /** * Gets or sets the {@link StyleExpression} object used to evaluate the style'sfont
property. Alternatively a string or object defining a string style can be used.
* The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
*
* The expression must return a String
.
*
* This expression is only applicable to point features in a Vector tile. *
* * @memberof Cesium3DTileStyle.prototype * * @type {StyleExpression} * * @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. * * @example * const style = new Cesium3DTileStyle({ * font : '(${Temperature} > 90) ? "30px Helvetica" : "24px Helvetica"' * }); * style.font.evaluate(feature); // returns a String * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override font expression with a custom function * style.font = { * evaluate : function(feature) { * return '24px Helvetica'; * } * }; */ font: { get: function() { return this._font; }, set: function(value) { this._font = getExpression(this, value); this._style.font = getJsonFromExpression(this._font); } }, /** * Gets or sets the {@link StyleExpression} object used to evaluate the style'slabel style
property. Alternatively a string or object defining a number style can be used.
* The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
*
* The expression must return a LabelStyle
.
*
* This expression is only applicable to point features in a Vector tile. *
* * @memberof Cesium3DTileStyle.prototype * * @type {StyleExpression} * * @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. * * @example * const style = new Cesium3DTileStyle({ * labelStyle : `(\${Temperature} > 90) ? ${LabelStyle.FILL_AND_OUTLINE} : ${LabelStyle.FILL}` * }); * style.labelStyle.evaluate(feature); // returns a LabelStyle * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override labelStyle expression with a custom function * style.labelStyle = { * evaluate : function(feature) { * return LabelStyle.FILL; * } * }; */ labelStyle: { get: function() { return this._labelStyle; }, set: function(value) { this._labelStyle = getExpression(this, value); this._style.labelStyle = getJsonFromExpression(this._labelStyle); } }, /** * Gets or sets the {@link StyleExpression} object used to evaluate the style'slabelText
property. Alternatively a string or object defining a string style can be used.
* The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
*
* The expression must return a String
.
*
* This expression is only applicable to point features in a Vector tile. *
* * @memberof Cesium3DTileStyle.prototype * * @type {StyleExpression} * * @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. * * @example * const style = new Cesium3DTileStyle({ * labelText : '(${Temperature} > 90) ? ">90" : "<=90"' * }); * style.labelText.evaluate(feature); // returns a String * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override labelText expression with a custom function * style.labelText = { * evaluate : function(feature) { * return 'Example label text'; * } * }; */ labelText: { get: function() { return this._labelText; }, set: function(value) { this._labelText = getExpression(this, value); this._style.labelText = getJsonFromExpression(this._labelText); } }, /** * Gets or sets the {@link StyleExpression} object used to evaluate the style'sbackgroundColor
property. Alternatively a string or object defining a color style can be used.
* The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
*
* The expression must return a Color
.
*
* This expression is only applicable to point features in a Vector tile. *
* * @memberof Cesium3DTileStyle.prototype * * @type {StyleExpression} * * @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. * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override backgroundColor expression with a string * style.backgroundColor = 'color("blue")'; * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override backgroundColor expression with a condition * style.backgroundColor = { * conditions : [ * ['${height} > 2', 'color("cyan")'], * ['true', 'color("blue")'] * ] * }; */ backgroundColor: { get: function() { return this._backgroundColor; }, set: function(value) { this._backgroundColor = getExpression(this, value); this._style.backgroundColor = getJsonFromExpression( this._backgroundColor ); } }, /** * Gets or sets the {@link StyleExpression} object used to evaluate the style'sbackgroundPadding
property. Alternatively a string or object defining a vec2 style can be used.
* The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
*
* The expression must return a Cartesian2
.
*
* This expression is only applicable to point features in a Vector tile. *
* * @memberof Cesium3DTileStyle.prototype * * @type {StyleExpression} * * @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. * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override backgroundPadding expression with a string * style.backgroundPadding = 'vec2(5.0, 7.0)'; * style.backgroundPadding.evaluate(feature); // returns a Cartesian2 */ backgroundPadding: { get: function() { return this._backgroundPadding; }, set: function(value) { this._backgroundPadding = getExpression(this, value); this._style.backgroundPadding = getJsonFromExpression( this._backgroundPadding ); } }, /** * Gets or sets the {@link StyleExpression} object used to evaluate the style'sbackgroundEnabled
property. Alternatively a string or object defining a boolean style can be used.
* The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
*
* The expression must return a Boolean
.
*
* This expression is only applicable to point features in a Vector tile. *
* * @memberof Cesium3DTileStyle.prototype * * @type {StyleExpression} * * @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. * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override backgroundEnabled expression with a string * style.backgroundEnabled = 'true'; * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override backgroundEnabled expression with a condition * style.backgroundEnabled = { * conditions : [ * ['${height} > 2', 'true'], * ['true', 'false'] * ] * }; */ backgroundEnabled: { get: function() { return this._backgroundEnabled; }, set: function(value) { this._backgroundEnabled = getExpression(this, value); this._style.backgroundEnabled = getJsonFromExpression( this._backgroundEnabled ); } }, /** * Gets or sets the {@link StyleExpression} object used to evaluate the style'sscaleByDistance
property. Alternatively a string or object defining a vec4 style can be used.
* The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
*
* The expression must return a Cartesian4
.
*
* This expression is only applicable to point features in a Vector tile. *
* * @memberof Cesium3DTileStyle.prototype * * @type {StyleExpression} * * @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. * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override scaleByDistance expression with a string * style.scaleByDistance = 'vec4(1.5e2, 2.0, 1.5e7, 0.5)'; * style.scaleByDistance.evaluate(feature); // returns a Cartesian4 */ scaleByDistance: { get: function() { return this._scaleByDistance; }, set: function(value) { this._scaleByDistance = getExpression(this, value); this._style.scaleByDistance = getJsonFromExpression( this._scaleByDistance ); } }, /** * Gets or sets the {@link StyleExpression} object used to evaluate the style'stranslucencyByDistance
property. Alternatively a string or object defining a vec4 style can be used.
* The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
*
* The expression must return a Cartesian4
.
*
* This expression is only applicable to point features in a Vector tile. *
* * @memberof Cesium3DTileStyle.prototype * * @type {StyleExpression} * * @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. * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override translucencyByDistance expression with a string * style.translucencyByDistance = 'vec4(1.5e2, 1.0, 1.5e7, 0.2)'; * style.translucencyByDistance.evaluate(feature); // returns a Cartesian4 */ translucencyByDistance: { get: function() { return this._translucencyByDistance; }, set: function(value) { this._translucencyByDistance = getExpression(this, value); this._style.translucencyByDistance = getJsonFromExpression( this._translucencyByDistance ); } }, /** * Gets or sets the {@link StyleExpression} object used to evaluate the style'sdistanceDisplayCondition
property. Alternatively a string or object defining a vec2 style can be used.
* The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
*
* The expression must return a Cartesian2
.
*
* This expression is only applicable to point features in a Vector tile. *
* * @memberof Cesium3DTileStyle.prototype * * @type {StyleExpression} * * @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. * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override distanceDisplayCondition expression with a string * style.distanceDisplayCondition = 'vec2(0.0, 5.5e6)'; * style.distanceDisplayCondition.evaluate(feature); // returns a Cartesian2 */ distanceDisplayCondition: { get: function() { return this._distanceDisplayCondition; }, set: function(value) { this._distanceDisplayCondition = getExpression(this, value); this._style.distanceDisplayCondition = getJsonFromExpression( this._distanceDisplayCondition ); } }, /** * Gets or sets the {@link StyleExpression} object used to evaluate the style'sheightOffset
property. Alternatively a string or object defining a number style can be used.
* The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
*
* The expression must return a Number
.
*
* This expression is only applicable to point features in a Vector tile. *
* * @memberof Cesium3DTileStyle.prototype * * @type {StyleExpression} * * @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. * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override heightOffset expression with a string * style.heightOffset = '2.0'; * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override heightOffset expression with a condition * style.heightOffset = { * conditions : [ * ['${height} > 2', '4.0'], * ['true', '2.0'] * ] * }; */ heightOffset: { get: function() { return this._heightOffset; }, set: function(value) { this._heightOffset = getExpression(this, value); this._style.heightOffset = getJsonFromExpression(this._heightOffset); } }, /** * Gets or sets the {@link StyleExpression} object used to evaluate the style'sanchorLineEnabled
property. Alternatively a string or object defining a boolean style can be used.
* The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
*
* The expression must return a Boolean
.
*
* This expression is only applicable to point features in a Vector tile. *
* * @memberof Cesium3DTileStyle.prototype * * @type {StyleExpression} * * @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. * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override anchorLineEnabled expression with a string * style.anchorLineEnabled = 'true'; * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override anchorLineEnabled expression with a condition * style.anchorLineEnabled = { * conditions : [ * ['${height} > 2', 'true'], * ['true', 'false'] * ] * }; */ anchorLineEnabled: { get: function() { return this._anchorLineEnabled; }, set: function(value) { this._anchorLineEnabled = getExpression(this, value); this._style.anchorLineEnabled = getJsonFromExpression( this._anchorLineEnabled ); } }, /** * Gets or sets the {@link StyleExpression} object used to evaluate the style'sanchorLineColor
property. Alternatively a string or object defining a color style can be used.
* The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
*
* The expression must return a Color
.
*
* This expression is only applicable to point features in a Vector tile. *
* * @memberof Cesium3DTileStyle.prototype * * @type {StyleExpression} * * @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. * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override anchorLineColor expression with a string * style.anchorLineColor = 'color("blue")'; * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override anchorLineColor expression with a condition * style.anchorLineColor = { * conditions : [ * ['${height} > 2', 'color("cyan")'], * ['true', 'color("blue")'] * ] * }; */ anchorLineColor: { get: function() { return this._anchorLineColor; }, set: function(value) { this._anchorLineColor = getExpression(this, value); this._style.anchorLineColor = getJsonFromExpression( this._anchorLineColor ); } }, /** * Gets or sets the {@link StyleExpression} object used to evaluate the style'simage
property. Alternatively a string or object defining a string style can be used.
* The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
*
* The expression must return a String
.
*
* This expression is only applicable to point features in a Vector tile. *
* * @memberof Cesium3DTileStyle.prototype * * @type {StyleExpression} * * @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. * * @example * const style = new Cesium3DTileStyle({ * image : '(${Temperature} > 90) ? "/url/to/image1" : "/url/to/image2"' * }); * style.image.evaluate(feature); // returns a String * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override image expression with a custom function * style.image = { * evaluate : function(feature) { * return '/url/to/image'; * } * }; */ image: { get: function() { return this._image; }, set: function(value) { this._image = getExpression(this, value); this._style.image = getJsonFromExpression(this._image); } }, /** * Gets or sets the {@link StyleExpression} object used to evaluate the style'sdisableDepthTestDistance
property. Alternatively a string or object defining a number style can be used.
* The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
*
* The expression must return a Number
.
*
* This expression is only applicable to point features in a Vector tile. *
* * @memberof Cesium3DTileStyle.prototype * * @type {StyleExpression} * * @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. * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override disableDepthTestDistance expression with a string * style.disableDepthTestDistance = '1000.0'; * style.disableDepthTestDistance.evaluate(feature); // returns a Number */ disableDepthTestDistance: { get: function() { return this._disableDepthTestDistance; }, set: function(value) { this._disableDepthTestDistance = getExpression(this, value); this._style.disableDepthTestDistance = getJsonFromExpression( this._disableDepthTestDistance ); } }, /** * Gets or sets the {@link StyleExpression} object used to evaluate the style'shorizontalOrigin
property. Alternatively a string or object defining a number style can be used.
* The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
*
* The expression must return a HorizontalOrigin
.
*
* This expression is only applicable to point features in a Vector tile. *
* * @memberof Cesium3DTileStyle.prototype * * @type {StyleExpression} * * @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. * * @example * const style = new Cesium3DTileStyle({ * horizontalOrigin : HorizontalOrigin.LEFT * }); * style.horizontalOrigin.evaluate(feature); // returns a HorizontalOrigin * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override horizontalOrigin expression with a custom function * style.horizontalOrigin = { * evaluate : function(feature) { * return HorizontalOrigin.CENTER; * } * }; */ horizontalOrigin: { get: function() { return this._horizontalOrigin; }, set: function(value) { this._horizontalOrigin = getExpression(this, value); this._style.horizontalOrigin = getJsonFromExpression( this._horizontalOrigin ); } }, /** * Gets or sets the {@link StyleExpression} object used to evaluate the style'sverticalOrigin
property. Alternatively a string or object defining a number style can be used.
* The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
*
* The expression must return a VerticalOrigin
.
*
* This expression is only applicable to point features in a Vector tile. *
* * @memberof Cesium3DTileStyle.prototype * * @type {StyleExpression} * * @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. * * @example * const style = new Cesium3DTileStyle({ * verticalOrigin : VerticalOrigin.TOP * }); * style.verticalOrigin.evaluate(feature); // returns a VerticalOrigin * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override verticalOrigin expression with a custom function * style.verticalOrigin = { * evaluate : function(feature) { * return VerticalOrigin.CENTER; * } * }; */ verticalOrigin: { get: function() { return this._verticalOrigin; }, set: function(value) { this._verticalOrigin = getExpression(this, value); this._style.verticalOrigin = getJsonFromExpression(this._verticalOrigin); } }, /** Gets or sets the {@link StyleExpression} object used to evaluate the style'slabelHorizontalOrigin
property. Alternatively a string or object defining a number style can be used.
* The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
*
* The expression must return a HorizontalOrigin
.
*
* This expression is only applicable to point features in a Vector tile. *
* * @memberof Cesium3DTileStyle.prototype * * @type {StyleExpression} * * @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. * * @example * const style = new Cesium3DTileStyle({ * labelHorizontalOrigin : HorizontalOrigin.LEFT * }); * style.labelHorizontalOrigin.evaluate(feature); // returns a HorizontalOrigin * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override labelHorizontalOrigin expression with a custom function * style.labelHorizontalOrigin = { * evaluate : function(feature) { * return HorizontalOrigin.CENTER; * } * }; */ labelHorizontalOrigin: { get: function() { return this._labelHorizontalOrigin; }, set: function(value) { this._labelHorizontalOrigin = getExpression(this, value); this._style.labelHorizontalOrigin = getJsonFromExpression( this._labelHorizontalOrigin ); } }, /** * Gets or sets the {@link StyleExpression} object used to evaluate the style'slabelVerticalOrigin
property. Alternatively a string or object defining a number style can be used.
* The getter will return the internal {@link Expression} or {@link ConditionsExpression}, which may differ from the value provided to the setter.
*
* The expression must return a VerticalOrigin
.
*
* This expression is only applicable to point features in a Vector tile. *
* * @memberof Cesium3DTileStyle.prototype * * @type {StyleExpression} * * @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. * * @example * const style = new Cesium3DTileStyle({ * labelVerticalOrigin : VerticalOrigin.TOP * }); * style.labelVerticalOrigin.evaluate(feature); // returns a VerticalOrigin * * @example * const style = new Cesium.Cesium3DTileStyle(); * // Override labelVerticalOrigin expression with a custom function * style.labelVerticalOrigin = { * evaluate : function(feature) { * return VerticalOrigin.CENTER; * } * }; */ labelVerticalOrigin: { get: function() { return this._labelVerticalOrigin; }, set: function(value) { this._labelVerticalOrigin = getExpression(this, value); this._style.labelVerticalOrigin = getJsonFromExpression( this._labelVerticalOrigin ); } }, /** * Gets or sets the object containing application-specific expression that can be explicitly * evaluated, e.g., for display in a UI. * * @memberof Cesium3DTileStyle.prototype * * @type {StyleExpression} * * @example * const style = new Cesium3DTileStyle({ * meta : { * description : '"Building id ${id} has height ${Height}."' * } * }); * style.meta.description.evaluate(feature); // returns a String with the substituted variables */ meta: { get: function() { return this._meta; }, set: function(value) { this._meta = value; } } }); Cesium3DTileStyle.fromUrl = function(url2) { if (!defined_default(url2)) { throw new DeveloperError_default("url is required"); } const resource = Resource_default.createIfNeeded(url2); return resource.fetchJson(url2).then(function(styleJson) { return new Cesium3DTileStyle(styleJson); }); }; Cesium3DTileStyle.prototype.getColorShaderFunction = function(functionSignature, variableSubstitutionMap, shaderState) { if (this._colorShaderFunctionReady) { shaderState.translucent = this._colorShaderTranslucent; return this._colorShaderFunction; } this._colorShaderFunctionReady = true; if (defined_default(this.color) && defined_default(this.color.getShaderFunction)) { this._colorShaderFunction = this.color.getShaderFunction( functionSignature, variableSubstitutionMap, shaderState, "vec4" ); } else { this._colorShaderFunction = void 0; } this._colorShaderTranslucent = shaderState.translucent; return this._colorShaderFunction; }; Cesium3DTileStyle.prototype.getShowShaderFunction = function(functionSignature, variableSubstitutionMap, shaderState) { if (this._showShaderFunctionReady) { return this._showShaderFunction; } this._showShaderFunctionReady = true; if (defined_default(this.show) && defined_default(this.show.getShaderFunction)) { this._showShaderFunction = this.show.getShaderFunction( functionSignature, variableSubstitutionMap, shaderState, "bool" ); } else { this._showShaderFunction = void 0; } return this._showShaderFunction; }; Cesium3DTileStyle.prototype.getPointSizeShaderFunction = function(functionSignature, variableSubstitutionMap, shaderState) { if (this._pointSizeShaderFunctionReady) { return this._pointSizeShaderFunction; } this._pointSizeShaderFunctionReady = true; if (defined_default(this.pointSize) && defined_default(this.pointSize.getShaderFunction)) { this._pointSizeShaderFunction = this.pointSize.getShaderFunction( functionSignature, variableSubstitutionMap, shaderState, "float" ); } else { this._pointSizeShaderFunction = void 0; } return this._pointSizeShaderFunction; }; Cesium3DTileStyle.prototype.getVariables = function() { let variables = []; if (defined_default(this.color) && defined_default(this.color.getVariables)) { variables.push.apply(variables, this.color.getVariables()); } if (defined_default(this.show) && defined_default(this.show.getVariables)) { variables.push.apply(variables, this.show.getVariables()); } if (defined_default(this.pointSize) && defined_default(this.pointSize.getVariables)) { variables.push.apply(variables, this.pointSize.getVariables()); } variables = variables.filter(function(variable, index, variables2) { return variables2.indexOf(variable) === index; }); return variables; }; var Cesium3DTileStyle_default = Cesium3DTileStyle; // packages/engine/Source/Core/DoubleEndedPriorityQueue.js function DoubleEndedPriorityQueue(options) { Check_default.typeOf.object("options", options); Check_default.defined("options.comparator", options.comparator); if (defined_default(options.maximumLength)) { Check_default.typeOf.number.greaterThanOrEquals( "options.maximumLength", options.maximumLength, 0 ); } this._comparator = options.comparator; this._maximumLength = options.maximumLength; this._array = defined_default(options.maximumLength) ? new Array(options.maximumLength) : []; this._length = 0; } Object.defineProperties(DoubleEndedPriorityQueue.prototype, { /** * Gets the number of elements in the queue. * * @memberof DoubleEndedPriorityQueue.prototype * * @type {number} * @readonly */ length: { get: function() { return this._length; } }, /** * Gets or sets the maximum number of elements in the queue. * If set to a smaller value than the current length of the queue, the lowest priority elements are removed. * If an element is inserted when the queue is at full capacity, the minimum element is removed. * If set to undefined, the size of the queue is unlimited. * * @memberof DoubleEndedPriorityQueue.prototype * * @type {number} * @readonly */ maximumLength: { get: function() { return this._maximumLength; }, set: function(value) { if (defined_default(value)) { Check_default.typeOf.number.greaterThanOrEquals("maximumLength", value, 0); while (this._length > value) { this.removeMinimum(); } this._array.length = value; } this._maximumLength = value; } }, /** * Gets the internal array. * * @memberof DoubleEndedPriorityQueue.prototype * * @type {Array} * @readonly */ internalArray: { get: function() { return this._array; } }, /** * The comparator used by the queue. * If comparator(a, b) is less than 0, a is lower priority than b. * * @memberof DoubleEndedPriorityQueue.prototype * * @type {DoubleEndedPriorityQueue.ComparatorCallback} * @readonly */ comparator: { get: function() { return this._comparator; } } }); DoubleEndedPriorityQueue.prototype.clone = function() { const maximumLength = this._maximumLength; const comparator = this._comparator; const array = this._array; const length3 = this._length; const result = new DoubleEndedPriorityQueue({ comparator, maximumLength }); result._length = length3; for (let i = 0; i < length3; i++) { result._array[i] = array[i]; } return result; }; DoubleEndedPriorityQueue.prototype.reset = function() { this._length = 0; const maximumLength = this._maximumLength; if (defined_default(maximumLength)) { for (let i = 0; i < maximumLength; i++) { this._array[i] = void 0; } } else { this._array.length = 0; } }; DoubleEndedPriorityQueue.prototype.resort = function() { const length3 = this._length; for (let i = 0; i < length3; i++) { pushUp(this, i); } }; DoubleEndedPriorityQueue.prototype.insert = function(element) { let removedElement; const maximumLength = this._maximumLength; if (defined_default(maximumLength)) { if (maximumLength === 0) { return void 0; } else if (this._length === maximumLength) { const minimumElement = this._array[0]; if (this._comparator(element, minimumElement) <= 0) { return element; } removedElement = this.removeMinimum(); } } const index = this._length; this._array[index] = element; this._length++; pushUp(this, index); return removedElement; }; DoubleEndedPriorityQueue.prototype.removeMinimum = function() { const length3 = this._length; if (length3 === 0) { return void 0; } this._length--; const minimumElement = this._array[0]; if (length3 >= 2) { this._array[0] = this._array[length3 - 1]; pushDown(this, 0); } this._array[length3 - 1] = void 0; return minimumElement; }; DoubleEndedPriorityQueue.prototype.removeMaximum = function() { const length3 = this._length; if (length3 === 0) { return void 0; } this._length--; let maximumElement; if (length3 <= 2) { maximumElement = this._array[length3 - 1]; } else { const maximumElementIndex = greaterThan(this, 1, 2) ? 1 : 2; maximumElement = this._array[maximumElementIndex]; this._array[maximumElementIndex] = this._array[length3 - 1]; if (length3 >= 4) { pushDown(this, maximumElementIndex); } } this._array[length3 - 1] = void 0; return maximumElement; }; DoubleEndedPriorityQueue.prototype.getMinimum = function() { const length3 = this._length; if (length3 === 0) { return void 0; } return this._array[0]; }; DoubleEndedPriorityQueue.prototype.getMaximum = function() { const length3 = this._length; if (length3 === 0) { return void 0; } if (length3 <= 2) { return this._array[length3 - 1]; } return this._array[greaterThan(this, 1, 2) ? 1 : 2]; }; function swap3(that, indexA, indexB) { const array = that._array; const temp = array[indexA]; array[indexA] = array[indexB]; array[indexB] = temp; } function lessThan(that, indexA, indexB) { return that._comparator(that._array[indexA], that._array[indexB]) < 0; } function greaterThan(that, indexA, indexB) { return that._comparator(that._array[indexA], that._array[indexB]) > 0; } function pushUp(that, index) { if (index === 0) { return; } const onMinLevel = Math.floor(Math_default.log2(index + 1)) % 2 === 0; const parentIndex = Math.floor((index - 1) / 2); const lessThanParent = lessThan(that, index, parentIndex); if (lessThanParent !== onMinLevel) { swap3(that, index, parentIndex); index = parentIndex; } while (index >= 3) { const grandparentIndex = Math.floor((index - 3) / 4); if (lessThan(that, index, grandparentIndex) !== lessThanParent) { break; } swap3(that, index, grandparentIndex); index = grandparentIndex; } } function pushDown(that, index) { const length3 = that._length; const onMinLevel = Math.floor(Math_default.log2(index + 1)) % 2 === 0; let leftChildIndex; while ((leftChildIndex = 2 * index + 1) < length3) { let target = leftChildIndex; const rightChildIndex = leftChildIndex + 1; if (rightChildIndex < length3) { if (lessThan(that, rightChildIndex, target) === onMinLevel) { target = rightChildIndex; } const grandChildStart = 2 * leftChildIndex + 1; const grandChildCount = Math.max( Math.min(length3 - grandChildStart, 4), 0 ); for (let i = 0; i < grandChildCount; i++) { const grandChildIndex = grandChildStart + i; if (lessThan(that, grandChildIndex, target) === onMinLevel) { target = grandChildIndex; } } } if (lessThan(that, target, index) === onMinLevel) { swap3(that, target, index); if (target !== leftChildIndex && target !== rightChildIndex) { const parentOfGrandchildIndex = Math.floor((target - 1) / 2); if (greaterThan(that, target, parentOfGrandchildIndex) === onMinLevel) { swap3(that, target, parentOfGrandchildIndex); } } } index = target; } } var DoubleEndedPriorityQueue_default = DoubleEndedPriorityQueue; // packages/engine/Source/Scene/ImplicitSubtreeCache.js function ImplicitSubtreeCache(options) { options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT); this._maximumSubtreeCount = defaultValue_default(options.maximumSubtreeCount, 0); this._subtreeRequestCounter = 0; this._queue = new DoubleEndedPriorityQueue_default({ comparator: ImplicitSubtreeCache.comparator }); } ImplicitSubtreeCache.prototype.addSubtree = function(subtree) { const cacheNode = new ImplicitSubtreeCacheNode( subtree, this._subtreeRequestCounter ); this._subtreeRequestCounter++; this._queue.insert(cacheNode); const subtreeCoord = subtree.implicitCoordinates; if (subtreeCoord.level > 0) { const parentCoord = subtreeCoord.getParentSubtreeCoordinates(); const parentNode = this.find(parentCoord); if (parentNode === void 0) { throw new DeveloperError_default("parent node needs to exist"); } } if (this._maximumSubtreeCount > 0) { while (this._queue.length > this._maximumSubtreeCount) { const lowestPriorityNode = this._queue.getMinimum(); if (lowestPriorityNode === cacheNode) { break; } this._queue.removeMinimum(); } } }; ImplicitSubtreeCache.prototype.find = function(subtreeCoord) { const queue = this._queue; const array = queue.internalArray; const arrayLength = queue.length; for (let i = 0; i < arrayLength; i++) { const other = array[i]; const otherSubtree = other.subtree; const otherCoord = otherSubtree.implicitCoordinates; if (subtreeCoord.isEqual(otherCoord)) { return other.subtree; } } return void 0; }; ImplicitSubtreeCache.comparator = function(a3, b) { const aCoord = a3.subtree.implicitCoordinates; const bCoord = b.subtree.implicitCoordinates; if (aCoord.isAncestor(bCoord)) { return 1; } else if (bCoord.isAncestor(aCoord)) { return -1; } return a3.stamp - b.stamp; }; function ImplicitSubtreeCacheNode(subtree, stamp) { this.subtree = subtree; this.stamp = stamp; } var ImplicitSubtreeCache_default = ImplicitSubtreeCache; // packages/engine/Source/Scene/VoxelBoxShape.js function VoxelBoxShape() { this.orientedBoundingBox = new OrientedBoundingBox_default(); this.boundingSphere = new BoundingSphere_default(); this.boundTransform = new Matrix4_default(); this.shapeTransform = new Matrix4_default(); this._minBounds = Cartesian3_default.clone( VoxelBoxShape.DefaultMinBounds, new Cartesian3_default() ); this._maxBounds = Cartesian3_default.clone( VoxelBoxShape.DefaultMaxBounds, new Cartesian3_default() ); this.shaderUniforms = { renderMinBounds: new Cartesian3_default(), renderMaxBounds: new Cartesian3_default(), boxUvToShapeUvScale: new Cartesian3_default(), boxUvToShapeUvTranslate: new Cartesian3_default() }; this.shaderDefines = { BOX_INTERSECTION_INDEX: void 0, BOX_HAS_SHAPE_BOUNDS: void 0 }; this.shaderMaximumIntersectionsLength = 0; } var scratchCenter11 = new Cartesian3_default(); var scratchScale6 = new Cartesian3_default(); var scratchRotation4 = new Matrix3_default(); var scratchClipMinBounds = new Cartesian3_default(); var scratchClipMaxBounds = new Cartesian3_default(); var scratchRenderMinBounds = new Cartesian3_default(); var scratchRenderMaxBounds = new Cartesian3_default(); var transformLocalToUv = Matrix4_default.fromRotationTranslation( Matrix3_default.fromUniformScale(0.5, new Matrix3_default()), new Cartesian3_default(0.5, 0.5, 0.5), new Matrix4_default() ); VoxelBoxShape.prototype.update = function(modelMatrix, minBounds, maxBounds, clipMinBounds, clipMaxBounds) { clipMinBounds = defaultValue_default(clipMinBounds, VoxelBoxShape.DefaultMinBounds); clipMaxBounds = defaultValue_default(clipMaxBounds, VoxelBoxShape.DefaultMaxBounds); Check_default.typeOf.object("modelMatrix", modelMatrix); Check_default.typeOf.object("minBounds", minBounds); Check_default.typeOf.object("maxBounds", maxBounds); const defaultMinBounds = VoxelBoxShape.DefaultMinBounds; const defaultMaxBounds = VoxelBoxShape.DefaultMaxBounds; minBounds = this._minBounds = Cartesian3_default.clamp( minBounds, defaultMinBounds, defaultMaxBounds, this._minBounds ); maxBounds = this._maxBounds = Cartesian3_default.clamp( maxBounds, defaultMinBounds, defaultMaxBounds, this._maxBounds ); clipMinBounds = Cartesian3_default.clamp( clipMinBounds, defaultMinBounds, defaultMaxBounds, scratchClipMinBounds ); clipMaxBounds = Cartesian3_default.clamp( clipMaxBounds, defaultMinBounds, defaultMaxBounds, scratchClipMaxBounds ); const renderMinBounds = Cartesian3_default.clamp( minBounds, clipMinBounds, clipMaxBounds, scratchRenderMinBounds ); const renderMaxBounds = Cartesian3_default.clamp( maxBounds, clipMinBounds, clipMaxBounds, scratchRenderMaxBounds ); const scale = Matrix4_default.getScale(modelMatrix, scratchScale6); if (renderMinBounds.x > renderMaxBounds.x || renderMinBounds.y > renderMaxBounds.y || renderMinBounds.z > renderMaxBounds.z || (renderMinBounds.x === renderMaxBounds.x) + (renderMinBounds.y === renderMaxBounds.y) + (renderMinBounds.z === renderMaxBounds.z) >= 2 || clipMinBounds.x > clipMaxBounds.x || clipMinBounds.y > clipMaxBounds.y || clipMinBounds.z > clipMaxBounds.z || scale.x === 0 || scale.y === 0 || scale.z === 0) { return false; } this.shapeTransform = Matrix4_default.clone(modelMatrix, this.shapeTransform); this.orientedBoundingBox = getBoxChunkObb( renderMinBounds, renderMaxBounds, this.shapeTransform, this.orientedBoundingBox ); this.boundTransform = Matrix4_default.fromRotationTranslation( this.orientedBoundingBox.halfAxes, this.orientedBoundingBox.center, this.boundTransform ); this.boundingSphere = BoundingSphere_default.fromOrientedBoundingBox( this.orientedBoundingBox, this.boundingSphere ); const { shaderUniforms, shaderDefines } = this; for (const key in shaderDefines) { if (shaderDefines.hasOwnProperty(key)) { shaderDefines[key] = void 0; } } const hasShapeBounds = !Cartesian3_default.equals(minBounds, defaultMinBounds) || !Cartesian3_default.equals(maxBounds, defaultMaxBounds); let intersectionCount = 0; shaderDefines["BOX_INTERSECTION_INDEX"] = intersectionCount; intersectionCount += 1; shaderUniforms.renderMinBounds = Matrix4_default.multiplyByPoint( transformLocalToUv, renderMinBounds, shaderUniforms.renderMinBounds ); shaderUniforms.renderMaxBounds = Matrix4_default.multiplyByPoint( transformLocalToUv, renderMaxBounds, shaderUniforms.renderMaxBounds ); if (hasShapeBounds) { shaderDefines["BOX_HAS_SHAPE_BOUNDS"] = true; const min3 = minBounds; const max3 = maxBounds; shaderUniforms.boxUvToShapeUvScale = Cartesian3_default.fromElements( 2 / (min3.x === max3.x ? 1 : max3.x - min3.x), 2 / (min3.y === max3.y ? 1 : max3.y - min3.y), 2 / (min3.z === max3.z ? 1 : max3.z - min3.z), shaderUniforms.boxUvToShapeUvScale ); shaderUniforms.boxUvToShapeUvTranslate = Cartesian3_default.fromElements( -shaderUniforms.boxUvToShapeUvScale.x * (min3.x * 0.5 + 0.5), -shaderUniforms.boxUvToShapeUvScale.y * (min3.y * 0.5 + 0.5), -shaderUniforms.boxUvToShapeUvScale.z * (min3.z * 0.5 + 0.5), shaderUniforms.boxUvToShapeUvTranslate ); } this.shaderMaximumIntersectionsLength = intersectionCount; return true; }; var scratchTileMinBounds = new Cartesian3_default(); var scratchTileMaxBounds = new Cartesian3_default(); VoxelBoxShape.prototype.computeOrientedBoundingBoxForTile = function(tileLevel, tileX, tileY, tileZ, result) { Check_default.typeOf.number("tileLevel", tileLevel); Check_default.typeOf.number("tileX", tileX); Check_default.typeOf.number("tileY", tileY); Check_default.typeOf.number("tileZ", tileZ); Check_default.typeOf.object("result", result); const minBounds = this._minBounds; const maxBounds = this._maxBounds; const sizeAtLevel = 1 / Math.pow(2, tileLevel); const tileMinBounds = Cartesian3_default.fromElements( Math_default.lerp(minBounds.x, maxBounds.x, sizeAtLevel * tileX), Math_default.lerp(minBounds.y, maxBounds.y, sizeAtLevel * tileY), Math_default.lerp(minBounds.z, maxBounds.z, sizeAtLevel * tileZ), scratchTileMinBounds ); const tileMaxBounds = Cartesian3_default.fromElements( Math_default.lerp(minBounds.x, maxBounds.x, sizeAtLevel * (tileX + 1)), Math_default.lerp(minBounds.y, maxBounds.y, sizeAtLevel * (tileY + 1)), Math_default.lerp(minBounds.z, maxBounds.z, sizeAtLevel * (tileZ + 1)), scratchTileMaxBounds ); return getBoxChunkObb( tileMinBounds, tileMaxBounds, this.shapeTransform, result ); }; VoxelBoxShape.prototype.computeApproximateStepSize = function(dimensions) { Check_default.typeOf.object("dimensions", dimensions); return 1 / Cartesian3_default.maximumComponent(dimensions); }; VoxelBoxShape.DefaultMinBounds = Object.freeze( new Cartesian3_default(-1, -1, -1) ); VoxelBoxShape.DefaultMaxBounds = Object.freeze( new Cartesian3_default(1, 1, 1) ); function getBoxChunkObb(minimumBounds, maximumBounds, matrix, result) { const defaultMinBounds = VoxelBoxShape.DefaultMinBounds; const defaultMaxBounds = VoxelBoxShape.DefaultMaxBounds; const isDefaultBounds = Cartesian3_default.equals(minimumBounds, defaultMinBounds) && Cartesian3_default.equals(maximumBounds, defaultMaxBounds); if (isDefaultBounds) { result.center = Matrix4_default.getTranslation(matrix, result.center); result.halfAxes = Matrix4_default.getMatrix3(matrix, result.halfAxes); } else { let scale = Matrix4_default.getScale(matrix, scratchScale6); const localCenter = Cartesian3_default.midpoint( minimumBounds, maximumBounds, scratchCenter11 ); result.center = Matrix4_default.multiplyByPoint(matrix, localCenter, result.center); scale = Cartesian3_default.fromElements( scale.x * 0.5 * (maximumBounds.x - minimumBounds.x), scale.y * 0.5 * (maximumBounds.y - minimumBounds.y), scale.z * 0.5 * (maximumBounds.z - minimumBounds.z), scratchScale6 ); const rotation = Matrix4_default.getRotation(matrix, scratchRotation4); result.halfAxes = Matrix3_default.setScale(rotation, scale, result.halfAxes); } return result; } var VoxelBoxShape_default = VoxelBoxShape; // packages/engine/Source/Scene/VoxelContent.js function VoxelContent(resource) { Check_default.typeOf.object("resource", resource); this._resource = resource; this._metadataTable = void 0; } Object.defineProperties(VoxelContent.prototype, { /** * The {@link MetadataTable} storing voxel property values. * * @type {MetadataTable} * @readonly * @private */ metadataTable: { get: function() { return this._metadataTable; } } }); VoxelContent.fromJson = async function(resource, json, binary, metadataSchema) { Check_default.typeOf.object("resource", resource); if (defined_default(json) === defined_default(binary)) { throw new DeveloperError_default("One of json and binary must be defined."); } let chunks; if (defined_default(json)) { chunks = { json, binary: void 0 }; } else { chunks = parseVoxelChunks(binary); } const buffersU8 = await requestBuffers(resource, chunks.json, chunks.binary); const bufferViewsU8 = {}; const bufferViewsLength = chunks.json.bufferViews.length; for (let i = 0; i < bufferViewsLength; ++i) { const bufferViewJson = chunks.json.bufferViews[i]; const start = bufferViewJson.byteOffset; const end = start + bufferViewJson.byteLength; const buffer = buffersU8[bufferViewJson.buffer]; const bufferView = buffer.subarray(start, end); bufferViewsU8[i] = bufferView; } const propertyTableIndex = chunks.json.voxelTable; const propertyTableJson = chunks.json.propertyTables[propertyTableIndex]; const content = new VoxelContent(resource); content._metadataTable = new MetadataTable_default({ count: propertyTableJson.count, properties: propertyTableJson.properties, class: metadataSchema.classes[propertyTableJson.class], bufferViews: bufferViewsU8 }); return content; }; function requestBuffers(resource, json, binary) { const buffersLength = json.buffers.length; const bufferPromises = new Array(buffersLength); for (let i = 0; i < buffersLength; i++) { const buffer = json.buffers[i]; if (defined_default(buffer.uri)) { const baseResource2 = resource; const bufferResource = baseResource2.getDerivedResource({ url: buffer.uri }); bufferPromises[i] = bufferResource.fetchArrayBuffer().then(function(arrayBuffer) { return new Uint8Array(arrayBuffer); }); } else { bufferPromises[i] = Promise.resolve(binary); } } return Promise.all(bufferPromises); } function parseVoxelChunks(binaryView) { const littleEndian2 = true; const reader = new DataView(binaryView.buffer, binaryView.byteOffset); let byteOffset = 8; const jsonByteLength = reader.getUint32(byteOffset, littleEndian2); byteOffset += 8; const binaryByteLength = reader.getUint32(byteOffset, littleEndian2); byteOffset += 8; const json = getJsonFromTypedArray_default(binaryView, byteOffset, jsonByteLength); byteOffset += jsonByteLength; const binary = binaryView.subarray(byteOffset, byteOffset + binaryByteLength); return { json, binary }; } var VoxelContent_default = VoxelContent; // packages/engine/Source/Scene/VoxelCylinderShape.js function VoxelCylinderShape() { this.orientedBoundingBox = new OrientedBoundingBox_default(); this.boundingSphere = new BoundingSphere_default(); this.boundTransform = new Matrix4_default(); this.shapeTransform = new Matrix4_default(); this._minimumRadius = VoxelCylinderShape.DefaultMinBounds.x; this._maximumRadius = VoxelCylinderShape.DefaultMaxBounds.x; this._minimumHeight = VoxelCylinderShape.DefaultMinBounds.y; this._maximumHeight = VoxelCylinderShape.DefaultMaxBounds.y; this._minimumAngle = VoxelCylinderShape.DefaultMinBounds.z; this._maximumAngle = VoxelCylinderShape.DefaultMaxBounds.z; this.shaderUniforms = { cylinderUvToRenderBoundsScale: new Cartesian3_default(), cylinderUvToRenderBoundsTranslate: new Cartesian3_default(), cylinderUvToRenderRadiusMin: 0, cylinderRenderAngleMinMax: new Cartesian2_default(), cylinderUvToShapeUvRadius: new Cartesian2_default(), cylinderUvToShapeUvHeight: new Cartesian2_default(), cylinderUvToShapeUvAngle: new Cartesian2_default(), cylinderShapeUvAngleMinMax: new Cartesian2_default(), cylinderShapeUvAngleRangeZeroMid: 0 }; this.shaderDefines = { CYLINDER_HAS_RENDER_BOUNDS_RADIUS_MIN: void 0, CYLINDER_HAS_RENDER_BOUNDS_RADIUS_MAX: void 0, CYLINDER_HAS_RENDER_BOUNDS_RADIUS_FLAT: void 0, CYLINDER_HAS_RENDER_BOUNDS_HEIGHT: void 0, CYLINDER_HAS_RENDER_BOUNDS_HEIGHT_FLAT: void 0, CYLINDER_HAS_RENDER_BOUNDS_ANGLE: void 0, CYLINDER_HAS_RENDER_BOUNDS_ANGLE_RANGE_EQUAL_ZERO: void 0, CYLINDER_HAS_RENDER_BOUNDS_ANGLE_RANGE_UNDER_HALF: void 0, CYLINDER_HAS_RENDER_BOUNDS_ANGLE_RANGE_EQUAL_HALF: void 0, CYLINDER_HAS_RENDER_BOUNDS_ANGLE_RANGE_OVER_HALF: void 0, CYLINDER_HAS_SHAPE_BOUNDS_RADIUS: void 0, CYLINDER_HAS_SHAPE_BOUNDS_RADIUS_FLAT: void 0, CYLINDER_HAS_SHAPE_BOUNDS_HEIGHT: void 0, CYLINDER_HAS_SHAPE_BOUNDS_HEIGHT_FLAT: void 0, CYLINDER_HAS_SHAPE_BOUNDS_ANGLE: void 0, CYLINDER_HAS_SHAPE_BOUNDS_ANGLE_RANGE_EQUAL_ZERO: void 0, CYLINDER_HAS_SHAPE_BOUNDS_ANGLE_MIN_DISCONTINUITY: void 0, CYLINDER_HAS_SHAPE_BOUNDS_ANGLE_MAX_DISCONTINUITY: void 0, CYLINDER_HAS_SHAPE_BOUNDS_ANGLE_MIN_MAX_REVERSED: void 0, CYLINDER_INTERSECTION_INDEX_RADIUS_MAX: void 0, CYLINDER_INTERSECTION_INDEX_RADIUS_MIN: void 0, CYLINDER_INTERSECTION_INDEX_ANGLE: void 0 }; this.shaderMaximumIntersectionsLength = 0; } var scratchScale7 = new Cartesian3_default(); var scratchBoundsTranslation = new Cartesian3_default(); var scratchBoundsScale = new Cartesian3_default(); var scratchBoundsScaleMatrix = new Matrix3_default(); var scratchTransformLocalToBounds = new Matrix4_default(); var scratchTransformUvToBounds = new Matrix4_default(); var transformUvToLocal = Matrix4_default.fromRotationTranslation( Matrix3_default.fromUniformScale(2, new Matrix3_default()), new Cartesian3_default(-1, -1, -1), new Matrix4_default() ); VoxelCylinderShape.prototype.update = function(modelMatrix, minBounds, maxBounds, clipMinBounds, clipMaxBounds) { clipMinBounds = defaultValue_default( clipMinBounds, VoxelCylinderShape.DefaultMinBounds ); clipMaxBounds = defaultValue_default( clipMaxBounds, VoxelCylinderShape.DefaultMaxBounds ); Check_default.typeOf.object("modelMatrix", modelMatrix); Check_default.typeOf.object("minBounds", minBounds); Check_default.typeOf.object("maxBounds", maxBounds); const defaultMinRadius = VoxelCylinderShape.DefaultMinBounds.x; const defaultMaxRadius = VoxelCylinderShape.DefaultMaxBounds.x; const defaultMinHeight = VoxelCylinderShape.DefaultMinBounds.y; const defaultMaxHeight = VoxelCylinderShape.DefaultMaxBounds.y; const defaultMinAngle = VoxelCylinderShape.DefaultMinBounds.z; const defaultMaxAngle = VoxelCylinderShape.DefaultMaxBounds.z; const defaultAngleRange = defaultMaxAngle - defaultMinAngle; const defaultAngleRangeHalf = 0.5 * defaultAngleRange; const epsilonZeroScale = Math_default.EPSILON10; const epsilonAngleDiscontinuity = Math_default.EPSILON3; const epsilonAngle = Math_default.EPSILON10; const shapeMinRadius = Math_default.clamp( minBounds.x, defaultMinRadius, defaultMaxRadius ); const shapeMaxRadius = Math_default.clamp( maxBounds.x, defaultMinRadius, defaultMaxRadius ); const clipMinRadius = Math_default.clamp( clipMinBounds.x, defaultMinRadius, defaultMaxRadius ); const clipMaxRadius = Math_default.clamp( clipMaxBounds.x, defaultMinRadius, defaultMaxRadius ); const renderMinRadius = Math.max(shapeMinRadius, clipMinRadius); const renderMaxRadius = Math.min(shapeMaxRadius, clipMaxRadius); const shapeMinHeight = Math_default.clamp( minBounds.y, defaultMinHeight, defaultMaxHeight ); const shapeMaxHeight = Math_default.clamp( maxBounds.y, defaultMinHeight, defaultMaxHeight ); const clipMinHeight = Math_default.clamp( clipMinBounds.y, defaultMinHeight, defaultMaxHeight ); const clipMaxHeight = Math_default.clamp( clipMaxBounds.y, defaultMinHeight, defaultMaxHeight ); const renderMinHeight = Math.max(shapeMinHeight, clipMinHeight); const renderMaxHeight = Math.min(shapeMaxHeight, clipMaxHeight); const shapeMinAngle = Math_default.negativePiToPi(minBounds.z); const shapeMaxAngle = Math_default.negativePiToPi(maxBounds.z); const clipMinAngle = Math_default.negativePiToPi(clipMinBounds.z); const clipMaxAngle = Math_default.negativePiToPi(clipMaxBounds.z); const renderMinAngle = Math.max(shapeMinAngle, clipMinAngle); const renderMaxAngle = Math.min(shapeMaxAngle, clipMaxAngle); const scale = Matrix4_default.getScale(modelMatrix, scratchScale7); if (renderMaxRadius === 0 || renderMinRadius > renderMaxRadius || renderMinHeight > renderMaxHeight || Math_default.equalsEpsilon(scale.x, 0, void 0, epsilonZeroScale) || Math_default.equalsEpsilon(scale.y, 0, void 0, epsilonZeroScale) || Math_default.equalsEpsilon(scale.z, 0, void 0, epsilonZeroScale)) { return false; } this._minimumRadius = shapeMinRadius; this._maximumRadius = shapeMaxRadius; this._minimumHeight = shapeMinHeight; this._maximumHeight = shapeMaxHeight; this._minimumAngle = shapeMinAngle; this._maximumAngle = shapeMaxAngle; this.shapeTransform = Matrix4_default.clone(modelMatrix, this.shapeTransform); this.orientedBoundingBox = getCylinderChunkObb( renderMinRadius, renderMaxRadius, renderMinHeight, renderMaxHeight, renderMinAngle, renderMaxAngle, this.shapeTransform, this.orientedBoundingBox ); this.boundTransform = Matrix4_default.fromRotationTranslation( this.orientedBoundingBox.halfAxes, this.orientedBoundingBox.center, this.boundTransform ); this.boundingSphere = BoundingSphere_default.fromOrientedBoundingBox( this.orientedBoundingBox, this.boundingSphere ); const shapeIsDefaultMaxRadius = shapeMaxRadius === defaultMaxRadius; const shapeIsDefaultMinRadius = shapeMinRadius === defaultMinRadius; const shapeIsDefaultRadius = shapeIsDefaultMinRadius && shapeIsDefaultMaxRadius; const shapeIsDefaultHeight = shapeMinHeight === defaultMinHeight && shapeMaxHeight === defaultMaxHeight; const shapeIsAngleReversed = shapeMaxAngle < shapeMinAngle; const shapeAngleRange = shapeMaxAngle - shapeMinAngle + shapeIsAngleReversed * defaultAngleRange; const shapeIsAngleRegular = shapeAngleRange > defaultAngleRangeHalf + epsilonAngle && shapeAngleRange < defaultAngleRange - epsilonAngle; const shapeIsAngleFlipped = shapeAngleRange > epsilonAngle && shapeAngleRange < defaultAngleRangeHalf - epsilonAngle; const shapeIsAngleRangeHalf = shapeAngleRange >= defaultAngleRangeHalf - epsilonAngle && shapeAngleRange <= defaultAngleRangeHalf + epsilonAngle; const shapeIsAngleRangeZero = shapeAngleRange <= epsilonAngle; const shapeHasAngle = shapeIsAngleRegular || shapeIsAngleFlipped || shapeIsAngleRangeHalf || shapeIsAngleRangeZero; const shapeIsMinAngleDiscontinuity = Math_default.equalsEpsilon( shapeMinAngle, defaultMinAngle, void 0, epsilonAngleDiscontinuity ); const shapeIsMaxAngleDiscontinuity = Math_default.equalsEpsilon( shapeMaxAngle, defaultMaxAngle, void 0, epsilonAngleDiscontinuity ); const renderIsDefaultMaxRadius = renderMaxRadius === defaultMaxRadius; const renderIsDefaultMinRadius = renderMinRadius === defaultMinRadius; const renderIsDefaultHeight = renderMinHeight === defaultMinHeight && renderMaxHeight === defaultMaxHeight; const renderIsAngleReversed = renderMaxAngle < renderMinAngle; const renderAngleRange = renderMaxAngle - renderMinAngle + renderIsAngleReversed * defaultAngleRange; const renderIsAngleRegular = renderAngleRange > defaultAngleRangeHalf + epsilonAngle && renderAngleRange < defaultAngleRange - epsilonAngle; const renderIsAngleFlipped = renderAngleRange > epsilonAngle && renderAngleRange < defaultAngleRangeHalf - epsilonAngle; const renderIsAngleRangeHalf = renderAngleRange >= defaultAngleRangeHalf - epsilonAngle && renderAngleRange <= defaultAngleRangeHalf + epsilonAngle; const renderIsAngleRangeZero = renderAngleRange <= epsilonAngle; const renderHasAngle = renderIsAngleRegular || renderIsAngleFlipped || renderIsAngleRangeHalf || renderIsAngleRangeZero; const shaderUniforms = this.shaderUniforms; const shaderDefines = this.shaderDefines; for (const key in shaderDefines) { if (shaderDefines.hasOwnProperty(key)) { shaderDefines[key] = void 0; } } let intersectionCount = 0; shaderDefines["CYLINDER_INTERSECTION_INDEX_RADIUS_MAX"] = intersectionCount; intersectionCount += 1; if (!renderIsDefaultMinRadius) { shaderDefines["CYLINDER_HAS_RENDER_BOUNDS_RADIUS_MIN"] = true; shaderDefines["CYLINDER_INTERSECTION_INDEX_RADIUS_MIN"] = intersectionCount; intersectionCount += 1; shaderUniforms.cylinderUvToRenderRadiusMin = renderMaxRadius / renderMinRadius; } if (!renderIsDefaultMaxRadius) { shaderDefines["CYLINDER_HAS_RENDER_BOUNDS_RADIUS_MAX"] = true; } if (renderMinRadius === renderMaxRadius) { shaderDefines["CYLINDER_HAS_RENDER_BOUNDS_RADIUS_FLAT"] = true; } if (!renderIsDefaultHeight) { shaderDefines["CYLINDER_HAS_RENDER_BOUNDS_HEIGHT"] = true; } if (renderMinHeight === renderMaxHeight) { shaderDefines["CYLINDER_HAS_RENDER_BOUNDS_HEIGHT_FLAT"] = true; } if (shapeMinHeight === shapeMaxHeight) { shaderDefines["CYLINDER_HAS_SHAPE_BOUNDS_HEIGHT_FLAT"] = true; } if (shapeMinRadius === shapeMaxRadius) { shaderDefines["CYLINDER_HAS_SHAPE_BOUNDS_RADIUS_FLAT"] = true; } if (!shapeIsDefaultRadius) { shaderDefines["CYLINDER_HAS_SHAPE_BOUNDS_RADIUS"] = true; const scale2 = 1 / (shapeMaxRadius - shapeMinRadius); const offset2 = shapeMinRadius / (shapeMinRadius - shapeMaxRadius); shaderUniforms.cylinderUvToShapeUvRadius = Cartesian2_default.fromElements( scale2, offset2, shaderUniforms.cylinderUvToShapeUvRadius ); } if (!shapeIsDefaultHeight) { shaderDefines["CYLINDER_HAS_SHAPE_BOUNDS_HEIGHT"] = true; const scale2 = 2 / (shapeMaxHeight - shapeMinHeight); const offset2 = (shapeMinHeight + 1) / (shapeMinHeight - shapeMaxHeight); shaderUniforms.cylinderUvToShapeUvHeight = Cartesian2_default.fromElements( scale2, offset2, shaderUniforms.cylinderUvToShapeUvHeight ); } if (!renderIsDefaultMaxRadius || !renderIsDefaultHeight) { const heightScale = 0.5 * (renderMaxHeight - renderMinHeight); const scaleLocalToBounds = Cartesian3_default.fromElements( 1 / renderMaxRadius, 1 / renderMaxRadius, 1 / (heightScale === 0 ? 1 : heightScale), scratchBoundsScale ); const translateLocalToBounds = Cartesian3_default.fromElements( 0, 0, -scaleLocalToBounds.z * 0.5 * (renderMinHeight + renderMaxHeight), scratchBoundsTranslation ); const transformLocalToBounds = Matrix4_default.fromRotationTranslation( Matrix3_default.fromScale(scaleLocalToBounds, scratchBoundsScaleMatrix), translateLocalToBounds, scratchTransformLocalToBounds ); const transformUvToBounds = Matrix4_default.multiplyTransformation( transformLocalToBounds, transformUvToLocal, scratchTransformUvToBounds ); shaderUniforms.cylinderUvToRenderBoundsScale = Matrix4_default.getScale( transformUvToBounds, shaderUniforms.cylinderUvToRenderBoundsScale ); shaderUniforms.cylinderUvToRenderBoundsTranslate = Matrix4_default.getTranslation( transformUvToBounds, shaderUniforms.cylinderUvToRenderBoundsTranslate ); } if (shapeIsAngleReversed) { shaderDefines["CYLINDER_HAS_SHAPE_BOUNDS_ANGLE_MIN_MAX_REVERSED"] = true; } if (renderHasAngle) { shaderDefines["CYLINDER_HAS_RENDER_BOUNDS_ANGLE"] = true; shaderDefines["CYLINDER_INTERSECTION_INDEX_ANGLE"] = intersectionCount; if (renderIsAngleRegular) { shaderDefines["CYLINDER_HAS_RENDER_BOUNDS_ANGLE_RANGE_UNDER_HALF"] = true; intersectionCount += 1; } else if (renderIsAngleFlipped) { shaderDefines["CYLINDER_HAS_RENDER_BOUNDS_ANGLE_RANGE_OVER_HALF"] = true; intersectionCount += 2; } else if (renderIsAngleRangeHalf) { shaderDefines["CYLINDER_HAS_RENDER_BOUNDS_ANGLE_RANGE_EQUAL_HALF"] = true; intersectionCount += 1; } else if (renderIsAngleRangeZero) { shaderDefines["CYLINDER_HAS_RENDER_BOUNDS_ANGLE_RANGE_EQUAL_ZERO"] = true; intersectionCount += 2; } shaderUniforms.cylinderRenderAngleMinMax = Cartesian2_default.fromElements( renderMinAngle, renderMaxAngle, shaderUniforms.cylinderAngleMinMax ); } if (shapeHasAngle) { shaderDefines["CYLINDER_HAS_SHAPE_BOUNDS_ANGLE"] = true; if (shapeIsAngleRangeZero) { shaderDefines["CYLINDER_HAS_SHAPE_BOUNDS_ANGLE_RANGE_EQUAL_ZERO"] = true; } if (shapeIsMinAngleDiscontinuity) { shaderDefines["CYLINDER_HAS_SHAPE_BOUNDS_ANGLE_MIN_DISCONTINUITY"] = true; } if (shapeIsMaxAngleDiscontinuity) { shaderDefines["CYLINDER_HAS_SHAPE_BOUNDS_ANGLE_MAX_DISCONTINUITY"] = true; } const uvMinAngle = (shapeMinAngle - defaultMinAngle) / defaultAngleRange; const uvMaxAngle = (shapeMaxAngle - defaultMinAngle) / defaultAngleRange; const uvAngleRangeZero = 1 - shapeAngleRange / defaultAngleRange; shaderUniforms.cylinderShapeUvAngleMinMax = Cartesian2_default.fromElements( uvMinAngle, uvMaxAngle, shaderUniforms.cylinderShapeUvAngleMinMax ); shaderUniforms.cylinderShapeUvAngleRangeZeroMid = (uvMaxAngle + 0.5 * uvAngleRangeZero) % 1; const scale2 = defaultAngleRange / shapeAngleRange; const offset2 = -(shapeMinAngle - defaultMinAngle) / shapeAngleRange; shaderUniforms.cylinderUvToShapeUvAngle = Cartesian2_default.fromElements( scale2, offset2, shaderUniforms.cylinderUvToShapeUvAngle ); } this.shaderMaximumIntersectionsLength = intersectionCount; return true; }; VoxelCylinderShape.prototype.computeOrientedBoundingBoxForTile = function(tileLevel, tileX, tileY, tileZ, result) { Check_default.typeOf.number("tileLevel", tileLevel); Check_default.typeOf.number("tileX", tileX); Check_default.typeOf.number("tileY", tileY); Check_default.typeOf.number("tileZ", tileZ); Check_default.typeOf.object("result", result); const minimumRadius = this._minimumRadius; const maximumRadius = this._maximumRadius; const minimumHeight = this._minimumHeight; const maximumHeight = this._maximumHeight; const minimumAngle = this._minimumAngle; const maximumAngle = this._maximumAngle; const sizeAtLevel = 1 / Math.pow(2, tileLevel); const radiusStart = Math_default.lerp( minimumRadius, maximumRadius, tileX * sizeAtLevel ); const radiusEnd = Math_default.lerp( minimumRadius, maximumRadius, (tileX + 1) * sizeAtLevel ); const heightStart = Math_default.lerp( minimumHeight, maximumHeight, tileY * sizeAtLevel ); const heightEnd = Math_default.lerp( minimumHeight, maximumHeight, (tileY + 1) * sizeAtLevel ); const angleStart = Math_default.lerp( minimumAngle, maximumAngle, tileZ * sizeAtLevel ); const angleEnd = Math_default.lerp( minimumAngle, maximumAngle, (tileZ + 1) * sizeAtLevel ); return getCylinderChunkObb( radiusStart, radiusEnd, heightStart, heightEnd, angleStart, angleEnd, this.shapeTransform, result ); }; var scratchOrientedBoundingBox2 = new OrientedBoundingBox_default(); var scratchVoxelScale = new Cartesian3_default(); var scratchRootScale = new Cartesian3_default(); var scratchScaleRatio = new Cartesian3_default(); VoxelCylinderShape.prototype.computeApproximateStepSize = function(dimensions) { Check_default.typeOf.object("dimensions", dimensions); const shapeTransform = this.shapeTransform; const minRadius = this._minimumRadius; const maxRadius = this._maximumRadius; const minHeight = this._minimumHeight; const maxHeight = this._maximumHeight; const minAngle = this._minimumAngle; const maxAngle = this._maximumAngle; const lerpRadius = 1 - 1 / dimensions.x; const lerpHeight = 1 - 1 / dimensions.y; const lerpAngle = 1 - 1 / dimensions.z; const voxelMinimumRadius = Math_default.lerp(minRadius, maxRadius, lerpRadius); const voxelMinimumHeight = Math_default.lerp(minHeight, maxHeight, lerpHeight); const voxelMinimumAngle = Math_default.lerp(minAngle, maxAngle, lerpAngle); const voxelMaximumRadius = maxRadius; const voxelMaximumHeight = maxHeight; const voxelMaximumAngle = maxAngle; const voxelObb = getCylinderChunkObb( voxelMinimumRadius, voxelMaximumRadius, voxelMinimumHeight, voxelMaximumHeight, voxelMinimumAngle, voxelMaximumAngle, shapeTransform, scratchOrientedBoundingBox2 ); const voxelScale = Matrix3_default.getScale(voxelObb.halfAxes, scratchVoxelScale); const rootScale = Matrix4_default.getScale(shapeTransform, scratchRootScale); const scaleRatio = Cartesian3_default.divideComponents( voxelScale, rootScale, scratchScaleRatio ); const stepSize = Cartesian3_default.minimumComponent(scaleRatio); return stepSize; }; VoxelCylinderShape.DefaultMinBounds = Object.freeze( new Cartesian3_default(0, -1, -Math_default.PI) ); VoxelCylinderShape.DefaultMaxBounds = Object.freeze( new Cartesian3_default(1, 1, +Math_default.PI) ); var maxTestAngles = 5; var scratchTestAngles = new Array(maxTestAngles); var scratchTranslation3 = new Cartesian3_default(); var scratchRotation5 = new Matrix3_default(); var scratchTranslationMatrix = new Matrix4_default(); var scratchRotationMatrix2 = new Matrix4_default(); var scratchScaleMatrix = new Matrix4_default(); var scratchMatrix6 = new Matrix4_default(); var scratchColumn0 = new Cartesian3_default(); var scratchColumn1 = new Cartesian3_default(); var scratchColumn22 = new Cartesian3_default(); var scratchCorners2 = new Array(8); for (let i = 0; i < 8; i++) { scratchCorners2[i] = new Cartesian3_default(); } function orthogonal(a3, b, epsilon) { return Math.abs(Cartesian4_default.dot(a3, b)) < epsilon; } function isValidOrientedBoundingBoxTransformation(matrix) { const column0 = Matrix4_default.getColumn(matrix, 0, scratchColumn0); const column1 = Matrix4_default.getColumn(matrix, 1, scratchColumn1); const column2 = Matrix4_default.getColumn(matrix, 2, scratchColumn22); const epsilon = Math_default.EPSILON4; return orthogonal(column0, column1, epsilon) && orthogonal(column1, column2, epsilon); } function computeLooseOrientedBoundingBox(matrix, result) { const corners2 = scratchCorners2; Cartesian3_default.fromElements(-0.5, -0.5, -0.5, corners2[0]); Cartesian3_default.fromElements(-0.5, -0.5, 0.5, corners2[1]); Cartesian3_default.fromElements(-0.5, 0.5, -0.5, corners2[2]); Cartesian3_default.fromElements(-0.5, 0.5, 0.5, corners2[3]); Cartesian3_default.fromElements(0.5, -0.5, -0.5, corners2[4]); Cartesian3_default.fromElements(0.5, -0.5, 0.5, corners2[5]); Cartesian3_default.fromElements(0.5, 0.5, -0.5, corners2[6]); Cartesian3_default.fromElements(0.5, 0.5, 0.5, corners2[7]); for (let i = 0; i < 8; ++i) { Matrix4_default.multiplyByPoint(matrix, corners2[i], corners2[i]); } return OrientedBoundingBox_default.fromPoints(corners2, result); } function getCylinderChunkObb(radiusStart, radiusEnd, heightStart, heightEnd, angleStart, angleEnd, matrix, result) { const defaultMinBounds = VoxelCylinderShape.DefaultMinBounds; const defaultMaxBounds = VoxelCylinderShape.DefaultMaxBounds; const defaultMinRadius = defaultMinBounds.x; const defaultMaxRadius = defaultMaxBounds.x; const defaultMinHeight = defaultMinBounds.y; const defaultMaxHeight = defaultMaxBounds.y; const defaultMinAngle = defaultMinBounds.z; const defaultMaxAngle = defaultMaxBounds.z; if (radiusStart === defaultMinRadius && radiusEnd === defaultMaxRadius && heightStart === defaultMinHeight && heightEnd === defaultMaxHeight && angleStart === defaultMinAngle && angleEnd === defaultMaxAngle) { result.center = Matrix4_default.getTranslation(matrix, result.center); result.halfAxes = Matrix4_default.getMatrix3(matrix, result.halfAxes); return result; } const isAngleReversed = angleEnd < angleStart; if (isAngleReversed) { angleEnd += Math_default.TWO_PI; } const angleRange = angleEnd - angleStart; const angleMid = angleStart + angleRange * 0.5; const testAngles = scratchTestAngles; let testAngleCount = 0; testAngles[testAngleCount++] = angleStart; testAngles[testAngleCount++] = angleEnd; testAngles[testAngleCount++] = angleMid; if (angleRange > Math_default.PI) { testAngles[testAngleCount++] = angleMid - Math_default.PI_OVER_TWO; testAngles[testAngleCount++] = angleMid + Math_default.PI_OVER_TWO; } let minX = 1; let minY = 1; let maxX = -1; let maxY = -1; for (let i = 0; i < testAngleCount; ++i) { const angle = testAngles[i] - angleMid; const cosAngle = Math.cos(angle); const sinAngle = Math.sin(angle); const x1 = cosAngle * radiusStart; const y1 = sinAngle * radiusStart; const x2 = cosAngle * radiusEnd; const y2 = sinAngle * radiusEnd; minX = Math.min(minX, x1); minY = Math.min(minY, y1); minX = Math.min(minX, x2); minY = Math.min(minY, y2); maxX = Math.max(maxX, x1); maxY = Math.max(maxY, y1); maxX = Math.max(maxX, x2); maxY = Math.max(maxY, y2); } const extentX = maxX - minX; const extentY = maxY - minY; const extentZ = heightEnd - heightStart; const centerX = (minX + maxX) * 0.5; const centerY = (minY + maxY) * 0.5; const centerZ = (heightStart + heightEnd) * 0.5; const translation3 = Cartesian3_default.fromElements( centerX, centerY, centerZ, scratchTranslation3 ); const rotation = Matrix3_default.fromRotationZ(angleMid, scratchRotation5); const scale = Cartesian3_default.fromElements( extentX, extentY, extentZ, scratchScale7 ); const scaleMatrix2 = Matrix4_default.fromScale(scale, scratchScaleMatrix); const rotationMatrix = Matrix4_default.fromRotation(rotation, scratchRotationMatrix2); const translationMatrix = Matrix4_default.fromTranslation( translation3, scratchTranslationMatrix ); const localMatrix = Matrix4_default.multiplyTransformation( rotationMatrix, Matrix4_default.multiplyTransformation( translationMatrix, scaleMatrix2, scratchMatrix6 ), scratchMatrix6 ); const globalMatrix = Matrix4_default.multiplyTransformation( matrix, localMatrix, scratchMatrix6 ); if (!isValidOrientedBoundingBoxTransformation(globalMatrix)) { return computeLooseOrientedBoundingBox(globalMatrix, result); } return OrientedBoundingBox_default.fromTransformation(globalMatrix, result); } var VoxelCylinderShape_default = VoxelCylinderShape; // packages/engine/Source/Scene/VoxelEllipsoidShape.js function VoxelEllipsoidShape() { this.orientedBoundingBox = new OrientedBoundingBox_default(); this.boundingSphere = new BoundingSphere_default(); this.boundTransform = new Matrix4_default(); this.shapeTransform = new Matrix4_default(); this._rectangle = new Rectangle_default(); this._minimumHeight = VoxelEllipsoidShape.DefaultMinBounds.z; this._maximumHeight = VoxelEllipsoidShape.DefaultMaxBounds.z; this._ellipsoid = new Ellipsoid_default(); this._translation = new Cartesian3_default(); this._rotation = new Matrix3_default(); this.shaderUniforms = { ellipsoidRadiiUv: new Cartesian3_default(), ellipsoidInverseRadiiSquaredUv: new Cartesian3_default(), ellipsoidRenderLongitudeMinMax: new Cartesian2_default(), ellipsoidShapeUvLongitudeMinMaxMid: new Cartesian3_default(), ellipsoidUvToShapeUvLongitude: new Cartesian2_default(), ellipsoidUvToShapeUvLatitude: new Cartesian2_default(), ellipsoidRenderLatitudeCosSqrHalfMinMax: new Cartesian2_default(), ellipsoidInverseHeightDifferenceUv: 0, ellipseInnerRadiiUv: new Cartesian2_default(), ellipsoidInverseInnerScaleUv: 0, ellipsoidInverseOuterScaleUv: 0 }; this.shaderDefines = { ELLIPSOID_HAS_RENDER_BOUNDS_LONGITUDE: void 0, ELLIPSOID_HAS_RENDER_BOUNDS_LONGITUDE_RANGE_EQUAL_ZERO: void 0, ELLIPSOID_HAS_RENDER_BOUNDS_LONGITUDE_RANGE_UNDER_HALF: void 0, ELLIPSOID_HAS_RENDER_BOUNDS_LONGITUDE_RANGE_EQUAL_HALF: void 0, ELLIPSOID_HAS_RENDER_BOUNDS_LONGITUDE_RANGE_OVER_HALF: void 0, ELLIPSOID_HAS_RENDER_BOUNDS_LONGITUDE_MIN_DISCONTINUITY: void 0, ELLIPSOID_HAS_RENDER_BOUNDS_LONGITUDE_MAX_DISCONTINUITY: void 0, ELLIPSOID_HAS_SHAPE_BOUNDS_LONGITUDE: void 0, ELLIPSOID_HAS_SHAPE_BOUNDS_LONGITUDE_RANGE_EQUAL_ZERO: void 0, ELLIPSOID_HAS_SHAPE_BOUNDS_LONGITUDE_MIN_MAX_REVERSED: void 0, ELLIPSOID_HAS_RENDER_BOUNDS_LATITUDE: void 0, ELLIPSOID_HAS_RENDER_BOUNDS_LATITUDE_MAX_UNDER_HALF: void 0, ELLIPSOID_HAS_RENDER_BOUNDS_LATITUDE_MAX_EQUAL_HALF: void 0, ELLIPSOID_HAS_RENDER_BOUNDS_LATITUDE_MAX_OVER_HALF: void 0, ELLIPSOID_HAS_RENDER_BOUNDS_LATITUDE_MIN_UNDER_HALF: void 0, ELLIPSOID_HAS_RENDER_BOUNDS_LATITUDE_MIN_EQUAL_HALF: void 0, ELLIPSOID_HAS_RENDER_BOUNDS_LATITUDE_MIN_OVER_HALF: void 0, ELLIPSOID_HAS_RENDER_BOUNDS_LATITUDE_RANGE_EQUAL_ZERO: void 0, ELLIPSOID_HAS_SHAPE_BOUNDS_LATITUDE: void 0, ELLIPSOID_HAS_SHAPE_BOUNDS_LATITUDE_RANGE_EQUAL_ZERO: void 0, ELLIPSOID_HAS_RENDER_BOUNDS_HEIGHT_MAX: void 0, ELLIPSOID_HAS_RENDER_BOUNDS_HEIGHT_MIN: void 0, ELLIPSOID_HAS_RENDER_BOUNDS_HEIGHT_FLAT: void 0, ELLIPSOID_HAS_SHAPE_BOUNDS_HEIGHT_MIN: void 0, ELLIPSOID_HAS_SHAPE_BOUNDS_HEIGHT_FLAT: void 0, ELLIPSOID_IS_SPHERE: void 0, ELLIPSOID_INTERSECTION_INDEX_LONGITUDE: void 0, ELLIPSOID_INTERSECTION_INDEX_LATITUDE_MAX: void 0, ELLIPSOID_INTERSECTION_INDEX_LATITUDE_MIN: void 0, ELLIPSOID_INTERSECTION_INDEX_HEIGHT_MAX: void 0, ELLIPSOID_INTERSECTION_INDEX_HEIGHT_MIN: void 0 }; this.shaderMaximumIntersectionsLength = 0; } var scratchScale8 = new Cartesian3_default(); var scratchRotationScale3 = new Matrix3_default(); var scratchShapeOuterExtent = new Cartesian3_default(); var scratchShapeInnerExtent = new Cartesian3_default(); var scratchRenderOuterExtent = new Cartesian3_default(); var scratchRenderInnerExtent = new Cartesian3_default(); var scratchRenderRectangle = new Rectangle_default(); VoxelEllipsoidShape.prototype.update = function(modelMatrix, minBounds, maxBounds, clipMinBounds, clipMaxBounds) { clipMinBounds = defaultValue_default( clipMinBounds, VoxelEllipsoidShape.DefaultMinBounds ); clipMaxBounds = defaultValue_default( clipMaxBounds, VoxelEllipsoidShape.DefaultMaxBounds ); Check_default.typeOf.object("modelMatrix", modelMatrix); Check_default.typeOf.object("minBounds", minBounds); Check_default.typeOf.object("maxBounds", maxBounds); const defaultMinLongitude = VoxelEllipsoidShape.DefaultMinBounds.x; const defaultMaxLongitude = VoxelEllipsoidShape.DefaultMaxBounds.x; const defaultLongitudeRange = defaultMaxLongitude - defaultMinLongitude; const defaultLongitudeRangeHalf = 0.5 * defaultLongitudeRange; const defaultMinLatitude = VoxelEllipsoidShape.DefaultMinBounds.y; const defaultMaxLatitude = VoxelEllipsoidShape.DefaultMaxBounds.y; const defaultLatitudeRange = defaultMaxLatitude - defaultMinLatitude; const epsilonZeroScale = Math_default.EPSILON10; const epsilonLongitudeDiscontinuity = Math_default.EPSILON3; const epsilonLongitude = Math_default.EPSILON10; const epsilonLatitude = Math_default.EPSILON10; const epsilonLatitudeFlat = Math_default.EPSILON3; const shapeMinLongitude = Math_default.clamp( minBounds.x, defaultMinLongitude, defaultMaxLongitude ); const shapeMaxLongitude = Math_default.clamp( maxBounds.x, defaultMinLongitude, defaultMaxLongitude ); const clipMinLongitude = Math_default.clamp( clipMinBounds.x, defaultMinLongitude, defaultMaxLongitude ); const clipMaxLongitude = Math_default.clamp( clipMaxBounds.x, defaultMinLongitude, defaultMaxLongitude ); const renderMinLongitude = Math.max(shapeMinLongitude, clipMinLongitude); const renderMaxLongitude = Math.min(shapeMaxLongitude, clipMaxLongitude); const shapeMinLatitude = Math_default.clamp( minBounds.y, defaultMinLatitude, defaultMaxLatitude ); const shapeMaxLatitude = Math_default.clamp( maxBounds.y, defaultMinLatitude, defaultMaxLatitude ); const clipMinLatitude = Math_default.clamp( clipMinBounds.y, defaultMinLatitude, defaultMaxLatitude ); const clipMaxLatitude = Math_default.clamp( clipMaxBounds.y, defaultMinLatitude, defaultMaxLatitude ); const renderMinLatitude = Math.max(shapeMinLatitude, clipMinLatitude); const renderMaxLatitude = Math.min(shapeMaxLatitude, clipMaxLatitude); const radii = Matrix4_default.getScale(modelMatrix, scratchScale8); const isSphere = radii.x === radii.y && radii.y === radii.z; const minRadius = Cartesian3_default.minimumComponent(radii); const shapeMinHeight = Math.max(minBounds.z, -minRadius); const shapeMaxHeight = Math.max(maxBounds.z, -minRadius); const clipMinHeight = Math.max(clipMinBounds.z, -minRadius); const clipMaxHeight = Math.max(clipMaxBounds.z, -minRadius); const renderMinHeight = Math.max(shapeMinHeight, clipMinHeight); const renderMaxHeight = Math.min(shapeMaxHeight, clipMaxHeight); const shapeInnerExtent = Cartesian3_default.add( radii, Cartesian3_default.fromElements( shapeMinHeight, shapeMinHeight, shapeMinHeight, scratchShapeInnerExtent ), scratchShapeInnerExtent ); const shapeOuterExtent = Cartesian3_default.add( radii, Cartesian3_default.fromElements( shapeMaxHeight, shapeMaxHeight, shapeMaxHeight, scratchShapeOuterExtent ), scratchShapeOuterExtent ); const shapeMaxExtent = Cartesian3_default.maximumComponent(shapeOuterExtent); const renderInnerExtent = Cartesian3_default.add( radii, Cartesian3_default.fromElements( renderMinHeight, renderMinHeight, renderMinHeight, scratchRenderInnerExtent ), scratchRenderInnerExtent ); const renderOuterExtent = Cartesian3_default.add( radii, Cartesian3_default.fromElements( renderMaxHeight, renderMaxHeight, renderMaxHeight, scratchRenderOuterExtent ), scratchRenderOuterExtent ); if (renderMinLatitude > renderMaxLatitude || renderMinLatitude === defaultMaxLatitude || renderMaxLatitude === defaultMinLatitude || renderMinHeight > renderMaxHeight || Math_default.equalsEpsilon( renderOuterExtent, Cartesian3_default.ZERO, void 0, epsilonZeroScale )) { return false; } this._rectangle = Rectangle_default.fromRadians( shapeMinLongitude, shapeMinLatitude, shapeMaxLongitude, shapeMaxLatitude ); this._translation = Matrix4_default.getTranslation(modelMatrix, this._translation); this._rotation = Matrix4_default.getRotation(modelMatrix, this._rotation); this._ellipsoid = Ellipsoid_default.fromCartesian3(radii, this._ellipsoid); this._minimumHeight = shapeMinHeight; this._maximumHeight = shapeMaxHeight; const renderRectangle = Rectangle_default.fromRadians( renderMinLongitude, renderMinLatitude, renderMaxLongitude, renderMaxLatitude, scratchRenderRectangle ); this.orientedBoundingBox = getEllipsoidChunkObb( renderRectangle, renderMinHeight, renderMaxHeight, this._ellipsoid, this._translation, this._rotation, this.orientedBoundingBox ); this.shapeTransform = Matrix4_default.fromRotationTranslation( Matrix3_default.setScale(this._rotation, shapeOuterExtent, scratchRotationScale3), this._translation, this.shapeTransform ); this.boundTransform = Matrix4_default.fromRotationTranslation( this.orientedBoundingBox.halfAxes, this.orientedBoundingBox.center, this.boundTransform ); this.boundingSphere = BoundingSphere_default.fromOrientedBoundingBox( this.orientedBoundingBox, this.boundingSphere ); const renderIsLongitudeReversed = renderMaxLongitude < renderMinLongitude; const renderLongitudeRange = renderMaxLongitude - renderMinLongitude + renderIsLongitudeReversed * defaultLongitudeRange; const renderIsLongitudeRangeZero = renderLongitudeRange <= epsilonLongitude; const renderIsLongitudeRangeUnderHalf = renderLongitudeRange > defaultLongitudeRangeHalf + epsilonLongitude && renderLongitudeRange < defaultLongitudeRange - epsilonLongitude; const renderIsLongitudeRangeHalf = renderLongitudeRange >= defaultLongitudeRangeHalf - epsilonLongitude && renderLongitudeRange <= defaultLongitudeRangeHalf + epsilonLongitude; const renderIsLongitudeRangeOverHalf = renderLongitudeRange > epsilonLongitude && renderLongitudeRange < defaultLongitudeRangeHalf - epsilonLongitude; const renderHasLongitude = renderIsLongitudeRangeZero || renderIsLongitudeRangeUnderHalf || renderIsLongitudeRangeHalf || renderIsLongitudeRangeOverHalf; const shapeIsLongitudeReversed = shapeMaxLongitude < shapeMinLongitude; const shapeLongitudeRange = shapeMaxLongitude - shapeMinLongitude + shapeIsLongitudeReversed * defaultLongitudeRange; const shapeIsLongitudeRangeZero = shapeLongitudeRange <= epsilonLongitude; const shapeIsLongitudeRangeUnderHalf = shapeLongitudeRange > defaultLongitudeRangeHalf + epsilonLongitude && shapeLongitudeRange < defaultLongitudeRange - epsilonLongitude; const shapeIsLongitudeRangeHalf = shapeLongitudeRange >= defaultLongitudeRangeHalf - epsilonLongitude && shapeLongitudeRange <= defaultLongitudeRangeHalf + epsilonLongitude; const shapeIsLongitudeRangeOverHalf = shapeLongitudeRange > epsilonLongitude && shapeLongitudeRange < defaultLongitudeRangeHalf - epsilonLongitude; const shapeHasLongitude = shapeIsLongitudeRangeZero || shapeIsLongitudeRangeUnderHalf || shapeIsLongitudeRangeHalf || shapeIsLongitudeRangeOverHalf; const renderIsLatitudeMaxUnderHalf = renderMaxLatitude < -epsilonLatitudeFlat; const renderIsLatitudeMaxHalf = renderMaxLatitude >= -epsilonLatitudeFlat && renderMaxLatitude <= +epsilonLatitudeFlat; const renderIsLatitudeMaxOverHalf = renderMaxLatitude > +epsilonLatitudeFlat && renderMaxLatitude < defaultMaxLatitude - epsilonLatitude; const renderHasLatitudeMax = renderIsLatitudeMaxUnderHalf || renderIsLatitudeMaxHalf || renderIsLatitudeMaxOverHalf; const renderIsLatitudeMinUnderHalf = renderMinLatitude > defaultMinLatitude + epsilonLatitude && renderMinLatitude < -epsilonLatitudeFlat; const renderIsLatitudeMinHalf = renderMinLatitude >= -epsilonLatitudeFlat && renderMinLatitude <= +epsilonLatitudeFlat; const renderIsLatitudeMinOverHalf = renderMinLatitude > +epsilonLatitudeFlat; const renderHasLatitudeMin = renderIsLatitudeMinUnderHalf || renderIsLatitudeMinHalf || renderIsLatitudeMinOverHalf; const renderHasLatitude = renderHasLatitudeMax || renderHasLatitudeMin; const shapeLatitudeRange = shapeMaxLatitude - shapeMinLatitude; const shapeIsLatitudeMaxUnderHalf = shapeMaxLatitude < -epsilonLatitudeFlat; const shapeIsLatitudeMaxHalf = shapeMaxLatitude >= -epsilonLatitudeFlat && shapeMaxLatitude <= +epsilonLatitudeFlat; const shapeIsLatitudeMaxOverHalf = shapeMaxLatitude > +epsilonLatitudeFlat && shapeMaxLatitude < defaultMaxLatitude - epsilonLatitude; const shapeHasLatitudeMax = shapeIsLatitudeMaxUnderHalf || shapeIsLatitudeMaxHalf || shapeIsLatitudeMaxOverHalf; const shapeIsLatitudeMinUnderHalf = shapeMinLatitude > defaultMinLatitude + epsilonLatitude && shapeMinLatitude < -epsilonLatitudeFlat; const shapeIsLatitudeMinHalf = shapeMinLatitude >= -epsilonLatitudeFlat && shapeMinLatitude <= +epsilonLatitudeFlat; const shapeIsLatitudeMinOverHalf = shapeMinLatitude > +epsilonLatitudeFlat; const shapeHasLatitudeMin = shapeIsLatitudeMinUnderHalf || shapeIsLatitudeMinHalf || shapeIsLatitudeMinOverHalf; const shapeHasLatitude = shapeHasLatitudeMax || shapeHasLatitudeMin; const renderHasMinHeight = !Cartesian3_default.equals( renderInnerExtent, Cartesian3_default.ZERO ); const renderHasMaxHeight = !Cartesian3_default.equals( renderOuterExtent, Cartesian3_default.ZERO ); const renderHasHeight = renderHasMinHeight || renderHasMaxHeight; const renderHeightRange = renderMaxHeight - renderMinHeight; const shapeHasMinHeight = !Cartesian3_default.equals( shapeInnerExtent, Cartesian3_default.ZERO ); const shapeHasMaxHeight = !Cartesian3_default.equals( shapeOuterExtent, Cartesian3_default.ZERO ); const shapeHasHeight = shapeHasMinHeight || shapeHasMaxHeight; const shaderUniforms = this.shaderUniforms; const shaderDefines = this.shaderDefines; for (const key in shaderDefines) { if (shaderDefines.hasOwnProperty(key)) { shaderDefines[key] = void 0; } } shaderUniforms.ellipsoidRadiiUv = Cartesian3_default.divideByScalar( shapeOuterExtent, shapeMaxExtent, shaderUniforms.ellipsoidRadiiUv ); shaderUniforms.ellipsoidInverseRadiiSquaredUv = Cartesian3_default.divideComponents( Cartesian3_default.ONE, Cartesian3_default.multiplyComponents( shaderUniforms.ellipsoidRadiiUv, shaderUniforms.ellipsoidRadiiUv, shaderUniforms.ellipsoidInverseRadiiSquaredUv ), shaderUniforms.ellipsoidInverseRadiiSquaredUv ); let intersectionCount = 0; shaderDefines["ELLIPSOID_INTERSECTION_INDEX_HEIGHT_MAX"] = intersectionCount; intersectionCount += 1; if (renderHasHeight) { if (renderHeightRange === 0) { shaderDefines["ELLIPSOID_HAS_RENDER_BOUNDS_HEIGHT_FLAT"] = true; } if (renderHasMinHeight) { shaderDefines["ELLIPSOID_HAS_RENDER_BOUNDS_HEIGHT_MIN"] = true; shaderDefines["ELLIPSOID_INTERSECTION_INDEX_HEIGHT_MIN"] = intersectionCount; intersectionCount += 1; shaderUniforms.ellipsoidInverseInnerScaleUv = shapeMaxExtent / (shapeMaxExtent - (shapeMaxHeight - renderMinHeight)); } if (renderHasMaxHeight) { shaderDefines["ELLIPSOID_HAS_RENDER_BOUNDS_HEIGHT_MAX"] = true; shaderUniforms.ellipsoidInverseOuterScaleUv = shapeMaxExtent / (shapeMaxExtent - (shapeMaxHeight - renderMaxHeight)); } } if (shapeHasHeight) { if (shapeHasMinHeight) { shaderDefines["ELLIPSOID_HAS_SHAPE_BOUNDS_HEIGHT_MIN"] = true; const thickness = (shapeMaxHeight - shapeMinHeight) / shapeMaxExtent; shaderUniforms.ellipsoidInverseHeightDifferenceUv = 1 / thickness; shaderUniforms.ellipseInnerRadiiUv = Cartesian2_default.fromElements( shaderUniforms.ellipsoidRadiiUv.x * (1 - thickness), shaderUniforms.ellipsoidRadiiUv.z * (1 - thickness), shaderUniforms.ellipseInnerRadiiUv ); } if (shapeMinHeight === shapeMaxHeight) { shaderDefines["ELLIPSOID_HAS_SHAPE_BOUNDS_HEIGHT_FLAT"] = true; } } if (renderHasLongitude) { shaderDefines["ELLIPSOID_HAS_RENDER_BOUNDS_LONGITUDE"] = true; shaderDefines["ELLIPSOID_INTERSECTION_INDEX_LONGITUDE"] = intersectionCount; if (renderIsLongitudeRangeUnderHalf) { shaderDefines["ELLIPSOID_HAS_RENDER_BOUNDS_LONGITUDE_RANGE_UNDER_HALF"] = true; intersectionCount += 1; } else if (renderIsLongitudeRangeOverHalf) { shaderDefines["ELLIPSOID_HAS_RENDER_BOUNDS_LONGITUDE_RANGE_OVER_HALF"] = true; intersectionCount += 2; } else if (renderIsLongitudeRangeHalf) { shaderDefines["ELLIPSOID_HAS_RENDER_BOUNDS_LONGITUDE_RANGE_EQUAL_HALF"] = true; intersectionCount += 1; } else if (renderIsLongitudeRangeZero) { shaderDefines["ELLIPSOID_HAS_RENDER_BOUNDS_LONGITUDE_RANGE_EQUAL_ZERO"] = true; intersectionCount += 2; } shaderUniforms.ellipsoidRenderLongitudeMinMax = Cartesian2_default.fromElements( renderMinLongitude, renderMaxLongitude, shaderUniforms.ellipsoidRenderLongitudeMinMax ); } if (shapeHasLongitude) { shaderDefines["ELLIPSOID_HAS_SHAPE_BOUNDS_LONGITUDE"] = true; const shapeIsLongitudeReversed2 = shapeMaxLongitude < shapeMinLongitude; if (shapeIsLongitudeReversed2) { shaderDefines["ELLIPSOID_HAS_SHAPE_BOUNDS_LONGITUDE_MIN_MAX_REVERSED"] = true; } const scale = defaultLongitudeRange / shapeLongitudeRange; const offset2 = -(shapeMinLongitude - defaultMinLongitude) / shapeLongitudeRange; shaderUniforms.ellipsoidUvToShapeUvLongitude = Cartesian2_default.fromElements( scale, offset2, shaderUniforms.ellipsoidUvToShapeUvLongitude ); } if (renderHasLongitude) { const renderIsMinLongitudeDiscontinuity = Math_default.equalsEpsilon( renderMinLongitude, defaultMinLongitude, void 0, epsilonLongitudeDiscontinuity ); const renderIsMaxLongitudeDiscontinuity = Math_default.equalsEpsilon( renderMaxLongitude, defaultMaxLongitude, void 0, epsilonLongitudeDiscontinuity ); if (renderIsMinLongitudeDiscontinuity) { shaderDefines["ELLIPSOID_HAS_RENDER_BOUNDS_LONGITUDE_MIN_DISCONTINUITY"] = true; } if (renderIsMaxLongitudeDiscontinuity) { shaderDefines["ELLIPSOID_HAS_RENDER_BOUNDS_LONGITUDE_MAX_DISCONTINUITY"] = true; } const uvShapeMinLongitude = (shapeMinLongitude - defaultMinLongitude) / defaultLongitudeRange; const uvShapeMaxLongitude = (shapeMaxLongitude - defaultMinLongitude) / defaultLongitudeRange; const uvRenderMaxLongitude = (renderMaxLongitude - defaultMinLongitude) / defaultLongitudeRange; const uvRenderLongitudeRangeZero = 1 - renderLongitudeRange / defaultLongitudeRange; const uvRenderLongitudeRangeZeroMid = (uvRenderMaxLongitude + 0.5 * uvRenderLongitudeRangeZero) % 1; shaderUniforms.ellipsoidShapeUvLongitudeMinMaxMid = Cartesian3_default.fromElements( uvShapeMinLongitude, uvShapeMaxLongitude, uvRenderLongitudeRangeZeroMid, shaderUniforms.ellipsoidShapeUvLongitudeMinMaxMid ); } if (renderHasLatitude) { shaderDefines["ELLIPSOID_HAS_RENDER_BOUNDS_LATITUDE"] = true; if (renderHasLatitudeMin) { shaderDefines["ELLIPSOID_HAS_RENDER_BOUNDS_LATITUDE_MIN"] = true; shaderDefines["ELLIPSOID_INTERSECTION_INDEX_LATITUDE_MIN"] = intersectionCount; if (renderIsLatitudeMinUnderHalf) { shaderDefines["ELLIPSOID_HAS_RENDER_BOUNDS_LATITUDE_MIN_UNDER_HALF"] = true; intersectionCount += 1; } else if (renderIsLatitudeMinHalf) { shaderDefines["ELLIPSOID_HAS_RENDER_BOUNDS_LATITUDE_MIN_EQUAL_HALF"] = true; intersectionCount += 1; } else if (renderIsLatitudeMinOverHalf) { shaderDefines["ELLIPSOID_HAS_RENDER_BOUNDS_LATITUDE_MIN_OVER_HALF"] = true; intersectionCount += 2; } } if (renderHasLatitudeMax) { shaderDefines["ELLIPSOID_HAS_RENDER_BOUNDS_LATITUDE_MAX"] = true; shaderDefines["ELLIPSOID_INTERSECTION_INDEX_LATITUDE_MAX"] = intersectionCount; if (renderIsLatitudeMaxUnderHalf) { shaderDefines["ELLIPSOID_HAS_RENDER_BOUNDS_LATITUDE_MAX_UNDER_HALF"] = true; intersectionCount += 2; } else if (renderIsLatitudeMaxHalf) { shaderDefines["ELLIPSOID_HAS_RENDER_BOUNDS_LATITUDE_MAX_EQUAL_HALF"] = true; intersectionCount += 1; } else if (renderIsLatitudeMaxOverHalf) { shaderDefines["ELLIPSOID_HAS_RENDER_BOUNDS_LATITUDE_MAX_OVER_HALF"] = true; intersectionCount += 1; } } if (renderMinLatitude === renderMaxLatitude) { shaderDefines["ELLIPSOID_HAS_RENDER_BOUNDS_LATITUDE_RANGE_EQUAL_ZERO"] = true; } const minCosHalfAngleSqr = Math.pow( Math.cos(Math_default.PI_OVER_TWO - Math.abs(renderMinLatitude)), 2 ); const maxCosHalfAngleSqr = Math.pow( Math.cos(Math_default.PI_OVER_TWO - Math.abs(renderMaxLatitude)), 2 ); shaderUniforms.ellipsoidRenderLatitudeCosSqrHalfMinMax = Cartesian2_default.fromElements( minCosHalfAngleSqr, maxCosHalfAngleSqr, shaderUniforms.ellipsoidRenderLatitudeCosSqrHalfMinMax ); } if (shapeHasLatitude) { shaderDefines["ELLIPSOID_HAS_SHAPE_BOUNDS_LATITUDE"] = true; if (shapeMinLatitude === shapeMaxLatitude) { shaderDefines["ELLIPSOID_HAS_SHAPE_BOUNDS_LATITUDE_RANGE_EQUAL_ZERO"] = true; } const scale = defaultLatitudeRange / shapeLatitudeRange; const offset2 = (defaultMinLatitude - shapeMinLatitude) / shapeLatitudeRange; shaderUniforms.ellipsoidUvToShapeUvLatitude = Cartesian2_default.fromElements( scale, offset2, shaderUniforms.ellipsoidUvToShapeUvLatitude ); } if (isSphere) { shaderDefines["ELLIPSOID_IS_SPHERE"] = true; } this.shaderMaximumIntersectionsLength = intersectionCount; return true; }; var scratchRectangle10 = new Rectangle_default(); VoxelEllipsoidShape.prototype.computeOrientedBoundingBoxForTile = function(tileLevel, tileX, tileY, tileZ, result) { Check_default.typeOf.number("tileLevel", tileLevel); Check_default.typeOf.number("tileX", tileX); Check_default.typeOf.number("tileY", tileY); Check_default.typeOf.number("tileZ", tileZ); Check_default.typeOf.object("result", result); const sizeAtLevel = 1 / Math.pow(2, tileLevel); const minLongitudeLerp = tileX * sizeAtLevel; const maxLongitudeLerp = (tileX + 1) * sizeAtLevel; const minLatitudeLerp = tileY * sizeAtLevel; const maxLatitudeLerp = (tileY + 1) * sizeAtLevel; const minHeightLerp = tileZ * sizeAtLevel; const maxHeightLerp = (tileZ + 1) * sizeAtLevel; const rectangle = Rectangle_default.subsection( this._rectangle, minLongitudeLerp, minLatitudeLerp, maxLongitudeLerp, maxLatitudeLerp, scratchRectangle10 ); const minHeight = Math_default.lerp( this._minimumHeight, this._maximumHeight, minHeightLerp ); const maxHeight = Math_default.lerp( this._minimumHeight, this._maximumHeight, maxHeightLerp ); return getEllipsoidChunkObb( rectangle, minHeight, maxHeight, this._ellipsoid, this._translation, this._rotation, result ); }; VoxelEllipsoidShape.prototype.computeApproximateStepSize = function(dimensions) { Check_default.typeOf.object("dimensions", dimensions); const ellipsoid = this._ellipsoid; const ellipsoidMaximumRadius = ellipsoid.maximumRadius; const minimumHeight = this._minimumHeight; const maximumHeight = this._maximumHeight; const shellToEllipsoidRatio = (maximumHeight - minimumHeight) / (ellipsoidMaximumRadius + maximumHeight); const stepSize = 0.5 * shellToEllipsoidRatio / dimensions.z; return stepSize; }; function getEllipsoidChunkObb(rectangle, minHeight, maxHeight, ellipsoid, translation3, rotation, result) { result = OrientedBoundingBox_default.fromRectangle( rectangle, minHeight, maxHeight, ellipsoid, result ); result.center = Cartesian3_default.add(result.center, translation3, result.center); result.halfAxes = Matrix3_default.multiply( result.halfAxes, rotation, result.halfAxes ); return result; } VoxelEllipsoidShape.DefaultMinBounds = Object.freeze( new Cartesian3_default(-Math_default.PI, -Math_default.PI_OVER_TWO, -Number.MAX_VALUE) ); VoxelEllipsoidShape.DefaultMaxBounds = Object.freeze( new Cartesian3_default(+Math_default.PI, +Math_default.PI_OVER_TWO, +Number.MAX_VALUE) ); var VoxelEllipsoidShape_default = VoxelEllipsoidShape; // packages/engine/Source/Scene/VoxelShapeType.js var VoxelShapeType = { /** * A box shape. * * @type {string} * @constant * @private */ BOX: "BOX", /** * An ellipsoid shape. * * @type {string} * @constant * @private */ ELLIPSOID: "ELLIPSOID", /** * A cylinder shape. * * @type {string} * @constant * @private */ CYLINDER: "CYLINDER" }; VoxelShapeType.getMinBounds = function(shapeType) { switch (shapeType) { case VoxelShapeType.BOX: return VoxelBoxShape_default.DefaultMinBounds; case VoxelShapeType.ELLIPSOID: return VoxelEllipsoidShape_default.DefaultMinBounds; case VoxelShapeType.CYLINDER: return VoxelCylinderShape_default.DefaultMinBounds; default: throw new DeveloperError_default(`Invalid shape type ${shapeType}`); } }; VoxelShapeType.getMaxBounds = function(shapeType) { switch (shapeType) { case VoxelShapeType.BOX: return VoxelBoxShape_default.DefaultMaxBounds; case VoxelShapeType.ELLIPSOID: return VoxelEllipsoidShape_default.DefaultMaxBounds; case VoxelShapeType.CYLINDER: return VoxelCylinderShape_default.DefaultMaxBounds; default: throw new DeveloperError_default(`Invalid shape type ${shapeType}`); } }; VoxelShapeType.getShapeConstructor = function(shapeType) { switch (shapeType) { case VoxelShapeType.BOX: return VoxelBoxShape_default; case VoxelShapeType.ELLIPSOID: return VoxelEllipsoidShape_default; case VoxelShapeType.CYLINDER: return VoxelCylinderShape_default; default: throw new DeveloperError_default(`Invalid shape type ${shapeType}`); } }; var VoxelShapeType_default = Object.freeze(VoxelShapeType); // packages/engine/Source/Scene/Cesium3DTilesVoxelProvider.js function Cesium3DTilesVoxelProvider(options) { options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT); this._ready = false; this.shapeTransform = void 0; this.globalTransform = void 0; this.shape = void 0; this.minBounds = void 0; this.maxBounds = void 0; this.dimensions = void 0; this.paddingBefore = void 0; this.paddingAfter = void 0; this.names = void 0; this.types = void 0; this.componentTypes = void 0; this.minimumValues = void 0; this.maximumValues = void 0; this.maximumTileCount = void 0; this._implicitTileset = void 0; this._subtreeCache = new ImplicitSubtreeCache_default(); const that = this; let tilesetJson; if (defined_default(options.url)) { deprecationWarning_default( "Cesium3DTilesVoxelProvider options.url", "Cesium3DTilesVoxelProvider constructor parameter options.url was deprecated in CesiumJS 1.104. It will be removed in 1.107. Use Cesium3DTilesVoxelProvider.fromUrl instead." ); this._readyPromise = Promise.resolve(options.url).then(function(url2) { const resource = Resource_default.createIfNeeded(url2); return resource.fetchJson().then(function(tileset) { tilesetJson = tileset; validate(tilesetJson); const schemaLoader = getMetadataSchemaLoader(tilesetJson, resource); return schemaLoader.load(); }).then(function(schemaLoader) { const root = tilesetJson.root; const voxel = root.content.extensions["3DTILES_content_voxels"]; const className = voxel.class; const metadataJson = hasExtension_default(tilesetJson, "3DTILES_metadata") ? tilesetJson.extensions["3DTILES_metadata"] : tilesetJson; const metadataSchema = schemaLoader.schema; const metadata = new Cesium3DTilesetMetadata_default({ metadataJson, schema: metadataSchema }); addAttributeInfo(that, metadata, className); const implicitTileset = new ImplicitTileset_default( resource, root, metadataSchema ); const { shape, minBounds, maxBounds, shapeTransform, globalTransform } = getShape(root); that.shape = shape; that.minBounds = minBounds; that.maxBounds = maxBounds; that.dimensions = Cartesian3_default.unpack(voxel.dimensions); that.shapeTransform = shapeTransform; that.globalTransform = globalTransform; that.maximumTileCount = getTileCount(metadata); let paddingBefore; let paddingAfter; if (defined_default(voxel.padding)) { paddingBefore = Cartesian3_default.unpack(voxel.padding.before); paddingAfter = Cartesian3_default.unpack(voxel.padding.after); } that.paddingBefore = paddingBefore; that.paddingAfter = paddingAfter; that._implicitTileset = implicitTileset; ResourceCache_default.unload(schemaLoader); that._ready = true; return that; }); }); } } Object.defineProperties(Cesium3DTilesVoxelProvider.prototype, { /** * Gets the promise that will be resolved when the provider is ready for use. * * @memberof Cesium3DTilesVoxelProvider.prototype * @type {PromiseGets or sets the scale of the cumulus cloud billboard in meters.
* The scale
property will affect the size of the billboard,
* but not the cloud's actual appearance.
* cloud.scale = new Cesium.Cartesian2(12, 8); * ![]() |
*
* cloud.scale = new Cesium.Cartesian2(24, 10); * ![]() |
*
To modify the cloud's appearance, modify its maximumSize
* and slice
properties.
Gets or sets the maximum size of the cumulus cloud rendered on the billboard. * This defines a maximum ellipsoid volume that the cloud can appear in. * Rather than guaranteeing a specific size, this specifies a boundary for the * cloud to appear in, and changing it can affect the shape of the cloud.
*Changing the z-value of maximumSize
has the most dramatic effect
* on the cloud's appearance because it changes the depth of the cloud, and thus the
* positions at which the cloud-shaping texture is sampled.
* cloud.maximumSize = new Cesium.Cartesian3(14, 9, 10); * ![]() |
*
* cloud.maximumSize.x = 25; * ![]() |
*
* cloud.maximumSize.y = 5; * ![]() |
*
* cloud.maximumSize.z = 17; * ![]() |
*
To modify the billboard's actual size, modify the cloud's scale
property.
Gets or sets the "slice" of the cloud that is rendered on the billboard, i.e. * the specific cross-section of the cloud chosen for the billboard's appearance. * Given a value between 0 and 1, the slice specifies how deeply into the cloud * to intersect based on its maximum size in the z-direction.
*cloud.slice = 0.32; ![]() |
* cloud.slice = 0.5; ![]() |
* cloud.slice = 0.6; ![]() |
*
Due to the nature in which this slice is calculated,
* values below 0.2
may result in cross-sections that are too small,
* and the edge of the ellipsoid will be visible. Similarly, values above 0.7
* will cause the cloud to appear smaller. Values outside the range [0.1, 0.9]
* should be avoided entirely because they do not produce desirable results.
cloud.slice = 0.08; ![]() |
* cloud.slice = 0.8; ![]() |
*
If slice
is set to a negative number, the cloud will not render a cross-section.
* Instead, it will render the outside of the ellipsoid that is visible. For clouds with
* small values of `maximumSize.z`, this can produce good-looking results, but for larger
* clouds, this can result in a cloud that is undesirably warped to the ellipsoid volume.
* cloud.slice = -1.0; * ![]() |
*
* cloud.slice = -1.0; * ![]() |
*
cloud.brightness = 1.0; ![]() |
* cloud.brightness = 0.6; ![]() |
* cloud.brightness = 0.0; ![]() |
*
true
, the geometry is expected to be closed.
*
* @memberof DebugAppearance.prototype
*
* @type {boolean}
* @readonly
*
* @default false
*/
closed: {
get: function() {
return this._closed;
}
},
/**
* The name of the attribute being visualized.
*
* @memberof DebugAppearance.prototype
*
* @type {string}
* @readonly
*/
attributeName: {
get: function() {
return this._attributeName;
}
},
/**
* The GLSL datatype of the attribute being visualized.
*
* @memberof DebugAppearance.prototype
*
* @type {string}
* @readonly
*/
glslDatatype: {
get: function() {
return this._glslDatatype;
}
}
});
DebugAppearance.prototype.getFragmentShaderSource = Appearance_default.prototype.getFragmentShaderSource;
DebugAppearance.prototype.isTranslucent = Appearance_default.prototype.isTranslucent;
DebugAppearance.prototype.getRenderState = Appearance_default.prototype.getRenderState;
var DebugAppearance_default = DebugAppearance;
// packages/engine/Source/Scene/DebugModelMatrixPrimitive.js
function DebugModelMatrixPrimitive(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this.length = defaultValue_default(options.length, 1e7);
this._length = void 0;
this.width = defaultValue_default(options.width, 2);
this._width = void 0;
this.show = defaultValue_default(options.show, true);
this.modelMatrix = Matrix4_default.clone(
defaultValue_default(options.modelMatrix, Matrix4_default.IDENTITY)
);
this._modelMatrix = new Matrix4_default();
this.id = options.id;
this._id = void 0;
this._primitive = void 0;
}
DebugModelMatrixPrimitive.prototype.update = function(frameState) {
if (!this.show) {
return;
}
if (!defined_default(this._primitive) || !Matrix4_default.equals(this._modelMatrix, this.modelMatrix) || this._length !== this.length || this._width !== this.width || this._id !== this.id) {
this._modelMatrix = Matrix4_default.clone(this.modelMatrix, this._modelMatrix);
this._length = this.length;
this._width = this.width;
this._id = this.id;
if (defined_default(this._primitive)) {
this._primitive.destroy();
}
if (this.modelMatrix[12] === 0 && this.modelMatrix[13] === 0 && this.modelMatrix[14] === 0) {
this.modelMatrix[14] = 0.01;
}
const x = new GeometryInstance_default({
geometry: new PolylineGeometry_default({
positions: [Cartesian3_default.ZERO, Cartesian3_default.UNIT_X],
width: this.width,
vertexFormat: PolylineColorAppearance_default.VERTEX_FORMAT,
colors: [Color_default.RED, Color_default.RED],
arcType: ArcType_default.NONE
}),
modelMatrix: Matrix4_default.multiplyByUniformScale(
this.modelMatrix,
this.length,
new Matrix4_default()
),
id: this.id,
pickPrimitive: this
});
const y = new GeometryInstance_default({
geometry: new PolylineGeometry_default({
positions: [Cartesian3_default.ZERO, Cartesian3_default.UNIT_Y],
width: this.width,
vertexFormat: PolylineColorAppearance_default.VERTEX_FORMAT,
colors: [Color_default.GREEN, Color_default.GREEN],
arcType: ArcType_default.NONE
}),
modelMatrix: Matrix4_default.multiplyByUniformScale(
this.modelMatrix,
this.length,
new Matrix4_default()
),
id: this.id,
pickPrimitive: this
});
const z = new GeometryInstance_default({
geometry: new PolylineGeometry_default({
positions: [Cartesian3_default.ZERO, Cartesian3_default.UNIT_Z],
width: this.width,
vertexFormat: PolylineColorAppearance_default.VERTEX_FORMAT,
colors: [Color_default.BLUE, Color_default.BLUE],
arcType: ArcType_default.NONE
}),
modelMatrix: Matrix4_default.multiplyByUniformScale(
this.modelMatrix,
this.length,
new Matrix4_default()
),
id: this.id,
pickPrimitive: this
});
this._primitive = new Primitive_default({
geometryInstances: [x, y, z],
appearance: new PolylineColorAppearance_default(),
asynchronous: false
});
}
this._primitive.update(frameState);
};
DebugModelMatrixPrimitive.prototype.isDestroyed = function() {
return false;
};
DebugModelMatrixPrimitive.prototype.destroy = function() {
this._primitive = this._primitive && this._primitive.destroy();
return destroyObject_default(this);
};
var DebugModelMatrixPrimitive_default = DebugModelMatrixPrimitive;
// packages/engine/Source/Scene/DirectionalLight.js
function DirectionalLight(options) {
Check_default.typeOf.object("options", options);
Check_default.typeOf.object("options.direction", options.direction);
if (Cartesian3_default.equals(options.direction, Cartesian3_default.ZERO)) {
throw new DeveloperError_default("options.direction cannot be zero-length");
}
this.direction = Cartesian3_default.clone(options.direction);
this.color = Color_default.clone(defaultValue_default(options.color, Color_default.WHITE));
this.intensity = defaultValue_default(options.intensity, 1);
}
var DirectionalLight_default = DirectionalLight;
// packages/engine/Source/Shaders/Appearances/EllipsoidSurfaceAppearanceFS.js
var EllipsoidSurfaceAppearanceFS_default = "in vec3 v_positionMC;\nin vec3 v_positionEC;\nin vec2 v_st;\n\nvoid main()\n{\n czm_materialInput materialInput;\n\n vec3 normalEC = normalize(czm_normal3D * czm_geodeticSurfaceNormal(v_positionMC, vec3(0.0), vec3(1.0)));\n#ifdef FACE_FORWARD\n normalEC = faceforward(normalEC, vec3(0.0, 0.0, 1.0), -normalEC);\n#endif\n\n materialInput.s = v_st.s;\n materialInput.st = v_st;\n materialInput.str = vec3(v_st, 0.0);\n\n // Convert tangent space material normal to eye space\n materialInput.normalEC = normalEC;\n materialInput.tangentToEyeMatrix = czm_eastNorthUpToEyeCoordinates(v_positionMC, materialInput.normalEC);\n\n // Convert view vector to world space\n vec3 positionToEyeEC = -v_positionEC;\n materialInput.positionToEyeEC = positionToEyeEC;\n\n czm_material material = czm_getMaterial(materialInput);\n\n#ifdef FLAT\n out_FragColor = vec4(material.diffuse + material.emission, material.alpha);\n#else\n out_FragColor = czm_phong(normalize(positionToEyeEC), material, czm_lightDirectionEC);\n#endif\n}\n";
// packages/engine/Source/Shaders/Appearances/EllipsoidSurfaceAppearanceVS.js
var EllipsoidSurfaceAppearanceVS_default = "in vec3 position3DHigh;\nin vec3 position3DLow;\nin vec2 st;\nin float batchId;\n\nout vec3 v_positionMC;\nout vec3 v_positionEC;\nout vec2 v_st;\n\nvoid main()\n{\n vec4 p = czm_computePosition();\n\n v_positionMC = position3DHigh + position3DLow; // position in model coordinates\n v_positionEC = (czm_modelViewRelativeToEye * p).xyz; // position in eye coordinates\n v_st = st;\n\n gl_Position = czm_modelViewProjectionRelativeToEye * p;\n}\n";
// packages/engine/Source/Scene/EllipsoidSurfaceAppearance.js
function EllipsoidSurfaceAppearance(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const translucent = defaultValue_default(options.translucent, true);
const aboveGround = defaultValue_default(options.aboveGround, false);
this.material = defined_default(options.material) ? options.material : Material_default.fromType(Material_default.ColorType);
this.translucent = defaultValue_default(options.translucent, true);
this._vertexShaderSource = defaultValue_default(
options.vertexShaderSource,
EllipsoidSurfaceAppearanceVS_default
);
this._fragmentShaderSource = defaultValue_default(
options.fragmentShaderSource,
EllipsoidSurfaceAppearanceFS_default
);
this._renderState = Appearance_default.getDefaultRenderState(
translucent,
!aboveGround,
options.renderState
);
this._closed = false;
this._flat = defaultValue_default(options.flat, false);
this._faceForward = defaultValue_default(options.faceForward, aboveGround);
this._aboveGround = aboveGround;
}
Object.defineProperties(EllipsoidSurfaceAppearance.prototype, {
/**
* The GLSL source code for the vertex shader.
*
* @memberof EllipsoidSurfaceAppearance.prototype
*
* @type {string}
* @readonly
*/
vertexShaderSource: {
get: function() {
return this._vertexShaderSource;
}
},
/**
* The GLSL source code for the fragment shader. The full fragment shader
* source is built procedurally taking into account {@link EllipsoidSurfaceAppearance#material},
* {@link EllipsoidSurfaceAppearance#flat}, and {@link EllipsoidSurfaceAppearance#faceForward}.
* Use {@link EllipsoidSurfaceAppearance#getFragmentShaderSource} to get the full source.
*
* @memberof EllipsoidSurfaceAppearance.prototype
*
* @type {string}
* @readonly
*/
fragmentShaderSource: {
get: function() {
return this._fragmentShaderSource;
}
},
/**
* The WebGL fixed-function state to use when rendering the geometry.
* * The render state can be explicitly defined when constructing a {@link EllipsoidSurfaceAppearance} * instance, or it is set implicitly via {@link EllipsoidSurfaceAppearance#translucent} * and {@link EllipsoidSurfaceAppearance#aboveGround}. *
* * @memberof EllipsoidSurfaceAppearance.prototype * * @type {object} * @readonly */ renderState: { get: function() { return this._renderState; } }, /** * Whentrue
, the geometry is expected to be closed so
* {@link EllipsoidSurfaceAppearance#renderState} has backface culling enabled.
* If the viewer enters the geometry, it will not be visible.
*
* @memberof EllipsoidSurfaceAppearance.prototype
*
* @type {boolean}
* @readonly
*
* @default false
*/
closed: {
get: function() {
return this._closed;
}
},
/**
* The {@link VertexFormat} that this appearance instance is compatible with.
* A geometry can have more vertex attributes and still be compatible - at a
* potential performance cost - but it can't have less.
*
* @memberof EllipsoidSurfaceAppearance.prototype
*
* @type VertexFormat
* @readonly
*
* @default {@link EllipsoidSurfaceAppearance.VERTEX_FORMAT}
*/
vertexFormat: {
get: function() {
return EllipsoidSurfaceAppearance.VERTEX_FORMAT;
}
},
/**
* When true
, flat shading is used in the fragment shader,
* which means lighting is not taking into account.
*
* @memberof EllipsoidSurfaceAppearance.prototype
*
* @type {boolean}
* @readonly
*
* @default false
*/
flat: {
get: function() {
return this._flat;
}
},
/**
* When true
, the fragment shader flips the surface normal
* as needed to ensure that the normal faces the viewer to avoid
* dark spots. This is useful when both sides of a geometry should be
* shaded like {@link WallGeometry}.
*
* @memberof EllipsoidSurfaceAppearance.prototype
*
* @type {boolean}
* @readonly
*
* @default true
*/
faceForward: {
get: function() {
return this._faceForward;
}
},
/**
* When true
, the geometry is expected to be on the ellipsoid's
* surface - not at a constant height above it - so {@link EllipsoidSurfaceAppearance#renderState}
* has backface culling enabled.
*
*
* @memberof EllipsoidSurfaceAppearance.prototype
*
* @type {boolean}
* @readonly
*
* @default false
*/
aboveGround: {
get: function() {
return this._aboveGround;
}
}
});
EllipsoidSurfaceAppearance.VERTEX_FORMAT = VertexFormat_default.POSITION_AND_ST;
EllipsoidSurfaceAppearance.prototype.getFragmentShaderSource = Appearance_default.prototype.getFragmentShaderSource;
EllipsoidSurfaceAppearance.prototype.isTranslucent = Appearance_default.prototype.isTranslucent;
EllipsoidSurfaceAppearance.prototype.getRenderState = Appearance_default.prototype.getRenderState;
var EllipsoidSurfaceAppearance_default = EllipsoidSurfaceAppearance;
// packages/engine/Source/Scene/FrameRateMonitor.js
function FrameRateMonitor(options) {
if (!defined_default(options) || !defined_default(options.scene)) {
throw new DeveloperError_default("options.scene is required.");
}
this._scene = options.scene;
this.samplingWindow = defaultValue_default(
options.samplingWindow,
FrameRateMonitor.defaultSettings.samplingWindow
);
this.quietPeriod = defaultValue_default(
options.quietPeriod,
FrameRateMonitor.defaultSettings.quietPeriod
);
this.warmupPeriod = defaultValue_default(
options.warmupPeriod,
FrameRateMonitor.defaultSettings.warmupPeriod
);
this.minimumFrameRateDuringWarmup = defaultValue_default(
options.minimumFrameRateDuringWarmup,
FrameRateMonitor.defaultSettings.minimumFrameRateDuringWarmup
);
this.minimumFrameRateAfterWarmup = defaultValue_default(
options.minimumFrameRateAfterWarmup,
FrameRateMonitor.defaultSettings.minimumFrameRateAfterWarmup
);
this._lowFrameRate = new Event_default();
this._nominalFrameRate = new Event_default();
this._frameTimes = [];
this._needsQuietPeriod = true;
this._quietPeriodEndTime = 0;
this._warmupPeriodEndTime = 0;
this._frameRateIsLow = false;
this._lastFramesPerSecond = void 0;
this._pauseCount = 0;
const that = this;
this._preUpdateRemoveListener = this._scene.preUpdate.addEventListener(
function(scene, time) {
update7(that, time);
}
);
this._hiddenPropertyName = document.hidden !== void 0 ? "hidden" : document.mozHidden !== void 0 ? "mozHidden" : document.msHidden !== void 0 ? "msHidden" : document.webkitHidden !== void 0 ? "webkitHidden" : void 0;
const visibilityChangeEventName = document.hidden !== void 0 ? "visibilitychange" : document.mozHidden !== void 0 ? "mozvisibilitychange" : document.msHidden !== void 0 ? "msvisibilitychange" : document.webkitHidden !== void 0 ? "webkitvisibilitychange" : void 0;
function visibilityChangeListener() {
visibilityChanged(that);
}
this._visibilityChangeRemoveListener = void 0;
if (defined_default(visibilityChangeEventName)) {
document.addEventListener(
visibilityChangeEventName,
visibilityChangeListener,
false
);
this._visibilityChangeRemoveListener = function() {
document.removeEventListener(
visibilityChangeEventName,
visibilityChangeListener,
false
);
};
}
}
FrameRateMonitor.defaultSettings = {
samplingWindow: 5,
quietPeriod: 2,
warmupPeriod: 5,
minimumFrameRateDuringWarmup: 4,
minimumFrameRateAfterWarmup: 8
};
FrameRateMonitor.fromScene = function(scene) {
if (!defined_default(scene)) {
throw new DeveloperError_default("scene is required.");
}
if (!defined_default(scene._frameRateMonitor) || scene._frameRateMonitor.isDestroyed()) {
scene._frameRateMonitor = new FrameRateMonitor({
scene
});
}
return scene._frameRateMonitor;
};
Object.defineProperties(FrameRateMonitor.prototype, {
/**
* Gets the {@link Scene} instance for which to monitor performance.
* @memberof FrameRateMonitor.prototype
* @type {Scene}
*/
scene: {
get: function() {
return this._scene;
}
},
/**
* Gets the event that is raised when a low frame rate is detected. The function will be passed
* the {@link Scene} instance as its first parameter and the average number of frames per second
* over the sampling window as its second parameter.
* @memberof FrameRateMonitor.prototype
* @type {Event}
*/
lowFrameRate: {
get: function() {
return this._lowFrameRate;
}
},
/**
* Gets the event that is raised when the frame rate returns to a normal level after having been low.
* The function will be passed the {@link Scene} instance as its first parameter and the average
* number of frames per second over the sampling window as its second parameter.
* @memberof FrameRateMonitor.prototype
* @type {Event}
*/
nominalFrameRate: {
get: function() {
return this._nominalFrameRate;
}
},
/**
* Gets the most recently computed average frames-per-second over the last samplingWindow
.
* This property may be undefined if the frame rate has not been computed.
* @memberof FrameRateMonitor.prototype
* @type {number}
*/
lastFramesPerSecond: {
get: function() {
return this._lastFramesPerSecond;
}
}
});
FrameRateMonitor.prototype.pause = function() {
++this._pauseCount;
if (this._pauseCount === 1) {
this._frameTimes.length = 0;
this._lastFramesPerSecond = void 0;
}
};
FrameRateMonitor.prototype.unpause = function() {
--this._pauseCount;
if (this._pauseCount <= 0) {
this._pauseCount = 0;
this._needsQuietPeriod = true;
}
};
FrameRateMonitor.prototype.isDestroyed = function() {
return false;
};
FrameRateMonitor.prototype.destroy = function() {
this._preUpdateRemoveListener();
if (defined_default(this._visibilityChangeRemoveListener)) {
this._visibilityChangeRemoveListener();
}
return destroyObject_default(this);
};
function update7(monitor, time) {
if (monitor._pauseCount > 0) {
return;
}
const timeStamp = getTimestamp_default();
if (monitor._needsQuietPeriod) {
monitor._needsQuietPeriod = false;
monitor._frameTimes.length = 0;
monitor._quietPeriodEndTime = timeStamp + monitor.quietPeriod / TimeConstants_default.SECONDS_PER_MILLISECOND;
monitor._warmupPeriodEndTime = monitor._quietPeriodEndTime + (monitor.warmupPeriod + monitor.samplingWindow) / TimeConstants_default.SECONDS_PER_MILLISECOND;
} else if (timeStamp >= monitor._quietPeriodEndTime) {
monitor._frameTimes.push(timeStamp);
const beginningOfWindow = timeStamp - monitor.samplingWindow / TimeConstants_default.SECONDS_PER_MILLISECOND;
if (monitor._frameTimes.length >= 2 && monitor._frameTimes[0] <= beginningOfWindow) {
while (monitor._frameTimes.length >= 2 && monitor._frameTimes[1] < beginningOfWindow) {
monitor._frameTimes.shift();
}
const averageTimeBetweenFrames = (timeStamp - monitor._frameTimes[0]) / (monitor._frameTimes.length - 1);
monitor._lastFramesPerSecond = 1e3 / averageTimeBetweenFrames;
const maximumFrameTime = 1e3 / (timeStamp > monitor._warmupPeriodEndTime ? monitor.minimumFrameRateAfterWarmup : monitor.minimumFrameRateDuringWarmup);
if (averageTimeBetweenFrames > maximumFrameTime) {
if (!monitor._frameRateIsLow) {
monitor._frameRateIsLow = true;
monitor._needsQuietPeriod = true;
monitor.lowFrameRate.raiseEvent(
monitor.scene,
monitor._lastFramesPerSecond
);
}
} else if (monitor._frameRateIsLow) {
monitor._frameRateIsLow = false;
monitor._needsQuietPeriod = true;
monitor.nominalFrameRate.raiseEvent(
monitor.scene,
monitor._lastFramesPerSecond
);
}
}
}
}
function visibilityChanged(monitor) {
if (document[monitor._hiddenPropertyName]) {
monitor.pause();
} else {
monitor.unpause();
}
}
var FrameRateMonitor_default = FrameRateMonitor;
// packages/engine/Source/Core/decodeGoogleEarthEnterpriseData.js
var compressedMagic = 1953029805;
var compressedMagicSwap = 2917034100;
function decodeGoogleEarthEnterpriseData(key, data) {
if (decodeGoogleEarthEnterpriseData.passThroughDataForTesting) {
return data;
}
Check_default.typeOf.object("key", key);
Check_default.typeOf.object("data", data);
const keyLength = key.byteLength;
if (keyLength === 0 || keyLength % 4 !== 0) {
throw new RuntimeError_default(
"The length of key must be greater than 0 and a multiple of 4."
);
}
const dataView = new DataView(data);
const magic = dataView.getUint32(0, true);
if (magic === compressedMagic || magic === compressedMagicSwap) {
return data;
}
const keyView = new DataView(key);
let dp = 0;
const dpend = data.byteLength;
const dpend64 = dpend - dpend % 8;
const kpend = keyLength;
let kp;
let off = 8;
while (dp < dpend64) {
off = (off + 8) % 24;
kp = off;
while (dp < dpend64 && kp < kpend) {
dataView.setUint32(
dp,
dataView.getUint32(dp, true) ^ keyView.getUint32(kp, true),
true
);
dataView.setUint32(
dp + 4,
dataView.getUint32(dp + 4, true) ^ keyView.getUint32(kp + 4, true),
true
);
dp += 8;
kp += 24;
}
}
if (dp < dpend) {
if (kp >= kpend) {
off = (off + 8) % 24;
kp = off;
}
while (dp < dpend) {
dataView.setUint8(dp, dataView.getUint8(dp) ^ keyView.getUint8(kp));
dp++;
kp++;
}
}
}
decodeGoogleEarthEnterpriseData.passThroughDataForTesting = false;
var decodeGoogleEarthEnterpriseData_default = decodeGoogleEarthEnterpriseData;
// packages/engine/Source/Core/GoogleEarthEnterpriseMetadata.js
var protobuf = __toESM(require_protobuf(), 1);
// packages/engine/Source/Core/isBitSet.js
function isBitSet(bits, mask) {
return (bits & mask) !== 0;
}
var isBitSet_default = isBitSet;
// packages/engine/Source/Core/GoogleEarthEnterpriseTileInformation.js
var childrenBitmasks = [1, 2, 4, 8];
var anyChildBitmask = 15;
var cacheFlagBitmask = 16;
var imageBitmask = 64;
var terrainBitmask = 128;
function GoogleEarthEnterpriseTileInformation(bits, cnodeVersion, imageryVersion, terrainVersion, imageryProvider, terrainProvider) {
this._bits = bits;
this.cnodeVersion = cnodeVersion;
this.imageryVersion = imageryVersion;
this.terrainVersion = terrainVersion;
this.imageryProvider = imageryProvider;
this.terrainProvider = terrainProvider;
this.ancestorHasTerrain = false;
this.terrainState = void 0;
}
GoogleEarthEnterpriseTileInformation.clone = function(info, result) {
if (!defined_default(result)) {
result = new GoogleEarthEnterpriseTileInformation(
info._bits,
info.cnodeVersion,
info.imageryVersion,
info.terrainVersion,
info.imageryProvider,
info.terrainProvider
);
} else {
result._bits = info._bits;
result.cnodeVersion = info.cnodeVersion;
result.imageryVersion = info.imageryVersion;
result.terrainVersion = info.terrainVersion;
result.imageryProvider = info.imageryProvider;
result.terrainProvider = info.terrainProvider;
}
result.ancestorHasTerrain = info.ancestorHasTerrain;
result.terrainState = info.terrainState;
return result;
};
GoogleEarthEnterpriseTileInformation.prototype.setParent = function(parent) {
this.ancestorHasTerrain = parent.ancestorHasTerrain || this.hasTerrain();
};
GoogleEarthEnterpriseTileInformation.prototype.hasSubtree = function() {
return isBitSet_default(this._bits, cacheFlagBitmask);
};
GoogleEarthEnterpriseTileInformation.prototype.hasImagery = function() {
return isBitSet_default(this._bits, imageBitmask);
};
GoogleEarthEnterpriseTileInformation.prototype.hasTerrain = function() {
return isBitSet_default(this._bits, terrainBitmask);
};
GoogleEarthEnterpriseTileInformation.prototype.hasChildren = function() {
return isBitSet_default(this._bits, anyChildBitmask);
};
GoogleEarthEnterpriseTileInformation.prototype.hasChild = function(index) {
return isBitSet_default(this._bits, childrenBitmasks[index]);
};
GoogleEarthEnterpriseTileInformation.prototype.getChildBitmask = function() {
return this._bits & anyChildBitmask;
};
var GoogleEarthEnterpriseTileInformation_default = GoogleEarthEnterpriseTileInformation;
// packages/engine/Source/Core/GoogleEarthEnterpriseMetadata.js
function stringToBuffer(str) {
const len = str.length;
const buffer = new ArrayBuffer(len);
const ui8 = new Uint8Array(buffer);
for (let i = 0; i < len; ++i) {
ui8[i] = str.charCodeAt(i);
}
return buffer;
}
var defaultKey = stringToBuffer(
`E\xF4\xBD\vy\xE2jE"\x92,\xCDq\xF8IFgQ\0B%\xC6\xE8a,f)\b\xC64\xDCjb%y
wmi\xD6\xF0\x9Ck\x93\xA1\xBDNu\xE0A[\xDF@V\f\xD9\xBBr\x9B\x81|3S\xEEOl\xD4q\xB0{\xC0\x7FEVZ\xADwUe\v3\x92*\xACl5\xC50s\xF83>mF8J\xB4\xDD\xF0.\xDDu\xDA\x8CDt"\xFAa"\f3"So\xAF9D\v\x8C9\xD99L\xB9\xBF\x7F\xAB\\\x8CP_\x9F"ux\xE9\x07q\x91h;\xC1\xC4\x9B\x7F\xF0true
, when the loaded I3S version is 1.6 or older
* @memberof I3SLayer.prototype
* @type {boolean}
* @readonly
*/
legacyVersion16: {
get: function() {
if (!defined_default(this.version)) {
return void 0;
}
if (this.majorVersion < 1 || this.majorVersion === 1 && this.minorVersion <= 6) {
return true;
}
return false;
}
}
});
I3SLayer.prototype.load = async function() {
if (this._data.spatialReference.wkid !== 4326) {
throw new RuntimeError_default(
`Unsupported spatial reference: ${this._data.spatialReference.wkid}`
);
}
await this._dataProvider.loadGeoidData();
await this._loadRootNode();
await this._create3DTileset();
this._rootNode._tile = this._tileset._root;
this._tileset._root._i3sNode = this._rootNode;
if (this.legacyVersion16) {
return this._rootNode._loadChildren();
}
};
I3SLayer.prototype._computeGeometryDefinitions = function(useCompression) {
this._geometryDefinitions = [];
if (defined_default(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_default(geometryBuffer.compressedAttributes) && useCompression) {
compressed = true;
const attributes = geometryBuffer.compressedAttributes.attributes;
for (let i = 0; i < attributes.length; i++) {
collectedAttributes.push(attributes[i]);
}
} else {
for (const attribute in geometryBuffer) {
if (attribute !== "offset") {
collectedAttributes.push(attribute);
}
}
}
geometryBuffersInfo.push({
compressed,
attributes: collectedAttributes,
index: geometryBuffers.indexOf(geometryBuffer)
});
}
geometryBuffersInfo.sort(function(a3, b) {
if (a3.compressed && !b.compressed) {
return -1;
} else if (!a3.compressed && b.compressed) {
return 1;
}
return a3.attributes.length - b.attributes.length;
});
this._geometryDefinitions.push(geometryBuffersInfo);
}
}
};
I3SLayer.prototype._findBestGeometryBuffers = function(definition, attributes) {
const geometryDefinition = this._geometryDefinitions[definition];
if (defined_default(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
};
}
}
}
return 0;
};
I3SLayer.prototype._loadRootNode = function() {
if (defined_default(this._data.nodePages)) {
let rootIndex = 0;
if (defined_default(this._data.nodePages.rootIndex)) {
rootIndex = this._data.nodePages.rootIndex;
}
this._rootNode = new I3SNode_default(this, rootIndex, true);
} else {
this._rootNode = new I3SNode_default(this, this._data.store.rootNode, true);
}
return this._rootNode.load();
};
I3SLayer.prototype._getNodeInNodePages = function(nodeIndex) {
const index = Math.floor(nodeIndex / this._data.nodePages.nodesPerPage);
const offsetInPage = nodeIndex % this._data.nodePages.nodesPerPage;
const that = this;
return this._loadNodePage(index).then(function() {
return that._nodePages[index][offsetInPage];
});
};
I3SLayer._fetchJson = function(resource) {
return resource.fetchJson();
};
I3SLayer.prototype._loadNodePage = function(page) {
const that = this;
if (!defined_default(this._nodePageFetches[page])) {
const nodePageResource = this.resource.getDerivedResource({
url: `nodepages/${page}/`
});
const fetchPromise = I3SLayer._fetchJson(nodePageResource).then(function(data) {
if (defined_default(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];
};
I3SLayer.prototype._computeExtent = function() {
if (defined_default(this._data.fullExtent)) {
this._extent = Rectangle_default.fromDegrees(
this._data.fullExtent.xmin,
this._data.fullExtent.ymin,
this._data.fullExtent.xmax,
this._data.fullExtent.ymax
);
} else if (defined_default(this._data.store.extent)) {
this._extent = Rectangle_default.fromDegrees(
this._data.store.extent[0],
this._data.store.extent[1],
this._data.store.extent[2],
this._data.store.extent[3]
);
}
};
I3SLayer.prototype._create3DTileset = async function() {
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 tilesetOptions = {};
if (defined_default(this._dataProvider._cesium3dTilesetOptions)) {
for (const x in this._dataProvider._cesium3dTilesetOptions) {
if (this._dataProvider._cesium3dTilesetOptions.hasOwnProperty(x)) {
tilesetOptions[x] = this._dataProvider._cesium3dTilesetOptions[x];
}
}
}
this._tileset = await Cesium3DTileset_default.fromUrl(tilesetUrl, tilesetOptions);
this._tileset.show = this._dataProvider.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_default(tile._i3sNode)) {
tile._i3sNode._loadChildren();
}
});
};
var I3SLayer_default = I3SLayer;
// packages/engine/Source/Scene/I3SDataProvider.js
var import_lerc = __toESM(require_LercDecode(), 1);
function I3SDataProvider(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this._name = options.name;
this._show = defaultValue_default(options.show, true);
this._geoidTiledTerrainProvider = options.geoidTiledTerrainProvider;
this._traceFetches = defaultValue_default(options.traceFetches, false);
this._cesium3dTilesetOptions = defaultValue_default(
options.cesium3dTilesetOptions,
defaultValue_default.EMPTY_OBJECT
);
this._layers = [];
this._data = void 0;
this._extent = void 0;
this._geoidDataPromise = void 0;
this._geoidDataList = void 0;
this._decoderTaskProcessor = void 0;
this._taskProcessorReadyPromise = void 0;
if (defined_default(options.url)) {
deprecationWarning_default(
"I3SDataProvider options.url",
"I3SDataProvider constructor parameter options.url was deprecated in CesiumJS 1.104. It will be removed in 1.107. Use I3SDataProvider.fromUrl instead."
);
this._readyPromise = void 0;
this._ready = false;
this._resource = Resource_default.createIfNeeded(options.url);
this._load();
}
}
Object.defineProperties(I3SDataProvider.prototype, {
/**
* Gets a human-readable name for this dataset.
* @memberof I3SDataProvider.prototype
* @type {string}
* @readonly
*/
name: {
get: function() {
return this._name;
}
},
/**
* Determines if the dataset will be shown.
* @memberof I3SDataProvider.prototype
* @type {boolean}
*/
show: {
get: function() {
return this._show;
},
set: function(value) {
Check_default.defined("value", value);
this._show = value;
for (let i = 0; i < this._layers.length; i++) {
if (defined_default(this._layers[i]._tileset)) {
this._layers[i]._tileset.show = this._show;
}
}
}
},
/**
* Gets or sets debugging and tracing of I3S fetches.
* @memberof I3SDataProvider.prototype
* @type {boolean}
*/
traceFetches: {
get: function() {
return this._traceFetches;
},
set: function(value) {
Check_default.defined("value", value);
this._traceFetches = value;
}
},
/**
* The terrain provider referencing the GEOID service to be used for orthometric to ellipsoidal conversion.
* @memberof I3SDataProvider.prototype
* @type {ArcGISTiledElevationTerrainProvider}
* @readonly
*/
geoidTiledTerrainProvider: {
get: function() {
return this._geoidTiledTerrainProvider;
}
},
/**
* Gets the collection of layers.
* @memberof I3SDataProvider.prototype
* @type {I3SLayer[]}
* @readonly
*/
layers: {
get: function() {
return this._layers;
}
},
/**
* Gets the I3S data for this object.
* @memberof I3SDataProvider.prototype
* @type {object}
* @readonly
*/
data: {
get: function() {
return this._data;
}
},
/**
* Gets the extent covered by this I3S.
* @memberof I3SDataProvider.prototype
* @type {Rectangle}
* @readonly
*/
extent: {
get: function() {
return this._extent;
}
},
/**
* Gets the promise that will be resolved when the I3S scene is loaded.
* @memberof I3SDataProvider.prototype
* @type {Promisetrue
, the I3S scene is loaded.
* This is set to true
right before {@link I3SDataProvider#readyPromise} is resolved.
* @memberof I3SDataProvider.prototype
* @type {boolean}
* @readonly
* @deprecated
*/
ready: {
get: function() {
deprecationWarning_default(
"I3SDataProvider.ready",
"I3SDataProvider.ready was deprecated in CesiumJS 1.104. It will be removed in 1.107. Use I3SDataProvider.fromUrl instead."
);
return this._ready;
}
},
/**
* The resource used to fetch the I3S dataset.
* @memberof I3SDataProvider.prototype
* @type {Resource}
* @readonly
*/
resource: {
get: function() {
return this._resource;
}
}
});
I3SDataProvider.prototype.destroy = function() {
for (let i = 0; i < this._layers.length; i++) {
if (defined_default(this._layers[i]._tileset)) {
this._layers[i]._tileset.destroy();
}
}
return destroyObject_default(this);
};
I3SDataProvider.prototype.isDestroyed = function() {
return false;
};
I3SDataProvider.prototype.update = function(frameState) {
for (let i = 0; i < this._layers.length; i++) {
if (defined_default(this._layers[i]._tileset)) {
this._layers[i]._tileset.update(frameState);
}
}
};
I3SDataProvider.prototype.prePassesUpdate = function(frameState) {
for (let i = 0; i < this._layers.length; i++) {
if (defined_default(this._layers[i]._tileset)) {
this._layers[i]._tileset.prePassesUpdate(frameState);
}
}
};
I3SDataProvider.prototype.postPassesUpdate = function(frameState) {
for (let i = 0; i < this._layers.length; i++) {
if (defined_default(this._layers[i]._tileset)) {
this._layers[i]._tileset.postPassesUpdate(frameState);
}
}
};
I3SDataProvider.prototype.updateForPass = function(frameState, passState) {
for (let i = 0; i < this._layers.length; i++) {
if (defined_default(this._layers[i]._tileset)) {
this._layers[i]._tileset.updateForPass(frameState, passState);
}
}
};
I3SDataProvider.fromUrl = async function(url2, options) {
Check_default.defined("url", url2);
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const resource = Resource_default.createIfNeeded(url2);
const data = await I3SDataProvider.loadJson(resource);
const provider = new I3SDataProvider(options);
provider._resource = resource;
provider._data = data;
if (defined_default(data.layers)) {
for (let layerIndex = 0; layerIndex < data.layers.length; layerIndex++) {
const newLayer = new I3SLayer_default(
provider,
data.layers[layerIndex],
layerIndex
);
provider._layers.push(newLayer);
}
} else {
const newLayer = new I3SLayer_default(provider, data, data.id);
provider._layers.push(newLayer);
}
provider._computeExtent();
const layerPromises = [];
for (let i = 0; i < provider._layers.length; i++) {
layerPromises.push(provider._layers[i].load());
}
await Promise.all(layerPromises);
provider._ready = true;
provider._readyPromise = Promise.resolve(provider);
return provider;
};
I3SDataProvider.prototype._load = function() {
const that = this;
this._readyPromise = I3SDataProvider.loadJson(
this._resource,
this._traceFetches
).then(function(data) {
that._data = data;
if (defined_default(data.layers)) {
for (let layerIndex = 0; layerIndex < data.layers.length; layerIndex++) {
const newLayer = new I3SLayer_default(
that,
data.layers[layerIndex],
layerIndex
);
that._layers.push(newLayer);
}
} else {
const newLayer = new I3SLayer_default(that, data, data.id);
that._layers.push(newLayer);
}
that._computeExtent();
const layerPromises = [];
for (let i = 0; i < that._layers.length; i++) {
layerPromises.push(that._layers[i].load());
}
return Promise.all(layerPromises).then(function() {
that._ready = true;
return that;
});
});
return this._readyPromise;
};
I3SDataProvider._fetchJson = function(resource) {
return resource.fetchJson();
};
I3SDataProvider.loadJson = async function(resource, trace) {
if (trace) {
console.log("I3S FETCH:", resource.url);
}
const data = await I3SDataProvider._fetchJson(resource);
if (defined_default(data.error)) {
console.error("Failed to fetch I3S ", resource.url);
if (defined_default(data.error.message)) {
console.error(data.error.message);
}
if (defined_default(data.error.details)) {
for (let i = 0; i < data.error.details.length; i++) {
console.log(data.error.details[i]);
}
}
throw new RuntimeError_default(data.error);
}
return data;
};
I3SDataProvider.prototype._loadBinary = function(resource) {
if (this._traceFetches) {
console.log("I3S FETCH:", resource.url);
}
return resource.fetchArrayBuffer();
};
I3SDataProvider.prototype._binarizeGltf = function(rawGltf) {
const encoder = new TextEncoder();
const rawGltfData = encoder.encode(JSON.stringify(rawGltf));
const binaryGltfData = new Uint8Array(rawGltfData.byteLength + 20);
const binaryGltf = {
magic: new Uint8Array(binaryGltfData.buffer, 0, 4),
version: new Uint32Array(binaryGltfData.buffer, 4, 1),
length: new Uint32Array(binaryGltfData.buffer, 8, 1),
chunkLength: new Uint32Array(binaryGltfData.buffer, 12, 1),
chunkType: new Uint32Array(binaryGltfData.buffer, 16, 1),
chunkData: new Uint8Array(
binaryGltfData.buffer,
20,
rawGltfData.byteLength
)
};
binaryGltf.magic[0] = "g".charCodeAt();
binaryGltf.magic[1] = "l".charCodeAt();
binaryGltf.magic[2] = "T".charCodeAt();
binaryGltf.magic[3] = "F".charCodeAt();
binaryGltf.version[0] = 2;
binaryGltf.length[0] = binaryGltfData.byteLength;
binaryGltf.chunkLength[0] = rawGltfData.byteLength;
binaryGltf.chunkType[0] = 1313821514;
binaryGltf.chunkData.set(rawGltfData);
return binaryGltfData;
};
I3SDataProvider.prototype.getDecoderTaskProcessor = function() {
if (defined_default(this._taskProcessorReadyPromise)) {
return this._taskProcessorReadyPromise;
}
if (!defined_default(this._decoderTaskProcessor)) {
const processor = new TaskProcessor_default("decodeI3S");
this._taskProcessorReadyPromise = processor.initWebAssemblyModule({
modulePath: "ThirdParty/Workers/draco_decoder_nodejs.js",
wasmBinaryFile: "ThirdParty/draco_decoder.wasm"
}).then(() => {
return processor;
});
this._decoderTaskProcessor = processor;
}
return this._taskProcessorReadyPromise;
};
function getCoveredTiles(terrainProvider, extent) {
return getTiles(terrainProvider, extent);
}
var scratchCartesian213 = new Cartesian2_default();
function getTiles(terrainProvider, extent) {
const tilingScheme2 = terrainProvider.tilingScheme;
const tileRequests = [];
const tileRequestSet = {};
const maxLevel = terrainProvider._lodCount;
const topLeftCorner = Cartographic_default.fromRadians(extent.west, extent.north);
const bottomRightCorner = Cartographic_default.fromRadians(extent.east, extent.south);
const minCornerXY = tilingScheme2.positionToTileXY(topLeftCorner, maxLevel);
const maxCornerXY = tilingScheme2.positionToTileXY(
bottomRightCorner,
maxLevel
);
for (let x = minCornerXY.x; x <= maxCornerXY.x; x++) {
for (let y = minCornerXY.y; y <= maxCornerXY.y; y++) {
const xy = Cartesian2_default.fromElements(x, y, scratchCartesian213);
const key = xy.toString();
if (!tileRequestSet.hasOwnProperty(key)) {
const value = {
x: xy.x,
y: xy.y,
level: maxLevel,
tilingScheme: tilingScheme2,
terrainProvider,
positions: []
};
tileRequestSet[key] = value;
tileRequests.push(value);
}
}
}
const tilePromises = [];
for (let i = 0; i < tileRequests.length; ++i) {
const tileRequest = tileRequests[i];
const requestPromise = tileRequest.terrainProvider.requestTileGeometry(
tileRequest.x,
tileRequest.y,
tileRequest.level
);
tilePromises.push(requestPromise);
}
return Promise.all(tilePromises).then(function(heightMapBuffers) {
const heightMaps = [];
for (let i = 0; i < heightMapBuffers.length; i++) {
const options = {
tilingScheme: tilingScheme2,
x: tileRequests[i].x,
y: tileRequests[i].y,
level: tileRequests[i].level
};
const heightMap = heightMapBuffers[i];
let projectionType = "Geographic";
if (tilingScheme2._projection instanceof WebMercatorProjection_default) {
projectionType = "WebMercator";
}
const heightMapData = {
projectionType,
projection: tilingScheme2._projection,
nativeExtent: tilingScheme2.tileXYToNativeRectangle(
options.x,
options.y,
options.level
),
height: heightMap._height,
width: heightMap._width,
scale: heightMap._structure.heightScale,
offset: heightMap._structure.heightOffset
};
if (heightMap._encoding === HeightmapEncoding_default.LERC) {
const result = import_lerc.default.decode(heightMap._buffer);
heightMapData.buffer = result.pixels[0];
} else {
heightMapData.buffer = heightMap._buffer;
}
heightMaps.push(heightMapData);
}
return heightMaps;
});
}
async function loadGeoidData(provider) {
const geoidTerrainProvider = provider._geoidTiledTerrainProvider;
if (!defined_default(geoidTerrainProvider)) {
console.log(
"No Geoid Terrain service provided - no geoid conversion will be performed."
);
return;
}
try {
const heightMaps = await getCoveredTiles(
geoidTerrainProvider,
provider._extent
);
provider._geoidDataList = heightMaps;
} catch (error) {
console.log(
"Error retrieving Geoid Terrain tiles - no geoid conversion will be performed."
);
}
}
I3SDataProvider.prototype.loadGeoidData = async function() {
if (defined_default(this._geoidDataPromise)) {
return this._geoidDataPromise;
}
this._geoidDataPromise = loadGeoidData(this);
return this._geoidDataPromise;
};
I3SDataProvider.prototype._computeExtent = function() {
let rectangle;
for (let layerIndex = 0; layerIndex < this._layers.length; layerIndex++) {
if (defined_default(this._layers[layerIndex]._extent)) {
const layerExtent = this._layers[layerIndex]._extent;
if (!defined_default(rectangle)) {
rectangle = Rectangle_default.clone(layerExtent);
} else {
Rectangle_default.union(rectangle, layerExtent, rectangle);
}
}
}
this._extent = rectangle;
};
var I3SDataProvider_default = I3SDataProvider;
// packages/engine/Source/Scene/KeyframeNode.js
var LoadState = Object.freeze({
UNLOADED: 0,
// Has no data and is in dormant state
RECEIVING: 1,
// Is waiting on data from the provider
RECEIVED: 2,
// Received data from the provider
LOADED: 3,
// Processed data from provider
FAILED: 4,
// Failed to receive data from the provider
UNAVAILABLE: 5
// No data available for this tile
});
function KeyframeNode(spatialNode, keyframe) {
this.spatialNode = spatialNode;
this.keyframe = keyframe;
this.state = LoadState.UNLOADED;
this.metadatas = [];
this.megatextureIndex = -1;
this.priority = -Number.MAX_VALUE;
this.highPriorityFrameNumber = -1;
}
KeyframeNode.priorityComparator = function(a3, b) {
return a3.priority - b.priority;
};
KeyframeNode.searchComparator = function(a3, b) {
return a3.keyframe - b.keyframe;
};
KeyframeNode.LoadState = LoadState;
var KeyframeNode_default = KeyframeNode;
// packages/engine/Source/Scene/Light.js
function Light() {
}
Object.defineProperties(Light.prototype, {
/**
* The color of the light.
* @memberof Light.prototype
* @type {Color}
*/
color: {
get: DeveloperError_default.throwInstantiationError
},
/**
* The intensity controls the strength of the light. intensity
has a minimum value of 0.0 and no maximum value.
* @memberof Light.prototype
* @type {number}
*/
intensity: {
get: DeveloperError_default.throwInstantiationError
}
});
var Light_default = Light;
// packages/engine/Source/Scene/MapboxStyleImageryProvider.js
var trailingSlashRegex2 = /\/$/;
var defaultCredit3 = new Credit_default(
'© Mapbox © OpenStreetMap Improve this map'
);
function MapboxStyleImageryProvider(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const styleId = options.styleId;
if (!defined_default(styleId)) {
throw new DeveloperError_default("options.styleId is required.");
}
const accessToken = options.accessToken;
if (!defined_default(accessToken)) {
throw new DeveloperError_default("options.accessToken is required.");
}
this._defaultAlpha = void 0;
this._defaultNightAlpha = void 0;
this._defaultDayAlpha = void 0;
this._defaultBrightness = void 0;
this._defaultContrast = void 0;
this._defaultHue = void 0;
this._defaultSaturation = void 0;
this._defaultGamma = void 0;
this._defaultMinificationFilter = void 0;
this._defaultMagnificationFilter = void 0;
const resource = Resource_default.createIfNeeded(
defaultValue_default(options.url, "https://api.mapbox.com/styles/v1/")
);
this._styleId = styleId;
this._accessToken = accessToken;
const tilesize = defaultValue_default(options.tilesize, 512);
this._tilesize = tilesize;
const username = defaultValue_default(options.username, "mapbox");
this._username = username;
const scaleFactor = defined_default(options.scaleFactor) ? "@2x" : "";
let templateUrl = resource.getUrlComponent();
if (!trailingSlashRegex2.test(templateUrl)) {
templateUrl += "/";
}
templateUrl += `${this._username}/${styleId}/tiles/${this._tilesize}/{z}/{x}/{y}${scaleFactor}`;
resource.url = templateUrl;
resource.setQueryParameters({
access_token: accessToken
});
let credit;
if (defined_default(options.credit)) {
credit = options.credit;
if (typeof credit === "string") {
credit = new Credit_default(credit);
}
} else {
credit = defaultCredit3;
}
this._resource = resource;
this._imageryProvider = new UrlTemplateImageryProvider_default({
url: resource,
credit,
ellipsoid: options.ellipsoid,
minimumLevel: options.minimumLevel,
maximumLevel: options.maximumLevel,
rectangle: options.rectangle
});
this._ready = true;
this._readyPromise = Promise.resolve(true);
}
Object.defineProperties(MapboxStyleImageryProvider.prototype, {
/**
* Gets the URL of the Mapbox server.
* @memberof MapboxStyleImageryProvider.prototype
* @type {string}
* @readonly
*/
url: {
get: function() {
return this._imageryProvider.url;
}
},
/**
* Gets a value indicating whether or not the provider is ready for use.
* @memberof MapboxStyleImageryProvider.prototype
* @type {boolean}
* @readonly
* @deprecated
*/
ready: {
get: function() {
deprecationWarning_default(
"MapboxStyleImageryProvider.ready",
"MapboxStyleImageryProvider.ready was deprecated in CesiumJS 1.104. It will be in CesiumJS 1.107."
);
return this._imageryProvider.ready;
}
},
/**
* Gets a promise that resolves to true when the provider is ready for use.
* @memberof MapboxStyleImageryProvider.prototype
* @type {Promisetrue
if the burst has been completed; false
otherwise.
* @memberof ParticleBurst.prototype
* @type {boolean}
*/
complete: {
get: function() {
return this._complete;
}
}
});
var ParticleBurst_default = ParticleBurst;
// packages/engine/Source/Scene/ParticleEmitter.js
function ParticleEmitter(options) {
throw new DeveloperError_default(
"This type should not be instantiated directly. Instead, use BoxEmitter, CircleEmitter, ConeEmitter or SphereEmitter."
);
}
ParticleEmitter.prototype.emit = function(particle) {
DeveloperError_default.throwInstantiationError();
};
var ParticleEmitter_default = ParticleEmitter;
// packages/engine/Source/Scene/ParticleSystem.js
var defaultImageSize = new Cartesian2_default(1, 1);
function ParticleSystem(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this.show = defaultValue_default(options.show, true);
this.updateCallback = options.updateCallback;
this.loop = defaultValue_default(options.loop, true);
this.image = defaultValue_default(options.image, void 0);
let emitter = options.emitter;
if (!defined_default(emitter)) {
emitter = new CircleEmitter_default(0.5);
}
this._emitter = emitter;
this._bursts = options.bursts;
this._modelMatrix = Matrix4_default.clone(
defaultValue_default(options.modelMatrix, Matrix4_default.IDENTITY)
);
this._emitterModelMatrix = Matrix4_default.clone(
defaultValue_default(options.emitterModelMatrix, Matrix4_default.IDENTITY)
);
this._matrixDirty = true;
this._combinedMatrix = new Matrix4_default();
this._startColor = Color_default.clone(
defaultValue_default(options.color, defaultValue_default(options.startColor, Color_default.WHITE))
);
this._endColor = Color_default.clone(
defaultValue_default(options.color, defaultValue_default(options.endColor, Color_default.WHITE))
);
this._startScale = defaultValue_default(
options.scale,
defaultValue_default(options.startScale, 1)
);
this._endScale = defaultValue_default(
options.scale,
defaultValue_default(options.endScale, 1)
);
this._emissionRate = defaultValue_default(options.emissionRate, 5);
this._minimumSpeed = defaultValue_default(
options.speed,
defaultValue_default(options.minimumSpeed, 1)
);
this._maximumSpeed = defaultValue_default(
options.speed,
defaultValue_default(options.maximumSpeed, 1)
);
this._minimumParticleLife = defaultValue_default(
options.particleLife,
defaultValue_default(options.minimumParticleLife, 5)
);
this._maximumParticleLife = defaultValue_default(
options.particleLife,
defaultValue_default(options.maximumParticleLife, 5)
);
this._minimumMass = defaultValue_default(
options.mass,
defaultValue_default(options.minimumMass, 1)
);
this._maximumMass = defaultValue_default(
options.mass,
defaultValue_default(options.maximumMass, 1)
);
this._minimumImageSize = Cartesian2_default.clone(
defaultValue_default(
options.imageSize,
defaultValue_default(options.minimumImageSize, defaultImageSize)
)
);
this._maximumImageSize = Cartesian2_default.clone(
defaultValue_default(
options.imageSize,
defaultValue_default(options.maximumImageSize, defaultImageSize)
)
);
this._sizeInMeters = defaultValue_default(options.sizeInMeters, false);
this._lifetime = defaultValue_default(options.lifetime, Number.MAX_VALUE);
this._billboardCollection = void 0;
this._particles = [];
this._particlePool = [];
this._previousTime = void 0;
this._currentTime = 0;
this._carryOver = 0;
this._complete = new Event_default();
this._isComplete = false;
this._updateParticlePool = true;
this._particleEstimate = 0;
}
Object.defineProperties(ParticleSystem.prototype, {
/**
* The particle emitter for this
* @memberof ParticleSystem.prototype
* @type {ParticleEmitter}
* @default CircleEmitter
*/
emitter: {
get: function() {
return this._emitter;
},
set: function(value) {
Check_default.defined("value", value);
this._emitter = value;
}
},
/**
* An array of {@link ParticleBurst}, emitting bursts of particles at periodic times.
* @memberof ParticleSystem.prototype
* @type {ParticleBurst[]}
* @default undefined
*/
bursts: {
get: function() {
return this._bursts;
},
set: function(value) {
this._bursts = value;
this._updateParticlePool = true;
}
},
/**
* The 4x4 transformation matrix that transforms the particle system from model to world coordinates.
* @memberof ParticleSystem.prototype
* @type {Matrix4}
* @default Matrix4.IDENTITY
*/
modelMatrix: {
get: function() {
return this._modelMatrix;
},
set: function(value) {
Check_default.defined("value", value);
this._matrixDirty = this._matrixDirty || !Matrix4_default.equals(this._modelMatrix, value);
Matrix4_default.clone(value, this._modelMatrix);
}
},
/**
* The 4x4 transformation matrix that transforms the particle system emitter within the particle systems local coordinate system.
* @memberof ParticleSystem.prototype
* @type {Matrix4}
* @default Matrix4.IDENTITY
*/
emitterModelMatrix: {
get: function() {
return this._emitterModelMatrix;
},
set: function(value) {
Check_default.defined("value", value);
this._matrixDirty = this._matrixDirty || !Matrix4_default.equals(this._emitterModelMatrix, value);
Matrix4_default.clone(value, this._emitterModelMatrix);
}
},
/**
* The color of the particle at the beginning of its life.
* @memberof ParticleSystem.prototype
* @type {Color}
* @default Color.WHITE
*/
startColor: {
get: function() {
return this._startColor;
},
set: function(value) {
Check_default.defined("value", value);
Color_default.clone(value, this._startColor);
}
},
/**
* The color of the particle at the end of its life.
* @memberof ParticleSystem.prototype
* @type {Color}
* @default Color.WHITE
*/
endColor: {
get: function() {
return this._endColor;
},
set: function(value) {
Check_default.defined("value", value);
Color_default.clone(value, this._endColor);
}
},
/**
* The initial scale to apply to the image of the particle at the beginning of its life.
* @memberof ParticleSystem.prototype
* @type {number}
* @default 1.0
*/
startScale: {
get: function() {
return this._startScale;
},
set: function(value) {
Check_default.typeOf.number.greaterThanOrEquals("value", value, 0);
this._startScale = value;
}
},
/**
* The final scale to apply to the image of the particle at the end of its life.
* @memberof ParticleSystem.prototype
* @type {number}
* @default 1.0
*/
endScale: {
get: function() {
return this._endScale;
},
set: function(value) {
Check_default.typeOf.number.greaterThanOrEquals("value", value, 0);
this._endScale = value;
}
},
/**
* The number of particles to emit per second.
* @memberof ParticleSystem.prototype
* @type {number}
* @default 5
*/
emissionRate: {
get: function() {
return this._emissionRate;
},
set: function(value) {
Check_default.typeOf.number.greaterThanOrEquals("value", value, 0);
this._emissionRate = value;
this._updateParticlePool = true;
}
},
/**
* Sets the minimum bound in meters per second above which a particle's actual speed will be randomly chosen.
* @memberof ParticleSystem.prototype
* @type {number}
* @default 1.0
*/
minimumSpeed: {
get: function() {
return this._minimumSpeed;
},
set: function(value) {
Check_default.typeOf.number.greaterThanOrEquals("value", value, 0);
this._minimumSpeed = value;
}
},
/**
* Sets the maximum bound in meters per second below which a particle's actual speed will be randomly chosen.
* @memberof ParticleSystem.prototype
* @type {number}
* @default 1.0
*/
maximumSpeed: {
get: function() {
return this._maximumSpeed;
},
set: function(value) {
Check_default.typeOf.number.greaterThanOrEquals("value", value, 0);
this._maximumSpeed = value;
}
},
/**
* Sets the minimum bound in seconds for the possible duration of a particle's life above which a particle's actual life will be randomly chosen.
* @memberof ParticleSystem.prototype
* @type {number}
* @default 5.0
*/
minimumParticleLife: {
get: function() {
return this._minimumParticleLife;
},
set: function(value) {
Check_default.typeOf.number.greaterThanOrEquals("value", value, 0);
this._minimumParticleLife = value;
}
},
/**
* Sets the maximum bound in seconds for the possible duration of a particle's life below which a particle's actual life will be randomly chosen.
* @memberof ParticleSystem.prototype
* @type {number}
* @default 5.0
*/
maximumParticleLife: {
get: function() {
return this._maximumParticleLife;
},
set: function(value) {
Check_default.typeOf.number.greaterThanOrEquals("value", value, 0);
this._maximumParticleLife = value;
this._updateParticlePool = true;
}
},
/**
* Sets the minimum mass of particles in kilograms.
* @memberof ParticleSystem.prototype
* @type {number}
* @default 1.0
*/
minimumMass: {
get: function() {
return this._minimumMass;
},
set: function(value) {
Check_default.typeOf.number.greaterThanOrEquals("value", value, 0);
this._minimumMass = value;
}
},
/**
* Sets the maximum mass of particles in kilograms.
* @memberof ParticleSystem.prototype
* @type {number}
* @default 1.0
*/
maximumMass: {
get: function() {
return this._maximumMass;
},
set: function(value) {
Check_default.typeOf.number.greaterThanOrEquals("value", value, 0);
this._maximumMass = value;
}
},
/**
* Sets the minimum bound, width by height, above which to randomly scale the particle image's dimensions in pixels.
* @memberof ParticleSystem.prototype
* @type {Cartesian2}
* @default new Cartesian2(1.0, 1.0)
*/
minimumImageSize: {
get: function() {
return this._minimumImageSize;
},
set: function(value) {
Check_default.typeOf.object("value", value);
Check_default.typeOf.number.greaterThanOrEquals("value.x", value.x, 0);
Check_default.typeOf.number.greaterThanOrEquals("value.y", value.y, 0);
this._minimumImageSize = value;
}
},
/**
* Sets the maximum bound, width by height, below which to randomly scale the particle image's dimensions in pixels.
* @memberof ParticleSystem.prototype
* @type {Cartesian2}
* @default new Cartesian2(1.0, 1.0)
*/
maximumImageSize: {
get: function() {
return this._maximumImageSize;
},
set: function(value) {
Check_default.typeOf.object("value", value);
Check_default.typeOf.number.greaterThanOrEquals("value.x", value.x, 0);
Check_default.typeOf.number.greaterThanOrEquals("value.y", value.y, 0);
this._maximumImageSize = value;
}
},
/**
* Gets or sets if the particle size is in meters or pixels. true
to size particles in meters; otherwise, the size is in pixels.
* @memberof ParticleSystem.prototype
* @type {boolean}
* @default false
*/
sizeInMeters: {
get: function() {
return this._sizeInMeters;
},
set: function(value) {
Check_default.typeOf.bool("value", value);
this._sizeInMeters = value;
}
},
/**
* How long the particle system will emit particles, in seconds.
* @memberof ParticleSystem.prototype
* @type {number}
* @default Number.MAX_VALUE
*/
lifetime: {
get: function() {
return this._lifetime;
},
set: function(value) {
Check_default.typeOf.number.greaterThanOrEquals("value", value, 0);
this._lifetime = value;
}
},
/**
* Fires an event when the particle system has reached the end of its lifetime.
* @memberof ParticleSystem.prototype
* @type {Event}
*/
complete: {
get: function() {
return this._complete;
}
},
/**
* When true
, the particle system has reached the end of its lifetime; false
otherwise.
* @memberof ParticleSystem.prototype
* @type {boolean}
*/
isComplete: {
get: function() {
return this._isComplete;
}
}
});
function updateParticlePool(system) {
const emissionRate = system._emissionRate;
const life = system._maximumParticleLife;
let burstAmount = 0;
const bursts = system._bursts;
if (defined_default(bursts)) {
const length3 = bursts.length;
for (let i = 0; i < length3; ++i) {
burstAmount += bursts[i].maximum;
}
}
const billboardCollection = system._billboardCollection;
const image = system.image;
const particleEstimate = Math.ceil(emissionRate * life + burstAmount);
const particles = system._particles;
const particlePool = system._particlePool;
const numToAdd = Math.max(
particleEstimate - particles.length - particlePool.length,
0
);
for (let j = 0; j < numToAdd; ++j) {
const particle = new Particle_default();
particle._billboard = billboardCollection.add({
image,
// Make the newly added billboards invisible when updating the particle pool
// to prevent the billboards from being displayed when the particles
// are not created. The billboard will always be set visible in
// updateBillboard function when its corresponding particle update.
show: false
});
particlePool.push(particle);
}
system._particleEstimate = particleEstimate;
}
function getOrCreateParticle(system) {
let particle = system._particlePool.pop();
if (!defined_default(particle)) {
particle = new Particle_default();
}
return particle;
}
function addParticleToPool(system, particle) {
system._particlePool.push(particle);
}
function freeParticlePool(system) {
const particles = system._particles;
const particlePool = system._particlePool;
const billboardCollection = system._billboardCollection;
const numParticles = particles.length;
const numInPool = particlePool.length;
const estimate = system._particleEstimate;
const start = numInPool - Math.max(estimate - numParticles - numInPool, 0);
for (let i = start; i < numInPool; ++i) {
const p = particlePool[i];
billboardCollection.remove(p._billboard);
}
particlePool.length = start;
}
function removeBillboard(particle) {
if (defined_default(particle._billboard)) {
particle._billboard.show = false;
}
}
function updateBillboard(system, particle) {
let billboard = particle._billboard;
if (!defined_default(billboard)) {
billboard = particle._billboard = system._billboardCollection.add({
image: particle.image
});
}
billboard.width = particle.imageSize.x;
billboard.height = particle.imageSize.y;
billboard.position = particle.position;
billboard.sizeInMeters = system.sizeInMeters;
billboard.show = true;
const r = Math_default.lerp(
particle.startColor.red,
particle.endColor.red,
particle.normalizedAge
);
const g = Math_default.lerp(
particle.startColor.green,
particle.endColor.green,
particle.normalizedAge
);
const b = Math_default.lerp(
particle.startColor.blue,
particle.endColor.blue,
particle.normalizedAge
);
const a3 = Math_default.lerp(
particle.startColor.alpha,
particle.endColor.alpha,
particle.normalizedAge
);
billboard.color = new Color_default(r, g, b, a3);
billboard.scale = Math_default.lerp(
particle.startScale,
particle.endScale,
particle.normalizedAge
);
}
function addParticle(system, particle) {
particle.startColor = Color_default.clone(system._startColor, particle.startColor);
particle.endColor = Color_default.clone(system._endColor, particle.endColor);
particle.startScale = system._startScale;
particle.endScale = system._endScale;
particle.image = system.image;
particle.life = Math_default.randomBetween(
system._minimumParticleLife,
system._maximumParticleLife
);
particle.mass = Math_default.randomBetween(
system._minimumMass,
system._maximumMass
);
particle.imageSize.x = Math_default.randomBetween(
system._minimumImageSize.x,
system._maximumImageSize.x
);
particle.imageSize.y = Math_default.randomBetween(
system._minimumImageSize.y,
system._maximumImageSize.y
);
particle._normalizedAge = 0;
particle._age = 0;
const speed = Math_default.randomBetween(
system._minimumSpeed,
system._maximumSpeed
);
Cartesian3_default.multiplyByScalar(particle.velocity, speed, particle.velocity);
system._particles.push(particle);
}
function calculateNumberToEmit(system, dt) {
if (system._isComplete) {
return 0;
}
dt = Math_default.mod(dt, system._lifetime);
const v7 = dt * system._emissionRate;
let numToEmit = Math.floor(v7);
system._carryOver += v7 - numToEmit;
if (system._carryOver > 1) {
numToEmit++;
system._carryOver -= 1;
}
if (defined_default(system.bursts)) {
const length3 = system.bursts.length;
for (let i = 0; i < length3; i++) {
const burst = system.bursts[i];
const currentTime = system._currentTime;
if (defined_default(burst) && !burst._complete && currentTime > burst.time) {
numToEmit += Math_default.randomBetween(burst.minimum, burst.maximum);
burst._complete = true;
}
}
}
return numToEmit;
}
var rotatedVelocityScratch = new Cartesian3_default();
ParticleSystem.prototype.update = function(frameState) {
if (!this.show) {
return;
}
if (!defined_default(this._billboardCollection)) {
this._billboardCollection = new BillboardCollection_default();
}
if (this._updateParticlePool) {
updateParticlePool(this);
this._updateParticlePool = false;
}
let dt = 0;
if (this._previousTime) {
dt = JulianDate_default.secondsDifference(frameState.time, this._previousTime);
}
if (dt < 0) {
dt = 0;
}
const particles = this._particles;
const emitter = this._emitter;
const updateCallback = this.updateCallback;
let i;
let particle;
let length3 = particles.length;
for (i = 0; i < length3; ++i) {
particle = particles[i];
if (!particle.update(dt, updateCallback)) {
removeBillboard(particle);
addParticleToPool(this, particle);
particles[i] = particles[length3 - 1];
--i;
--length3;
} else {
updateBillboard(this, particle);
}
}
particles.length = length3;
const numToEmit = calculateNumberToEmit(this, dt);
if (numToEmit > 0 && defined_default(emitter)) {
if (this._matrixDirty) {
this._combinedMatrix = Matrix4_default.multiply(
this.modelMatrix,
this.emitterModelMatrix,
this._combinedMatrix
);
this._matrixDirty = false;
}
const combinedMatrix = this._combinedMatrix;
for (i = 0; i < numToEmit; i++) {
particle = getOrCreateParticle(this);
this._emitter.emit(particle);
Cartesian3_default.add(
particle.position,
particle.velocity,
rotatedVelocityScratch
);
Matrix4_default.multiplyByPoint(
combinedMatrix,
rotatedVelocityScratch,
rotatedVelocityScratch
);
particle.position = Matrix4_default.multiplyByPoint(
combinedMatrix,
particle.position,
particle.position
);
Cartesian3_default.subtract(
rotatedVelocityScratch,
particle.position,
particle.velocity
);
Cartesian3_default.normalize(particle.velocity, particle.velocity);
addParticle(this, particle);
updateBillboard(this, particle);
}
}
this._billboardCollection.update(frameState);
this._previousTime = JulianDate_default.clone(frameState.time, this._previousTime);
this._currentTime += dt;
if (this._lifetime !== Number.MAX_VALUE && this._currentTime > this._lifetime) {
if (this.loop) {
this._currentTime = Math_default.mod(this._currentTime, this._lifetime);
if (this.bursts) {
const burstLength = this.bursts.length;
for (i = 0; i < burstLength; i++) {
this.bursts[i]._complete = false;
}
}
} else {
this._isComplete = true;
this._complete.raiseEvent(this);
}
}
if (frameState.frameNumber % 120 === 0) {
freeParticlePool(this);
}
};
ParticleSystem.prototype.isDestroyed = function() {
return false;
};
ParticleSystem.prototype.destroy = function() {
this._billboardCollection = this._billboardCollection && this._billboardCollection.destroy();
return destroyObject_default(this);
};
var ParticleSystem_default = ParticleSystem;
// packages/engine/Source/Scene/PointCloud.js
var import_mersenne_twister3 = __toESM(require_mersenne_twister(), 1);
// packages/engine/Source/Scene/getClipAndStyleCode.js
function getClipAndStyleCode(samplerUniformName, matrixUniformName, styleUniformName) {
Check_default.typeOf.string("samplerUniformName", samplerUniformName);
Check_default.typeOf.string("matrixUniformName", matrixUniformName);
Check_default.typeOf.string("styleUniformName", styleUniformName);
const shaderCode = ` float clipDistance = clip(gl_FragCoord, ${samplerUniformName}, ${matrixUniformName});
vec4 clippingPlanesEdgeColor = vec4(1.0);
clippingPlanesEdgeColor.rgb = ${styleUniformName}.rgb;
float clippingPlanesEdgeWidth = ${styleUniformName}.a;
if (clipDistance > 0.0 && clipDistance < clippingPlanesEdgeWidth)
{
out_FragColor = clippingPlanesEdgeColor;
}
`;
return shaderCode;
}
var getClipAndStyleCode_default = getClipAndStyleCode;
// packages/engine/Source/Scene/Splitter.js
var Splitter = {
/**
* Given a fragment shader string, returns a modified version of it that
* only renders on one side of the screen or the other. Fragments on the
* other side are discarded. The screen side is given by a uniform called
* `czm_splitDirection`, which can be added by calling
* {@link Splitter#addUniforms}, and the split position is given by an
* automatic uniform called `czm_splitPosition`.
*/
modifyFragmentShader: function modifyFragmentShader(shader) {
shader = ShaderSource_default.replaceMain(shader, "czm_splitter_main");
shader += // czm_splitPosition is not declared because it is an automatic uniform.
"uniform float czm_splitDirection; \nvoid main() \n{ \n#ifndef SHADOW_MAP\n if (czm_splitDirection < 0.0 && gl_FragCoord.x > czm_splitPosition) discard; \n if (czm_splitDirection > 0.0 && gl_FragCoord.x < czm_splitPosition) discard; \n#endif\n czm_splitter_main(); \n} \n";
return shader;
},
/**
* Add `czm_splitDirection` to the given uniform map.
*
* @param {object} object The object on which the `splitDirection` property may be found.
* @param {object} uniformMap The uniform map.
*/
addUniforms: function addUniforms(object2, uniformMap2) {
uniformMap2.czm_splitDirection = function() {
return object2.splitDirection;
};
}
};
var Splitter_default = Splitter;
// packages/engine/Source/Scene/PointCloud.js
var DecodingState = {
NEEDS_DECODE: 0,
DECODING: 1,
READY: 2,
FAILED: 3
};
function PointCloud(options) {
Check_default.typeOf.object("options", options);
Check_default.typeOf.object("options.arrayBuffer", options.arrayBuffer);
this._parsedContent = void 0;
this._drawCommand = void 0;
this._isTranslucent = false;
this._styleTranslucent = false;
this._constantColor = Color_default.clone(Color_default.DARKGRAY);
this._highlightColor = Color_default.clone(Color_default.WHITE);
this._pointSize = 1;
this._rtcCenter = void 0;
this._quantizedVolumeScale = void 0;
this._quantizedVolumeOffset = void 0;
this._styleableShaderAttributes = void 0;
this._isQuantized = false;
this._isOctEncoded16P = false;
this._isRGB565 = false;
this._hasColors = false;
this._hasNormals = false;
this._hasBatchIds = false;
this._decodingState = DecodingState.READY;
this._dequantizeInShader = true;
this._isQuantizedDraco = false;
this._isOctEncodedDraco = false;
this._quantizedRange = 0;
this._octEncodedRange = 0;
this.backFaceCulling = false;
this._backFaceCulling = false;
this.normalShading = true;
this._normalShading = true;
this._opaqueRenderState = void 0;
this._translucentRenderState = void 0;
this._mode = void 0;
this._ready = false;
this._pointsLength = 0;
this._geometryByteLength = 0;
this._vertexShaderLoaded = options.vertexShaderLoaded;
this._fragmentShaderLoaded = options.fragmentShaderLoaded;
this._uniformMapLoaded = options.uniformMapLoaded;
this._batchTableLoaded = options.batchTableLoaded;
this._pickIdLoaded = options.pickIdLoaded;
this._opaquePass = defaultValue_default(options.opaquePass, Pass_default.OPAQUE);
this._cull = defaultValue_default(options.cull, true);
this.style = void 0;
this._style = void 0;
this.styleDirty = false;
this.modelMatrix = Matrix4_default.clone(Matrix4_default.IDENTITY);
this._modelMatrix = Matrix4_default.clone(Matrix4_default.IDENTITY);
this.time = 0;
this.shadows = ShadowMode_default.ENABLED;
this._boundingSphere = void 0;
this.clippingPlanes = void 0;
this.isClipped = false;
this.clippingPlanesDirty = false;
this.clippingPlanesOriginMatrix = void 0;
this.attenuation = false;
this._attenuation = false;
this.geometricError = 0;
this.geometricErrorScale = 1;
this.maximumAttenuation = this._pointSize;
this.splitDirection = defaultValue_default(
options.splitDirection,
SplitDirection_default.NONE
);
this._splittingEnabled = false;
this._error = void 0;
initialize17(this, options);
}
Object.defineProperties(PointCloud.prototype, {
pointsLength: {
get: function() {
return this._pointsLength;
}
},
geometryByteLength: {
get: function() {
return this._geometryByteLength;
}
},
ready: {
get: function() {
return this._ready;
}
},
color: {
get: function() {
return Color_default.clone(this._highlightColor);
},
set: function(value) {
this._highlightColor = Color_default.clone(value, this._highlightColor);
}
},
boundingSphere: {
get: function() {
if (defined_default(this._drawCommand)) {
return this._drawCommand.boundingVolume;
}
return void 0;
},
set: function(value) {
this._boundingSphere = BoundingSphere_default.clone(value, this._boundingSphere);
}
}
});
function initialize17(pointCloud, options) {
const parsedContent = PntsParser_default.parse(
options.arrayBuffer,
options.byteOffset
);
pointCloud._parsedContent = parsedContent;
pointCloud._rtcCenter = parsedContent.rtcCenter;
pointCloud._hasNormals = parsedContent.hasNormals;
pointCloud._hasColors = parsedContent.hasColors;
pointCloud._hasBatchIds = parsedContent.hasBatchIds;
pointCloud._isTranslucent = parsedContent.isTranslucent;
if (!parsedContent.hasBatchIds && defined_default(parsedContent.batchTableBinary)) {
parsedContent.styleableProperties = Cesium3DTileBatchTable_default.getBinaryProperties(
parsedContent.pointsLength,
parsedContent.batchTableJson,
parsedContent.batchTableBinary
);
}
if (defined_default(parsedContent.draco)) {
const draco = parsedContent.draco;
pointCloud._decodingState = DecodingState.NEEDS_DECODE;
draco.dequantizeInShader = pointCloud._dequantizeInShader;
}
const positions = parsedContent.positions;
if (defined_default(positions)) {
pointCloud._isQuantized = positions.isQuantized;
pointCloud._quantizedVolumeScale = positions.quantizedVolumeScale;
pointCloud._quantizedVolumeOffset = positions.quantizedVolumeOffset;
pointCloud._quantizedRange = positions.quantizedRange;
}
const normals = parsedContent.normals;
if (defined_default(normals)) {
pointCloud._isOctEncoded16P = normals.octEncoded;
}
const colors = parsedContent.colors;
if (defined_default(colors)) {
if (defined_default(colors.constantColor)) {
pointCloud._constantColor = Color_default.clone(
colors.constantColor,
pointCloud._constantColor
);
pointCloud._hasColors = false;
}
pointCloud._isRGB565 = colors.isRGB565;
}
const batchIds = parsedContent.batchIds;
if (defined_default(parsedContent.batchIds)) {
batchIds.name = "BATCH_ID";
batchIds.semantic = "BATCH_ID";
batchIds.setIndex = void 0;
}
if (parsedContent.hasBatchIds) {
pointCloud._batchTableLoaded(
parsedContent.batchLength,
parsedContent.batchTableJson,
parsedContent.batchTableBinary
);
}
pointCloud._pointsLength = parsedContent.pointsLength;
}
var scratchMin5 = new Cartesian3_default();
var scratchMax5 = new Cartesian3_default();
var scratchPosition16 = new Cartesian3_default();
var randomNumberGenerator3;
var randomValues2;
function getRandomValues3(samplesLength) {
if (!defined_default(randomValues2)) {
randomNumberGenerator3 = new import_mersenne_twister3.default(0);
randomValues2 = new Array(samplesLength);
for (let i = 0; i < samplesLength; ++i) {
randomValues2[i] = randomNumberGenerator3.random();
}
}
return randomValues2;
}
function computeApproximateBoundingSphereFromPositions(positions) {
const maximumSamplesLength = 20;
const pointsLength = positions.length / 3;
const samplesLength = Math.min(pointsLength, maximumSamplesLength);
const randomValues3 = getRandomValues3(maximumSamplesLength);
const maxValue = Number.MAX_VALUE;
const minValue = -Number.MAX_VALUE;
const min3 = Cartesian3_default.fromElements(maxValue, maxValue, maxValue, scratchMin5);
const max3 = Cartesian3_default.fromElements(minValue, minValue, minValue, scratchMax5);
for (let i = 0; i < samplesLength; ++i) {
const index = Math.floor(randomValues3[i] * pointsLength);
const position = Cartesian3_default.unpack(positions, index * 3, scratchPosition16);
Cartesian3_default.minimumByComponent(min3, position, min3);
Cartesian3_default.maximumByComponent(max3, position, max3);
}
const boundingSphere = BoundingSphere_default.fromCornerPoints(min3, max3);
boundingSphere.radius += Math_default.EPSILON2;
return boundingSphere;
}
function prepareVertexAttribute(typedArray, name) {
const componentDatatype = ComponentDatatype_default.fromTypedArray(typedArray);
if (componentDatatype === ComponentDatatype_default.INT || componentDatatype === ComponentDatatype_default.UNSIGNED_INT || componentDatatype === ComponentDatatype_default.DOUBLE) {
oneTimeWarning_default(
"Cast pnts property to floats",
`Point cloud property "${name}" will be cast to a float array because INT, UNSIGNED_INT, and DOUBLE are not valid WebGL vertex attribute types. Some precision may be lost.`
);
return new Float32Array(typedArray);
}
return typedArray;
}
var scratchPointSizeAndTimeAndGeometricErrorAndDepthMultiplier = new Cartesian4_default();
var scratchQuantizedVolumeScaleAndOctEncodedRange = new Cartesian4_default();
var scratchColor25 = new Color_default();
var positionLocation = 0;
var colorLocation = 1;
var normalLocation = 2;
var batchIdLocation = 3;
var numberOfAttributes = 4;
var scratchClippingPlanesMatrix3 = new Matrix4_default();
var scratchInverseTransposeClippingPlanesMatrix2 = new Matrix4_default();
function createResources4(pointCloud, frameState) {
const context = frameState.context;
const parsedContent = pointCloud._parsedContent;
const pointsLength = pointCloud._pointsLength;
const positions = parsedContent.positions;
const colors = parsedContent.colors;
const normals = parsedContent.normals;
const batchIds = parsedContent.batchIds;
const styleableProperties = parsedContent.styleableProperties;
const hasStyleableProperties = defined_default(styleableProperties);
const isQuantized = pointCloud._isQuantized;
const isQuantizedDraco = pointCloud._isQuantizedDraco;
const isOctEncoded16P = pointCloud._isOctEncoded16P;
const isOctEncodedDraco = pointCloud._isOctEncodedDraco;
const quantizedRange = pointCloud._quantizedRange;
const octEncodedRange = pointCloud._octEncodedRange;
const isRGB565 = pointCloud._isRGB565;
const isTranslucent = pointCloud._isTranslucent;
const hasColors = pointCloud._hasColors;
const hasNormals = pointCloud._hasNormals;
const hasBatchIds = pointCloud._hasBatchIds;
let componentsPerAttribute;
let componentDatatype;
const styleableVertexAttributes = [];
const styleableShaderAttributes = {};
pointCloud._styleableShaderAttributes = styleableShaderAttributes;
if (hasStyleableProperties) {
let attributeLocation = numberOfAttributes;
for (const name in styleableProperties) {
if (styleableProperties.hasOwnProperty(name)) {
const property = styleableProperties[name];
const typedArray = prepareVertexAttribute(property.typedArray, name);
componentsPerAttribute = property.componentCount;
componentDatatype = ComponentDatatype_default.fromTypedArray(typedArray);
const vertexBuffer = Buffer_default.createVertexBuffer({
context,
typedArray,
usage: BufferUsage_default.STATIC_DRAW
});
pointCloud._geometryByteLength += vertexBuffer.sizeInBytes;
const vertexAttribute = {
index: attributeLocation,
vertexBuffer,
componentsPerAttribute,
componentDatatype,
normalize: false,
offsetInBytes: 0,
strideInBytes: 0
};
styleableVertexAttributes.push(vertexAttribute);
styleableShaderAttributes[name] = {
location: attributeLocation,
componentCount: componentsPerAttribute
};
++attributeLocation;
}
}
}
const positionsVertexBuffer = Buffer_default.createVertexBuffer({
context,
typedArray: positions.typedArray,
usage: BufferUsage_default.STATIC_DRAW
});
pointCloud._geometryByteLength += positionsVertexBuffer.sizeInBytes;
let colorsVertexBuffer;
if (hasColors) {
colorsVertexBuffer = Buffer_default.createVertexBuffer({
context,
typedArray: colors.typedArray,
usage: BufferUsage_default.STATIC_DRAW
});
pointCloud._geometryByteLength += colorsVertexBuffer.sizeInBytes;
}
let normalsVertexBuffer;
if (hasNormals) {
normalsVertexBuffer = Buffer_default.createVertexBuffer({
context,
typedArray: normals.typedArray,
usage: BufferUsage_default.STATIC_DRAW
});
pointCloud._geometryByteLength += normalsVertexBuffer.sizeInBytes;
}
let batchIdsVertexBuffer;
if (hasBatchIds) {
batchIds.typedArray = prepareVertexAttribute(
batchIds.typedArray,
"batchIds"
);
batchIdsVertexBuffer = Buffer_default.createVertexBuffer({
context,
typedArray: batchIds.typedArray,
usage: BufferUsage_default.STATIC_DRAW
});
pointCloud._geometryByteLength += batchIdsVertexBuffer.sizeInBytes;
}
let attributes = [];
if (isQuantized) {
componentDatatype = ComponentDatatype_default.UNSIGNED_SHORT;
} else if (isQuantizedDraco) {
componentDatatype = quantizedRange <= 255 ? ComponentDatatype_default.UNSIGNED_BYTE : ComponentDatatype_default.UNSIGNED_SHORT;
} else {
componentDatatype = ComponentDatatype_default.FLOAT;
}
attributes.push({
index: positionLocation,
vertexBuffer: positionsVertexBuffer,
componentsPerAttribute: 3,
componentDatatype,
normalize: false,
offsetInBytes: 0,
strideInBytes: 0
});
if (pointCloud._cull) {
if (isQuantized || isQuantizedDraco) {
pointCloud._boundingSphere = BoundingSphere_default.fromCornerPoints(
Cartesian3_default.ZERO,
pointCloud._quantizedVolumeScale
);
} else {
pointCloud._boundingSphere = computeApproximateBoundingSphereFromPositions(
positions.typedArray
);
}
}
if (hasColors) {
if (isRGB565) {
attributes.push({
index: colorLocation,
vertexBuffer: colorsVertexBuffer,
componentsPerAttribute: 1,
componentDatatype: ComponentDatatype_default.UNSIGNED_SHORT,
normalize: false,
offsetInBytes: 0,
strideInBytes: 0
});
} else {
const colorComponentsPerAttribute = isTranslucent ? 4 : 3;
attributes.push({
index: colorLocation,
vertexBuffer: colorsVertexBuffer,
componentsPerAttribute: colorComponentsPerAttribute,
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
normalize: true,
offsetInBytes: 0,
strideInBytes: 0
});
}
}
if (hasNormals) {
if (isOctEncoded16P) {
componentsPerAttribute = 2;
componentDatatype = ComponentDatatype_default.UNSIGNED_BYTE;
} else if (isOctEncodedDraco) {
componentsPerAttribute = 2;
componentDatatype = octEncodedRange <= 255 ? ComponentDatatype_default.UNSIGNED_BYTE : ComponentDatatype_default.UNSIGNED_SHORT;
} else {
componentsPerAttribute = 3;
componentDatatype = ComponentDatatype_default.FLOAT;
}
attributes.push({
index: normalLocation,
vertexBuffer: normalsVertexBuffer,
componentsPerAttribute,
componentDatatype,
normalize: false,
offsetInBytes: 0,
strideInBytes: 0
});
}
if (hasBatchIds) {
attributes.push({
index: batchIdLocation,
vertexBuffer: batchIdsVertexBuffer,
componentsPerAttribute: 1,
componentDatatype: ComponentDatatype_default.fromTypedArray(batchIds.typedArray),
normalize: false,
offsetInBytes: 0,
strideInBytes: 0
});
}
if (hasStyleableProperties) {
attributes = attributes.concat(styleableVertexAttributes);
}
const vertexArray = new VertexArray_default({
context,
attributes
});
const opaqueRenderState = {
depthTest: {
enabled: true
}
};
const translucentRenderState = {
depthTest: {
enabled: true
},
depthMask: false,
blending: BlendingState_default.ALPHA_BLEND
};
if (pointCloud._opaquePass === Pass_default.CESIUM_3D_TILE) {
opaqueRenderState.stencilTest = StencilConstants_default.setCesium3DTileBit();
opaqueRenderState.stencilMask = StencilConstants_default.CESIUM_3D_TILE_MASK;
translucentRenderState.stencilTest = StencilConstants_default.setCesium3DTileBit();
translucentRenderState.stencilMask = StencilConstants_default.CESIUM_3D_TILE_MASK;
}
pointCloud._opaqueRenderState = RenderState_default.fromCache(opaqueRenderState);
pointCloud._translucentRenderState = RenderState_default.fromCache(
translucentRenderState
);
pointCloud._drawCommand = new DrawCommand_default({
boundingVolume: new BoundingSphere_default(),
cull: pointCloud._cull,
modelMatrix: new Matrix4_default(),
primitiveType: PrimitiveType_default.POINTS,
vertexArray,
count: pointsLength,
shaderProgram: void 0,
// Updated in createShaders
uniformMap: void 0,
// Updated in createShaders
renderState: isTranslucent ? pointCloud._translucentRenderState : pointCloud._opaqueRenderState,
pass: isTranslucent ? Pass_default.TRANSLUCENT : pointCloud._opaquePass,
owner: pointCloud,
castShadows: false,
receiveShadows: false,
pickId: pointCloud._pickIdLoaded()
});
}
function createUniformMap6(pointCloud, frameState) {
const context = frameState.context;
const isQuantized = pointCloud._isQuantized;
const isQuantizedDraco = pointCloud._isQuantizedDraco;
const isOctEncodedDraco = pointCloud._isOctEncodedDraco;
let uniformMap2 = {
u_pointSizeAndTimeAndGeometricErrorAndDepthMultiplier: function() {
const scratch = scratchPointSizeAndTimeAndGeometricErrorAndDepthMultiplier;
scratch.x = pointCloud._attenuation ? pointCloud.maximumAttenuation : pointCloud._pointSize;
scratch.x *= frameState.pixelRatio;
scratch.y = pointCloud.time;
if (pointCloud._attenuation) {
const frustum = frameState.camera.frustum;
let depthMultiplier;
if (frameState.mode === SceneMode_default.SCENE2D || frustum instanceof OrthographicFrustum_default) {
depthMultiplier = Number.POSITIVE_INFINITY;
} else {
depthMultiplier = context.drawingBufferHeight / frameState.camera.frustum.sseDenominator;
}
scratch.z = pointCloud.geometricError * pointCloud.geometricErrorScale;
scratch.w = depthMultiplier;
}
return scratch;
},
u_highlightColor: function() {
return pointCloud._highlightColor;
},
u_constantColor: function() {
return pointCloud._constantColor;
},
u_clippingPlanes: function() {
const clippingPlanes = pointCloud.clippingPlanes;
const isClipped = pointCloud.isClipped;
return isClipped ? clippingPlanes.texture : context.defaultTexture;
},
u_clippingPlanesEdgeStyle: function() {
const clippingPlanes = pointCloud.clippingPlanes;
if (!defined_default(clippingPlanes)) {
return Color_default.TRANSPARENT;
}
const style = Color_default.clone(clippingPlanes.edgeColor, scratchColor25);
style.alpha = clippingPlanes.edgeWidth;
return style;
},
u_clippingPlanesMatrix: function() {
const clippingPlanes = pointCloud.clippingPlanes;
if (!defined_default(clippingPlanes)) {
return Matrix4_default.IDENTITY;
}
const clippingPlanesOriginMatrix = defaultValue_default(
pointCloud.clippingPlanesOriginMatrix,
pointCloud._modelMatrix
);
Matrix4_default.multiply(
context.uniformState.view3D,
clippingPlanesOriginMatrix,
scratchClippingPlanesMatrix3
);
const transform3 = Matrix4_default.multiply(
scratchClippingPlanesMatrix3,
clippingPlanes.modelMatrix,
scratchClippingPlanesMatrix3
);
return Matrix4_default.inverseTranspose(
transform3,
scratchInverseTransposeClippingPlanesMatrix2
);
}
};
Splitter_default.addUniforms(pointCloud, uniformMap2);
if (isQuantized || isQuantizedDraco || isOctEncodedDraco) {
uniformMap2 = combine_default(uniformMap2, {
u_quantizedVolumeScaleAndOctEncodedRange: function() {
const scratch = scratchQuantizedVolumeScaleAndOctEncodedRange;
if (defined_default(pointCloud._quantizedVolumeScale)) {
const scale = Cartesian3_default.clone(
pointCloud._quantizedVolumeScale,
scratch
);
Cartesian3_default.divideByScalar(scale, pointCloud._quantizedRange, scratch);
}
scratch.w = pointCloud._octEncodedRange;
return scratch;
}
});
}
if (defined_default(pointCloud._uniformMapLoaded)) {
uniformMap2 = pointCloud._uniformMapLoaded(uniformMap2);
}
pointCloud._drawCommand.uniformMap = uniformMap2;
}
function getStyleablePropertyIds(source, propertyIds) {
const regex = /czm_3dtiles_property_(\d+)/g;
let matches = regex.exec(source);
while (matches !== null) {
const id = parseInt(matches[1]);
if (propertyIds.indexOf(id) === -1) {
propertyIds.push(id);
}
matches = regex.exec(source);
}
}
function getBuiltinPropertyNames2(source, propertyNames) {
source = source.slice(source.indexOf("\n"));
const regex = /czm_3dtiles_builtin_property_(\w+)/g;
let matches = regex.exec(source);
while (matches !== null) {
const name = matches[1];
if (propertyNames.indexOf(name) === -1) {
propertyNames.push(name);
}
matches = regex.exec(source);
}
}
function getVertexAttribute(vertexArray, index) {
const numberOfAttributes2 = vertexArray.numberOfAttributes;
for (let i = 0; i < numberOfAttributes2; ++i) {
const attribute = vertexArray.getAttribute(i);
if (attribute.index === index) {
return attribute;
}
}
}
var builtinVariableSubstitutionMap2 = {
POSITION: "czm_3dtiles_builtin_property_POSITION",
POSITION_ABSOLUTE: "czm_3dtiles_builtin_property_POSITION_ABSOLUTE",
COLOR: "czm_3dtiles_builtin_property_COLOR",
NORMAL: "czm_3dtiles_builtin_property_NORMAL"
};
function createShaders4(pointCloud, frameState, style) {
let i;
let name;
let attribute;
const context = frameState.context;
const hasStyle = defined_default(style);
const isQuantized = pointCloud._isQuantized;
const isQuantizedDraco = pointCloud._isQuantizedDraco;
const isOctEncoded16P = pointCloud._isOctEncoded16P;
const isOctEncodedDraco = pointCloud._isOctEncodedDraco;
const isRGB565 = pointCloud._isRGB565;
const isTranslucent = pointCloud._isTranslucent;
const hasColors = pointCloud._hasColors;
const hasNormals = pointCloud._hasNormals;
const hasBatchIds = pointCloud._hasBatchIds;
const backFaceCulling = pointCloud._backFaceCulling;
const normalShading = pointCloud._normalShading;
const vertexArray = pointCloud._drawCommand.vertexArray;
const clippingPlanes = pointCloud.clippingPlanes;
const attenuation = pointCloud._attenuation;
let colorStyleFunction;
let showStyleFunction;
let pointSizeStyleFunction;
let styleTranslucent = isTranslucent;
const variableSubstitutionMap = clone_default(builtinVariableSubstitutionMap2);
const propertyIdToAttributeMap = {};
const styleableShaderAttributes = pointCloud._styleableShaderAttributes;
for (name in styleableShaderAttributes) {
if (styleableShaderAttributes.hasOwnProperty(name)) {
attribute = styleableShaderAttributes[name];
variableSubstitutionMap[name] = `czm_3dtiles_property_${attribute.location}`;
propertyIdToAttributeMap[attribute.location] = attribute;
}
}
if (hasStyle) {
const shaderState = {
translucent: false
};
const parameterList2 = "(vec3 czm_3dtiles_builtin_property_POSITION, vec3 czm_3dtiles_builtin_property_POSITION_ABSOLUTE, vec4 czm_3dtiles_builtin_property_COLOR, vec3 czm_3dtiles_builtin_property_NORMAL)";
colorStyleFunction = style.getColorShaderFunction(
`getColorFromStyle${parameterList2}`,
variableSubstitutionMap,
shaderState
);
showStyleFunction = style.getShowShaderFunction(
`getShowFromStyle${parameterList2}`,
variableSubstitutionMap,
shaderState
);
pointSizeStyleFunction = style.getPointSizeShaderFunction(
`getPointSizeFromStyle${parameterList2}`,
variableSubstitutionMap,
shaderState
);
if (defined_default(colorStyleFunction) && shaderState.translucent) {
styleTranslucent = true;
}
}
pointCloud._styleTranslucent = styleTranslucent;
const hasColorStyle = defined_default(colorStyleFunction);
const hasShowStyle = defined_default(showStyleFunction);
const hasPointSizeStyle = defined_default(pointSizeStyleFunction);
const hasClippedContent = pointCloud.isClipped;
const styleablePropertyIds = [];
const builtinPropertyNames = [];
if (hasColorStyle) {
getStyleablePropertyIds(colorStyleFunction, styleablePropertyIds);
getBuiltinPropertyNames2(colorStyleFunction, builtinPropertyNames);
}
if (hasShowStyle) {
getStyleablePropertyIds(showStyleFunction, styleablePropertyIds);
getBuiltinPropertyNames2(showStyleFunction, builtinPropertyNames);
}
if (hasPointSizeStyle) {
getStyleablePropertyIds(pointSizeStyleFunction, styleablePropertyIds);
getBuiltinPropertyNames2(pointSizeStyleFunction, builtinPropertyNames);
}
const usesColorSemantic = builtinPropertyNames.indexOf("COLOR") >= 0;
const usesNormalSemantic = builtinPropertyNames.indexOf("NORMAL") >= 0;
if (usesNormalSemantic && !hasNormals) {
throw new RuntimeError_default(
"Style references the NORMAL semantic but the point cloud does not have normals"
);
}
for (name in styleableShaderAttributes) {
if (styleableShaderAttributes.hasOwnProperty(name)) {
attribute = styleableShaderAttributes[name];
const enabled = styleablePropertyIds.indexOf(attribute.location) >= 0;
const vertexAttribute = getVertexAttribute(
vertexArray,
attribute.location
);
vertexAttribute.enabled = enabled;
}
}
const usesColors = hasColors && (!hasColorStyle || usesColorSemantic);
if (hasColors) {
const colorVertexAttribute = getVertexAttribute(vertexArray, colorLocation);
colorVertexAttribute.enabled = usesColors;
}
const usesNormals = hasNormals && (normalShading || backFaceCulling || usesNormalSemantic);
if (hasNormals) {
const normalVertexAttribute = getVertexAttribute(
vertexArray,
normalLocation
);
normalVertexAttribute.enabled = usesNormals;
}
const attributeLocations8 = {
a_position: positionLocation
};
if (usesColors) {
attributeLocations8.a_color = colorLocation;
}
if (usesNormals) {
attributeLocations8.a_normal = normalLocation;
}
if (hasBatchIds) {
attributeLocations8.a_batchId = batchIdLocation;
}
let attributeDeclarations = "";
const length3 = styleablePropertyIds.length;
for (i = 0; i < length3; ++i) {
const propertyId = styleablePropertyIds[i];
attribute = propertyIdToAttributeMap[propertyId];
const componentCount = attribute.componentCount;
const attributeName = `czm_3dtiles_property_${propertyId}`;
let attributeType;
if (componentCount === 1) {
attributeType = "float";
} else {
attributeType = `vec${componentCount}`;
}
attributeDeclarations += `in ${attributeType} ${attributeName};
`;
attributeLocations8[attributeName] = attribute.location;
}
createUniformMap6(pointCloud, frameState);
let vs = "in vec3 a_position; \nout vec4 v_color; \nuniform vec4 u_pointSizeAndTimeAndGeometricErrorAndDepthMultiplier; \nuniform vec4 u_constantColor; \nuniform vec4 u_highlightColor; \n";
vs += "float u_pointSize; \nfloat tiles3d_tileset_time; \n";
if (attenuation) {
vs += "float u_geometricError; \nfloat u_depthMultiplier; \n";
}
vs += attributeDeclarations;
if (usesColors) {
if (isTranslucent) {
vs += "in vec4 a_color; \n";
} else if (isRGB565) {
vs += "in float a_color; \nconst float SHIFT_RIGHT_11 = 1.0 / 2048.0; \nconst float SHIFT_RIGHT_5 = 1.0 / 32.0; \nconst float SHIFT_LEFT_11 = 2048.0; \nconst float SHIFT_LEFT_5 = 32.0; \nconst float NORMALIZE_6 = 1.0 / 64.0; \nconst float NORMALIZE_5 = 1.0 / 32.0; \n";
} else {
vs += "in vec3 a_color; \n";
}
}
if (usesNormals) {
if (isOctEncoded16P || isOctEncodedDraco) {
vs += "in vec2 a_normal; \n";
} else {
vs += "in vec3 a_normal; \n";
}
}
if (hasBatchIds) {
vs += "in float a_batchId; \n";
}
if (isQuantized || isQuantizedDraco || isOctEncodedDraco) {
vs += "uniform vec4 u_quantizedVolumeScaleAndOctEncodedRange; \n";
}
if (hasColorStyle) {
vs += colorStyleFunction;
}
if (hasShowStyle) {
vs += showStyleFunction;
}
if (hasPointSizeStyle) {
vs += pointSizeStyleFunction;
}
vs += "void main() \n{ \n u_pointSize = u_pointSizeAndTimeAndGeometricErrorAndDepthMultiplier.x; \n tiles3d_tileset_time = u_pointSizeAndTimeAndGeometricErrorAndDepthMultiplier.y; \n";
if (attenuation) {
vs += " u_geometricError = u_pointSizeAndTimeAndGeometricErrorAndDepthMultiplier.z; \n u_depthMultiplier = u_pointSizeAndTimeAndGeometricErrorAndDepthMultiplier.w; \n";
}
if (usesColors) {
if (isTranslucent) {
vs += " vec4 color = a_color; \n";
} else if (isRGB565) {
vs += " float compressed = a_color; \n float r = floor(compressed * SHIFT_RIGHT_11); \n compressed -= r * SHIFT_LEFT_11; \n float g = floor(compressed * SHIFT_RIGHT_5); \n compressed -= g * SHIFT_LEFT_5; \n float b = compressed; \n vec3 rgb = vec3(r * NORMALIZE_5, g * NORMALIZE_6, b * NORMALIZE_5); \n vec4 color = vec4(rgb, 1.0); \n";
} else {
vs += " vec4 color = vec4(a_color, 1.0); \n";
}
} else {
vs += " vec4 color = u_constantColor; \n";
}
if (isQuantized || isQuantizedDraco) {
vs += " vec3 position = a_position * u_quantizedVolumeScaleAndOctEncodedRange.xyz; \n";
} else {
vs += " vec3 position = a_position; \n";
}
vs += " vec3 position_absolute = vec3(czm_model * vec4(position, 1.0)); \n";
if (usesNormals) {
if (isOctEncoded16P) {
vs += " vec3 normal = czm_octDecode(a_normal); \n";
} else if (isOctEncodedDraco) {
vs += " vec3 normal = czm_octDecode(a_normal, u_quantizedVolumeScaleAndOctEncodedRange.w).zxy; \n";
} else {
vs += " vec3 normal = a_normal; \n";
}
vs += " vec3 normalEC = czm_normal * normal; \n";
} else {
vs += " vec3 normal = vec3(1.0); \n";
}
if (hasColorStyle) {
vs += " color = getColorFromStyle(position, position_absolute, color, normal); \n";
}
if (hasShowStyle) {
vs += " float show = float(getShowFromStyle(position, position_absolute, color, normal)); \n";
}
if (hasPointSizeStyle) {
vs += " gl_PointSize = getPointSizeFromStyle(position, position_absolute, color, normal) * czm_pixelRatio; \n";
} else if (attenuation) {
vs += " vec4 positionEC = czm_modelView * vec4(position, 1.0); \n float depth = -positionEC.z; \n gl_PointSize = min((u_geometricError / depth) * u_depthMultiplier, u_pointSize); \n";
} else {
vs += " gl_PointSize = u_pointSize; \n";
}
vs += " color = color * u_highlightColor; \n";
if (usesNormals && normalShading) {
vs += " float diffuseStrength = czm_getLambertDiffuse(czm_lightDirectionEC, normalEC); \n diffuseStrength = max(diffuseStrength, 0.4); \n color.xyz *= diffuseStrength * czm_lightColor; \n";
}
vs += " v_color = color; \n gl_Position = czm_modelViewProjection * vec4(position, 1.0); \n";
if (usesNormals && backFaceCulling) {
vs += " float visible = step(-normalEC.z, 0.0); \n gl_Position *= visible; \n gl_PointSize *= visible; \n";
}
if (hasShowStyle) {
vs += " gl_Position.w *= float(show); \n gl_PointSize *= float(show); \n";
}
vs += "} \n";
let fs = "in vec4 v_color; \n";
if (hasClippedContent) {
fs += "uniform highp sampler2D u_clippingPlanes; \nuniform mat4 u_clippingPlanesMatrix; \nuniform vec4 u_clippingPlanesEdgeStyle; \n";
fs += "\n";
fs += getClippingFunction_default(clippingPlanes, context);
fs += "\n";
}
fs += "void main() \n{ \n out_FragColor = czm_gammaCorrect(v_color); \n";
if (hasClippedContent) {
fs += getClipAndStyleCode_default(
"u_clippingPlanes",
"u_clippingPlanesMatrix",
"u_clippingPlanesEdgeStyle"
);
}
fs += "} \n";
if (pointCloud.splitDirection !== SplitDirection_default.NONE) {
fs = Splitter_default.modifyFragmentShader(fs);
}
if (defined_default(pointCloud._vertexShaderLoaded)) {
vs = pointCloud._vertexShaderLoaded(vs);
}
if (defined_default(pointCloud._fragmentShaderLoaded)) {
fs = pointCloud._fragmentShaderLoaded(fs);
}
const drawCommand = pointCloud._drawCommand;
if (defined_default(drawCommand.shaderProgram)) {
drawCommand.shaderProgram.destroy();
}
drawCommand.shaderProgram = ShaderProgram_default.fromCache({
context,
vertexShaderSource: vs,
fragmentShaderSource: fs,
attributeLocations: attributeLocations8
});
try {
drawCommand.shaderProgram._bind();
} catch (error) {
throw new RuntimeError_default(
"Error generating style shader: this may be caused by a type mismatch, index out-of-bounds, or other syntax error."
);
}
}
function decodeDraco2(pointCloud, context) {
if (pointCloud._decodingState === DecodingState.READY) {
return false;
}
if (pointCloud._decodingState === DecodingState.NEEDS_DECODE) {
const parsedContent = pointCloud._parsedContent;
const draco = parsedContent.draco;
const decodePromise = DracoLoader_default.decodePointCloud(draco, context);
if (defined_default(decodePromise)) {
pointCloud._decodingState = DecodingState.DECODING;
decodePromise.then(function(result) {
pointCloud._decodingState = DecodingState.READY;
const decodedPositions = defined_default(result.POSITION) ? result.POSITION.array : void 0;
const decodedRgb = defined_default(result.RGB) ? result.RGB.array : void 0;
const decodedRgba = defined_default(result.RGBA) ? result.RGBA.array : void 0;
const decodedNormals = defined_default(result.NORMAL) ? result.NORMAL.array : void 0;
const decodedBatchIds = defined_default(result.BATCH_ID) ? result.BATCH_ID.array : void 0;
const isQuantizedDraco = defined_default(decodedPositions) && defined_default(result.POSITION.data.quantization);
const isOctEncodedDraco = defined_default(decodedNormals) && defined_default(result.NORMAL.data.quantization);
if (isQuantizedDraco) {
const quantization = result.POSITION.data.quantization;
const range = quantization.range;
pointCloud._quantizedVolumeScale = Cartesian3_default.fromElements(
range,
range,
range
);
pointCloud._quantizedVolumeOffset = Cartesian3_default.unpack(
quantization.minValues
);
pointCloud._quantizedRange = (1 << quantization.quantizationBits) - 1;
pointCloud._isQuantizedDraco = true;
}
if (isOctEncodedDraco) {
pointCloud._octEncodedRange = (1 << result.NORMAL.data.quantization.quantizationBits) - 1;
pointCloud._isOctEncodedDraco = true;
}
let styleableProperties = parsedContent.styleableProperties;
const batchTableProperties = draco.batchTableProperties;
for (const name in batchTableProperties) {
if (batchTableProperties.hasOwnProperty(name)) {
const property = result[name];
if (!defined_default(styleableProperties)) {
styleableProperties = {};
}
styleableProperties[name] = {
typedArray: property.array,
componentCount: property.data.componentsPerAttribute
};
}
}
if (defined_default(decodedPositions)) {
parsedContent.positions = {
typedArray: decodedPositions
};
}
const decodedColors = defaultValue_default(decodedRgba, decodedRgb);
if (defined_default(decodedColors)) {
parsedContent.colors = {
typedArray: decodedColors
};
}
if (defined_default(decodedNormals)) {
parsedContent.normals = {
typedArray: decodedNormals
};
}
if (defined_default(decodedBatchIds)) {
parsedContent.batchIds = {
typedArray: decodedBatchIds
};
}
parsedContent.styleableProperties = styleableProperties;
}).catch(function(error) {
pointCloud._decodingState = DecodingState.FAILED;
pointCloud._error = error;
});
}
}
return true;
}
var scratchComputedTranslation2 = new Cartesian4_default();
var scratchScale9 = new Cartesian3_default();
PointCloud.prototype.update = function(frameState) {
const context = frameState.context;
if (defined_default(this._error)) {
const error = this._error;
this._error = void 0;
throw error;
}
const decoding = decodeDraco2(this, context);
if (decoding) {
return;
}
let shadersDirty = false;
let modelMatrixDirty = !Matrix4_default.equals(this._modelMatrix, this.modelMatrix);
if (this._mode !== frameState.mode) {
this._mode = frameState.mode;
modelMatrixDirty = true;
}
if (!defined_default(this._drawCommand)) {
createResources4(this, frameState);
modelMatrixDirty = true;
shadersDirty = true;
this._ready = true;
this._parsedContent = void 0;
}
if (modelMatrixDirty) {
Matrix4_default.clone(this.modelMatrix, this._modelMatrix);
const modelMatrix = this._drawCommand.modelMatrix;
Matrix4_default.clone(this._modelMatrix, modelMatrix);
if (defined_default(this._rtcCenter)) {
Matrix4_default.multiplyByTranslation(modelMatrix, this._rtcCenter, modelMatrix);
}
if (defined_default(this._quantizedVolumeOffset)) {
Matrix4_default.multiplyByTranslation(
modelMatrix,
this._quantizedVolumeOffset,
modelMatrix
);
}
if (frameState.mode !== SceneMode_default.SCENE3D) {
const projection = frameState.mapProjection;
const translation3 = Matrix4_default.getColumn(
modelMatrix,
3,
scratchComputedTranslation2
);
if (!Cartesian4_default.equals(translation3, Cartesian4_default.UNIT_W)) {
Transforms_default.basisTo2D(projection, modelMatrix, modelMatrix);
}
}
const boundingSphere = this._drawCommand.boundingVolume;
BoundingSphere_default.clone(this._boundingSphere, boundingSphere);
if (this._cull) {
const center = boundingSphere.center;
Matrix4_default.multiplyByPoint(modelMatrix, center, center);
const scale = Matrix4_default.getScale(modelMatrix, scratchScale9);
boundingSphere.radius *= Cartesian3_default.maximumComponent(scale);
}
}
if (this.clippingPlanesDirty) {
this.clippingPlanesDirty = false;
shadersDirty = true;
}
if (this._attenuation !== this.attenuation) {
this._attenuation = this.attenuation;
shadersDirty = true;
}
if (this.backFaceCulling !== this._backFaceCulling) {
this._backFaceCulling = this.backFaceCulling;
shadersDirty = true;
}
if (this.normalShading !== this._normalShading) {
this._normalShading = this.normalShading;
shadersDirty = true;
}
if (this._style !== this.style || this.styleDirty) {
this._style = this.style;
this.styleDirty = false;
shadersDirty = true;
}
const splittingEnabled = this.splitDirection !== SplitDirection_default.NONE;
if (this._splittingEnabled !== splittingEnabled) {
this._splittingEnabled = splittingEnabled;
shadersDirty = true;
}
if (shadersDirty) {
createShaders4(this, frameState, this._style);
}
this._drawCommand.castShadows = ShadowMode_default.castShadows(this.shadows);
this._drawCommand.receiveShadows = ShadowMode_default.receiveShadows(this.shadows);
const isTranslucent = this._highlightColor.alpha < 1 || this._constantColor.alpha < 1 || this._styleTranslucent;
this._drawCommand.renderState = isTranslucent ? this._translucentRenderState : this._opaqueRenderState;
this._drawCommand.pass = isTranslucent ? Pass_default.TRANSLUCENT : this._opaquePass;
const commandList = frameState.commandList;
const passes = frameState.passes;
if (passes.render || passes.pick) {
commandList.push(this._drawCommand);
}
};
PointCloud.prototype.isDestroyed = function() {
return false;
};
PointCloud.prototype.destroy = function() {
const command = this._drawCommand;
if (defined_default(command)) {
command.vertexArray = command.vertexArray && command.vertexArray.destroy();
command.shaderProgram = command.shaderProgram && command.shaderProgram.destroy();
}
return destroyObject_default(this);
};
var PointCloud_default = PointCloud;
// packages/engine/Source/Scene/QuadtreeTileProvider.js
function QuadtreeTileProvider() {
DeveloperError_default.throwInstantiationError();
}
QuadtreeTileProvider.computeDefaultLevelZeroMaximumGeometricError = function(tilingScheme2) {
return tilingScheme2.ellipsoid.maximumRadius * 2 * Math.PI * 0.25 / (65 * tilingScheme2.getNumberOfXTilesAtLevel(0));
};
Object.defineProperties(QuadtreeTileProvider.prototype, {
/**
* Gets or sets the {@link QuadtreePrimitive} for which this provider is
* providing tiles.
* @memberof QuadtreeTileProvider.prototype
* @type {QuadtreePrimitive}
*/
quadtree: {
get: DeveloperError_default.throwInstantiationError,
set: DeveloperError_default.throwInstantiationError
},
/**
* Gets a value indicating whether or not the provider is ready for use.
* @memberof QuadtreeTileProvider.prototype
* @type {boolean}
* @deprecated
*/
ready: {
get: DeveloperError_default.throwInstantiationError
},
/**
* Gets the tiling scheme used by the provider.
* @memberof QuadtreeTileProvider.prototype
* @type {TilingScheme}
*/
tilingScheme: {
get: DeveloperError_default.throwInstantiationError
},
/**
* Gets an event that is raised when the geometry provider encounters an asynchronous error. By subscribing
* to the event, you will be notified of the error and can potentially recover from it. Event listeners
* are passed an instance of {@link TileProviderError}.
* @memberof QuadtreeTileProvider.prototype
* @type {Event}
*/
errorEvent: {
get: DeveloperError_default.throwInstantiationError
}
});
QuadtreeTileProvider.prototype.update = DeveloperError_default.throwInstantiationError;
QuadtreeTileProvider.prototype.beginUpdate = DeveloperError_default.throwInstantiationError;
QuadtreeTileProvider.prototype.endUpdate = DeveloperError_default.throwInstantiationError;
QuadtreeTileProvider.prototype.getLevelMaximumGeometricError = DeveloperError_default.throwInstantiationError;
QuadtreeTileProvider.prototype.loadTile = DeveloperError_default.throwInstantiationError;
QuadtreeTileProvider.prototype.computeTileVisibility = DeveloperError_default.throwInstantiationError;
QuadtreeTileProvider.prototype.showTileThisFrame = DeveloperError_default.throwInstantiationError;
QuadtreeTileProvider.prototype.computeDistanceToTile = DeveloperError_default.throwInstantiationError;
QuadtreeTileProvider.prototype.isDestroyed = DeveloperError_default.throwInstantiationError;
QuadtreeTileProvider.prototype.destroy = DeveloperError_default.throwInstantiationError;
var QuadtreeTileProvider_default = QuadtreeTileProvider;
// packages/engine/Source/Scene/SpatialNode.js
function SpatialNode(level, x, y, z, parent, shape, voxelDimensions) {
this.children = void 0;
this.parent = parent;
this.level = level;
this.x = x;
this.y = y;
this.z = z;
this.keyframeNodes = [];
this.renderableKeyframeNodes = [];
this.renderableKeyframeNodeLerp = 0;
this.renderableKeyframeNodePrevious = void 0;
this.renderableKeyframeNodeNext = void 0;
this.orientedBoundingBox = new OrientedBoundingBox_default();
this.approximateVoxelSize = 0;
this.screenSpaceError = 0;
this.visitedFrameNumber = -1;
this.computeBoundingVolumes(shape, voxelDimensions);
}
var scratchObbHalfScale = new Cartesian3_default();
SpatialNode.prototype.computeBoundingVolumes = function(shape, voxelDimensions) {
this.orientedBoundingBox = shape.computeOrientedBoundingBoxForTile(
this.level,
this.x,
this.y,
this.z,
this.orientedBoundingBox
);
const halfScale = Matrix3_default.getScale(
this.orientedBoundingBox.halfAxes,
scratchObbHalfScale
);
const maximumScale = 2 * Cartesian3_default.maximumComponent(halfScale);
this.approximateVoxelSize = maximumScale / Cartesian3_default.minimumComponent(voxelDimensions);
};
SpatialNode.prototype.constructChildNodes = function(shape, voxelDimensions) {
const { level, x, y, z } = this;
const xMin = x * 2;
const yMin = y * 2;
const zMin = z * 2;
const yMax = yMin + 1;
const xMax = xMin + 1;
const zMax = zMin + 1;
const childLevel = level + 1;
const childCoords = [
[childLevel, xMin, yMin, zMin],
[childLevel, xMax, yMin, zMin],
[childLevel, xMin, yMax, zMin],
[childLevel, xMax, yMax, zMin],
[childLevel, xMin, yMin, zMax],
[childLevel, xMax, yMin, zMax],
[childLevel, xMin, yMax, zMax],
[childLevel, xMax, yMax, zMax]
];
this.children = childCoords.map(([level2, x2, y2, z2]) => {
return new SpatialNode(level2, x2, y2, z2, this, shape, voxelDimensions);
});
};
SpatialNode.prototype.visibility = function(frameState, visibilityPlaneMask) {
const obb = this.orientedBoundingBox;
const cullingVolume = frameState.cullingVolume;
return cullingVolume.computeVisibilityWithPlaneMask(obb, visibilityPlaneMask);
};
SpatialNode.prototype.computeScreenSpaceError = function(cameraPosition, screenSpaceErrorMultiplier) {
const obb = this.orientedBoundingBox;
let distance2 = Math.sqrt(obb.distanceSquaredTo(cameraPosition));
distance2 = Math.max(distance2, Math_default.EPSILON7);
const approximateVoxelSize = this.approximateVoxelSize;
const error = screenSpaceErrorMultiplier * (approximateVoxelSize / distance2);
this.screenSpaceError = error;
};
var scratchBinarySearchKeyframeNode = {
keyframe: 0
};
function findKeyframeIndex(keyframe, keyframeNodes) {
scratchBinarySearchKeyframeNode.keyframe = keyframe;
return binarySearch_default(
keyframeNodes,
scratchBinarySearchKeyframeNode,
KeyframeNode_default.searchComparator
);
}
SpatialNode.prototype.computeSurroundingRenderableKeyframeNodes = function(keyframeLocation) {
let spatialNode = this;
const startLevel = spatialNode.level;
const targetKeyframePrev = Math.floor(keyframeLocation);
const targetKeyframeNext = Math.ceil(keyframeLocation);
let bestKeyframeNodePrev;
let bestKeyframeNodeNext;
let minimumDistancePrev = +Number.MAX_VALUE;
let minimumDistanceNext = +Number.MAX_VALUE;
while (defined_default(spatialNode)) {
const { renderableKeyframeNodes } = spatialNode;
if (renderableKeyframeNodes.length >= 1) {
const indexPrev = getKeyframeIndexPrev(
targetKeyframePrev,
renderableKeyframeNodes
);
const keyframeNodePrev = renderableKeyframeNodes[indexPrev];
const indexNext = targetKeyframeNext === targetKeyframePrev || targetKeyframePrev < keyframeNodePrev.keyframe ? indexPrev : Math.min(indexPrev + 1, renderableKeyframeNodes.length - 1);
const keyframeNodeNext = renderableKeyframeNodes[indexNext];
const distancePrev = targetKeyframePrev - keyframeNodePrev.keyframe;
const weightedDistancePrev = getWeightedKeyframeDistance(
startLevel - spatialNode.level,
distancePrev
);
if (weightedDistancePrev < minimumDistancePrev) {
minimumDistancePrev = weightedDistancePrev;
bestKeyframeNodePrev = keyframeNodePrev;
}
const distanceNext = keyframeNodeNext.keyframe - targetKeyframeNext;
const weightedDistanceNext = getWeightedKeyframeDistance(
startLevel - spatialNode.level,
distanceNext
);
if (weightedDistanceNext < minimumDistanceNext) {
minimumDistanceNext = weightedDistanceNext;
bestKeyframeNodeNext = keyframeNodeNext;
}
if (distancePrev === 0 && distanceNext === 0) {
break;
}
}
spatialNode = spatialNode.parent;
}
this.renderableKeyframeNodePrevious = bestKeyframeNodePrev;
this.renderableKeyframeNodeNext = bestKeyframeNodeNext;
if (!defined_default(bestKeyframeNodePrev) || !defined_default(bestKeyframeNodeNext)) {
return;
}
const bestKeyframePrev = bestKeyframeNodePrev.keyframe;
const bestKeyframeNext = bestKeyframeNodeNext.keyframe;
this.renderableKeyframeNodeLerp = bestKeyframePrev === bestKeyframeNext ? 0 : Math_default.clamp(
(keyframeLocation - bestKeyframePrev) / (bestKeyframeNext - bestKeyframePrev),
0,
1
);
};
function getKeyframeIndexPrev(targetKeyframe, keyframeNodes) {
const keyframeIndex = findKeyframeIndex(targetKeyframe, keyframeNodes);
return keyframeIndex < 0 ? Math_default.clamp(~keyframeIndex - 1, 0, keyframeNodes.length - 1) : keyframeIndex;
}
function getWeightedKeyframeDistance(levelDistance, keyframeDistance) {
const levelWeight = Math.exp(levelDistance * 4);
const keyframeWeight = keyframeDistance >= 0 ? 1 : -200;
return levelDistance * levelWeight + keyframeDistance * keyframeWeight;
}
SpatialNode.prototype.isVisited = function(frameNumber) {
return this.visitedFrameNumber === frameNumber;
};
SpatialNode.prototype.createKeyframeNode = function(keyframe) {
let index = findKeyframeIndex(keyframe, this.keyframeNodes);
if (index < 0) {
index = ~index;
const keyframeNode = new KeyframeNode_default(this, keyframe);
this.keyframeNodes.splice(index, 0, keyframeNode);
}
};
SpatialNode.prototype.destroyKeyframeNode = function(keyframeNode, megatextures) {
const keyframe = keyframeNode.keyframe;
const keyframeIndex = findKeyframeIndex(keyframe, this.keyframeNodes);
if (keyframeIndex < 0) {
throw new DeveloperError_default("Keyframe node does not exist.");
}
this.keyframeNodes.splice(keyframeIndex, 1);
if (keyframeNode.megatextureIndex !== -1) {
for (let i = 0; i < megatextures.length; i++) {
megatextures[i].remove(keyframeNode.megatextureIndex);
}
const renderableKeyframeNodeIndex = findKeyframeIndex(
keyframe,
this.renderableKeyframeNodes
);
if (renderableKeyframeNodeIndex < 0) {
throw new DeveloperError_default("Renderable keyframe node does not exist.");
}
this.renderableKeyframeNodes.splice(renderableKeyframeNodeIndex, 1);
}
keyframeNode.spatialNode = void 0;
keyframeNode.state = KeyframeNode_default.LoadState.UNLOADED;
keyframeNode.metadatas = {};
keyframeNode.megatextureIndex = -1;
keyframeNode.priority = -Number.MAX_VALUE;
keyframeNode.highPriorityFrameNumber = -1;
};
SpatialNode.prototype.addKeyframeNodeToMegatextures = function(keyframeNode, megatextures) {
if (keyframeNode.state !== KeyframeNode_default.LoadState.RECEIVED || keyframeNode.megatextureIndex !== -1 || keyframeNode.metadatas.length !== megatextures.length) {
throw new DeveloperError_default("Keyframe node cannot be added to megatexture");
}
for (let i = 0; i < megatextures.length; i++) {
const megatexture = megatextures[i];
keyframeNode.megatextureIndex = megatexture.add(keyframeNode.metadatas[i]);
keyframeNode.metadatas[i] = void 0;
}
keyframeNode.state = KeyframeNode_default.LoadState.LOADED;
const renderableKeyframeNodes = this.renderableKeyframeNodes;
let renderableKeyframeNodeIndex = findKeyframeIndex(
keyframeNode.keyframe,
renderableKeyframeNodes
);
if (renderableKeyframeNodeIndex >= 0) {
throw new DeveloperError_default("Keyframe already renderable");
}
renderableKeyframeNodeIndex = ~renderableKeyframeNodeIndex;
renderableKeyframeNodes.splice(renderableKeyframeNodeIndex, 0, keyframeNode);
};
SpatialNode.prototype.isRenderable = function(frameNumber) {
const previousNode = this.renderableKeyframeNodePrevious;
const nextNode = this.renderableKeyframeNodeNext;
const level = this.level;
return defined_default(previousNode) && defined_default(nextNode) && (previousNode.spatialNode.level === level || nextNode.spatialNode.level === level) && this.visitedFrameNumber === frameNumber;
};
var SpatialNode_default = SpatialNode;
// packages/engine/Source/Scene/SphereEmitter.js
function SphereEmitter(radius) {
radius = defaultValue_default(radius, 1);
Check_default.typeOf.number.greaterThan("radius", radius, 0);
this._radius = defaultValue_default(radius, 1);
}
Object.defineProperties(SphereEmitter.prototype, {
/**
* The radius of the sphere in meters.
* @memberof SphereEmitter.prototype
* @type {number}
* @default 1.0
*/
radius: {
get: function() {
return this._radius;
},
set: function(value) {
Check_default.typeOf.number.greaterThan("value", value, 0);
this._radius = value;
}
}
});
SphereEmitter.prototype.emit = function(particle) {
const theta = Math_default.randomBetween(0, Math_default.TWO_PI);
const phi = Math_default.randomBetween(0, Math_default.PI);
const rad = Math_default.randomBetween(0, this._radius);
const x = rad * Math.cos(theta) * Math.sin(phi);
const y = rad * Math.sin(theta) * Math.sin(phi);
const z = rad * Math.cos(phi);
particle.position = Cartesian3_default.fromElements(x, y, z, particle.position);
particle.velocity = Cartesian3_default.normalize(
particle.position,
particle.velocity
);
};
var SphereEmitter_default = SphereEmitter;
// packages/engine/Source/Scene/StyleExpression.js
function StyleExpression() {
}
StyleExpression.prototype.evaluate = function(feature2, result) {
DeveloperError_default.throwInstantiationError();
};
StyleExpression.prototype.evaluateColor = function(feature2, result) {
DeveloperError_default.throwInstantiationError();
};
StyleExpression.prototype.getShaderFunction = function(functionSignature, variableSubstitutionMap, shaderState, returnType) {
DeveloperError_default.throwInstantiationError();
};
StyleExpression.prototype.getVariables = function() {
DeveloperError_default.throwInstantiationError();
};
var StyleExpression_default = StyleExpression;
// packages/engine/Source/Core/Intersections2D.js
var Intersections2D = {};
Intersections2D.clipTriangleAtAxisAlignedThreshold = function(threshold, keepAbove, u0, u12, u22, result) {
if (!defined_default(threshold)) {
throw new DeveloperError_default("threshold is required.");
}
if (!defined_default(keepAbove)) {
throw new DeveloperError_default("keepAbove is required.");
}
if (!defined_default(u0)) {
throw new DeveloperError_default("u0 is required.");
}
if (!defined_default(u12)) {
throw new DeveloperError_default("u1 is required.");
}
if (!defined_default(u22)) {
throw new DeveloperError_default("u2 is required.");
}
if (!defined_default(result)) {
result = [];
} else {
result.length = 0;
}
let u0Behind;
let u1Behind;
let u2Behind;
if (keepAbove) {
u0Behind = u0 < threshold;
u1Behind = u12 < threshold;
u2Behind = u22 < threshold;
} else {
u0Behind = u0 > threshold;
u1Behind = u12 > threshold;
u2Behind = u22 > threshold;
}
const numBehind = u0Behind + u1Behind + u2Behind;
let u01Ratio;
let u02Ratio;
let u12Ratio;
let u10Ratio;
let u20Ratio;
let u21Ratio;
if (numBehind === 1) {
if (u0Behind) {
u01Ratio = (threshold - u0) / (u12 - u0);
u02Ratio = (threshold - u0) / (u22 - u0);
result.push(1);
result.push(2);
if (u02Ratio !== 1) {
result.push(-1);
result.push(0);
result.push(2);
result.push(u02Ratio);
}
if (u01Ratio !== 1) {
result.push(-1);
result.push(0);
result.push(1);
result.push(u01Ratio);
}
} else if (u1Behind) {
u12Ratio = (threshold - u12) / (u22 - u12);
u10Ratio = (threshold - u12) / (u0 - u12);
result.push(2);
result.push(0);
if (u10Ratio !== 1) {
result.push(-1);
result.push(1);
result.push(0);
result.push(u10Ratio);
}
if (u12Ratio !== 1) {
result.push(-1);
result.push(1);
result.push(2);
result.push(u12Ratio);
}
} else if (u2Behind) {
u20Ratio = (threshold - u22) / (u0 - u22);
u21Ratio = (threshold - u22) / (u12 - u22);
result.push(0);
result.push(1);
if (u21Ratio !== 1) {
result.push(-1);
result.push(2);
result.push(1);
result.push(u21Ratio);
}
if (u20Ratio !== 1) {
result.push(-1);
result.push(2);
result.push(0);
result.push(u20Ratio);
}
}
} else if (numBehind === 2) {
if (!u0Behind && u0 !== threshold) {
u10Ratio = (threshold - u12) / (u0 - u12);
u20Ratio = (threshold - u22) / (u0 - u22);
result.push(0);
result.push(-1);
result.push(1);
result.push(0);
result.push(u10Ratio);
result.push(-1);
result.push(2);
result.push(0);
result.push(u20Ratio);
} else if (!u1Behind && u12 !== threshold) {
u21Ratio = (threshold - u22) / (u12 - u22);
u01Ratio = (threshold - u0) / (u12 - u0);
result.push(1);
result.push(-1);
result.push(2);
result.push(1);
result.push(u21Ratio);
result.push(-1);
result.push(0);
result.push(1);
result.push(u01Ratio);
} else if (!u2Behind && u22 !== threshold) {
u02Ratio = (threshold - u0) / (u22 - u0);
u12Ratio = (threshold - u12) / (u22 - u12);
result.push(2);
result.push(-1);
result.push(0);
result.push(2);
result.push(u02Ratio);
result.push(-1);
result.push(1);
result.push(2);
result.push(u12Ratio);
}
} else if (numBehind !== 3) {
result.push(0);
result.push(1);
result.push(2);
}
return result;
};
Intersections2D.computeBarycentricCoordinates = function(x, y, x1, y1, x2, y2, x3, y3, result) {
if (!defined_default(x)) {
throw new DeveloperError_default("x is required.");
}
if (!defined_default(y)) {
throw new DeveloperError_default("y is required.");
}
if (!defined_default(x1)) {
throw new DeveloperError_default("x1 is required.");
}
if (!defined_default(y1)) {
throw new DeveloperError_default("y1 is required.");
}
if (!defined_default(x2)) {
throw new DeveloperError_default("x2 is required.");
}
if (!defined_default(y2)) {
throw new DeveloperError_default("y2 is required.");
}
if (!defined_default(x3)) {
throw new DeveloperError_default("x3 is required.");
}
if (!defined_default(y3)) {
throw new DeveloperError_default("y3 is required.");
}
const x1mx3 = x1 - x3;
const x3mx2 = x3 - x2;
const y2my3 = y2 - y3;
const y1my3 = y1 - y3;
const inverseDeterminant = 1 / (y2my3 * x1mx3 + x3mx2 * y1my3);
const ymy3 = y - y3;
const xmx3 = x - x3;
const l1 = (y2my3 * xmx3 + x3mx2 * ymy3) * inverseDeterminant;
const l2 = (-y1my3 * xmx3 + x1mx3 * ymy3) * inverseDeterminant;
const l3 = 1 - l1 - l2;
if (defined_default(result)) {
result.x = l1;
result.y = l2;
result.z = l3;
return result;
}
return new Cartesian3_default(l1, l2, l3);
};
Intersections2D.computeLineSegmentLineSegmentIntersection = function(x00, y00, x01, y01, x10, y10, x11, y11, result) {
Check_default.typeOf.number("x00", x00);
Check_default.typeOf.number("y00", y00);
Check_default.typeOf.number("x01", x01);
Check_default.typeOf.number("y01", y01);
Check_default.typeOf.number("x10", x10);
Check_default.typeOf.number("y10", y10);
Check_default.typeOf.number("x11", x11);
Check_default.typeOf.number("y11", y11);
const numerator1A = (x11 - x10) * (y00 - y10) - (y11 - y10) * (x00 - x10);
const numerator1B = (x01 - x00) * (y00 - y10) - (y01 - y00) * (x00 - x10);
const denominator1 = (y11 - y10) * (x01 - x00) - (x11 - x10) * (y01 - y00);
if (denominator1 === 0) {
return;
}
const ua1 = numerator1A / denominator1;
const ub1 = numerator1B / denominator1;
if (ua1 >= 0 && ua1 <= 1 && ub1 >= 0 && ub1 <= 1) {
if (!defined_default(result)) {
result = new Cartesian2_default();
}
result.x = x00 + ua1 * (x01 - x00);
result.y = y00 + ua1 * (y01 - y00);
return result;
}
};
var Intersections2D_default = Intersections2D;
// packages/engine/Source/Core/QuantizedMeshTerrainData.js
function QuantizedMeshTerrainData(options) {
if (!defined_default(options) || !defined_default(options.quantizedVertices)) {
throw new DeveloperError_default("options.quantizedVertices is required.");
}
if (!defined_default(options.indices)) {
throw new DeveloperError_default("options.indices is required.");
}
if (!defined_default(options.minimumHeight)) {
throw new DeveloperError_default("options.minimumHeight is required.");
}
if (!defined_default(options.maximumHeight)) {
throw new DeveloperError_default("options.maximumHeight is required.");
}
if (!defined_default(options.maximumHeight)) {
throw new DeveloperError_default("options.maximumHeight is required.");
}
if (!defined_default(options.boundingSphere)) {
throw new DeveloperError_default("options.boundingSphere is required.");
}
if (!defined_default(options.horizonOcclusionPoint)) {
throw new DeveloperError_default("options.horizonOcclusionPoint is required.");
}
if (!defined_default(options.westIndices)) {
throw new DeveloperError_default("options.westIndices is required.");
}
if (!defined_default(options.southIndices)) {
throw new DeveloperError_default("options.southIndices is required.");
}
if (!defined_default(options.eastIndices)) {
throw new DeveloperError_default("options.eastIndices is required.");
}
if (!defined_default(options.northIndices)) {
throw new DeveloperError_default("options.northIndices is required.");
}
if (!defined_default(options.westSkirtHeight)) {
throw new DeveloperError_default("options.westSkirtHeight is required.");
}
if (!defined_default(options.southSkirtHeight)) {
throw new DeveloperError_default("options.southSkirtHeight is required.");
}
if (!defined_default(options.eastSkirtHeight)) {
throw new DeveloperError_default("options.eastSkirtHeight is required.");
}
if (!defined_default(options.northSkirtHeight)) {
throw new DeveloperError_default("options.northSkirtHeight is required.");
}
this._quantizedVertices = options.quantizedVertices;
this._encodedNormals = options.encodedNormals;
this._indices = options.indices;
this._minimumHeight = options.minimumHeight;
this._maximumHeight = options.maximumHeight;
this._boundingSphere = options.boundingSphere;
this._orientedBoundingBox = options.orientedBoundingBox;
this._horizonOcclusionPoint = options.horizonOcclusionPoint;
this._credits = options.credits;
const vertexCount = this._quantizedVertices.length / 3;
const uValues = this._uValues = this._quantizedVertices.subarray(
0,
vertexCount
);
const vValues = this._vValues = this._quantizedVertices.subarray(
vertexCount,
2 * vertexCount
);
this._heightValues = this._quantizedVertices.subarray(
2 * vertexCount,
3 * vertexCount
);
function sortByV(a3, b) {
return vValues[a3] - vValues[b];
}
function sortByU(a3, b) {
return uValues[a3] - uValues[b];
}
this._westIndices = sortIndicesIfNecessary(
options.westIndices,
sortByV,
vertexCount
);
this._southIndices = sortIndicesIfNecessary(
options.southIndices,
sortByU,
vertexCount
);
this._eastIndices = sortIndicesIfNecessary(
options.eastIndices,
sortByV,
vertexCount
);
this._northIndices = sortIndicesIfNecessary(
options.northIndices,
sortByU,
vertexCount
);
this._westSkirtHeight = options.westSkirtHeight;
this._southSkirtHeight = options.southSkirtHeight;
this._eastSkirtHeight = options.eastSkirtHeight;
this._northSkirtHeight = options.northSkirtHeight;
this._childTileMask = defaultValue_default(options.childTileMask, 15);
this._createdByUpsampling = defaultValue_default(options.createdByUpsampling, false);
this._waterMask = options.waterMask;
this._mesh = void 0;
}
Object.defineProperties(QuantizedMeshTerrainData.prototype, {
/**
* An array of credits for this tile.
* @memberof QuantizedMeshTerrainData.prototype
* @type {Credit[]}
*/
credits: {
get: function() {
return this._credits;
}
},
/**
* The water mask included in this terrain data, if any. A water mask is a rectangular
* Uint8Array or image where a value of 255 indicates water and a value of 0 indicates land.
* Values in between 0 and 255 are allowed as well to smoothly blend between land and water.
* @memberof QuantizedMeshTerrainData.prototype
* @type {Uint8Array|HTMLImageElement|HTMLCanvasElement}
*/
waterMask: {
get: function() {
return this._waterMask;
}
},
childTileMask: {
get: function() {
return this._childTileMask;
}
},
canUpsample: {
get: function() {
return defined_default(this._mesh);
}
}
});
var arrayScratch2 = [];
function sortIndicesIfNecessary(indices2, sortFunction, vertexCount) {
arrayScratch2.length = indices2.length;
let needsSort = false;
for (let i = 0, len = indices2.length; i < len; ++i) {
arrayScratch2[i] = indices2[i];
needsSort = needsSort || i > 0 && sortFunction(indices2[i - 1], indices2[i]) > 0;
}
if (needsSort) {
arrayScratch2.sort(sortFunction);
return IndexDatatype_default.createTypedArray(vertexCount, arrayScratch2);
}
return indices2;
}
var createMeshTaskName2 = "createVerticesFromQuantizedTerrainMesh";
var createMeshTaskProcessorNoThrottle2 = new TaskProcessor_default(createMeshTaskName2);
var createMeshTaskProcessorThrottle2 = new TaskProcessor_default(
createMeshTaskName2,
TerrainData_default.maximumAsynchronousTasks
);
QuantizedMeshTerrainData.prototype.createMesh = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
Check_default.typeOf.object("options.tilingScheme", options.tilingScheme);
Check_default.typeOf.number("options.x", options.x);
Check_default.typeOf.number("options.y", options.y);
Check_default.typeOf.number("options.level", options.level);
const tilingScheme2 = options.tilingScheme;
const x = options.x;
const y = options.y;
const level = options.level;
const exaggeration = defaultValue_default(options.exaggeration, 1);
const exaggerationRelativeHeight = defaultValue_default(
options.exaggerationRelativeHeight,
0
);
const throttle = defaultValue_default(options.throttle, true);
const ellipsoid = tilingScheme2.ellipsoid;
const rectangle = tilingScheme2.tileXYToRectangle(x, y, level);
const createMeshTaskProcessor = throttle ? createMeshTaskProcessorThrottle2 : createMeshTaskProcessorNoThrottle2;
const verticesPromise = createMeshTaskProcessor.scheduleTask({
minimumHeight: this._minimumHeight,
maximumHeight: this._maximumHeight,
quantizedVertices: this._quantizedVertices,
octEncodedNormals: this._encodedNormals,
includeWebMercatorT: true,
indices: this._indices,
westIndices: this._westIndices,
southIndices: this._southIndices,
eastIndices: this._eastIndices,
northIndices: this._northIndices,
westSkirtHeight: this._westSkirtHeight,
southSkirtHeight: this._southSkirtHeight,
eastSkirtHeight: this._eastSkirtHeight,
northSkirtHeight: this._northSkirtHeight,
rectangle,
relativeToCenter: this._boundingSphere.center,
ellipsoid,
exaggeration,
exaggerationRelativeHeight
});
if (!defined_default(verticesPromise)) {
return void 0;
}
const that = this;
return Promise.resolve(verticesPromise).then(function(result) {
const vertexCountWithoutSkirts = that._quantizedVertices.length / 3;
const vertexCount = vertexCountWithoutSkirts + that._westIndices.length + that._southIndices.length + that._eastIndices.length + that._northIndices.length;
const indicesTypedArray = IndexDatatype_default.createTypedArray(
vertexCount,
result.indices
);
const vertices = new Float32Array(result.vertices);
const rtc = result.center;
const minimumHeight = result.minimumHeight;
const maximumHeight = result.maximumHeight;
const boundingSphere = that._boundingSphere;
const obb = that._orientedBoundingBox;
const occludeePointInScaledSpace = defaultValue_default(
Cartesian3_default.clone(result.occludeePointInScaledSpace),
that._horizonOcclusionPoint
);
const stride = result.vertexStride;
const terrainEncoding = TerrainEncoding_default.clone(result.encoding);
that._mesh = new TerrainMesh_default(
rtc,
vertices,
indicesTypedArray,
result.indexCountWithoutSkirts,
vertexCountWithoutSkirts,
minimumHeight,
maximumHeight,
boundingSphere,
occludeePointInScaledSpace,
stride,
obb,
terrainEncoding,
result.westIndicesSouthToNorth,
result.southIndicesEastToWest,
result.eastIndicesNorthToSouth,
result.northIndicesWestToEast
);
that._quantizedVertices = void 0;
that._encodedNormals = void 0;
that._indices = void 0;
that._uValues = void 0;
that._vValues = void 0;
that._heightValues = void 0;
that._westIndices = void 0;
that._southIndices = void 0;
that._eastIndices = void 0;
that._northIndices = void 0;
return that._mesh;
});
};
var upsampleTaskProcessor = new TaskProcessor_default(
"upsampleQuantizedTerrainMesh",
TerrainData_default.maximumAsynchronousTasks
);
QuantizedMeshTerrainData.prototype.upsample = function(tilingScheme2, thisX, thisY, thisLevel, descendantX, descendantY, descendantLevel) {
if (!defined_default(tilingScheme2)) {
throw new DeveloperError_default("tilingScheme is required.");
}
if (!defined_default(thisX)) {
throw new DeveloperError_default("thisX is required.");
}
if (!defined_default(thisY)) {
throw new DeveloperError_default("thisY is required.");
}
if (!defined_default(thisLevel)) {
throw new DeveloperError_default("thisLevel is required.");
}
if (!defined_default(descendantX)) {
throw new DeveloperError_default("descendantX is required.");
}
if (!defined_default(descendantY)) {
throw new DeveloperError_default("descendantY is required.");
}
if (!defined_default(descendantLevel)) {
throw new DeveloperError_default("descendantLevel is required.");
}
const levelDifference = descendantLevel - thisLevel;
if (levelDifference > 1) {
throw new DeveloperError_default(
"Upsampling through more than one level at a time is not currently supported."
);
}
const mesh = this._mesh;
if (!defined_default(this._mesh)) {
return void 0;
}
const isEastChild = thisX * 2 !== descendantX;
const isNorthChild = thisY * 2 === descendantY;
const ellipsoid = tilingScheme2.ellipsoid;
const childRectangle = tilingScheme2.tileXYToRectangle(
descendantX,
descendantY,
descendantLevel
);
const upsamplePromise = upsampleTaskProcessor.scheduleTask({
vertices: mesh.vertices,
vertexCountWithoutSkirts: mesh.vertexCountWithoutSkirts,
indices: mesh.indices,
indexCountWithoutSkirts: mesh.indexCountWithoutSkirts,
encoding: mesh.encoding,
minimumHeight: this._minimumHeight,
maximumHeight: this._maximumHeight,
isEastChild,
isNorthChild,
childRectangle,
ellipsoid
});
if (!defined_default(upsamplePromise)) {
return void 0;
}
let shortestSkirt = Math.min(this._westSkirtHeight, this._eastSkirtHeight);
shortestSkirt = Math.min(shortestSkirt, this._southSkirtHeight);
shortestSkirt = Math.min(shortestSkirt, this._northSkirtHeight);
const westSkirtHeight = isEastChild ? shortestSkirt * 0.5 : this._westSkirtHeight;
const southSkirtHeight = isNorthChild ? shortestSkirt * 0.5 : this._southSkirtHeight;
const eastSkirtHeight = isEastChild ? this._eastSkirtHeight : shortestSkirt * 0.5;
const northSkirtHeight = isNorthChild ? this._northSkirtHeight : shortestSkirt * 0.5;
const credits = this._credits;
return Promise.resolve(upsamplePromise).then(function(result) {
const quantizedVertices = new Uint16Array(result.vertices);
const indicesTypedArray = IndexDatatype_default.createTypedArray(
quantizedVertices.length / 3,
result.indices
);
let encodedNormals;
if (defined_default(result.encodedNormals)) {
encodedNormals = new Uint8Array(result.encodedNormals);
}
return new QuantizedMeshTerrainData({
quantizedVertices,
indices: indicesTypedArray,
encodedNormals,
minimumHeight: result.minimumHeight,
maximumHeight: result.maximumHeight,
boundingSphere: BoundingSphere_default.clone(result.boundingSphere),
orientedBoundingBox: OrientedBoundingBox_default.clone(
result.orientedBoundingBox
),
horizonOcclusionPoint: Cartesian3_default.clone(result.horizonOcclusionPoint),
westIndices: result.westIndices,
southIndices: result.southIndices,
eastIndices: result.eastIndices,
northIndices: result.northIndices,
westSkirtHeight,
southSkirtHeight,
eastSkirtHeight,
northSkirtHeight,
childTileMask: 0,
credits,
createdByUpsampling: true
});
});
};
var maxShort2 = 32767;
var barycentricCoordinateScratch = new Cartesian3_default();
QuantizedMeshTerrainData.prototype.interpolateHeight = function(rectangle, longitude, latitude) {
let u3 = Math_default.clamp(
(longitude - rectangle.west) / rectangle.width,
0,
1
);
u3 *= maxShort2;
let v7 = Math_default.clamp(
(latitude - rectangle.south) / rectangle.height,
0,
1
);
v7 *= maxShort2;
if (!defined_default(this._mesh)) {
return interpolateHeight2(this, u3, v7);
}
return interpolateMeshHeight2(this, u3, v7);
};
function pointInBoundingBox(u3, v7, u0, v02, u12, v13, u22, v23) {
const minU = Math.min(u0, u12, u22);
const maxU = Math.max(u0, u12, u22);
const minV = Math.min(v02, v13, v23);
const maxV = Math.max(v02, v13, v23);
return u3 >= minU && u3 <= maxU && v7 >= minV && v7 <= maxV;
}
var texCoordScratch0 = new Cartesian2_default();
var texCoordScratch1 = new Cartesian2_default();
var texCoordScratch2 = new Cartesian2_default();
function interpolateMeshHeight2(terrainData, u3, v7) {
const mesh = terrainData._mesh;
const vertices = mesh.vertices;
const encoding = mesh.encoding;
const indices2 = mesh.indices;
for (let i = 0, len = indices2.length; i < len; i += 3) {
const i0 = indices2[i];
const i1 = indices2[i + 1];
const i2 = indices2[i + 2];
const uv0 = encoding.decodeTextureCoordinates(
vertices,
i0,
texCoordScratch0
);
const uv1 = encoding.decodeTextureCoordinates(
vertices,
i1,
texCoordScratch1
);
const uv2 = encoding.decodeTextureCoordinates(
vertices,
i2,
texCoordScratch2
);
if (pointInBoundingBox(u3, v7, uv0.x, uv0.y, uv1.x, uv1.y, uv2.x, uv2.y)) {
const barycentric = Intersections2D_default.computeBarycentricCoordinates(
u3,
v7,
uv0.x,
uv0.y,
uv1.x,
uv1.y,
uv2.x,
uv2.y,
barycentricCoordinateScratch
);
if (barycentric.x >= -1e-15 && barycentric.y >= -1e-15 && barycentric.z >= -1e-15) {
const h0 = encoding.decodeHeight(vertices, i0);
const h1 = encoding.decodeHeight(vertices, i1);
const h2 = encoding.decodeHeight(vertices, i2);
return barycentric.x * h0 + barycentric.y * h1 + barycentric.z * h2;
}
}
}
return void 0;
}
function interpolateHeight2(terrainData, u3, v7) {
const uBuffer = terrainData._uValues;
const vBuffer = terrainData._vValues;
const heightBuffer = terrainData._heightValues;
const indices2 = terrainData._indices;
for (let i = 0, len = indices2.length; i < len; i += 3) {
const i0 = indices2[i];
const i1 = indices2[i + 1];
const i2 = indices2[i + 2];
const u0 = uBuffer[i0];
const u12 = uBuffer[i1];
const u22 = uBuffer[i2];
const v02 = vBuffer[i0];
const v13 = vBuffer[i1];
const v23 = vBuffer[i2];
if (pointInBoundingBox(u3, v7, u0, v02, u12, v13, u22, v23)) {
const barycentric = Intersections2D_default.computeBarycentricCoordinates(
u3,
v7,
u0,
v02,
u12,
v13,
u22,
v23,
barycentricCoordinateScratch
);
if (barycentric.x >= -1e-15 && barycentric.y >= -1e-15 && barycentric.z >= -1e-15) {
const quantizedHeight = barycentric.x * heightBuffer[i0] + barycentric.y * heightBuffer[i1] + barycentric.z * heightBuffer[i2];
return Math_default.lerp(
terrainData._minimumHeight,
terrainData._maximumHeight,
quantizedHeight / maxShort2
);
}
}
}
return void 0;
}
QuantizedMeshTerrainData.prototype.isChildAvailable = function(thisX, thisY, childX, childY) {
if (!defined_default(thisX)) {
throw new DeveloperError_default("thisX is required.");
}
if (!defined_default(thisY)) {
throw new DeveloperError_default("thisY is required.");
}
if (!defined_default(childX)) {
throw new DeveloperError_default("childX is required.");
}
if (!defined_default(childY)) {
throw new DeveloperError_default("childY is required.");
}
let bitNumber = 2;
if (childX !== thisX * 2) {
++bitNumber;
}
if (childY !== thisY * 2) {
bitNumber -= 2;
}
return (this._childTileMask & 1 << bitNumber) !== 0;
};
QuantizedMeshTerrainData.prototype.wasCreatedByUpsampling = function() {
return this._createdByUpsampling;
};
var QuantizedMeshTerrainData_default = QuantizedMeshTerrainData;
// packages/engine/Source/Core/TileAvailability.js
function TileAvailability(tilingScheme2, maximumLevel) {
this._tilingScheme = tilingScheme2;
this._maximumLevel = maximumLevel;
this._rootNodes = [];
}
var rectangleScratch5 = new Rectangle_default();
function findNode2(level, x, y, nodes) {
const count = nodes.length;
for (let i = 0; i < count; ++i) {
const node = nodes[i];
if (node.x === x && node.y === y && node.level === level) {
return true;
}
}
return false;
}
TileAvailability.prototype.addAvailableTileRange = function(level, startX, startY, endX, endY) {
const tilingScheme2 = this._tilingScheme;
const rootNodes = this._rootNodes;
if (level === 0) {
for (let y = startY; y <= endY; ++y) {
for (let x = startX; x <= endX; ++x) {
if (!findNode2(level, x, y, rootNodes)) {
rootNodes.push(new QuadtreeNode(tilingScheme2, void 0, 0, x, y));
}
}
}
}
tilingScheme2.tileXYToRectangle(startX, startY, level, rectangleScratch5);
const west = rectangleScratch5.west;
const north = rectangleScratch5.north;
tilingScheme2.tileXYToRectangle(endX, endY, level, rectangleScratch5);
const east = rectangleScratch5.east;
const south = rectangleScratch5.south;
const rectangleWithLevel = new RectangleWithLevel(
level,
west,
south,
east,
north
);
for (let i = 0; i < rootNodes.length; ++i) {
const rootNode = rootNodes[i];
if (rectanglesOverlap(rootNode.extent, rectangleWithLevel)) {
putRectangleInQuadtree(this._maximumLevel, rootNode, rectangleWithLevel);
}
}
};
TileAvailability.prototype.computeMaximumLevelAtPosition = function(position) {
let node;
for (let nodeIndex = 0; nodeIndex < this._rootNodes.length; ++nodeIndex) {
const rootNode = this._rootNodes[nodeIndex];
if (rectangleContainsPosition(rootNode.extent, position)) {
node = rootNode;
break;
}
}
if (!defined_default(node)) {
return -1;
}
return findMaxLevelFromNode(void 0, node, position);
};
var rectanglesScratch = [];
var remainingToCoverByLevelScratch = [];
var westScratch2 = new Rectangle_default();
var eastScratch = new Rectangle_default();
TileAvailability.prototype.computeBestAvailableLevelOverRectangle = function(rectangle) {
const rectangles = rectanglesScratch;
rectangles.length = 0;
if (rectangle.east < rectangle.west) {
rectangles.push(
Rectangle_default.fromRadians(
-Math.PI,
rectangle.south,
rectangle.east,
rectangle.north,
westScratch2
)
);
rectangles.push(
Rectangle_default.fromRadians(
rectangle.west,
rectangle.south,
Math.PI,
rectangle.north,
eastScratch
)
);
} else {
rectangles.push(rectangle);
}
const remainingToCoverByLevel = remainingToCoverByLevelScratch;
remainingToCoverByLevel.length = 0;
let i;
for (i = 0; i < this._rootNodes.length; ++i) {
updateCoverageWithNode(
remainingToCoverByLevel,
this._rootNodes[i],
rectangles
);
}
for (i = remainingToCoverByLevel.length - 1; i >= 0; --i) {
if (defined_default(remainingToCoverByLevel[i]) && remainingToCoverByLevel[i].length === 0) {
return i;
}
}
return 0;
};
var cartographicScratch5 = new Cartographic_default();
TileAvailability.prototype.isTileAvailable = function(level, x, y) {
const rectangle = this._tilingScheme.tileXYToRectangle(
x,
y,
level,
rectangleScratch5
);
Rectangle_default.center(rectangle, cartographicScratch5);
return this.computeMaximumLevelAtPosition(cartographicScratch5) >= level;
};
TileAvailability.prototype.computeChildMaskForTile = function(level, x, y) {
const childLevel = level + 1;
if (childLevel >= this._maximumLevel) {
return 0;
}
let mask = 0;
mask |= this.isTileAvailable(childLevel, 2 * x, 2 * y + 1) ? 1 : 0;
mask |= this.isTileAvailable(childLevel, 2 * x + 1, 2 * y + 1) ? 2 : 0;
mask |= this.isTileAvailable(childLevel, 2 * x, 2 * y) ? 4 : 0;
mask |= this.isTileAvailable(childLevel, 2 * x + 1, 2 * y) ? 8 : 0;
return mask;
};
function QuadtreeNode(tilingScheme2, parent, level, x, y) {
this.tilingScheme = tilingScheme2;
this.parent = parent;
this.level = level;
this.x = x;
this.y = y;
this.extent = tilingScheme2.tileXYToRectangle(x, y, level);
this.rectangles = [];
this._sw = void 0;
this._se = void 0;
this._nw = void 0;
this._ne = void 0;
}
Object.defineProperties(QuadtreeNode.prototype, {
nw: {
get: function() {
if (!this._nw) {
this._nw = new QuadtreeNode(
this.tilingScheme,
this,
this.level + 1,
this.x * 2,
this.y * 2
);
}
return this._nw;
}
},
ne: {
get: function() {
if (!this._ne) {
this._ne = new QuadtreeNode(
this.tilingScheme,
this,
this.level + 1,
this.x * 2 + 1,
this.y * 2
);
}
return this._ne;
}
},
sw: {
get: function() {
if (!this._sw) {
this._sw = new QuadtreeNode(
this.tilingScheme,
this,
this.level + 1,
this.x * 2,
this.y * 2 + 1
);
}
return this._sw;
}
},
se: {
get: function() {
if (!this._se) {
this._se = new QuadtreeNode(
this.tilingScheme,
this,
this.level + 1,
this.x * 2 + 1,
this.y * 2 + 1
);
}
return this._se;
}
}
});
function RectangleWithLevel(level, west, south, east, north) {
this.level = level;
this.west = west;
this.south = south;
this.east = east;
this.north = north;
}
function rectanglesOverlap(rectangle1, rectangle2) {
const west = Math.max(rectangle1.west, rectangle2.west);
const south = Math.max(rectangle1.south, rectangle2.south);
const east = Math.min(rectangle1.east, rectangle2.east);
const north = Math.min(rectangle1.north, rectangle2.north);
return south < north && west < east;
}
function putRectangleInQuadtree(maxDepth, node, rectangle) {
while (node.level < maxDepth) {
if (rectangleFullyContainsRectangle(node.nw.extent, rectangle)) {
node = node.nw;
} else if (rectangleFullyContainsRectangle(node.ne.extent, rectangle)) {
node = node.ne;
} else if (rectangleFullyContainsRectangle(node.sw.extent, rectangle)) {
node = node.sw;
} else if (rectangleFullyContainsRectangle(node.se.extent, rectangle)) {
node = node.se;
} else {
break;
}
}
if (node.rectangles.length === 0 || node.rectangles[node.rectangles.length - 1].level <= rectangle.level) {
node.rectangles.push(rectangle);
} else {
let index = binarySearch_default(
node.rectangles,
rectangle.level,
rectangleLevelComparator
);
if (index < 0) {
index = ~index;
}
node.rectangles.splice(index, 0, rectangle);
}
}
function rectangleLevelComparator(a3, b) {
return a3.level - b;
}
function rectangleFullyContainsRectangle(potentialContainer, rectangleToTest) {
return rectangleToTest.west >= potentialContainer.west && rectangleToTest.east <= potentialContainer.east && rectangleToTest.south >= potentialContainer.south && rectangleToTest.north <= potentialContainer.north;
}
function rectangleContainsPosition(potentialContainer, positionToTest) {
return positionToTest.longitude >= potentialContainer.west && positionToTest.longitude <= potentialContainer.east && positionToTest.latitude >= potentialContainer.south && positionToTest.latitude <= potentialContainer.north;
}
function findMaxLevelFromNode(stopNode, node, position) {
let maxLevel = 0;
let found = false;
while (!found) {
const nw = node._nw && rectangleContainsPosition(node._nw.extent, position);
const ne = node._ne && rectangleContainsPosition(node._ne.extent, position);
const sw = node._sw && rectangleContainsPosition(node._sw.extent, position);
const se = node._se && rectangleContainsPosition(node._se.extent, position);
if (nw + ne + sw + se > 1) {
if (nw) {
maxLevel = Math.max(
maxLevel,
findMaxLevelFromNode(node, node._nw, position)
);
}
if (ne) {
maxLevel = Math.max(
maxLevel,
findMaxLevelFromNode(node, node._ne, position)
);
}
if (sw) {
maxLevel = Math.max(
maxLevel,
findMaxLevelFromNode(node, node._sw, position)
);
}
if (se) {
maxLevel = Math.max(
maxLevel,
findMaxLevelFromNode(node, node._se, position)
);
}
break;
} else if (nw) {
node = node._nw;
} else if (ne) {
node = node._ne;
} else if (sw) {
node = node._sw;
} else if (se) {
node = node._se;
} else {
found = true;
}
}
while (node !== stopNode) {
const rectangles = node.rectangles;
for (let i = rectangles.length - 1; i >= 0 && rectangles[i].level > maxLevel; --i) {
const rectangle = rectangles[i];
if (rectangleContainsPosition(rectangle, position)) {
maxLevel = rectangle.level;
}
}
node = node.parent;
}
return maxLevel;
}
function updateCoverageWithNode(remainingToCoverByLevel, node, rectanglesToCover) {
if (!node) {
return;
}
let i;
let anyOverlap = false;
for (i = 0; i < rectanglesToCover.length; ++i) {
anyOverlap = anyOverlap || rectanglesOverlap(node.extent, rectanglesToCover[i]);
}
if (!anyOverlap) {
return;
}
const rectangles = node.rectangles;
for (i = 0; i < rectangles.length; ++i) {
const rectangle = rectangles[i];
if (!remainingToCoverByLevel[rectangle.level]) {
remainingToCoverByLevel[rectangle.level] = rectanglesToCover;
}
remainingToCoverByLevel[rectangle.level] = subtractRectangle(
remainingToCoverByLevel[rectangle.level],
rectangle
);
}
updateCoverageWithNode(remainingToCoverByLevel, node._nw, rectanglesToCover);
updateCoverageWithNode(remainingToCoverByLevel, node._ne, rectanglesToCover);
updateCoverageWithNode(remainingToCoverByLevel, node._sw, rectanglesToCover);
updateCoverageWithNode(remainingToCoverByLevel, node._se, rectanglesToCover);
}
function subtractRectangle(rectangleList, rectangleToSubtract) {
const result = [];
for (let i = 0; i < rectangleList.length; ++i) {
const rectangle = rectangleList[i];
if (!rectanglesOverlap(rectangle, rectangleToSubtract)) {
result.push(rectangle);
} else {
if (rectangle.west < rectangleToSubtract.west) {
result.push(
new Rectangle_default(
rectangle.west,
rectangle.south,
rectangleToSubtract.west,
rectangle.north
)
);
}
if (rectangle.east > rectangleToSubtract.east) {
result.push(
new Rectangle_default(
rectangleToSubtract.east,
rectangle.south,
rectangle.east,
rectangle.north
)
);
}
if (rectangle.south < rectangleToSubtract.south) {
result.push(
new Rectangle_default(
Math.max(rectangleToSubtract.west, rectangle.west),
rectangle.south,
Math.min(rectangleToSubtract.east, rectangle.east),
rectangleToSubtract.south
)
);
}
if (rectangle.north > rectangleToSubtract.north) {
result.push(
new Rectangle_default(
Math.max(rectangleToSubtract.west, rectangle.west),
rectangleToSubtract.north,
Math.min(rectangleToSubtract.east, rectangle.east),
rectangle.north
)
);
}
}
}
return result;
}
var TileAvailability_default = TileAvailability;
// packages/engine/Source/Core/CesiumTerrainProvider.js
function LayerInformation(layer) {
this.resource = layer.resource;
this.version = layer.version;
this.isHeightmap = layer.isHeightmap;
this.tileUrlTemplates = layer.tileUrlTemplates;
this.availability = layer.availability;
this.hasVertexNormals = layer.hasVertexNormals;
this.hasWaterMask = layer.hasWaterMask;
this.hasMetadata = layer.hasMetadata;
this.availabilityLevels = layer.availabilityLevels;
this.availabilityTilesLoaded = layer.availabilityTilesLoaded;
this.littleEndianExtensionSize = layer.littleEndianExtensionSize;
this.availabilityPromiseCache = {};
}
function TerrainProviderBuilder(options) {
this.requestVertexNormals = defaultValue_default(options.requestVertexNormals, false);
this.requestWaterMask = defaultValue_default(options.requestWaterMask, false);
this.requestMetadata = defaultValue_default(options.requestMetadata, true);
this.ellipsoid = options.ellipsoid;
this.heightmapWidth = 65;
this.heightmapStructure = void 0;
this.hasWaterMask = false;
this.hasMetadata = false;
this.hasVertexNormals = false;
this.scheme = void 0;
this.lastResource = void 0;
this.layerJsonResource = void 0;
this.previousError = void 0;
this.availability = void 0;
this.tilingScheme = void 0;
this.levelZeroMaximumGeometricError = void 0;
this.heightmapStructure = void 0;
this.layers = [];
this.attribution = "";
this.overallAvailability = [];
this.overallMaxZoom = 0;
this.tileCredits = [];
}
TerrainProviderBuilder.prototype.build = function(provider) {
provider._heightmapWidth = this.heightmapWidth;
provider._scheme = this.scheme;
const credits = defined_default(this.lastResource.credits) ? this.lastResource.credits : [];
provider._tileCredits = credits.concat(this.tileCredits);
provider._availability = this.availability;
provider._tilingScheme = this.tilingScheme;
provider._requestWaterMask = this.requestWaterMask;
provider._levelZeroMaximumGeometricError = this.levelZeroMaximumGeometricError;
provider._heightmapStructure = this.heightmapStructure;
provider._layers = this.layers;
provider._hasWaterMask = this.hasWaterMask;
provider._hasVertexNormals = this.hasVertexNormals;
provider._hasMetadata = this.hasMetadata;
provider._ready = true;
};
async function parseMetadataSuccess(terrainProviderBuilder, data, provider) {
if (!data.format) {
const message = "The tile format is not specified in the layer.json file.";
terrainProviderBuilder.previousError = TileProviderError_default.reportError(
terrainProviderBuilder.previousError,
provider,
defined_default(provider) ? provider._errorEvent : void 0,
message
);
throw new RuntimeError_default(message);
}
if (!data.tiles || data.tiles.length === 0) {
const message = "The layer.json file does not specify any tile URL templates.";
terrainProviderBuilder.previousError = TileProviderError_default.reportError(
terrainProviderBuilder.previousError,
provider,
defined_default(provider) ? provider._errorEvent : void 0,
message
);
throw new RuntimeError_default(message);
}
let hasVertexNormals = false;
let hasWaterMask = false;
let hasMetadata = false;
let littleEndianExtensionSize = true;
let isHeightmap = false;
if (data.format === "heightmap-1.0") {
isHeightmap = true;
if (!defined_default(terrainProviderBuilder.heightmapStructure)) {
terrainProviderBuilder.heightmapStructure = {
heightScale: 1 / 5,
heightOffset: -1e3,
elementsPerHeight: 1,
stride: 1,
elementMultiplier: 256,
isBigEndian: false,
lowestEncodedHeight: 0,
highestEncodedHeight: 256 * 256 - 1
};
}
hasWaterMask = true;
terrainProviderBuilder.requestWaterMask = true;
} else if (data.format.indexOf("quantized-mesh-1.") !== 0) {
const message = `The tile format "${data.format}" is invalid or not supported.`;
terrainProviderBuilder.previousError = TileProviderError_default.reportError(
terrainProviderBuilder.previousError,
provider,
defined_default(provider) ? provider._errorEvent : void 0,
message
);
throw new RuntimeError_default(message);
}
const tileUrlTemplates = data.tiles;
const maxZoom = data.maxzoom;
terrainProviderBuilder.overallMaxZoom = Math.max(
terrainProviderBuilder.overallMaxZoom,
maxZoom
);
if (!data.projection || data.projection === "EPSG:4326") {
terrainProviderBuilder.tilingScheme = new GeographicTilingScheme_default({
numberOfLevelZeroTilesX: 2,
numberOfLevelZeroTilesY: 1,
ellipsoid: terrainProviderBuilder.ellipsoid
});
} else if (data.projection === "EPSG:3857") {
terrainProviderBuilder.tilingScheme = new WebMercatorTilingScheme_default({
numberOfLevelZeroTilesX: 1,
numberOfLevelZeroTilesY: 1,
ellipsoid: terrainProviderBuilder.ellipsoid
});
} else {
const message = `The projection "${data.projection}" is invalid or not supported.`;
terrainProviderBuilder.previousError = TileProviderError_default.reportError(
terrainProviderBuilder.previousError,
provider,
defined_default(provider) ? provider._errorEvent : void 0,
message
);
throw new RuntimeError_default(message);
}
terrainProviderBuilder.levelZeroMaximumGeometricError = TerrainProvider_default.getEstimatedLevelZeroGeometricErrorForAHeightmap(
terrainProviderBuilder.tilingScheme.ellipsoid,
terrainProviderBuilder.heightmapWidth,
terrainProviderBuilder.tilingScheme.getNumberOfXTilesAtLevel(0)
);
if (!data.scheme || data.scheme === "tms" || data.scheme === "slippyMap") {
terrainProviderBuilder.scheme = data.scheme;
} else {
const message = `The scheme "${data.scheme}" is invalid or not supported.`;
terrainProviderBuilder.previousError = TileProviderError_default.reportError(
terrainProviderBuilder.previousError,
provider,
defined_default(provider) ? provider._errorEvent : void 0,
message
);
throw new RuntimeError_default(message);
}
let availabilityTilesLoaded;
if (defined_default(data.extensions) && data.extensions.indexOf("octvertexnormals") !== -1) {
hasVertexNormals = true;
} else if (defined_default(data.extensions) && data.extensions.indexOf("vertexnormals") !== -1) {
hasVertexNormals = true;
littleEndianExtensionSize = false;
}
if (defined_default(data.extensions) && data.extensions.indexOf("watermask") !== -1) {
hasWaterMask = true;
}
if (defined_default(data.extensions) && data.extensions.indexOf("metadata") !== -1) {
hasMetadata = true;
}
const availabilityLevels = data.metadataAvailability;
const availableTiles = data.available;
let availability;
if (defined_default(availableTiles) && !defined_default(availabilityLevels)) {
availability = new TileAvailability_default(
terrainProviderBuilder.tilingScheme,
availableTiles.length
);
for (let level = 0; level < availableTiles.length; ++level) {
const rangesAtLevel = availableTiles[level];
const yTiles = terrainProviderBuilder.tilingScheme.getNumberOfYTilesAtLevel(
level
);
if (!defined_default(terrainProviderBuilder.overallAvailability[level])) {
terrainProviderBuilder.overallAvailability[level] = [];
}
for (let rangeIndex = 0; rangeIndex < rangesAtLevel.length; ++rangeIndex) {
const range = rangesAtLevel[rangeIndex];
const yStart = yTiles - range.endY - 1;
const yEnd = yTiles - range.startY - 1;
terrainProviderBuilder.overallAvailability[level].push([
range.startX,
yStart,
range.endX,
yEnd
]);
availability.addAvailableTileRange(
level,
range.startX,
yStart,
range.endX,
yEnd
);
}
}
} else if (defined_default(availabilityLevels)) {
availabilityTilesLoaded = new TileAvailability_default(
terrainProviderBuilder.tilingScheme,
maxZoom
);
availability = new TileAvailability_default(
terrainProviderBuilder.tilingScheme,
maxZoom
);
terrainProviderBuilder.overallAvailability[0] = [[0, 0, 1, 0]];
availability.addAvailableTileRange(0, 0, 0, 1, 0);
}
terrainProviderBuilder.hasWaterMask = terrainProviderBuilder.hasWaterMask || hasWaterMask;
terrainProviderBuilder.hasVertexNormals = terrainProviderBuilder.hasVertexNormals || hasVertexNormals;
terrainProviderBuilder.hasMetadata = terrainProviderBuilder.hasMetadata || hasMetadata;
if (defined_default(data.attribution)) {
if (terrainProviderBuilder.attribution.length > 0) {
terrainProviderBuilder.attribution += " ";
}
terrainProviderBuilder.attribution += data.attribution;
}
terrainProviderBuilder.layers.push(
new LayerInformation({
resource: terrainProviderBuilder.lastResource,
version: data.version,
isHeightmap,
tileUrlTemplates,
availability,
hasVertexNormals,
hasWaterMask,
hasMetadata,
availabilityLevels,
availabilityTilesLoaded,
littleEndianExtensionSize
})
);
const parentUrl = data.parentUrl;
if (defined_default(parentUrl)) {
if (!defined_default(availability)) {
console.log(
"A layer.json can't have a parentUrl if it does't have an available array."
);
return true;
}
terrainProviderBuilder.lastResource = terrainProviderBuilder.lastResource.getDerivedResource(
{
url: parentUrl
}
);
terrainProviderBuilder.lastResource.appendForwardSlash();
terrainProviderBuilder.layerJsonResource = terrainProviderBuilder.lastResource.getDerivedResource(
{
url: "layer.json"
}
);
await requestLayerJson(terrainProviderBuilder);
return true;
}
return true;
}
function parseMetadataFailure(terrainProviderBuilder, error, provider) {
let message = `An error occurred while accessing ${terrainProviderBuilder.layerJsonResource.url}.`;
if (defined_default(error)) {
message += `
${error.message}`;
}
terrainProviderBuilder.previousError = TileProviderError_default.reportError(
terrainProviderBuilder.previousError,
provider,
defined_default(provider) ? provider._errorEvent : void 0,
message
);
if (terrainProviderBuilder.previousError.retry) {
return requestLayerJson(terrainProviderBuilder, provider);
}
throw new RuntimeError_default(message);
}
async function metadataSuccess4(terrainProviderBuilder, data, provider) {
await parseMetadataSuccess(terrainProviderBuilder, data, provider);
const length3 = terrainProviderBuilder.overallAvailability.length;
if (length3 > 0) {
const availability = terrainProviderBuilder.availability = new TileAvailability_default(
terrainProviderBuilder.tilingScheme,
terrainProviderBuilder.overallMaxZoom
);
for (let level = 0; level < length3; ++level) {
const levelRanges = terrainProviderBuilder.overallAvailability[level];
for (let i = 0; i < levelRanges.length; ++i) {
const range = levelRanges[i];
availability.addAvailableTileRange(
level,
range[0],
range[1],
range[2],
range[3]
);
}
}
}
if (terrainProviderBuilder.attribution.length > 0) {
const layerJsonCredit = new Credit_default(terrainProviderBuilder.attribution);
terrainProviderBuilder.tileCredits.push(layerJsonCredit);
}
return true;
}
async function requestLayerJson(terrainProviderBuilder, provider) {
try {
const data = await terrainProviderBuilder.layerJsonResource.fetchJson();
return metadataSuccess4(terrainProviderBuilder, data, provider);
} catch (error) {
if (defined_default(error) && error.statusCode === 404) {
await parseMetadataSuccess(
terrainProviderBuilder,
{
tilejson: "2.1.0",
format: "heightmap-1.0",
version: "1.0.0",
scheme: "tms",
tiles: ["{z}/{x}/{y}.terrain?v={version}"]
},
provider
);
return true;
}
return parseMetadataFailure(terrainProviderBuilder, error, provider);
}
}
function CesiumTerrainProvider(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this._heightmapWidth = void 0;
this._heightmapStructure = void 0;
this._hasWaterMask = false;
this._hasVertexNormals = false;
this._hasMetadata = false;
this._scheme = void 0;
this._ellipsoid = options.ellipsoid;
this._requestVertexNormals = defaultValue_default(
options.requestVertexNormals,
false
);
this._requestWaterMask = defaultValue_default(options.requestWaterMask, false);
this._requestMetadata = defaultValue_default(options.requestMetadata, true);
this._errorEvent = new Event_default();
let credit = options.credit;
if (typeof credit === "string") {
credit = new Credit_default(credit);
}
this._credit = credit;
this._availability = void 0;
this._tilingScheme = void 0;
this._levelZeroMaximumGeometricError = void 0;
this._layers = void 0;
this._ready = false;
this._tileCredits = void 0;
this._readyPromise = Promise.resolve(true);
if (defined_default(options.url)) {
deprecationWarning_default(
"CesiumTerrainProvider options.url",
"options.url was deprecated in CesiumJS 1.104. It will be in CesiumJS 1.107. Use CesiumTerrainProvider.fromIonAssetId or CesiumTerrainProvider.fromUrl instead."
);
this._readyPromise = CesiumTerrainProvider._initializeReadyPromise(
options,
this
);
}
}
CesiumTerrainProvider._initializeReadyPromise = async function(options, provider) {
const url2 = await Promise.resolve(options.url);
const terrainProviderBuilder = new TerrainProviderBuilder(options);
const resource = Resource_default.createIfNeeded(url2);
resource.appendForwardSlash();
terrainProviderBuilder.lastResource = resource;
terrainProviderBuilder.layerJsonResource = terrainProviderBuilder.lastResource.getDerivedResource(
{
url: "layer.json"
}
);
await requestLayerJson(terrainProviderBuilder, provider);
terrainProviderBuilder.build(provider);
return true;
};
var QuantizedMeshExtensionIds = {
/**
* Oct-Encoded Per-Vertex Normals are included as an extension to the tile mesh
*
* @type {number}
* @constant
* @default 1
*/
OCT_VERTEX_NORMALS: 1,
/**
* A watermask is included as an extension to the tile mesh
*
* @type {number}
* @constant
* @default 2
*/
WATER_MASK: 2,
/**
* A json object contain metadata about the tile
*
* @type {number}
* @constant
* @default 4
*/
METADATA: 4
};
function getRequestHeader(extensionsList) {
if (!defined_default(extensionsList) || extensionsList.length === 0) {
return {
Accept: "application/vnd.quantized-mesh,application/octet-stream;q=0.9,*/*;q=0.01"
};
}
const extensions = extensionsList.join("-");
return {
Accept: `application/vnd.quantized-mesh;extensions=${extensions},application/octet-stream;q=0.9,*/*;q=0.01`
};
}
function createHeightmapTerrainData(provider, buffer, level, x, y) {
const heightBuffer = new Uint16Array(
buffer,
0,
provider._heightmapWidth * provider._heightmapWidth
);
return new HeightmapTerrainData_default({
buffer: heightBuffer,
childTileMask: new Uint8Array(buffer, heightBuffer.byteLength, 1)[0],
waterMask: new Uint8Array(
buffer,
heightBuffer.byteLength + 1,
buffer.byteLength - heightBuffer.byteLength - 1
),
width: provider._heightmapWidth,
height: provider._heightmapWidth,
structure: provider._heightmapStructure,
credits: provider._tileCredits
});
}
function createQuantizedMeshTerrainData(provider, buffer, level, x, y, layer) {
const littleEndianExtensionSize = layer.littleEndianExtensionSize;
let pos = 0;
const cartesian3Elements = 3;
const boundingSphereElements = cartesian3Elements + 1;
const cartesian3Length = Float64Array.BYTES_PER_ELEMENT * cartesian3Elements;
const boundingSphereLength = Float64Array.BYTES_PER_ELEMENT * boundingSphereElements;
const encodedVertexElements = 3;
const encodedVertexLength = Uint16Array.BYTES_PER_ELEMENT * encodedVertexElements;
const triangleElements = 3;
let bytesPerIndex = Uint16Array.BYTES_PER_ELEMENT;
let triangleLength = bytesPerIndex * triangleElements;
const view = new DataView(buffer);
const center = new Cartesian3_default(
view.getFloat64(pos, true),
view.getFloat64(pos + 8, true),
view.getFloat64(pos + 16, true)
);
pos += cartesian3Length;
const minimumHeight = view.getFloat32(pos, true);
pos += Float32Array.BYTES_PER_ELEMENT;
const maximumHeight = view.getFloat32(pos, true);
pos += Float32Array.BYTES_PER_ELEMENT;
const boundingSphere = new BoundingSphere_default(
new Cartesian3_default(
view.getFloat64(pos, true),
view.getFloat64(pos + 8, true),
view.getFloat64(pos + 16, true)
),
view.getFloat64(pos + cartesian3Length, true)
);
pos += boundingSphereLength;
const horizonOcclusionPoint = new Cartesian3_default(
view.getFloat64(pos, true),
view.getFloat64(pos + 8, true),
view.getFloat64(pos + 16, true)
);
pos += cartesian3Length;
const vertexCount = view.getUint32(pos, true);
pos += Uint32Array.BYTES_PER_ELEMENT;
const encodedVertexBuffer = new Uint16Array(buffer, pos, vertexCount * 3);
pos += vertexCount * encodedVertexLength;
if (vertexCount > 64 * 1024) {
bytesPerIndex = Uint32Array.BYTES_PER_ELEMENT;
triangleLength = bytesPerIndex * triangleElements;
}
const uBuffer = encodedVertexBuffer.subarray(0, vertexCount);
const vBuffer = encodedVertexBuffer.subarray(vertexCount, 2 * vertexCount);
const heightBuffer = encodedVertexBuffer.subarray(
vertexCount * 2,
3 * vertexCount
);
AttributeCompression_default.zigZagDeltaDecode(uBuffer, vBuffer, heightBuffer);
if (pos % bytesPerIndex !== 0) {
pos += bytesPerIndex - pos % bytesPerIndex;
}
const triangleCount = view.getUint32(pos, true);
pos += Uint32Array.BYTES_PER_ELEMENT;
const indices2 = IndexDatatype_default.createTypedArrayFromArrayBuffer(
vertexCount,
buffer,
pos,
triangleCount * triangleElements
);
pos += triangleCount * triangleLength;
let highest = 0;
const length3 = indices2.length;
for (let i = 0; i < length3; ++i) {
const code = indices2[i];
indices2[i] = highest - code;
if (code === 0) {
++highest;
}
}
const westVertexCount = view.getUint32(pos, true);
pos += Uint32Array.BYTES_PER_ELEMENT;
const westIndices = IndexDatatype_default.createTypedArrayFromArrayBuffer(
vertexCount,
buffer,
pos,
westVertexCount
);
pos += westVertexCount * bytesPerIndex;
const southVertexCount = view.getUint32(pos, true);
pos += Uint32Array.BYTES_PER_ELEMENT;
const southIndices = IndexDatatype_default.createTypedArrayFromArrayBuffer(
vertexCount,
buffer,
pos,
southVertexCount
);
pos += southVertexCount * bytesPerIndex;
const eastVertexCount = view.getUint32(pos, true);
pos += Uint32Array.BYTES_PER_ELEMENT;
const eastIndices = IndexDatatype_default.createTypedArrayFromArrayBuffer(
vertexCount,
buffer,
pos,
eastVertexCount
);
pos += eastVertexCount * bytesPerIndex;
const northVertexCount = view.getUint32(pos, true);
pos += Uint32Array.BYTES_PER_ELEMENT;
const northIndices = IndexDatatype_default.createTypedArrayFromArrayBuffer(
vertexCount,
buffer,
pos,
northVertexCount
);
pos += northVertexCount * bytesPerIndex;
let encodedNormalBuffer;
let waterMaskBuffer;
while (pos < view.byteLength) {
const extensionId = view.getUint8(pos, true);
pos += Uint8Array.BYTES_PER_ELEMENT;
const extensionLength = view.getUint32(pos, littleEndianExtensionSize);
pos += Uint32Array.BYTES_PER_ELEMENT;
if (extensionId === QuantizedMeshExtensionIds.OCT_VERTEX_NORMALS && provider._requestVertexNormals) {
encodedNormalBuffer = new Uint8Array(buffer, pos, vertexCount * 2);
} else if (extensionId === QuantizedMeshExtensionIds.WATER_MASK && provider._requestWaterMask) {
waterMaskBuffer = new Uint8Array(buffer, pos, extensionLength);
} else if (extensionId === QuantizedMeshExtensionIds.METADATA && provider._requestMetadata) {
const stringLength = view.getUint32(pos, true);
if (stringLength > 0) {
const metadata = getJsonFromTypedArray_default(
new Uint8Array(buffer),
pos + Uint32Array.BYTES_PER_ELEMENT,
stringLength
);
const availableTiles = metadata.available;
if (defined_default(availableTiles)) {
for (let offset2 = 0; offset2 < availableTiles.length; ++offset2) {
const availableLevel = level + offset2 + 1;
const rangesAtLevel = availableTiles[offset2];
const yTiles = provider._tilingScheme.getNumberOfYTilesAtLevel(
availableLevel
);
for (let rangeIndex = 0; rangeIndex < rangesAtLevel.length; ++rangeIndex) {
const range = rangesAtLevel[rangeIndex];
const yStart = yTiles - range.endY - 1;
const yEnd = yTiles - range.startY - 1;
provider.availability.addAvailableTileRange(
availableLevel,
range.startX,
yStart,
range.endX,
yEnd
);
layer.availability.addAvailableTileRange(
availableLevel,
range.startX,
yStart,
range.endX,
yEnd
);
}
}
}
}
layer.availabilityTilesLoaded.addAvailableTileRange(level, x, y, x, y);
}
pos += extensionLength;
}
const skirtHeight = provider.getLevelMaximumGeometricError(level) * 5;
const rectangle = provider._tilingScheme.tileXYToRectangle(x, y, level);
const orientedBoundingBox = OrientedBoundingBox_default.fromRectangle(
rectangle,
minimumHeight,
maximumHeight,
provider._tilingScheme.ellipsoid
);
return new QuantizedMeshTerrainData_default({
center,
minimumHeight,
maximumHeight,
boundingSphere,
orientedBoundingBox,
horizonOcclusionPoint,
quantizedVertices: encodedVertexBuffer,
encodedNormals: encodedNormalBuffer,
indices: indices2,
westIndices,
southIndices,
eastIndices,
northIndices,
westSkirtHeight: skirtHeight,
southSkirtHeight: skirtHeight,
eastSkirtHeight: skirtHeight,
northSkirtHeight: skirtHeight,
childTileMask: provider.availability.computeChildMaskForTile(level, x, y),
waterMask: waterMaskBuffer,
credits: provider._tileCredits
});
}
CesiumTerrainProvider.prototype.requestTileGeometry = function(x, y, level, request) {
const layers = this._layers;
let layerToUse;
const layerCount = layers.length;
if (layerCount === 1) {
layerToUse = layers[0];
} else {
for (let i = 0; i < layerCount; ++i) {
const layer = layers[i];
if (!defined_default(layer.availability) || layer.availability.isTileAvailable(level, x, y)) {
layerToUse = layer;
break;
}
}
}
return requestTileGeometry2(this, x, y, level, layerToUse, request);
};
function requestTileGeometry2(provider, x, y, level, layerToUse, request) {
if (!defined_default(layerToUse)) {
return Promise.reject(new RuntimeError_default("Terrain tile doesn't exist"));
}
const urlTemplates = layerToUse.tileUrlTemplates;
if (urlTemplates.length === 0) {
return void 0;
}
let terrainY;
if (!provider._scheme || provider._scheme === "tms") {
const yTiles = provider._tilingScheme.getNumberOfYTilesAtLevel(level);
terrainY = yTiles - y - 1;
} else {
terrainY = y;
}
const extensionList = [];
if (provider._requestVertexNormals && layerToUse.hasVertexNormals) {
extensionList.push(
layerToUse.littleEndianExtensionSize ? "octvertexnormals" : "vertexnormals"
);
}
if (provider._requestWaterMask && layerToUse.hasWaterMask) {
extensionList.push("watermask");
}
if (provider._requestMetadata && layerToUse.hasMetadata) {
extensionList.push("metadata");
}
let headers;
let query;
const url2 = urlTemplates[(x + terrainY + level) % urlTemplates.length];
const resource = layerToUse.resource;
if (defined_default(resource._ionEndpoint) && !defined_default(resource._ionEndpoint.externalType)) {
if (extensionList.length !== 0) {
query = { extensions: extensionList.join("-") };
}
headers = getRequestHeader(void 0);
} else {
headers = getRequestHeader(extensionList);
}
const promise = resource.getDerivedResource({
url: url2,
templateValues: {
version: layerToUse.version,
z: level,
x,
y: terrainY
},
queryParameters: query,
headers,
request
}).fetchArrayBuffer();
if (!defined_default(promise)) {
return void 0;
}
return promise.then(function(buffer) {
if (!defined_default(buffer)) {
return Promise.reject(new RuntimeError_default("Mesh buffer doesn't exist."));
}
if (defined_default(provider._heightmapStructure)) {
return createHeightmapTerrainData(provider, buffer, level, x, y);
}
return createQuantizedMeshTerrainData(
provider,
buffer,
level,
x,
y,
layerToUse
);
});
}
Object.defineProperties(CesiumTerrainProvider.prototype, {
/**
* Gets an event that is raised when the terrain provider encounters an asynchronous error. By subscribing
* to the event, you will be notified of the error and can potentially recover from it. Event listeners
* are passed an instance of {@link TileProviderError}.
* @memberof CesiumTerrainProvider.prototype
* @type {Event}
* @readonly
*/
errorEvent: {
get: function() {
return this._errorEvent;
}
},
/**
* Gets the credit to display when this terrain provider is active. Typically this is used to credit
* the source of the terrain.
* @memberof CesiumTerrainProvider.prototype
* @type {Credit}
* @readonly
*/
credit: {
get: function() {
return this._credit;
}
},
/**
* Gets the tiling scheme used by this provider.
* @memberof CesiumTerrainProvider.prototype
* @type {GeographicTilingScheme}
* @readonly
*/
tilingScheme: {
get: function() {
return this._tilingScheme;
}
},
/**
* Gets a value indicating whether or not the provider is ready for use.
* @memberof CesiumTerrainProvider.prototype
* @type {boolean}
* @readonly
* @deprecated
*/
ready: {
get: function() {
deprecationWarning_default(
"CesiumTerrainProvider.ready",
"CesiumTerrainProvider.ready was deprecated in CesiumJS 1.104. It will be in CesiumJS 1.107. Use CesiumTerrainProvider.fromIonAssetId or CesiumTerrainProvider.fromUrl instead."
);
return this._ready;
}
},
/**
* Gets a promise that resolves to true when the provider is ready for use.
* @memberof CesiumTerrainProvider.prototype
* @type {Promiseundefined
if no frame is being rendered.
*
* @memberof TimeDynamicPointCloud.prototype
*
* @type {BoundingSphere}
* @readonly
*/
boundingSphere: {
get: function() {
if (defined_default(this._lastRenderedFrame)) {
return this._lastRenderedFrame.pointCloud.boundingSphere;
}
return void 0;
}
},
/**
* Gets the promise that will be resolved when the point cloud renders a frame for the first time.
*
* @memberof TimeDynamicPointCloud.prototype
*
* @type {Promise