/**
* @license
* Cesium - https://github.com/CesiumGS/cesium
* Version 1.144.0
*
* 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 __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 __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
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 Error('Dynamic require of "' + x + '" is not supported');
});
var __commonJS = (cb, mod) => function __require2() {
try {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
} catch (e) {
throw mod = 0, e;
}
};
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 = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __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 || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
// node_modules/mersenne-twister/src/mersenne-twister.js
var require_mersenne_twister = __commonJS({
"node_modules/mersenne-twister/src/mersenne-twister.js"(exports, module) {
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(s2) {
this.mt[0] = s2 >>> 0;
for (this.mti = 1; this.mti < this.N; this.mti++) {
var s2 = this.mt[this.mti - 1] ^ this.mt[this.mti - 1] >>> 30;
this.mt[this.mti] = (((s2 & 4294901760) >>> 16) * 1812433253 << 16) + (s2 & 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 s2 = this.mt[i - 1] ^ this.mt[i - 1] >>> 30;
this.mt[i] = (this.mt[i] ^ (((s2 & 4294901760) >>> 16) * 1664525 << 16) + (s2 & 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 s2 = this.mt[i - 1] ^ this.mt[i - 1] >>> 30;
this.mt[i] = (this.mt[i] ^ (((s2 & 4294901760) >>> 16) * 1566083941 << 16) + (s2 & 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);
};
module.exports = MersenneTwister4;
}
});
// node_modules/urijs/src/punycode.js
var require_punycode = __commonJS({
"node_modules/urijs/src/punycode.js"(exports, module) {
/*! https://mths.be/punycode v1.4.0 by @mathias */
(function(root) {
var freeExports = typeof exports == "object" && exports && !exports.nodeType && exports;
var freeModule = typeof module == "object" && module && !module.nodeType && module;
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 length2 = array.length;
var result = [];
while (length2--) {
result[length2] = fn(array[length2]);
}
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, length2 = string.length, value, extra;
while (counter < length2) {
value = string.charCodeAt(counter++);
if (value >= 55296 && value <= 56319 && counter < length2) {
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, n2 = initialN, bias = initialBias, basic, j, index, oldi, w, k, digit, t2, 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;
t2 = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
if (digit < t2) {
break;
}
baseMinusT = base - t2;
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 - n2) {
error("overflow");
}
n2 += floor(i / out);
i %= out;
output.splice(i++, 0, n2);
}
return ucs2encode(output);
}
function encode(input) {
var n2, delta, handledCPCount, basicLength, bias, j, m, q, k, t2, currentValue, output = [], inputLength, handledCPCountPlusOne, baseMinusT, qMinusT;
input = ucs2decode(input);
inputLength = input.length;
n2 = 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 >= n2 && currentValue < m) {
m = currentValue;
}
}
handledCPCountPlusOne = handledCPCount + 1;
if (m - n2 > floor((maxInt - delta) / handledCPCountPlusOne)) {
error("overflow");
}
delta += (m - n2) * handledCPCountPlusOne;
n2 = m;
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < n2 && ++delta > maxInt) {
error("overflow");
}
if (currentValue == n2) {
for (q = delta, k = base; ; k += base) {
t2 = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
if (q < t2) {
break;
}
qMinusT = q - t2;
baseMinusT = base - t2;
output.push(
stringFromCharCode(digitToBasic(t2 + qMinusT % baseMinusT, 0))
);
q = floor(qMinusT / baseMinusT);
}
output.push(stringFromCharCode(digitToBasic(q, 0)));
bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
delta = 0;
++handledCPCount;
}
}
++delta;
++n2;
}
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
* Returns a diagonal matrix and unitary matrix such that:
*
* The values along the diagonal of the diagonal matrix are the eigenvalues. The columns
* of the unitary matrix are the corresponding eigenvectors.
*
* 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 {@MaterialStageFS}\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 *
* true if they are equal, false otherwise.
*
* @param {Cartesian3} [left] The first Cartesian.
* @param {Cartesian3} [right] The second Cartesian.
* @returns {boolean} true if left and right are equal, false otherwise.
*/
static equals(left, right) {
return left === right || defined_default(left) && defined_default(right) && left.x === right.x && left.y === right.y && left.z === right.z;
}
/**
* @param {Cartesian3} cartesian
* @param {number[]} array
* @param {number} offset
* @ignore
*/
static equalsArray(cartesian11, array, offset) {
return cartesian11.x === array[offset] && cartesian11.y === array[offset + 1] && cartesian11.z === array[offset + 2];
}
/**
* Compares the provided Cartesians componentwise and returns
* true if they pass an absolute or relative tolerance test,
* false otherwise.
*
* @param {Cartesian3} [left] The first Cartesian.
* @param {Cartesian3} [right] The second Cartesian.
* @param {number} [relativeEpsilon=0] The relative epsilon tolerance to use for equality testing.
* @param {number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
* @returns {boolean} true if left and right are within the provided epsilon, false otherwise.
*/
static equalsEpsilon(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
) && Math_default.equalsEpsilon(
left.z,
right.z,
relativeEpsilon,
absoluteEpsilon
);
}
/**
* Computes the cross (outer) product of two Cartesians.
*
* @param {Cartesian3} left The first Cartesian.
* @param {Cartesian3} right The second Cartesian.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The cross product.
*/
static cross(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 rightX = right.x;
const rightY = right.y;
const rightZ = right.z;
const x = leftY * rightZ - leftZ * rightY;
const y = leftZ * rightX - leftX * rightZ;
const z2 = leftX * rightY - leftY * rightX;
result.x = x;
result.y = y;
result.z = z2;
return result;
}
/**
* Computes the midpoint between the right and left Cartesian.
* @param {Cartesian3} left The first Cartesian.
* @param {Cartesian3} right The second Cartesian.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The midpoint.
*/
static midpoint(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) * 0.5;
result.y = (left.y + right.y) * 0.5;
result.z = (left.z + right.z) * 0.5;
return result;
}
/**
* Returns a Cartesian3 position from longitude and latitude values given in degrees.
*
* @param {number} longitude The longitude, in degrees
* @param {number} latitude The latitude, in degrees
* @param {number} [height=0.0] The height, in meters, above the ellipsoid.
* @param {Ellipsoid} [ellipsoid=Ellipsoid.default] The ellipsoid on which the position lies.
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The position
*
* @example
* const position = Cesium.Cartesian3.fromDegrees(-115.0, 37.0);
*/
static fromDegrees(longitude, latitude, height, ellipsoid, result) {
Check_default.typeOf.number("longitude", longitude);
Check_default.typeOf.number("latitude", latitude);
longitude = Math_default.toRadians(longitude);
latitude = Math_default.toRadians(latitude);
return _Cartesian3.fromRadians(
longitude,
latitude,
height,
ellipsoid,
result
);
}
/**
* Returns a Cartesian3 position from longitude and latitude values given in radians.
*
* @param {number} longitude The longitude, in radians
* @param {number} latitude The latitude, in radians
* @param {number} [height=0.0] The height, in meters, above the ellipsoid.
* @param {Ellipsoid} [ellipsoid=Ellipsoid.default] The ellipsoid on which the position lies.
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The position
*
* @example
* const position = Cesium.Cartesian3.fromRadians(-2.007, 0.645);
*/
static fromRadians(longitude, latitude, height, ellipsoid, result) {
Check_default.typeOf.number("longitude", longitude);
Check_default.typeOf.number("latitude", latitude);
height = height ?? 0;
const radiiSquared = !defined_default(ellipsoid) ? _Cartesian3._ellipsoidRadiiSquared : ellipsoid.radiiSquared;
const cosLatitude = Math.cos(latitude);
scratchN.x = cosLatitude * Math.cos(longitude);
scratchN.y = cosLatitude * Math.sin(longitude);
scratchN.z = Math.sin(latitude);
scratchN = _Cartesian3.normalize(scratchN, scratchN);
_Cartesian3.multiplyComponents(radiiSquared, scratchN, scratchK);
const gamma = Math.sqrt(_Cartesian3.dot(scratchN, scratchK));
scratchK = _Cartesian3.divideByScalar(scratchK, gamma, scratchK);
scratchN = _Cartesian3.multiplyByScalar(scratchN, height, scratchN);
if (!defined_default(result)) {
result = new _Cartesian3();
}
return _Cartesian3.add(scratchK, scratchN, result);
}
/**
* Returns an array of Cartesian3 positions given an array of longitude and latitude values given in degrees.
*
* @param {number[]} coordinates A list of longitude and latitude values. Values alternate [longitude, latitude, longitude, latitude...].
* @param {Ellipsoid} [ellipsoid=Ellipsoid.default] The ellipsoid on which the coordinates lie.
* @param {Cartesian3[]} [result] An array of Cartesian3 objects to store the result.
* @returns {Cartesian3[]} The array of positions.
*
* @example
* const positions = Cesium.Cartesian3.fromDegreesArray([-115.0, 37.0, -107.0, 33.0]);
*/
static fromDegreesArray(coordinates, ellipsoid, result) {
Check_default.defined("coordinates", coordinates);
if (coordinates.length < 2 || coordinates.length % 2 !== 0) {
throw new DeveloperError_default(
"the number of coordinates must be a multiple of 2 and at least 2"
);
}
const length2 = coordinates.length;
if (!defined_default(result)) {
result = new Array(length2 / 2);
} else {
result.length = length2 / 2;
}
for (let i = 0; i < length2; i += 2) {
const longitude = coordinates[i];
const latitude = coordinates[i + 1];
const index = i / 2;
result[index] = _Cartesian3.fromDegrees(
longitude,
latitude,
0,
ellipsoid,
result[index]
);
}
return result;
}
/**
* Returns an array of Cartesian3 positions given an array of longitude and latitude values given in radians.
*
* @param {number[]} coordinates A list of longitude and latitude values. Values alternate [longitude, latitude, longitude, latitude...].
* @param {Ellipsoid} [ellipsoid=Ellipsoid.default] The ellipsoid on which the coordinates lie.
* @param {Cartesian3[]} [result] An array of Cartesian3 objects to store the result.
* @returns {Cartesian3[]} The array of positions.
*
* @example
* const positions = Cesium.Cartesian3.fromRadiansArray([-2.007, 0.645, -1.867, .575]);
*/
static fromRadiansArray(coordinates, ellipsoid, result) {
Check_default.defined("coordinates", coordinates);
if (coordinates.length < 2 || coordinates.length % 2 !== 0) {
throw new DeveloperError_default(
"the number of coordinates must be a multiple of 2 and at least 2"
);
}
const length2 = coordinates.length;
if (!defined_default(result)) {
result = new Array(length2 / 2);
} else {
result.length = length2 / 2;
}
for (let i = 0; i < length2; i += 2) {
const longitude = coordinates[i];
const latitude = coordinates[i + 1];
const index = i / 2;
result[index] = _Cartesian3.fromRadians(
longitude,
latitude,
0,
ellipsoid,
result[index]
);
}
return result;
}
/**
* Returns an array of Cartesian3 positions given an array of longitude, latitude and height values where longitude and latitude are given in degrees.
*
* @param {number[]} coordinates A list of longitude, latitude and height values. Values alternate [longitude, latitude, height, longitude, latitude, height...].
* @param {Ellipsoid} [ellipsoid=Ellipsoid.default] The ellipsoid on which the position lies.
* @param {Cartesian3[]} [result] An array of Cartesian3 objects to store the result.
* @returns {Cartesian3[]} The array of positions.
*
* @example
* const positions = Cesium.Cartesian3.fromDegreesArrayHeights([-115.0, 37.0, 100000.0, -107.0, 33.0, 150000.0]);
*/
static fromDegreesArrayHeights(coordinates, ellipsoid, result) {
Check_default.defined("coordinates", coordinates);
if (coordinates.length < 3 || coordinates.length % 3 !== 0) {
throw new DeveloperError_default(
"the number of coordinates must be a multiple of 3 and at least 3"
);
}
const length2 = coordinates.length;
if (!defined_default(result)) {
result = new Array(length2 / 3);
} else {
result.length = length2 / 3;
}
for (let i = 0; i < length2; i += 3) {
const longitude = coordinates[i];
const latitude = coordinates[i + 1];
const height = coordinates[i + 2];
const index = i / 3;
result[index] = _Cartesian3.fromDegrees(
longitude,
latitude,
height,
ellipsoid,
result[index]
);
}
return result;
}
/**
* Returns an array of Cartesian3 positions given an array of longitude, latitude and height values where longitude and latitude are given in radians.
*
* @param {number[]} coordinates A list of longitude, latitude and height values. Values alternate [longitude, latitude, height, longitude, latitude, height...].
* @param {Ellipsoid} [ellipsoid=Ellipsoid.default] The ellipsoid on which the position lies.
* @param {Cartesian3[]} [result] An array of Cartesian3 objects to store the result.
* @returns {Cartesian3[]} The array of positions.
*
* @example
* const positions = Cesium.Cartesian3.fromRadiansArrayHeights([-2.007, 0.645, 100000.0, -1.867, .575, 150000.0]);
*/
static fromRadiansArrayHeights(coordinates, ellipsoid, result) {
Check_default.defined("coordinates", coordinates);
if (coordinates.length < 3 || coordinates.length % 3 !== 0) {
throw new DeveloperError_default(
"the number of coordinates must be a multiple of 3 and at least 3"
);
}
const length2 = coordinates.length;
if (!defined_default(result)) {
result = new Array(length2 / 3);
} else {
result.length = length2 / 3;
}
for (let i = 0; i < length2; i += 3) {
const longitude = coordinates[i];
const latitude = coordinates[i + 1];
const height = coordinates[i + 2];
const index = i / 3;
result[index] = _Cartesian3.fromRadians(
longitude,
latitude,
height,
ellipsoid,
result[index]
);
}
return result;
}
/**
* Duplicates this Cartesian3 instance.
*
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
*/
clone(result) {
return _Cartesian3.clone(this, result);
}
/**
* Compares this Cartesian against the provided Cartesian componentwise and returns
* true if they are equal, false otherwise.
*
* @param {Cartesian3} [right] The right hand side Cartesian.
* @returns {boolean} true if they are equal, false otherwise.
*/
equals(right) {
return _Cartesian3.equals(this, right);
}
/**
* Compares this Cartesian against the provided Cartesian componentwise and returns
* true if they pass an absolute or relative tolerance test,
* false otherwise.
*
* @param {Cartesian3} [right] The right hand side Cartesian.
* @param {number} [relativeEpsilon=0] The relative epsilon tolerance to use for equality testing.
* @param {number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
* @returns {boolean} true if they are within the provided epsilon, false otherwise.
*/
equalsEpsilon(right, relativeEpsilon, absoluteEpsilon) {
return _Cartesian3.equalsEpsilon(
this,
right,
relativeEpsilon,
absoluteEpsilon
);
}
/**
* Creates a string representing this Cartesian in the format '(x, y, z)'.
*
* @returns {string} A string representing this Cartesian in the format '(x, y, z)'.
*/
toString() {
return `(${this.x}, ${this.y}, ${this.z})`;
}
};
Cartesian3.fromCartesian4 = Cartesian3.clone;
Cartesian3.packedLength = 3;
Cartesian3.fromArray = Cartesian3.unpack;
var distanceScratch = new Cartesian3();
var lerpScratch = new Cartesian3();
var angleBetweenScratch = new Cartesian3();
var angleBetweenScratch2 = new Cartesian3();
var mostOrthogonalAxisScratch = new Cartesian3();
var scratchN = new Cartesian3();
var scratchK = new Cartesian3();
Cartesian3._ellipsoidRadiiSquared = new Cartesian3(
6378137 * 6378137,
6378137 * 6378137,
6356752314245179e-9 * 6356752314245179e-9
);
Cartesian3.ZERO = Object.freeze(new Cartesian3(0, 0, 0));
Cartesian3.ONE = Object.freeze(new Cartesian3(1, 1, 1));
Cartesian3.UNIT_X = Object.freeze(new Cartesian3(1, 0, 0));
Cartesian3.UNIT_Y = Object.freeze(new Cartesian3(0, 1, 0));
Cartesian3.UNIT_Z = Object.freeze(new Cartesian3(0, 0, 1));
var Cartesian3_default = Cartesian3;
// packages/engine/Source/Core/Cartesian4.js
var Cartesian4 = class _Cartesian4 {
/**
* @param {number} [x=0.0] The X component.
* @param {number} [y=0.0] The Y component.
* @param {number} [z=0.0] The Z component.
* @param {number} [w=0.0] The W component.
*/
constructor(x, y, z2, w) {
this.x = x ?? 0;
this.y = y ?? 0;
this.z = z2 ?? 0;
this.w = w ?? 0;
}
/**
* Creates a Cartesian4 instance from x, y, z and w coordinates.
*
* @param {number} x The x coordinate.
* @param {number} y The y coordinate.
* @param {number} z The z coordinate.
* @param {number} w The w coordinate.
* @param {Cartesian4} [result] The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
*/
static fromElements(x, y, z2, w, result) {
if (!defined_default(result)) {
return new _Cartesian4(x, y, z2, w);
}
result.x = x;
result.y = y;
result.z = z2;
result.w = w;
return result;
}
/**
* Creates a Cartesian4 instance from a {@link Color}. red, green, blue,
* and alpha map to x, y, z, and w, respectively.
*
* @param {Color} color The source color.
* @param {Cartesian4} [result] The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
*/
static fromColor(color, result) {
Check_default.typeOf.object("color", color);
if (!defined_default(result)) {
return new _Cartesian4(color.red, color.green, color.blue, color.alpha);
}
result.x = color.red;
result.y = color.green;
result.z = color.blue;
result.w = color.alpha;
return result;
}
/**
* Duplicates a Cartesian4 instance.
*
* @param {Cartesian4} cartesian The Cartesian to duplicate.
* @param {Cartesian4} [result] The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided. (Returns undefined if cartesian is undefined)
*/
static clone(cartesian11, result) {
if (!defined_default(cartesian11)) {
return void 0;
}
if (!defined_default(result)) {
return new _Cartesian4(cartesian11.x, cartesian11.y, cartesian11.z, cartesian11.w);
}
result.x = cartesian11.x;
result.y = cartesian11.y;
result.z = cartesian11.z;
result.w = cartesian11.w;
return result;
}
/**
* Stores the provided instance into the provided array.
*
* @param {Cartesian4} value The value to pack.
* @param {number[]} array The array to pack into.
* @param {number} [startingIndex=0] The index into the array at which to start packing the elements.
*
* @returns {number[]} The array that was packed into
*/
static pack(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
Check_default.defined("array", array);
startingIndex = startingIndex ?? 0;
array[startingIndex++] = value.x;
array[startingIndex++] = value.y;
array[startingIndex++] = value.z;
array[startingIndex] = value.w;
return array;
}
/**
* Retrieves an instance from a packed array.
*
* @param {number[]} array The packed array.
* @param {number} [startingIndex=0] The starting index of the element to be unpacked.
* @param {Cartesian4} [result] The object into which to store the result.
* @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
*/
static unpack(array, startingIndex, result) {
Check_default.defined("array", array);
startingIndex = startingIndex ?? 0;
if (!defined_default(result)) {
result = new _Cartesian4();
}
result.x = array[startingIndex++];
result.y = array[startingIndex++];
result.z = array[startingIndex++];
result.w = array[startingIndex];
return result;
}
/**
* Flattens an array of Cartesian4s into an array of components.
*
* @param {Cartesian4[]} array The array of cartesians to pack.
* @param {number[]} [result] The array onto which to store the result. If this is a typed array, it must have array.length * 4 components, else a {@link DeveloperError} will be thrown. If it is a regular array, it will be resized to have (array.length * 4) elements.
* @returns {number[]} The packed array.
*/
static packArray(array, result) {
Check_default.defined("array", array);
const length2 = array.length;
const resultLength = length2 * 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 < length2; ++i) {
_Cartesian4.pack(array[i], result, i * 4);
}
return result;
}
/**
* Unpacks an array of cartesian components into an array of Cartesian4s.
*
* @param {number[]} array The array of components to unpack.
* @param {Cartesian4[]} [result] The array onto which to store the result.
* @returns {Cartesian4[]} The unpacked array.
*/
static unpackArray(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 length2 = array.length;
if (!defined_default(result)) {
result = new Array(length2 / 4);
} else {
result.length = length2 / 4;
}
for (let i = 0; i < length2; i += 4) {
const index = i / 4;
result[index] = _Cartesian4.unpack(array, i, result[index]);
}
return result;
}
/**
* Computes the value of the maximum component for the supplied Cartesian.
*
* @param {Cartesian4} cartesian The cartesian to use.
* @returns {number} The value of the maximum component.
*/
static maximumComponent(cartesian11) {
Check_default.typeOf.object("cartesian", cartesian11);
return Math.max(cartesian11.x, cartesian11.y, cartesian11.z, cartesian11.w);
}
/**
* Computes the value of the minimum component for the supplied Cartesian.
*
* @param {Cartesian4} cartesian The cartesian to use.
* @returns {number} The value of the minimum component.
*/
static minimumComponent(cartesian11) {
Check_default.typeOf.object("cartesian", cartesian11);
return Math.min(cartesian11.x, cartesian11.y, cartesian11.z, cartesian11.w);
}
/**
* Compares two Cartesians and computes a Cartesian which contains the minimum components of the supplied Cartesians.
*
* @param {Cartesian4} first A cartesian to compare.
* @param {Cartesian4} second A cartesian to compare.
* @param {Cartesian4} result The object into which to store the result.
* @returns {Cartesian4} A cartesian with the minimum components.
*/
static minimumByComponent(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);
result.z = Math.min(first.z, second.z);
result.w = Math.min(first.w, second.w);
return result;
}
/**
* Compares two Cartesians and computes a Cartesian which contains the maximum components of the supplied Cartesians.
*
* @param {Cartesian4} first A cartesian to compare.
* @param {Cartesian4} second A cartesian to compare.
* @param {Cartesian4} result The object into which to store the result.
* @returns {Cartesian4} A cartesian with the maximum components.
*/
static maximumByComponent(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);
result.z = Math.max(first.z, second.z);
result.w = Math.max(first.w, second.w);
return result;
}
/**
* Constrain a value to lie between two values.
*
* @param {Cartesian4} value The value to clamp.
* @param {Cartesian4} min The minimum bound.
* @param {Cartesian4} max The maximum bound.
* @param {Cartesian4} result The object into which to store the result.
* @returns {Cartesian4} The clamped value such that min <= result <= max.
*/
static clamp(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);
const z2 = Math_default.clamp(value.z, min3.z, max3.z);
const w = Math_default.clamp(value.w, min3.w, max3.w);
result.x = x;
result.y = y;
result.z = z2;
result.w = w;
return result;
}
/**
* Computes the provided Cartesian's squared magnitude.
*
* @param {Cartesian4} cartesian The Cartesian instance whose squared magnitude is to be computed.
* @returns {number} The squared magnitude.
*/
static magnitudeSquared(cartesian11) {
Check_default.typeOf.object("cartesian", cartesian11);
return cartesian11.x * cartesian11.x + cartesian11.y * cartesian11.y + cartesian11.z * cartesian11.z + cartesian11.w * cartesian11.w;
}
/**
* Computes the Cartesian's magnitude (length).
*
* @param {Cartesian4} cartesian The Cartesian instance whose magnitude is to be computed.
* @returns {number} The magnitude.
*/
static magnitude(cartesian11) {
return Math.sqrt(_Cartesian4.magnitudeSquared(cartesian11));
}
/**
* Computes the 4-space distance between two points.
*
* @param {Cartesian4} left The first point to compute the distance from.
* @param {Cartesian4} right The second point to compute the distance to.
* @returns {number} The distance between two points.
*
* @example
* // Returns 1.0
* const d = Cesium.Cartesian4.distance(
* new Cesium.Cartesian4(1.0, 0.0, 0.0, 0.0),
* new Cesium.Cartesian4(2.0, 0.0, 0.0, 0.0));
*/
static distance(left, right) {
Check_default.typeOf.object("left", left);
Check_default.typeOf.object("right", right);
_Cartesian4.subtract(left, right, distanceScratch2);
return _Cartesian4.magnitude(distanceScratch2);
}
/**
* Computes the squared distance between two points. Comparing squared distances
* using this function is more efficient than comparing distances using {@link Cartesian4#distance}.
*
* @param {Cartesian4} left The first point to compute the distance from.
* @param {Cartesian4} right The second point to compute the distance to.
* @returns {number} The distance between two points.
*
* @example
* // Returns 4.0, not 2.0
* const d = Cesium.Cartesian4.distance(
* new Cesium.Cartesian4(1.0, 0.0, 0.0, 0.0),
* new Cesium.Cartesian4(3.0, 0.0, 0.0, 0.0));
*/
static distanceSquared(left, right) {
Check_default.typeOf.object("left", left);
Check_default.typeOf.object("right", right);
_Cartesian4.subtract(left, right, distanceScratch2);
return _Cartesian4.magnitudeSquared(distanceScratch2);
}
/**
* Computes the normalized form of the supplied Cartesian.
*
* @param {Cartesian4} cartesian The Cartesian to be normalized.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*/
static normalize(cartesian11, result) {
Check_default.typeOf.object("cartesian", cartesian11);
Check_default.typeOf.object("result", result);
const magnitude = _Cartesian4.magnitude(cartesian11);
result.x = cartesian11.x / magnitude;
result.y = cartesian11.y / magnitude;
result.z = cartesian11.z / magnitude;
result.w = cartesian11.w / magnitude;
if (isNaN(result.x) || isNaN(result.y) || isNaN(result.z) || isNaN(result.w)) {
throw new DeveloperError_default("normalized result is not a number");
}
return result;
}
/**
* Computes the dot (scalar) product of two Cartesians.
*
* @param {Cartesian4} left The first Cartesian.
* @param {Cartesian4} right The second Cartesian.
* @returns {number} The dot product.
*/
static dot(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;
}
/**
* Computes the componentwise product of two Cartesians.
*
* @param {Cartesian4} left The first Cartesian.
* @param {Cartesian4} right The second Cartesian.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*/
static multiplyComponents(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;
}
/**
* Computes the componentwise quotient of two Cartesians.
*
* @param {Cartesian4} left The first Cartesian.
* @param {Cartesian4} right The second Cartesian.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*/
static divideComponents(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;
}
/**
* Computes the componentwise sum of two Cartesians.
*
* @param {Cartesian4} left The first Cartesian.
* @param {Cartesian4} right The second Cartesian.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*/
static add(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;
}
/**
* Computes the componentwise difference of two Cartesians.
*
* @param {Cartesian4} left The first Cartesian.
* @param {Cartesian4} right The second Cartesian.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*/
static subtract(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;
}
/**
* Multiplies the provided Cartesian componentwise by the provided scalar.
*
* @param {Cartesian4} cartesian The Cartesian to be scaled.
* @param {number} scalar The scalar to multiply with.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*/
static multiplyByScalar(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;
result.z = cartesian11.z * scalar;
result.w = cartesian11.w * scalar;
return result;
}
/**
* Divides the provided Cartesian componentwise by the provided scalar.
*
* @param {Cartesian4} cartesian The Cartesian to be divided.
* @param {number} scalar The scalar to divide by.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*/
static divideByScalar(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;
result.z = cartesian11.z / scalar;
result.w = cartesian11.w / scalar;
return result;
}
/**
* Negates the provided Cartesian.
*
* @param {Cartesian4} cartesian The Cartesian to be negated.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*/
static negate(cartesian11, result) {
Check_default.typeOf.object("cartesian", cartesian11);
Check_default.typeOf.object("result", result);
result.x = -cartesian11.x;
result.y = -cartesian11.y;
result.z = -cartesian11.z;
result.w = -cartesian11.w;
return result;
}
/**
* Computes the absolute value of the provided Cartesian.
*
* @param {Cartesian4} cartesian The Cartesian whose absolute value is to be computed.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*/
static abs(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);
result.z = Math.abs(cartesian11.z);
result.w = Math.abs(cartesian11.w);
return result;
}
/**
* Computes the linear interpolation or extrapolation at t using the provided cartesians.
*
* @param {Cartesian4} start The value corresponding to t at 0.0.
* @param {Cartesian4}end The value corresponding to t at 1.0.
* @param {number} t The point along t at which to interpolate.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*/
static lerp(start, end, t2, result) {
Check_default.typeOf.object("start", start);
Check_default.typeOf.object("end", end);
Check_default.typeOf.number("t", t2);
Check_default.typeOf.object("result", result);
_Cartesian4.multiplyByScalar(end, t2, lerpScratch2);
result = _Cartesian4.multiplyByScalar(start, 1 - t2, result);
return _Cartesian4.add(lerpScratch2, result, result);
}
/**
* Returns the axis that is most orthogonal to the provided Cartesian.
*
* @param {Cartesian4} cartesian The Cartesian on which to find the most orthogonal axis.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The most orthogonal axis.
*/
static mostOrthogonalAxis(cartesian11, result) {
Check_default.typeOf.object("cartesian", cartesian11);
Check_default.typeOf.object("result", result);
const f2 = _Cartesian4.normalize(cartesian11, mostOrthogonalAxisScratch2);
_Cartesian4.abs(f2, f2);
if (f2.x <= f2.y) {
if (f2.x <= f2.z) {
if (f2.x <= f2.w) {
result = _Cartesian4.clone(_Cartesian4.UNIT_X, result);
} else {
result = _Cartesian4.clone(_Cartesian4.UNIT_W, result);
}
} else if (f2.z <= f2.w) {
result = _Cartesian4.clone(_Cartesian4.UNIT_Z, result);
} else {
result = _Cartesian4.clone(_Cartesian4.UNIT_W, result);
}
} else if (f2.y <= f2.z) {
if (f2.y <= f2.w) {
result = _Cartesian4.clone(_Cartesian4.UNIT_Y, result);
} else {
result = _Cartesian4.clone(_Cartesian4.UNIT_W, result);
}
} else if (f2.z <= f2.w) {
result = _Cartesian4.clone(_Cartesian4.UNIT_Z, result);
} else {
result = _Cartesian4.clone(_Cartesian4.UNIT_W, result);
}
return result;
}
/**
* Compares the provided Cartesians componentwise and returns
* true if they are equal, false otherwise.
*
* @param {Cartesian4} [left] The first Cartesian.
* @param {Cartesian4} [right] The second Cartesian.
* @returns {boolean} true if left and right are equal, false otherwise.
*/
static equals(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;
}
/**
* @param {Cartesian4} cartesian
* @param {number[]} array
* @param {number} offset
* @ignore
*/
static equalsArray(cartesian11, array, offset) {
return cartesian11.x === array[offset] && cartesian11.y === array[offset + 1] && cartesian11.z === array[offset + 2] && cartesian11.w === array[offset + 3];
}
/**
* Compares the provided Cartesians componentwise and returns
* true if they pass an absolute or relative tolerance test,
* false otherwise.
*
* @param {Cartesian4} [left] The first Cartesian.
* @param {Cartesian4} [right] The second Cartesian.
* @param {number} [relativeEpsilon=0] The relative epsilon tolerance to use for equality testing.
* @param {number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
* @returns {boolean} true if left and right are within the provided epsilon, false otherwise.
*/
static equalsEpsilon(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
) && Math_default.equalsEpsilon(
left.z,
right.z,
relativeEpsilon,
absoluteEpsilon
) && Math_default.equalsEpsilon(
left.w,
right.w,
relativeEpsilon,
absoluteEpsilon
);
}
/**
* Duplicates this Cartesian4 instance.
*
* @param {Cartesian4} [result] The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
*/
clone(result) {
return _Cartesian4.clone(this, result);
}
/**
* Compares this Cartesian against the provided Cartesian componentwise and returns
* true if they are equal, false otherwise.
*
* @param {Cartesian4} [right] The right hand side Cartesian.
* @returns {boolean} true if they are equal, false otherwise.
*/
equals(right) {
return _Cartesian4.equals(this, right);
}
/**
* Compares this Cartesian against the provided Cartesian componentwise and returns
* true if they pass an absolute or relative tolerance test,
* false otherwise.
*
* @param {Cartesian4} [right] The right hand side Cartesian.
* @param {number} [relativeEpsilon=0] The relative epsilon tolerance to use for equality testing.
* @param {number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
* @returns {boolean} true if they are within the provided epsilon, false otherwise.
*/
equalsEpsilon(right, relativeEpsilon, absoluteEpsilon) {
return _Cartesian4.equalsEpsilon(
this,
right,
relativeEpsilon,
absoluteEpsilon
);
}
/**
* Creates a string representing this Cartesian in the format '(x, y, z, w)'.
*
* @returns {string} A string representing the provided Cartesian in the format '(x, y, z, w)'.
*/
toString() {
return `(${this.x}, ${this.y}, ${this.z}, ${this.w})`;
}
/**
* Packs an arbitrary floating point value to 4 values representable using uint8.
*
* @param {number} value A floating point number.
* @param {Cartesian4} [result] The Cartesian4 that will contain the packed float.
* @returns {Cartesian4} A Cartesian4 representing the float packed to values in x, y, z, and w.
*/
static packFloat(value, result) {
Check_default.typeOf.number("value", value);
if (!defined_default(result)) {
result = new _Cartesian4();
}
scratchF32Array[0] = value;
if (littleEndian) {
result.x = scratchU8Array[0];
result.y = scratchU8Array[1];
result.z = scratchU8Array[2];
result.w = scratchU8Array[3];
} else {
result.x = scratchU8Array[3];
result.y = scratchU8Array[2];
result.z = scratchU8Array[1];
result.w = scratchU8Array[0];
}
return result;
}
/**
* Unpacks a float packed using Cartesian4.packFloat.
*
* @param {Cartesian4} packedFloat A Cartesian4 containing a float packed to 4 values representable using uint8.
* @returns {number} The unpacked float.
* @private
*/
static unpackFloat(packedFloat) {
Check_default.typeOf.object("packedFloat", packedFloat);
if (littleEndian) {
scratchU8Array[0] = packedFloat.x;
scratchU8Array[1] = packedFloat.y;
scratchU8Array[2] = packedFloat.z;
scratchU8Array[3] = packedFloat.w;
} else {
scratchU8Array[0] = packedFloat.w;
scratchU8Array[1] = packedFloat.z;
scratchU8Array[2] = packedFloat.y;
scratchU8Array[3] = packedFloat.x;
}
return scratchF32Array[0];
}
};
Cartesian4.packedLength = 4;
Cartesian4.fromArray = Cartesian4.unpack;
var distanceScratch2 = new Cartesian4();
var lerpScratch2 = new Cartesian4();
var mostOrthogonalAxisScratch2 = new Cartesian4();
Cartesian4.ZERO = Object.freeze(new Cartesian4(0, 0, 0, 0));
Cartesian4.ONE = Object.freeze(new Cartesian4(1, 1, 1, 1));
Cartesian4.UNIT_X = Object.freeze(new Cartesian4(1, 0, 0, 0));
Cartesian4.UNIT_Y = Object.freeze(new Cartesian4(0, 1, 0, 0));
Cartesian4.UNIT_Z = Object.freeze(new Cartesian4(0, 0, 1, 0));
Cartesian4.UNIT_W = Object.freeze(new Cartesian4(0, 0, 0, 1));
var scratchF32Array = new Float32Array(1);
var scratchU8Array = new Uint8Array(scratchF32Array.buffer);
var testU32 = new Uint32Array([287454020]);
var testU8 = new Uint8Array(testU32.buffer);
var littleEndian = testU8[0] === 68;
var Cartesian4_default = Cartesian4;
// packages/engine/Source/Core/Frozen.js
var Frozen = {};
Frozen.EMPTY_OBJECT = Object.freeze({});
Frozen.EMPTY_ARRAY = Object.freeze([]);
var Frozen_default = Frozen;
// packages/engine/Source/Core/Matrix3.js
var Matrix3 = class _Matrix3 {
/**
* @param {number} [column0Row0=0.0] The value for column 0, row 0.
* @param {number} [column1Row0=0.0] The value for column 1, row 0.
* @param {number} [column2Row0=0.0] The value for column 2, row 0.
* @param {number} [column0Row1=0.0] The value for column 0, row 1.
* @param {number} [column1Row1=0.0] The value for column 1, row 1.
* @param {number} [column2Row1=0.0] The value for column 2, row 1.
* @param {number} [column0Row2=0.0] The value for column 0, row 2.
* @param {number} [column1Row2=0.0] The value for column 1, row 2.
* @param {number} [column2Row2=0.0] The value for column 2, row 2.
*/
constructor(column0Row0, column1Row0, column2Row0, column0Row1, column1Row1, column2Row1, column0Row2, column1Row2, column2Row2) {
this[0] = column0Row0 ?? 0;
this[1] = column0Row1 ?? 0;
this[2] = column0Row2 ?? 0;
this[3] = column1Row0 ?? 0;
this[4] = column1Row1 ?? 0;
this[5] = column1Row2 ?? 0;
this[6] = column2Row0 ?? 0;
this[7] = column2Row1 ?? 0;
this[8] = column2Row2 ?? 0;
}
/**
* Stores the provided instance into the provided array.
*
* @param {Matrix3} value The value to pack.
* @param {number[]} array The array to pack into.
* @param {number} [startingIndex=0] The index into the array at which to start packing the elements.
*
* @returns {number[]} The array that was packed into
*/
static pack(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
Check_default.defined("array", array);
startingIndex = startingIndex ?? 0;
array[startingIndex++] = value[0];
array[startingIndex++] = value[1];
array[startingIndex++] = value[2];
array[startingIndex++] = value[3];
array[startingIndex++] = value[4];
array[startingIndex++] = value[5];
array[startingIndex++] = value[6];
array[startingIndex++] = value[7];
array[startingIndex] = value[8];
return array;
}
/**
* Retrieves an instance from a packed array.
*
* @param {number[]} array The packed array.
* @param {number} [startingIndex=0] The starting index of the element to be unpacked.
* @param {Matrix3} [result] The object into which to store the result.
* @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided.
*/
static unpack(array, startingIndex, result) {
Check_default.defined("array", array);
startingIndex = startingIndex ?? 0;
if (!defined_default(result)) {
result = new _Matrix3();
}
result[0] = array[startingIndex++];
result[1] = array[startingIndex++];
result[2] = array[startingIndex++];
result[3] = array[startingIndex++];
result[4] = array[startingIndex++];
result[5] = array[startingIndex++];
result[6] = array[startingIndex++];
result[7] = array[startingIndex++];
result[8] = array[startingIndex];
return result;
}
/**
* Flattens an array of Matrix3s into an array of components. The components
* are stored in column-major order.
*
* @param {Matrix3[]} array The array of matrices to pack.
* @param {number[]} [result] The array onto which to store the result. If this is a typed array, it must have array.length * 9 components, else a {@link DeveloperError} will be thrown. If it is a regular array, it will be resized to have (array.length * 9) elements.
* @returns {number[]} The packed array.
*/
static packArray(array, result) {
Check_default.defined("array", array);
const length2 = array.length;
const resultLength = length2 * 9;
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 * 9 elements"
);
} else if (result.length !== resultLength) {
result.length = resultLength;
}
for (let i = 0; i < length2; ++i) {
_Matrix3.pack(array[i], result, i * 9);
}
return result;
}
/**
* Unpacks an array of column-major matrix components into an array of Matrix3s.
*
* @param {number[]} array The array of components to unpack.
* @param {Matrix3[]} [result] The array onto which to store the result.
* @returns {Matrix3[]} The unpacked array.
*/
static unpackArray(array, result) {
Check_default.defined("array", array);
Check_default.typeOf.number.greaterThanOrEquals("array.length", array.length, 9);
if (array.length % 9 !== 0) {
throw new DeveloperError_default("array length must be a multiple of 9.");
}
const length2 = array.length;
if (!defined_default(result)) {
result = new Array(length2 / 9);
} else {
result.length = length2 / 9;
}
for (let i = 0; i < length2; i += 9) {
const index = i / 9;
result[index] = _Matrix3.unpack(array, i, result[index]);
}
return result;
}
/**
* Duplicates a Matrix3 instance.
*
* @param {Matrix3} matrix The matrix to duplicate.
* @param {Matrix3} [result] The object onto which to store the result.
* @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided. (Returns undefined if matrix is undefined)
*/
static clone(matrix, result) {
if (!defined_default(matrix)) {
return void 0;
}
if (!defined_default(result)) {
return new _Matrix3(
matrix[0],
matrix[3],
matrix[6],
matrix[1],
matrix[4],
matrix[7],
matrix[2],
matrix[5],
matrix[8]
);
}
result[0] = matrix[0];
result[1] = matrix[1];
result[2] = matrix[2];
result[3] = matrix[3];
result[4] = matrix[4];
result[5] = matrix[5];
result[6] = matrix[6];
result[7] = matrix[7];
result[8] = matrix[8];
return result;
}
/**
* Creates a Matrix3 instance from a column-major order array.
*
* @param {number[]} values The column-major order array.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
*/
static fromColumnMajorArray(values, result) {
Check_default.defined("values", values);
return _Matrix3.clone(values, result);
}
/**
* Creates a Matrix3 instance from a row-major order array.
* The resulting matrix will be in column-major order.
*
* @param {number[]} values The row-major order array.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
*/
static fromRowMajorArray(values, result) {
Check_default.defined("values", values);
if (!defined_default(result)) {
return new _Matrix3(
values[0],
values[1],
values[2],
values[3],
values[4],
values[5],
values[6],
values[7],
values[8]
);
}
result[0] = values[0];
result[1] = values[3];
result[2] = values[6];
result[3] = values[1];
result[4] = values[4];
result[5] = values[7];
result[6] = values[2];
result[7] = values[5];
result[8] = values[8];
return result;
}
/**
* Computes a 3x3 rotation matrix from the provided quaternion.
*
* @param {Quaternion} quaternion the quaternion to use.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix3} The 3x3 rotation matrix from this quaternion.
*/
static fromQuaternion(quaternion, result) {
Check_default.typeOf.object("quaternion", quaternion);
const x2 = quaternion.x * quaternion.x;
const xy = quaternion.x * quaternion.y;
const xz = quaternion.x * quaternion.z;
const xw = quaternion.x * quaternion.w;
const y2 = quaternion.y * quaternion.y;
const yz = quaternion.y * quaternion.z;
const yw = quaternion.y * quaternion.w;
const z2 = quaternion.z * quaternion.z;
const zw = quaternion.z * quaternion.w;
const w2 = quaternion.w * quaternion.w;
const m00 = x2 - y2 - z2 + w2;
const m01 = 2 * (xy - zw);
const m02 = 2 * (xz + yw);
const m10 = 2 * (xy + zw);
const m11 = -x2 + y2 - z2 + w2;
const m12 = 2 * (yz - xw);
const m20 = 2 * (xz - yw);
const m21 = 2 * (yz + xw);
const m22 = -x2 - y2 + z2 + w2;
if (!defined_default(result)) {
return new _Matrix3(m00, m01, m02, m10, m11, m12, m20, m21, m22);
}
result[0] = m00;
result[1] = m10;
result[2] = m20;
result[3] = m01;
result[4] = m11;
result[5] = m21;
result[6] = m02;
result[7] = m12;
result[8] = m22;
return result;
}
/**
* Computes a 3x3 rotation matrix from the provided headingPitchRoll. (see http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles )
*
* @param {HeadingPitchRoll} headingPitchRoll the headingPitchRoll to use.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix3} The 3x3 rotation matrix from this headingPitchRoll.
*/
static fromHeadingPitchRoll(headingPitchRoll, result) {
Check_default.typeOf.object("headingPitchRoll", headingPitchRoll);
const cosTheta = Math.cos(-headingPitchRoll.pitch);
const cosPsi = Math.cos(-headingPitchRoll.heading);
const cosPhi = Math.cos(headingPitchRoll.roll);
const sinTheta = Math.sin(-headingPitchRoll.pitch);
const sinPsi = Math.sin(-headingPitchRoll.heading);
const sinPhi = Math.sin(headingPitchRoll.roll);
const m00 = cosTheta * cosPsi;
const m01 = -cosPhi * sinPsi + sinPhi * sinTheta * cosPsi;
const m02 = sinPhi * sinPsi + cosPhi * sinTheta * cosPsi;
const m10 = cosTheta * sinPsi;
const m11 = cosPhi * cosPsi + sinPhi * sinTheta * sinPsi;
const m12 = -sinPhi * cosPsi + cosPhi * sinTheta * sinPsi;
const m20 = -sinTheta;
const m21 = sinPhi * cosTheta;
const m22 = cosPhi * cosTheta;
if (!defined_default(result)) {
return new _Matrix3(m00, m01, m02, m10, m11, m12, m20, m21, m22);
}
result[0] = m00;
result[1] = m10;
result[2] = m20;
result[3] = m01;
result[4] = m11;
result[5] = m21;
result[6] = m02;
result[7] = m12;
result[8] = m22;
return result;
}
/**
* Computes a Matrix3 instance representing a non-uniform scale.
*
* @param {Cartesian3} scale The x, y, and z scale factors.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
*
* @example
* // Creates
* // [7.0, 0.0, 0.0]
* // [0.0, 8.0, 0.0]
* // [0.0, 0.0, 9.0]
* const m = Cesium.Matrix3.fromScale(new Cesium.Cartesian3(7.0, 8.0, 9.0));
*/
static fromScale(scale, result) {
Check_default.typeOf.object("scale", scale);
if (!defined_default(result)) {
return new _Matrix3(
scale.x,
0,
0,
0,
scale.y,
0,
0,
0,
scale.z
);
}
result[0] = scale.x;
result[1] = 0;
result[2] = 0;
result[3] = 0;
result[4] = scale.y;
result[5] = 0;
result[6] = 0;
result[7] = 0;
result[8] = scale.z;
return result;
}
/**
* Computes a Matrix3 instance representing a uniform scale.
*
* @param {number} scale The uniform scale factor.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
*
* @example
* // Creates
* // [2.0, 0.0, 0.0]
* // [0.0, 2.0, 0.0]
* // [0.0, 0.0, 2.0]
* const m = Cesium.Matrix3.fromUniformScale(2.0);
*/
static fromUniformScale(scale, result) {
Check_default.typeOf.number("scale", scale);
if (!defined_default(result)) {
return new _Matrix3(scale, 0, 0, 0, scale, 0, 0, 0, scale);
}
result[0] = scale;
result[1] = 0;
result[2] = 0;
result[3] = 0;
result[4] = scale;
result[5] = 0;
result[6] = 0;
result[7] = 0;
result[8] = scale;
return result;
}
/**
* Computes a Matrix3 instance representing the cross product equivalent matrix of a Cartesian3 vector.
*
* @param {Cartesian3} vector the vector on the left hand side of the cross product operation.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
*
* @example
* // Creates
* // [0.0, -9.0, 8.0]
* // [9.0, 0.0, -7.0]
* // [-8.0, 7.0, 0.0]
* const m = Cesium.Matrix3.fromCrossProduct(new Cesium.Cartesian3(7.0, 8.0, 9.0));
*/
static fromCrossProduct(vector, result) {
Check_default.typeOf.object("vector", vector);
if (!defined_default(result)) {
return new _Matrix3(
0,
-vector.z,
vector.y,
vector.z,
0,
-vector.x,
-vector.y,
vector.x,
0
);
}
result[0] = 0;
result[1] = vector.z;
result[2] = -vector.y;
result[3] = -vector.z;
result[4] = 0;
result[5] = vector.x;
result[6] = vector.y;
result[7] = -vector.x;
result[8] = 0;
return result;
}
/**
* Creates a rotation matrix around the x-axis.
*
* @param {number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
*
* @example
* // Rotate a point 45 degrees counterclockwise around the x-axis.
* const p = new Cesium.Cartesian3(5, 6, 7);
* const m = Cesium.Matrix3.fromRotationX(Cesium.Math.toRadians(45.0));
* const rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
*/
static fromRotationX(angle, result) {
Check_default.typeOf.number("angle", angle);
const cosAngle = Math.cos(angle);
const sinAngle = Math.sin(angle);
if (!defined_default(result)) {
return new _Matrix3(
1,
0,
0,
0,
cosAngle,
-sinAngle,
0,
sinAngle,
cosAngle
);
}
result[0] = 1;
result[1] = 0;
result[2] = 0;
result[3] = 0;
result[4] = cosAngle;
result[5] = sinAngle;
result[6] = 0;
result[7] = -sinAngle;
result[8] = cosAngle;
return result;
}
/**
* Creates a rotation matrix around the y-axis.
*
* @param {number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
*
* @example
* // Rotate a point 45 degrees counterclockwise around the y-axis.
* const p = new Cesium.Cartesian3(5, 6, 7);
* const m = Cesium.Matrix3.fromRotationY(Cesium.Math.toRadians(45.0));
* const rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
*/
static fromRotationY(angle, result) {
Check_default.typeOf.number("angle", angle);
const cosAngle = Math.cos(angle);
const sinAngle = Math.sin(angle);
if (!defined_default(result)) {
return new _Matrix3(
cosAngle,
0,
sinAngle,
0,
1,
0,
-sinAngle,
0,
cosAngle
);
}
result[0] = cosAngle;
result[1] = 0;
result[2] = -sinAngle;
result[3] = 0;
result[4] = 1;
result[5] = 0;
result[6] = sinAngle;
result[7] = 0;
result[8] = cosAngle;
return result;
}
/**
* Creates a rotation matrix around the z-axis.
*
* @param {number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
*
* @example
* // Rotate a point 45 degrees counterclockwise around the z-axis.
* const p = new Cesium.Cartesian3(5, 6, 7);
* const m = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(45.0));
* const rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
*/
static fromRotationZ(angle, result) {
Check_default.typeOf.number("angle", angle);
const cosAngle = Math.cos(angle);
const sinAngle = Math.sin(angle);
if (!defined_default(result)) {
return new _Matrix3(
cosAngle,
-sinAngle,
0,
sinAngle,
cosAngle,
0,
0,
0,
1
);
}
result[0] = cosAngle;
result[1] = sinAngle;
result[2] = 0;
result[3] = -sinAngle;
result[4] = cosAngle;
result[5] = 0;
result[6] = 0;
result[7] = 0;
result[8] = 1;
return result;
}
/**
* Creates an Array from the provided Matrix3 instance.
* The array will be in column-major order.
*
* @param {Matrix3} matrix The matrix to use..
* @param {number[]} [result] The Array onto which to store the result.
* @returns {number[]} The modified Array parameter or a new Array instance if one was not provided.
*/
static toArray(matrix, result) {
Check_default.typeOf.object("matrix", matrix);
if (!defined_default(result)) {
return [
matrix[0],
matrix[1],
matrix[2],
matrix[3],
matrix[4],
matrix[5],
matrix[6],
matrix[7],
matrix[8]
];
}
result[0] = matrix[0];
result[1] = matrix[1];
result[2] = matrix[2];
result[3] = matrix[3];
result[4] = matrix[4];
result[5] = matrix[5];
result[6] = matrix[6];
result[7] = matrix[7];
result[8] = matrix[8];
return result;
}
/**
* Computes the array index of the element at the provided row and column.
*
* @param {number} column The zero-based index of the column.
* @param {number} row The zero-based index of the row.
* @returns {number} The index of the element at the provided row and column.
*
* @exception {DeveloperError} row must be 0, 1, or 2.
* @exception {DeveloperError} column must be 0, 1, or 2.
*
* @example
* const myMatrix = new Cesium.Matrix3();
* const column1Row0Index = Cesium.Matrix3.getElementIndex(1, 0);
* const column1Row0 = myMatrix[column1Row0Index]
* myMatrix[column1Row0Index] = 10.0;
*/
static getElementIndex(column, row) {
Check_default.typeOf.number.greaterThanOrEquals("row", row, 0);
Check_default.typeOf.number.lessThanOrEquals("row", row, 2);
Check_default.typeOf.number.greaterThanOrEquals("column", column, 0);
Check_default.typeOf.number.lessThanOrEquals("column", column, 2);
return column * 3 + row;
}
/**
* Retrieves a copy of the matrix column at the provided index as a Cartesian3 instance.
*
* @param {Matrix3} matrix The matrix to use.
* @param {number} index The zero-based index of the column to retrieve.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*
* @exception {DeveloperError} index must be 0, 1, or 2.
*/
static getColumn(matrix, index, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.number.greaterThanOrEquals("index", index, 0);
Check_default.typeOf.number.lessThanOrEquals("index", index, 2);
Check_default.typeOf.object("result", result);
const startIndex = index * 3;
const x = matrix[startIndex];
const y = matrix[startIndex + 1];
const z2 = matrix[startIndex + 2];
result.x = x;
result.y = y;
result.z = z2;
return result;
}
/**
* Computes a new matrix that replaces the specified column in the provided matrix with the provided Cartesian3 instance.
*
* @param {Matrix3} matrix The matrix to use.
* @param {number} index The zero-based index of the column to set.
* @param {Cartesian3} cartesian The Cartesian whose values will be assigned to the specified column.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*
* @exception {DeveloperError} index must be 0, 1, or 2.
*/
static setColumn(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, 2);
Check_default.typeOf.object("cartesian", cartesian11);
Check_default.typeOf.object("result", result);
result = _Matrix3.clone(matrix, result);
const startIndex = index * 3;
result[startIndex] = cartesian11.x;
result[startIndex + 1] = cartesian11.y;
result[startIndex + 2] = cartesian11.z;
return result;
}
/**
* Retrieves a copy of the matrix row at the provided index as a Cartesian3 instance.
*
* @param {Matrix3} matrix The matrix to use.
* @param {number} index The zero-based index of the row to retrieve.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*
* @exception {DeveloperError} index must be 0, 1, or 2.
*/
static getRow(matrix, index, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.number.greaterThanOrEquals("index", index, 0);
Check_default.typeOf.number.lessThanOrEquals("index", index, 2);
Check_default.typeOf.object("result", result);
const x = matrix[index];
const y = matrix[index + 3];
const z2 = matrix[index + 6];
result.x = x;
result.y = y;
result.z = z2;
return result;
}
/**
* Computes a new matrix that replaces the specified row in the provided matrix with the provided Cartesian3 instance.
*
* @param {Matrix3} matrix The matrix to use.
* @param {number} index The zero-based index of the row to set.
* @param {Cartesian3} cartesian The Cartesian whose values will be assigned to the specified row.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*
* @exception {DeveloperError} index must be 0, 1, or 2.
*/
static setRow(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, 2);
Check_default.typeOf.object("cartesian", cartesian11);
Check_default.typeOf.object("result", result);
result = _Matrix3.clone(matrix, result);
result[index] = cartesian11.x;
result[index + 3] = cartesian11.y;
result[index + 6] = cartesian11.z;
return result;
}
/**
* Computes a new matrix that replaces the scale with the provided scale.
* This assumes the matrix is an affine transformation.
*
* @param {Matrix3} matrix The matrix to use.
* @param {Cartesian3} scale The scale that replaces the scale of the provided matrix.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*
* @see Matrix3.setUniformScale
* @see Matrix3.fromScale
* @see Matrix3.fromUniformScale
* @see Matrix3.multiplyByScale
* @see Matrix3.multiplyByUniformScale
* @see Matrix3.getScale
*/
static setScale(matrix, scale, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.object("scale", scale);
Check_default.typeOf.object("result", result);
const existingScale = _Matrix3.getScale(matrix, scaleScratch1);
const scaleRatioX = scale.x / existingScale.x;
const scaleRatioY = scale.y / existingScale.y;
const scaleRatioZ = scale.z / existingScale.z;
result[0] = matrix[0] * scaleRatioX;
result[1] = matrix[1] * scaleRatioX;
result[2] = matrix[2] * scaleRatioX;
result[3] = matrix[3] * scaleRatioY;
result[4] = matrix[4] * scaleRatioY;
result[5] = matrix[5] * scaleRatioY;
result[6] = matrix[6] * scaleRatioZ;
result[7] = matrix[7] * scaleRatioZ;
result[8] = matrix[8] * scaleRatioZ;
return result;
}
/**
* Computes a new matrix that replaces the scale with the provided uniform scale.
* This assumes the matrix is an affine transformation.
*
* @param {Matrix3} matrix The matrix to use.
* @param {number} scale The uniform scale that replaces the scale of the provided matrix.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*
* @see Matrix3.setScale
* @see Matrix3.fromScale
* @see Matrix3.fromUniformScale
* @see Matrix3.multiplyByScale
* @see Matrix3.multiplyByUniformScale
* @see Matrix3.getScale
*/
static setUniformScale(matrix, scale, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.number("scale", scale);
Check_default.typeOf.object("result", result);
const existingScale = _Matrix3.getScale(matrix, scaleScratch2);
const scaleRatioX = scale / existingScale.x;
const scaleRatioY = scale / existingScale.y;
const scaleRatioZ = scale / existingScale.z;
result[0] = matrix[0] * scaleRatioX;
result[1] = matrix[1] * scaleRatioX;
result[2] = matrix[2] * scaleRatioX;
result[3] = matrix[3] * scaleRatioY;
result[4] = matrix[4] * scaleRatioY;
result[5] = matrix[5] * scaleRatioY;
result[6] = matrix[6] * scaleRatioZ;
result[7] = matrix[7] * scaleRatioZ;
result[8] = matrix[8] * scaleRatioZ;
return result;
}
/**
* Extracts the non-uniform scale assuming the matrix is an affine transformation.
*
* @param {Matrix3} matrix The matrix.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*
* @see Matrix3.multiplyByScale
* @see Matrix3.multiplyByUniformScale
* @see Matrix3.fromScale
* @see Matrix3.fromUniformScale
* @see Matrix3.setScale
* @see Matrix3.setUniformScale
*/
static getScale(matrix, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.object("result", result);
result.x = Cartesian3_default.magnitude(
Cartesian3_default.fromElements(matrix[0], matrix[1], matrix[2], scratchColumn)
);
result.y = Cartesian3_default.magnitude(
Cartesian3_default.fromElements(matrix[3], matrix[4], matrix[5], scratchColumn)
);
result.z = Cartesian3_default.magnitude(
Cartesian3_default.fromElements(matrix[6], matrix[7], matrix[8], scratchColumn)
);
return result;
}
/**
* Computes the maximum scale assuming the matrix is an affine transformation.
* The maximum scale is the maximum length of the column vectors.
*
* @param {Matrix3} matrix The matrix.
* @returns {number} The maximum scale.
*/
static getMaximumScale(matrix) {
_Matrix3.getScale(matrix, scaleScratch3);
return Cartesian3_default.maximumComponent(scaleScratch3);
}
/**
* Sets the rotation assuming the matrix is an affine transformation.
*
* @param {Matrix3} matrix The matrix.
* @param {Matrix3} rotation The rotation matrix.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*
* @see Matrix3.getRotation
*/
static setRotation(matrix, rotation, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.object("result", result);
const scale = _Matrix3.getScale(matrix, scaleScratch4);
result[0] = rotation[0] * scale.x;
result[1] = rotation[1] * scale.x;
result[2] = rotation[2] * scale.x;
result[3] = rotation[3] * scale.y;
result[4] = rotation[4] * scale.y;
result[5] = rotation[5] * scale.y;
result[6] = rotation[6] * scale.z;
result[7] = rotation[7] * scale.z;
result[8] = rotation[8] * scale.z;
return result;
}
/**
* Extracts the rotation matrix assuming the matrix is an affine transformation.
*
* @param {Matrix3} matrix The matrix.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*
* @see Matrix3.setRotation
*/
static getRotation(matrix, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.object("result", result);
const scale = _Matrix3.getScale(matrix, scaleScratch5);
result[0] = matrix[0] / scale.x;
result[1] = matrix[1] / scale.x;
result[2] = matrix[2] / scale.x;
result[3] = matrix[3] / scale.y;
result[4] = matrix[4] / scale.y;
result[5] = matrix[5] / scale.y;
result[6] = matrix[6] / scale.z;
result[7] = matrix[7] / scale.z;
result[8] = matrix[8] / scale.z;
return result;
}
/**
* Computes the product of two matrices.
*
* @param {Matrix3} left The first matrix.
* @param {Matrix3} right The second matrix.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*/
static multiply(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[3] * right[1] + left[6] * right[2];
const column0Row1 = left[1] * right[0] + left[4] * right[1] + left[7] * right[2];
const column0Row2 = left[2] * right[0] + left[5] * right[1] + left[8] * right[2];
const column1Row0 = left[0] * right[3] + left[3] * right[4] + left[6] * right[5];
const column1Row1 = left[1] * right[3] + left[4] * right[4] + left[7] * right[5];
const column1Row2 = left[2] * right[3] + left[5] * right[4] + left[8] * right[5];
const column2Row0 = left[0] * right[6] + left[3] * right[7] + left[6] * right[8];
const column2Row1 = left[1] * right[6] + left[4] * right[7] + left[7] * right[8];
const column2Row2 = left[2] * right[6] + left[5] * right[7] + left[8] * right[8];
result[0] = column0Row0;
result[1] = column0Row1;
result[2] = column0Row2;
result[3] = column1Row0;
result[4] = column1Row1;
result[5] = column1Row2;
result[6] = column2Row0;
result[7] = column2Row1;
result[8] = column2Row2;
return result;
}
/**
* Computes the sum of two matrices.
*
* @param {Matrix3} left The first matrix.
* @param {Matrix3} right The second matrix.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*/
static add(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];
result[4] = left[4] + right[4];
result[5] = left[5] + right[5];
result[6] = left[6] + right[6];
result[7] = left[7] + right[7];
result[8] = left[8] + right[8];
return result;
}
/**
* Computes the difference of two matrices.
*
* @param {Matrix3} left The first matrix.
* @param {Matrix3} right The second matrix.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*/
static subtract(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];
result[4] = left[4] - right[4];
result[5] = left[5] - right[5];
result[6] = left[6] - right[6];
result[7] = left[7] - right[7];
result[8] = left[8] - right[8];
return result;
}
/**
* Computes the product of a matrix and a column vector.
*
* @param {Matrix3} matrix The matrix.
* @param {Cartesian3} cartesian The column.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*/
static multiplyByVector(matrix, cartesian11, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.object("cartesian", cartesian11);
Check_default.typeOf.object("result", result);
const vX = cartesian11.x;
const vY = cartesian11.y;
const vZ = cartesian11.z;
const x = matrix[0] * vX + matrix[3] * vY + matrix[6] * vZ;
const y = matrix[1] * vX + matrix[4] * vY + matrix[7] * vZ;
const z2 = matrix[2] * vX + matrix[5] * vY + matrix[8] * vZ;
result.x = x;
result.y = y;
result.z = z2;
return result;
}
/**
* Computes the product of a matrix and a scalar.
*
* @param {Matrix3} matrix The matrix.
* @param {number} scalar The number to multiply by.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*/
static multiplyByScalar(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;
result[4] = matrix[4] * scalar;
result[5] = matrix[5] * scalar;
result[6] = matrix[6] * scalar;
result[7] = matrix[7] * scalar;
result[8] = matrix[8] * scalar;
return result;
}
/**
* Computes the product of a matrix times a (non-uniform) scale, as if the scale were a scale matrix.
*
* @param {Matrix3} matrix The matrix on the left-hand side.
* @param {Cartesian3} scale The non-uniform scale on the right-hand side.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*
*
* @example
* // Instead of Cesium.Matrix3.multiply(m, Cesium.Matrix3.fromScale(scale), m);
* Cesium.Matrix3.multiplyByScale(m, scale, m);
*
* @see Matrix3.multiplyByUniformScale
* @see Matrix3.fromScale
* @see Matrix3.fromUniformScale
* @see Matrix3.setScale
* @see Matrix3.setUniformScale
* @see Matrix3.getScale
*/
static multiplyByScale(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.x;
result[3] = matrix[3] * scale.y;
result[4] = matrix[4] * scale.y;
result[5] = matrix[5] * scale.y;
result[6] = matrix[6] * scale.z;
result[7] = matrix[7] * scale.z;
result[8] = matrix[8] * scale.z;
return result;
}
/**
* Computes the product of a matrix times a uniform scale, as if the scale were a scale matrix.
*
* @param {Matrix3} matrix The matrix on the left-hand side.
* @param {number} scale The uniform scale on the right-hand side.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*
* @example
* // Instead of Cesium.Matrix3.multiply(m, Cesium.Matrix3.fromUniformScale(scale), m);
* Cesium.Matrix3.multiplyByUniformScale(m, scale, m);
*
* @see Matrix3.multiplyByScale
* @see Matrix3.fromScale
* @see Matrix3.fromUniformScale
* @see Matrix3.setScale
* @see Matrix3.setUniformScale
* @see Matrix3.getScale
*/
static multiplyByUniformScale(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;
result[4] = matrix[4] * scale;
result[5] = matrix[5] * scale;
result[6] = matrix[6] * scale;
result[7] = matrix[7] * scale;
result[8] = matrix[8] * scale;
return result;
}
/**
* Creates a negated copy of the provided matrix.
*
* @param {Matrix3} matrix The matrix to negate.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*/
static negate(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];
result[4] = -matrix[4];
result[5] = -matrix[5];
result[6] = -matrix[6];
result[7] = -matrix[7];
result[8] = -matrix[8];
return result;
}
/**
* Computes the transpose of the provided matrix.
*
* @param {Matrix3} matrix The matrix to transpose.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*/
static transpose(matrix, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.object("result", result);
const column0Row0 = matrix[0];
const column0Row1 = matrix[3];
const column0Row2 = matrix[6];
const column1Row0 = matrix[1];
const column1Row1 = matrix[4];
const column1Row2 = matrix[7];
const column2Row0 = matrix[2];
const column2Row1 = matrix[5];
const column2Row2 = matrix[8];
result[0] = column0Row0;
result[1] = column0Row1;
result[2] = column0Row2;
result[3] = column1Row0;
result[4] = column1Row1;
result[5] = column1Row2;
result[6] = column2Row0;
result[7] = column2Row1;
result[8] = column2Row2;
return result;
}
/**
* Computes the eigenvectors and eigenvalues of a symmetric matrix.
* matrix = unitary matrix * diagonal matrix * transpose(unitary matrix)
* true if they are equal, false otherwise.
*
* @param {Matrix3} [left] The first matrix.
* @param {Matrix3} [right] The second matrix.
* @returns {boolean} true if left and right are equal, false otherwise.
*/
static equals(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] && left[4] === right[4] && left[5] === right[5] && left[6] === right[6] && left[7] === right[7] && left[8] === right[8];
}
/**
* Compares the provided matrices componentwise and returns
* true if they are within the provided epsilon,
* false otherwise.
*
* @param {Matrix3} [left] The first matrix.
* @param {Matrix3} [right] The second matrix.
* @param {number} [epsilon=0] The epsilon to use for equality testing.
* @returns {boolean} true if left and right are within the provided epsilon, false otherwise.
*/
static equalsEpsilon(left, right, epsilon) {
epsilon = 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 && Math.abs(left[4] - right[4]) <= epsilon && Math.abs(left[5] - right[5]) <= epsilon && Math.abs(left[6] - right[6]) <= epsilon && Math.abs(left[7] - right[7]) <= epsilon && Math.abs(left[8] - right[8]) <= epsilon;
}
/**
* Gets the number of items in the collection.
*
* @type {number}
*/
get length() {
return _Matrix3.packedLength;
}
/**
* Duplicates the provided Matrix3 instance.
*
* @param {Matrix3} [result] The object onto which to store the result.
* @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided.
*/
clone(result) {
return _Matrix3.clone(this, result);
}
/**
* Compares this matrix to the provided matrix componentwise and returns
* true if they are equal, false otherwise.
*
* @param {Matrix3} [right] The right hand side matrix.
* @returns {boolean} true if they are equal, false otherwise.
*/
equals(right) {
return _Matrix3.equals(this, right);
}
/**
* Compares provided matrix and array, starting from a given array offset.
*
* @param {Matrix3} matrix
* @param {number[]} array
* @param {number} offset
* @ignore
*/
static equalsArray(matrix, array, offset) {
return matrix[0] === array[offset] && matrix[1] === array[offset + 1] && matrix[2] === array[offset + 2] && matrix[3] === array[offset + 3] && matrix[4] === array[offset + 4] && matrix[5] === array[offset + 5] && matrix[6] === array[offset + 6] && matrix[7] === array[offset + 7] && matrix[8] === array[offset + 8];
}
/**
* Compares this matrix to the provided matrix componentwise and returns
* true if they are within the provided epsilon,
* false otherwise.
*
* @param {Matrix3} [right] The right hand side matrix.
* @param {number} [epsilon=0] The epsilon to use for equality testing.
* @returns {boolean} true if they are within the provided epsilon, false otherwise.
*/
equalsEpsilon(right, epsilon) {
return _Matrix3.equalsEpsilon(this, right, epsilon);
}
/**
* Creates a string representing this Matrix with each row being
* on a separate line and in the format '(column0, column1, column2)'.
*
* @returns {string} A string representing the provided Matrix with each row being on a separate line and in the format '(column0, column1, column2)'.
*/
toString() {
return `(${this[0]}, ${this[3]}, ${this[6]})
(${this[1]}, ${this[4]}, ${this[7]})
(${this[2]}, ${this[5]}, ${this[8]})`;
}
};
Matrix3.packedLength = 9;
Matrix3.fromArray = Matrix3.unpack;
Matrix3.IDENTITY = Object.freeze(
new Matrix3(1, 0, 0, 0, 1, 0, 0, 0, 1)
);
Matrix3.ZERO = Object.freeze(
new Matrix3(0, 0, 0, 0, 0, 0, 0, 0, 0)
);
Matrix3.COLUMN0ROW0 = 0;
Matrix3.COLUMN0ROW1 = 1;
Matrix3.COLUMN0ROW2 = 2;
Matrix3.COLUMN1ROW0 = 3;
Matrix3.COLUMN1ROW1 = 4;
Matrix3.COLUMN1ROW2 = 5;
Matrix3.COLUMN2ROW0 = 6;
Matrix3.COLUMN2ROW1 = 7;
Matrix3.COLUMN2ROW2 = 8;
var scaleScratch1 = new Cartesian3_default();
var scaleScratch2 = new Cartesian3_default();
var scratchColumn = new Cartesian3_default();
var scaleScratch3 = new Cartesian3_default();
var scaleScratch4 = new Cartesian3_default();
var scaleScratch5 = new Cartesian3_default();
var jMatrix = new Matrix3();
var jMatrixTranspose = new Matrix3();
var scratchTransposeMatrix = new Matrix3();
function computeFrobeniusNorm(matrix) {
let norm = 0;
for (let i = 0; i < 9; ++i) {
const temp = matrix[i];
norm += temp * temp;
}
return Math.sqrt(norm);
}
var rowVal = [1, 0, 0];
var colVal = [2, 2, 1];
function offDiagonalFrobeniusNorm(matrix) {
let norm = 0;
for (let i = 0; i < 3; ++i) {
const temp = matrix[Matrix3.getElementIndex(colVal[i], rowVal[i])];
norm += 2 * temp * temp;
}
return Math.sqrt(norm);
}
function shurDecomposition(matrix, result) {
const tolerance = Math_default.EPSILON15;
let maxDiagonal = 0;
let rotAxis2 = 1;
for (let i = 0; i < 3; ++i) {
const temp = Math.abs(
// @ts-expect-error TODO(tsd-jsdoc): Requires index signature support.
matrix[Matrix3.getElementIndex(colVal[i], rowVal[i])]
);
if (temp > maxDiagonal) {
rotAxis2 = i;
maxDiagonal = temp;
}
}
let c14 = 1;
let s2 = 0;
const p = rowVal[rotAxis2];
const q = colVal[rotAxis2];
if (Math.abs(matrix[Matrix3.getElementIndex(q, p)]) > tolerance) {
const qq = matrix[Matrix3.getElementIndex(q, q)];
const pp = matrix[Matrix3.getElementIndex(p, p)];
const qp = matrix[Matrix3.getElementIndex(q, p)];
const tau = (qq - pp) / 2 / qp;
let t2;
if (tau < 0) {
t2 = -1 / (-tau + Math.sqrt(1 + tau * tau));
} else {
t2 = 1 / (tau + Math.sqrt(1 + tau * tau));
}
c14 = 1 / Math.sqrt(1 + t2 * t2);
s2 = t2 * c14;
}
result = Matrix3.clone(Matrix3.IDENTITY, result);
result[Matrix3.getElementIndex(p, p)] = result[Matrix3.getElementIndex(q, q)] = c14;
result[Matrix3.getElementIndex(q, p)] = s2;
result[Matrix3.getElementIndex(p, q)] = -s2;
return result;
}
var Matrix3_default = Matrix3;
// packages/engine/Source/Core/RuntimeError.js
function RuntimeError(message) {
this.name = "RuntimeError";
this.message = message;
let stack;
try {
throw new Error();
} catch (e) {
stack = e.stack;
}
this.stack = stack;
}
if (defined_default(Object.create)) {
RuntimeError.prototype = Object.create(Error.prototype);
RuntimeError.prototype.constructor = RuntimeError;
}
RuntimeError.prototype.toString = function() {
let str = `${this.name}: ${this.message}`;
if (defined_default(this.stack)) {
str += `
${this.stack.toString()}`;
}
return str;
};
var RuntimeError_default = RuntimeError;
// packages/engine/Source/Core/Matrix4.js
var Matrix4 = class _Matrix4 {
/**
* @param {number} [column0Row0=0.0] The value for column 0, row 0.
* @param {number} [column1Row0=0.0] The value for column 1, row 0.
* @param {number} [column2Row0=0.0] The value for column 2, row 0.
* @param {number} [column3Row0=0.0] The value for column 3, row 0.
* @param {number} [column0Row1=0.0] The value for column 0, row 1.
* @param {number} [column1Row1=0.0] The value for column 1, row 1.
* @param {number} [column2Row1=0.0] The value for column 2, row 1.
* @param {number} [column3Row1=0.0] The value for column 3, row 1.
* @param {number} [column0Row2=0.0] The value for column 0, row 2.
* @param {number} [column1Row2=0.0] The value for column 1, row 2.
* @param {number} [column2Row2=0.0] The value for column 2, row 2.
* @param {number} [column3Row2=0.0] The value for column 3, row 2.
* @param {number} [column0Row3=0.0] The value for column 0, row 3.
* @param {number} [column1Row3=0.0] The value for column 1, row 3.
* @param {number} [column2Row3=0.0] The value for column 2, row 3.
* @param {number} [column3Row3=0.0] The value for column 3, row 3.
*/
constructor(column0Row0, column1Row0, column2Row0, column3Row0, column0Row1, column1Row1, column2Row1, column3Row1, column0Row2, column1Row2, column2Row2, column3Row2, column0Row3, column1Row3, column2Row3, column3Row3) {
this[0] = column0Row0 ?? 0;
this[1] = column0Row1 ?? 0;
this[2] = column0Row2 ?? 0;
this[3] = column0Row3 ?? 0;
this[4] = column1Row0 ?? 0;
this[5] = column1Row1 ?? 0;
this[6] = column1Row2 ?? 0;
this[7] = column1Row3 ?? 0;
this[8] = column2Row0 ?? 0;
this[9] = column2Row1 ?? 0;
this[10] = column2Row2 ?? 0;
this[11] = column2Row3 ?? 0;
this[12] = column3Row0 ?? 0;
this[13] = column3Row1 ?? 0;
this[14] = column3Row2 ?? 0;
this[15] = column3Row3 ?? 0;
}
/**
* Stores the provided instance into the provided array.
*
* @param {Matrix4} value The value to pack.
* @param {number[]} array The array to pack into.
* @param {number} [startingIndex=0] The index into the array at which to start packing the elements.
*
* @returns {number[]} The array that was packed into
*/
static pack(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
Check_default.defined("array", array);
startingIndex = startingIndex ?? 0;
array[startingIndex++] = value[0];
array[startingIndex++] = value[1];
array[startingIndex++] = value[2];
array[startingIndex++] = value[3];
array[startingIndex++] = value[4];
array[startingIndex++] = value[5];
array[startingIndex++] = value[6];
array[startingIndex++] = value[7];
array[startingIndex++] = value[8];
array[startingIndex++] = value[9];
array[startingIndex++] = value[10];
array[startingIndex++] = value[11];
array[startingIndex++] = value[12];
array[startingIndex++] = value[13];
array[startingIndex++] = value[14];
array[startingIndex] = value[15];
return array;
}
/**
* Retrieves an instance from a packed array.
*
* @param {number[]} array The packed array.
* @param {number} [startingIndex=0] The starting index of the element to be unpacked.
* @param {Matrix4} [result] The object into which to store the result.
* @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
*/
static unpack(array, startingIndex, result) {
Check_default.defined("array", array);
startingIndex = startingIndex ?? 0;
if (!defined_default(result)) {
result = new _Matrix4();
}
result[0] = array[startingIndex++];
result[1] = array[startingIndex++];
result[2] = array[startingIndex++];
result[3] = array[startingIndex++];
result[4] = array[startingIndex++];
result[5] = array[startingIndex++];
result[6] = array[startingIndex++];
result[7] = array[startingIndex++];
result[8] = array[startingIndex++];
result[9] = array[startingIndex++];
result[10] = array[startingIndex++];
result[11] = array[startingIndex++];
result[12] = array[startingIndex++];
result[13] = array[startingIndex++];
result[14] = array[startingIndex++];
result[15] = array[startingIndex];
return result;
}
/**
* Flattens an array of Matrix4s into an array of components. The components
* are stored in column-major order.
*
* @param {Matrix4[]} array The array of matrices to pack.
* @param {number[]} [result] The array onto which to store the result. If this is a typed array, it must have array.length * 16 components, else a {@link DeveloperError} will be thrown. If it is a regular array, it will be resized to have (array.length * 16) elements.
* @returns {number[]} The packed array.
*/
static packArray(array, result) {
Check_default.defined("array", array);
const length2 = array.length;
const resultLength = length2 * 16;
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 * 16 elements"
);
} else if (result.length !== resultLength) {
result.length = resultLength;
}
for (let i = 0; i < length2; ++i) {
_Matrix4.pack(array[i], result, i * 16);
}
return result;
}
/**
* Unpacks an array of column-major matrix components into an array of Matrix4s.
*
* @param {number[]} array The array of components to unpack.
* @param {Matrix4[]} [result] The array onto which to store the result.
* @returns {Matrix4[]} The unpacked array.
*/
static unpackArray(array, result) {
Check_default.defined("array", array);
Check_default.typeOf.number.greaterThanOrEquals("array.length", array.length, 16);
if (array.length % 16 !== 0) {
throw new DeveloperError_default("array length must be a multiple of 16.");
}
const length2 = array.length;
if (!defined_default(result)) {
result = new Array(length2 / 16);
} else {
result.length = length2 / 16;
}
for (let i = 0; i < length2; i += 16) {
const index = i / 16;
result[index] = _Matrix4.unpack(array, i, result[index]);
}
return result;
}
/**
* Duplicates a Matrix4 instance.
*
* @param {Matrix4} matrix The matrix to duplicate.
* @param {Matrix4} [result] The object onto which to store the result.
* @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided. (Returns undefined if matrix is undefined)
*/
static clone(matrix, result) {
if (!defined_default(matrix)) {
return void 0;
}
if (!defined_default(result)) {
return new _Matrix4(
matrix[0],
matrix[4],
matrix[8],
matrix[12],
matrix[1],
matrix[5],
matrix[9],
matrix[13],
matrix[2],
matrix[6],
matrix[10],
matrix[14],
matrix[3],
matrix[7],
matrix[11],
matrix[15]
);
}
result[0] = matrix[0];
result[1] = matrix[1];
result[2] = matrix[2];
result[3] = matrix[3];
result[4] = matrix[4];
result[5] = matrix[5];
result[6] = matrix[6];
result[7] = matrix[7];
result[8] = matrix[8];
result[9] = matrix[9];
result[10] = matrix[10];
result[11] = matrix[11];
result[12] = matrix[12];
result[13] = matrix[13];
result[14] = matrix[14];
result[15] = matrix[15];
return result;
}
/**
* Computes a Matrix4 instance from a column-major order array.
*
* @param {number[]} values The column-major order array.
* @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
*/
static fromColumnMajorArray(values, result) {
Check_default.defined("values", values);
return _Matrix4.clone(values, result);
}
/**
* Computes a Matrix4 instance from a row-major order array.
* The resulting matrix will be in column-major order.
*
* @param {number[]} values The row-major order array.
* @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
*/
static fromRowMajorArray(values, result) {
Check_default.defined("values", values);
if (!defined_default(result)) {
return new _Matrix4(
values[0],
values[1],
values[2],
values[3],
values[4],
values[5],
values[6],
values[7],
values[8],
values[9],
values[10],
values[11],
values[12],
values[13],
values[14],
values[15]
);
}
result[0] = values[0];
result[1] = values[4];
result[2] = values[8];
result[3] = values[12];
result[4] = values[1];
result[5] = values[5];
result[6] = values[9];
result[7] = values[13];
result[8] = values[2];
result[9] = values[6];
result[10] = values[10];
result[11] = values[14];
result[12] = values[3];
result[13] = values[7];
result[14] = values[11];
result[15] = values[15];
return result;
}
/**
* Computes a Matrix4 instance from a Matrix3 representing the rotation
* and a Cartesian3 representing the translation.
*
* @param {Matrix3} rotation The upper left portion of the matrix representing the rotation.
* @param {Cartesian3} [translation=Cartesian3.ZERO] The upper right portion of the matrix representing the translation.
* @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
*/
static fromRotationTranslation(rotation, translation3, result) {
Check_default.typeOf.object("rotation", rotation);
translation3 = translation3 ?? Cartesian3_default.ZERO;
if (!defined_default(result)) {
return new _Matrix4(
rotation[0],
rotation[3],
rotation[6],
translation3.x,
rotation[1],
rotation[4],
rotation[7],
translation3.y,
rotation[2],
rotation[5],
rotation[8],
translation3.z,
0,
0,
0,
1
);
}
result[0] = rotation[0];
result[1] = rotation[1];
result[2] = rotation[2];
result[3] = 0;
result[4] = rotation[3];
result[5] = rotation[4];
result[6] = rotation[5];
result[7] = 0;
result[8] = rotation[6];
result[9] = rotation[7];
result[10] = rotation[8];
result[11] = 0;
result[12] = translation3.x;
result[13] = translation3.y;
result[14] = translation3.z;
result[15] = 1;
return result;
}
/**
* Computes a Matrix4 instance from a translation, rotation, and scale (TRS)
* representation with the rotation represented as a quaternion.
*
* @param {Cartesian3} translation The translation transformation.
* @param {Quaternion} rotation The rotation transformation.
* @param {Cartesian3} scale The non-uniform scale transformation.
* @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
*
* @example
* const result = Cesium.Matrix4.fromTranslationQuaternionRotationScale(
* new Cesium.Cartesian3(1.0, 2.0, 3.0), // translation
* Cesium.Quaternion.IDENTITY, // rotation
* new Cesium.Cartesian3(7.0, 8.0, 9.0), // scale
* result);
*/
static fromTranslationQuaternionRotationScale(translation3, rotation, scale, result) {
Check_default.typeOf.object("translation", translation3);
Check_default.typeOf.object("rotation", rotation);
Check_default.typeOf.object("scale", scale);
if (!defined_default(result)) {
result = new _Matrix4();
}
const scaleX = scale.x;
const scaleY = scale.y;
const scaleZ = scale.z;
const x2 = rotation.x * rotation.x;
const xy = rotation.x * rotation.y;
const xz = rotation.x * rotation.z;
const xw = rotation.x * rotation.w;
const y2 = rotation.y * rotation.y;
const yz = rotation.y * rotation.z;
const yw = rotation.y * rotation.w;
const z2 = rotation.z * rotation.z;
const zw = rotation.z * rotation.w;
const w2 = rotation.w * rotation.w;
const m00 = x2 - y2 - z2 + w2;
const m01 = 2 * (xy - zw);
const m02 = 2 * (xz + yw);
const m10 = 2 * (xy + zw);
const m11 = -x2 + y2 - z2 + w2;
const m12 = 2 * (yz - xw);
const m20 = 2 * (xz - yw);
const m21 = 2 * (yz + xw);
const m22 = -x2 - y2 + z2 + w2;
result[0] = m00 * scaleX;
result[1] = m10 * scaleX;
result[2] = m20 * scaleX;
result[3] = 0;
result[4] = m01 * scaleY;
result[5] = m11 * scaleY;
result[6] = m21 * scaleY;
result[7] = 0;
result[8] = m02 * scaleZ;
result[9] = m12 * scaleZ;
result[10] = m22 * scaleZ;
result[11] = 0;
result[12] = translation3.x;
result[13] = translation3.y;
result[14] = translation3.z;
result[15] = 1;
return result;
}
/**
* Creates a Matrix4 instance from a {@link TranslationRotationScale} instance.
*
* @param {TranslationRotationScale} translationRotationScale The instance.
* @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
*/
static fromTranslationRotationScale(translationRotationScale, result) {
Check_default.typeOf.object("translationRotationScale", translationRotationScale);
return _Matrix4.fromTranslationQuaternionRotationScale(
translationRotationScale.translation,
translationRotationScale.rotation,
translationRotationScale.scale,
result
);
}
/**
* Creates a Matrix4 instance from a Cartesian3 representing the translation.
*
* @param {Cartesian3} translation The upper right portion of the matrix representing the translation.
* @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
*
* @see Matrix4.multiplyByTranslation
*/
static fromTranslation(translation3, result) {
Check_default.typeOf.object("translation", translation3);
return _Matrix4.fromRotationTranslation(
Matrix3_default.IDENTITY,
translation3,
result
);
}
/**
* Computes a Matrix4 instance representing a non-uniform scale.
*
* @param {Cartesian3} scale The x, y, and z scale factors.
* @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
*
* @example
* // Creates
* // [7.0, 0.0, 0.0, 0.0]
* // [0.0, 8.0, 0.0, 0.0]
* // [0.0, 0.0, 9.0, 0.0]
* // [0.0, 0.0, 0.0, 1.0]
* const m = Cesium.Matrix4.fromScale(new Cesium.Cartesian3(7.0, 8.0, 9.0));
*/
static fromScale(scale, result) {
Check_default.typeOf.object("scale", scale);
if (!defined_default(result)) {
return new _Matrix4(
scale.x,
0,
0,
0,
0,
scale.y,
0,
0,
0,
0,
scale.z,
0,
0,
0,
0,
1
);
}
result[0] = scale.x;
result[1] = 0;
result[2] = 0;
result[3] = 0;
result[4] = 0;
result[5] = scale.y;
result[6] = 0;
result[7] = 0;
result[8] = 0;
result[9] = 0;
result[10] = scale.z;
result[11] = 0;
result[12] = 0;
result[13] = 0;
result[14] = 0;
result[15] = 1;
return result;
}
/**
* Computes a Matrix4 instance representing a uniform scale.
*
* @param {number} scale The uniform scale factor.
* @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
*
* @example
* // Creates
* // [2.0, 0.0, 0.0, 0.0]
* // [0.0, 2.0, 0.0, 0.0]
* // [0.0, 0.0, 2.0, 0.0]
* // [0.0, 0.0, 0.0, 1.0]
* const m = Cesium.Matrix4.fromUniformScale(2.0);
*/
static fromUniformScale(scale, result) {
Check_default.typeOf.number("scale", scale);
if (!defined_default(result)) {
return new _Matrix4(
scale,
0,
0,
0,
0,
scale,
0,
0,
0,
0,
scale,
0,
0,
0,
0,
1
);
}
result[0] = scale;
result[1] = 0;
result[2] = 0;
result[3] = 0;
result[4] = 0;
result[5] = scale;
result[6] = 0;
result[7] = 0;
result[8] = 0;
result[9] = 0;
result[10] = scale;
result[11] = 0;
result[12] = 0;
result[13] = 0;
result[14] = 0;
result[15] = 1;
return result;
}
/**
* Creates a rotation matrix.
*
* @param {Matrix3} rotation The rotation matrix.
* @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
*/
static fromRotation(rotation, result) {
Check_default.typeOf.object("rotation", rotation);
if (!defined_default(result)) {
result = new _Matrix4();
}
result[0] = rotation[0];
result[1] = rotation[1];
result[2] = rotation[2];
result[3] = 0;
result[4] = rotation[3];
result[5] = rotation[4];
result[6] = rotation[5];
result[7] = 0;
result[8] = rotation[6];
result[9] = rotation[7];
result[10] = rotation[8];
result[11] = 0;
result[12] = 0;
result[13] = 0;
result[14] = 0;
result[15] = 1;
return result;
}
/**
* Computes a Matrix4 instance from a Camera.
*
* @param {Camera} camera The camera to use.
* @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
*/
static fromCamera(camera, result) {
Check_default.typeOf.object("camera", camera);
const position = camera.position;
const direction2 = camera.direction;
const up = camera.up;
Check_default.typeOf.object("camera.position", position);
Check_default.typeOf.object("camera.direction", direction2);
Check_default.typeOf.object("camera.up", up);
Cartesian3_default.normalize(direction2, fromCameraF);
Cartesian3_default.normalize(
Cartesian3_default.cross(fromCameraF, up, fromCameraR),
fromCameraR
);
Cartesian3_default.normalize(
Cartesian3_default.cross(fromCameraR, fromCameraF, fromCameraU),
fromCameraU
);
const sX = fromCameraR.x;
const sY = fromCameraR.y;
const sZ = fromCameraR.z;
const fX = fromCameraF.x;
const fY = fromCameraF.y;
const fZ = fromCameraF.z;
const uX = fromCameraU.x;
const uY = fromCameraU.y;
const uZ = fromCameraU.z;
const positionX = position.x;
const positionY = position.y;
const positionZ = position.z;
const t0 = sX * -positionX + sY * -positionY + sZ * -positionZ;
const t1 = uX * -positionX + uY * -positionY + uZ * -positionZ;
const t2 = fX * positionX + fY * positionY + fZ * positionZ;
if (!defined_default(result)) {
return new _Matrix4(
sX,
sY,
sZ,
t0,
uX,
uY,
uZ,
t1,
-fX,
-fY,
-fZ,
t2,
0,
0,
0,
1
);
}
result[0] = sX;
result[1] = uX;
result[2] = -fX;
result[3] = 0;
result[4] = sY;
result[5] = uY;
result[6] = -fY;
result[7] = 0;
result[8] = sZ;
result[9] = uZ;
result[10] = -fZ;
result[11] = 0;
result[12] = t0;
result[13] = t1;
result[14] = t2;
result[15] = 1;
return result;
}
/**
* Computes a Matrix4 instance representing a perspective transformation matrix.
*
* @param {number} fovY The field of view along the Y axis in radians.
* @param {number} aspectRatio The aspect ratio.
* @param {number} near The distance to the near plane in meters.
* @param {number} far The distance to the far plane in meters.
* @param {Matrix4} result The object in which the result will be stored.
* @returns {Matrix4} The modified result parameter.
*
* @exception {DeveloperError} fovY must be in (0, PI].
* @exception {DeveloperError} aspectRatio must be greater than zero.
* @exception {DeveloperError} near must be greater than zero.
* @exception {DeveloperError} far must be greater than zero.
*/
static computePerspectiveFieldOfView(fovY, aspectRatio, near, far, result) {
Check_default.typeOf.number.greaterThan("fovY", fovY, 0);
Check_default.typeOf.number.lessThan("fovY", fovY, Math.PI);
Check_default.typeOf.number.greaterThan("near", near, 0);
Check_default.typeOf.number.greaterThan("far", far, 0);
Check_default.typeOf.object("result", result);
const bottom = Math.tan(fovY * 0.5);
const column1Row1 = 1 / bottom;
const column0Row0 = column1Row1 / aspectRatio;
const column2Row2 = (far + near) / (near - far);
const column3Row2 = 2 * far * near / (near - far);
result[0] = column0Row0;
result[1] = 0;
result[2] = 0;
result[3] = 0;
result[4] = 0;
result[5] = column1Row1;
result[6] = 0;
result[7] = 0;
result[8] = 0;
result[9] = 0;
result[10] = column2Row2;
result[11] = -1;
result[12] = 0;
result[13] = 0;
result[14] = column3Row2;
result[15] = 0;
return result;
}
/**
* Computes a Matrix4 instance representing an orthographic transformation matrix.
*
* @param {number} left The number of meters to the left of the camera that will be in view.
* @param {number} right The number of meters to the right of the camera that will be in view.
* @param {number} bottom The number of meters below of the camera that will be in view.
* @param {number} top The number of meters above of the camera that will be in view.
* @param {number} near The distance to the near plane in meters.
* @param {number} far The distance to the far plane in meters.
* @param {Matrix4} result The object in which the result will be stored.
* @returns {Matrix4} The modified result parameter.
*/
static computeOrthographicOffCenter(left, right, bottom, top, near, far, result) {
Check_default.typeOf.number("left", left);
Check_default.typeOf.number("right", right);
Check_default.typeOf.number("bottom", bottom);
Check_default.typeOf.number("top", top);
Check_default.typeOf.number("near", near);
Check_default.typeOf.number("far", far);
Check_default.typeOf.object("result", result);
let a3 = 1 / (right - left);
let b = 1 / (top - bottom);
let c14 = 1 / (far - near);
const tx = -(right + left) * a3;
const ty = -(top + bottom) * b;
const tz = -(far + near) * c14;
a3 *= 2;
b *= 2;
c14 *= -2;
result[0] = a3;
result[1] = 0;
result[2] = 0;
result[3] = 0;
result[4] = 0;
result[5] = b;
result[6] = 0;
result[7] = 0;
result[8] = 0;
result[9] = 0;
result[10] = c14;
result[11] = 0;
result[12] = tx;
result[13] = ty;
result[14] = tz;
result[15] = 1;
return result;
}
/**
* Computes a Matrix4 instance representing an off center perspective transformation.
*
* @param {number} left The number of meters to the left of the camera that will be in view.
* @param {number} right The number of meters to the right of the camera that will be in view.
* @param {number} bottom The number of meters below the camera that will be in view.
* @param {number} top The number of meters above the camera that will be in view.
* @param {number} near The distance to the near plane in meters.
* @param {number} far The distance to the far plane in meters.
* @param {Matrix4} result The object in which the result will be stored.
* @returns {Matrix4} The modified result parameter.
*/
static computePerspectiveOffCenter(left, right, bottom, top, near, far, result) {
Check_default.typeOf.number("left", left);
Check_default.typeOf.number("right", right);
Check_default.typeOf.number("bottom", bottom);
Check_default.typeOf.number("top", top);
Check_default.typeOf.number("near", near);
Check_default.typeOf.number("far", far);
Check_default.typeOf.object("result", result);
const column0Row0 = 2 * near / (right - left);
const column1Row1 = 2 * near / (top - bottom);
const column2Row0 = (right + left) / (right - left);
const column2Row1 = (top + bottom) / (top - bottom);
const column2Row2 = -(far + near) / (far - near);
const column2Row3 = -1;
const column3Row2 = -2 * far * near / (far - near);
result[0] = column0Row0;
result[1] = 0;
result[2] = 0;
result[3] = 0;
result[4] = 0;
result[5] = column1Row1;
result[6] = 0;
result[7] = 0;
result[8] = column2Row0;
result[9] = column2Row1;
result[10] = column2Row2;
result[11] = column2Row3;
result[12] = 0;
result[13] = 0;
result[14] = column3Row2;
result[15] = 0;
return result;
}
/**
* Computes a Matrix4 instance representing an infinite off center perspective transformation.
*
* @param {number} left The number of meters to the left of the camera that will be in view.
* @param {number} right The number of meters to the right of the camera that will be in view.
* @param {number} bottom The number of meters below of the camera that will be in view.
* @param {number} top The number of meters above of the camera that will be in view.
* @param {number} near The distance to the near plane in meters.
* @param {Matrix4} result The object in which the result will be stored.
* @returns {Matrix4} The modified result parameter.
*/
static computeInfinitePerspectiveOffCenter(left, right, bottom, top, near, result) {
Check_default.typeOf.number("left", left);
Check_default.typeOf.number("right", right);
Check_default.typeOf.number("bottom", bottom);
Check_default.typeOf.number("top", top);
Check_default.typeOf.number("near", near);
Check_default.typeOf.object("result", result);
const column0Row0 = 2 * near / (right - left);
const column1Row1 = 2 * near / (top - bottom);
const column2Row0 = (right + left) / (right - left);
const column2Row1 = (top + bottom) / (top - bottom);
const column2Row2 = -1;
const column2Row3 = -1;
const column3Row2 = -2 * near;
result[0] = column0Row0;
result[1] = 0;
result[2] = 0;
result[3] = 0;
result[4] = 0;
result[5] = column1Row1;
result[6] = 0;
result[7] = 0;
result[8] = column2Row0;
result[9] = column2Row1;
result[10] = column2Row2;
result[11] = column2Row3;
result[12] = 0;
result[13] = 0;
result[14] = column3Row2;
result[15] = 0;
return result;
}
/**
* Computes a Matrix4 instance that transforms from normalized device coordinates to window coordinates.
*
* @param {Viewport} [viewport = { x : 0.0, y : 0.0, width : 0.0, height : 0.0 }] The viewport's corners as shown in Example 1.
* @param {number} [nearDepthRange=0.0] The near plane distance in window coordinates.
* @param {number} [farDepthRange=1.0] The far plane distance in window coordinates.
* @param {Matrix4} [result] The object in which the result will be stored.
* @returns {Matrix4} The modified result parameter.
*
* @example
* // Create viewport transformation using an explicit viewport and depth range.
* const m = Cesium.Matrix4.computeViewportTransformation({
* x : 0.0,
* y : 0.0,
* width : 1024.0,
* height : 768.0
* }, 0.0, 1.0, new Cesium.Matrix4());
*/
static computeViewportTransformation(viewport, nearDepthRange, farDepthRange, result) {
if (!defined_default(result)) {
result = new _Matrix4();
}
viewport = viewport ?? Frozen_default.EMPTY_OBJECT;
const x = viewport.x ?? 0;
const y = viewport.y ?? 0;
const width = viewport.width ?? 0;
const height = viewport.height ?? 0;
nearDepthRange = nearDepthRange ?? 0;
farDepthRange = farDepthRange ?? 1;
const halfWidth = width * 0.5;
const halfHeight = height * 0.5;
const halfDepth = (farDepthRange - nearDepthRange) * 0.5;
const column0Row0 = halfWidth;
const column1Row1 = halfHeight;
const column2Row2 = halfDepth;
const column3Row0 = x + halfWidth;
const column3Row1 = y + halfHeight;
const column3Row2 = nearDepthRange + halfDepth;
const column3Row3 = 1;
result[0] = column0Row0;
result[1] = 0;
result[2] = 0;
result[3] = 0;
result[4] = 0;
result[5] = column1Row1;
result[6] = 0;
result[7] = 0;
result[8] = 0;
result[9] = 0;
result[10] = column2Row2;
result[11] = 0;
result[12] = column3Row0;
result[13] = column3Row1;
result[14] = column3Row2;
result[15] = column3Row3;
return result;
}
/**
* Computes a Matrix4 instance that transforms from world space to view space.
*
* @param {Cartesian3} position The position of the camera.
* @param {Cartesian3} direction The forward direction.
* @param {Cartesian3} up The up direction.
* @param {Cartesian3} right The right direction.
* @param {Matrix4} result The object in which the result will be stored.
* @returns {Matrix4} The modified result parameter.
*/
static computeView(position, direction2, up, right, result) {
Check_default.typeOf.object("position", position);
Check_default.typeOf.object("direction", direction2);
Check_default.typeOf.object("up", up);
Check_default.typeOf.object("right", right);
Check_default.typeOf.object("result", result);
result[0] = right.x;
result[1] = up.x;
result[2] = -direction2.x;
result[3] = 0;
result[4] = right.y;
result[5] = up.y;
result[6] = -direction2.y;
result[7] = 0;
result[8] = right.z;
result[9] = up.z;
result[10] = -direction2.z;
result[11] = 0;
result[12] = -Cartesian3_default.dot(right, position);
result[13] = -Cartesian3_default.dot(up, position);
result[14] = Cartesian3_default.dot(direction2, position);
result[15] = 1;
return result;
}
/**
* Computes an Array from the provided Matrix4 instance.
* The array will be in column-major order.
*
* @param {Matrix4} matrix The matrix to use..
* @param {number[]} [result] The Array onto which to store the result.
* @returns {number[]} The modified Array parameter or a new Array instance if one was not provided.
*
* @example
* //create an array from an instance of Matrix4
* // m = [10.0, 14.0, 18.0, 22.0]
* // [11.0, 15.0, 19.0, 23.0]
* // [12.0, 16.0, 20.0, 24.0]
* // [13.0, 17.0, 21.0, 25.0]
* const a = Cesium.Matrix4.toArray(m);
*
* // m remains the same
* //creates a = [10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0, 25.0]
*/
static toArray(matrix, result) {
Check_default.typeOf.object("matrix", matrix);
if (!defined_default(result)) {
return [
matrix[0],
matrix[1],
matrix[2],
matrix[3],
matrix[4],
matrix[5],
matrix[6],
matrix[7],
matrix[8],
matrix[9],
matrix[10],
matrix[11],
matrix[12],
matrix[13],
matrix[14],
matrix[15]
];
}
result[0] = matrix[0];
result[1] = matrix[1];
result[2] = matrix[2];
result[3] = matrix[3];
result[4] = matrix[4];
result[5] = matrix[5];
result[6] = matrix[6];
result[7] = matrix[7];
result[8] = matrix[8];
result[9] = matrix[9];
result[10] = matrix[10];
result[11] = matrix[11];
result[12] = matrix[12];
result[13] = matrix[13];
result[14] = matrix[14];
result[15] = matrix[15];
return result;
}
/**
* Computes the array index of the element at the provided row and column.
*
* @param {number} row The zero-based index of the row.
* @param {number} column The zero-based index of the column.
* @returns {number} The index of the element at the provided row and column.
*
* @exception {DeveloperError} row must be 0, 1, 2, or 3.
* @exception {DeveloperError} column must be 0, 1, 2, or 3.
*
* @example
* const myMatrix = new Cesium.Matrix4();
* const column1Row0Index = Cesium.Matrix4.getElementIndex(1, 0);
* const column1Row0 = myMatrix[column1Row0Index];
* myMatrix[column1Row0Index] = 10.0;
*/
static getElementIndex(column, row) {
Check_default.typeOf.number.greaterThanOrEquals("row", row, 0);
Check_default.typeOf.number.lessThanOrEquals("row", row, 3);
Check_default.typeOf.number.greaterThanOrEquals("column", column, 0);
Check_default.typeOf.number.lessThanOrEquals("column", column, 3);
return column * 4 + row;
}
/**
* Retrieves a copy of the matrix column at the provided index as a Cartesian4 instance.
*
* @param {Matrix4} matrix The matrix to use.
* @param {number} index The zero-based index of the column to retrieve.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*
* @exception {DeveloperError} index must be 0, 1, 2, or 3.
*
* @example
* //returns a Cartesian4 instance with values from the specified column
* // m = [10.0, 11.0, 12.0, 13.0]
* // [14.0, 15.0, 16.0, 17.0]
* // [18.0, 19.0, 20.0, 21.0]
* // [22.0, 23.0, 24.0, 25.0]
*
* //Example 1: Creates an instance of Cartesian
* const a = Cesium.Matrix4.getColumn(m, 2, new Cesium.Cartesian4());
*
* @example
* //Example 2: Sets values for Cartesian instance
* const a = new Cesium.Cartesian4();
* Cesium.Matrix4.getColumn(m, 2, a);
*
* // a.x = 12.0; a.y = 16.0; a.z = 20.0; a.w = 24.0;
*/
static getColumn(matrix, index, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.number.greaterThanOrEquals("index", index, 0);
Check_default.typeOf.number.lessThanOrEquals("index", index, 3);
Check_default.typeOf.object("result", result);
const startIndex = index * 4;
const x = matrix[startIndex];
const y = matrix[startIndex + 1];
const z2 = matrix[startIndex + 2];
const w = matrix[startIndex + 3];
result.x = x;
result.y = y;
result.z = z2;
result.w = w;
return result;
}
/**
* Computes a new matrix that replaces the specified column in the provided matrix with the provided Cartesian4 instance.
*
* @param {Matrix4} matrix The matrix to use.
* @param {number} index The zero-based index of the column to set.
* @param {Cartesian4} cartesian The Cartesian whose values will be assigned to the specified column.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @exception {DeveloperError} index must be 0, 1, 2, or 3.
*
* @example
* //creates a new Matrix4 instance with new column values from the Cartesian4 instance
* // m = [10.0, 11.0, 12.0, 13.0]
* // [14.0, 15.0, 16.0, 17.0]
* // [18.0, 19.0, 20.0, 21.0]
* // [22.0, 23.0, 24.0, 25.0]
*
* const a = Cesium.Matrix4.setColumn(m, 2, new Cesium.Cartesian4(99.0, 98.0, 97.0, 96.0), new Cesium.Matrix4());
*
* // m remains the same
* // a = [10.0, 11.0, 99.0, 13.0]
* // [14.0, 15.0, 98.0, 17.0]
* // [18.0, 19.0, 97.0, 21.0]
* // [22.0, 23.0, 96.0, 25.0]
*/
static setColumn(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, 3);
Check_default.typeOf.object("cartesian", cartesian11);
Check_default.typeOf.object("result", result);
result = _Matrix4.clone(matrix, result);
const startIndex = index * 4;
result[startIndex] = cartesian11.x;
result[startIndex + 1] = cartesian11.y;
result[startIndex + 2] = cartesian11.z;
result[startIndex + 3] = cartesian11.w;
return result;
}
/**
* Retrieves a copy of the matrix row at the provided index as a Cartesian4 instance.
*
* @param {Matrix4} matrix The matrix to use.
* @param {number} index The zero-based index of the row to retrieve.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*
* @exception {DeveloperError} index must be 0, 1, 2, or 3.
*
* @example
* //returns a Cartesian4 instance with values from the specified column
* // m = [10.0, 11.0, 12.0, 13.0]
* // [14.0, 15.0, 16.0, 17.0]
* // [18.0, 19.0, 20.0, 21.0]
* // [22.0, 23.0, 24.0, 25.0]
*
* //Example 1: Returns an instance of Cartesian
* const a = Cesium.Matrix4.getRow(m, 2, new Cesium.Cartesian4());
*
* @example
* //Example 2: Sets values for a Cartesian instance
* const a = new Cesium.Cartesian4();
* Cesium.Matrix4.getRow(m, 2, a);
*
* // a.x = 18.0; a.y = 19.0; a.z = 20.0; a.w = 21.0;
*/
static getRow(matrix, index, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.number.greaterThanOrEquals("index", index, 0);
Check_default.typeOf.number.lessThanOrEquals("index", index, 3);
Check_default.typeOf.object("result", result);
const x = matrix[index];
const y = matrix[index + 4];
const z2 = matrix[index + 8];
const w = matrix[index + 12];
result.x = x;
result.y = y;
result.z = z2;
result.w = w;
return result;
}
/**
* Computes a new matrix that replaces the specified row in the provided matrix with the provided Cartesian4 instance.
*
* @param {Matrix4} matrix The matrix to use.
* @param {number} index The zero-based index of the row to set.
* @param {Cartesian4} cartesian The Cartesian whose values will be assigned to the specified row.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @exception {DeveloperError} index must be 0, 1, 2, or 3.
*
* @example
* //create a new Matrix4 instance with new row values from the Cartesian4 instance
* // m = [10.0, 11.0, 12.0, 13.0]
* // [14.0, 15.0, 16.0, 17.0]
* // [18.0, 19.0, 20.0, 21.0]
* // [22.0, 23.0, 24.0, 25.0]
*
* const a = Cesium.Matrix4.setRow(m, 2, new Cesium.Cartesian4(99.0, 98.0, 97.0, 96.0), new Cesium.Matrix4());
*
* // m remains the same
* // a = [10.0, 11.0, 12.0, 13.0]
* // [14.0, 15.0, 16.0, 17.0]
* // [99.0, 98.0, 97.0, 96.0]
* // [22.0, 23.0, 24.0, 25.0]
*/
static setRow(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, 3);
Check_default.typeOf.object("cartesian", cartesian11);
Check_default.typeOf.object("result", result);
result = _Matrix4.clone(matrix, result);
result[index] = cartesian11.x;
result[index + 4] = cartesian11.y;
result[index + 8] = cartesian11.z;
result[index + 12] = cartesian11.w;
return result;
}
/**
* Computes a new matrix that replaces the translation in the rightmost column of the provided
* matrix with the provided translation. This assumes the matrix is an affine transformation.
*
* @param {Matrix4} matrix The matrix to use.
* @param {Cartesian3} translation The translation that replaces the translation of the provided matrix.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*/
static setTranslation(matrix, translation3, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.object("translation", translation3);
Check_default.typeOf.object("result", result);
result[0] = matrix[0];
result[1] = matrix[1];
result[2] = matrix[2];
result[3] = matrix[3];
result[4] = matrix[4];
result[5] = matrix[5];
result[6] = matrix[6];
result[7] = matrix[7];
result[8] = matrix[8];
result[9] = matrix[9];
result[10] = matrix[10];
result[11] = matrix[11];
result[12] = translation3.x;
result[13] = translation3.y;
result[14] = translation3.z;
result[15] = matrix[15];
return result;
}
/**
* Computes a new matrix that replaces the scale with the provided scale.
* This assumes the matrix is an affine transformation.
*
* @param {Matrix4} matrix The matrix to use.
* @param {Cartesian3} scale The scale that replaces the scale of the provided matrix.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @see Matrix4.setUniformScale
* @see Matrix4.fromScale
* @see Matrix4.fromUniformScale
* @see Matrix4.multiplyByScale
* @see Matrix4.multiplyByUniformScale
* @see Matrix4.getScale
*/
static setScale(matrix, scale, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.object("scale", scale);
Check_default.typeOf.object("result", result);
const existingScale = _Matrix4.getScale(matrix, scaleScratch12);
const scaleRatioX = scale.x / existingScale.x;
const scaleRatioY = scale.y / existingScale.y;
const scaleRatioZ = scale.z / existingScale.z;
result[0] = matrix[0] * scaleRatioX;
result[1] = matrix[1] * scaleRatioX;
result[2] = matrix[2] * scaleRatioX;
result[3] = matrix[3];
result[4] = matrix[4] * scaleRatioY;
result[5] = matrix[5] * scaleRatioY;
result[6] = matrix[6] * scaleRatioY;
result[7] = matrix[7];
result[8] = matrix[8] * scaleRatioZ;
result[9] = matrix[9] * scaleRatioZ;
result[10] = matrix[10] * scaleRatioZ;
result[11] = matrix[11];
result[12] = matrix[12];
result[13] = matrix[13];
result[14] = matrix[14];
result[15] = matrix[15];
return result;
}
/**
* Computes a new matrix that replaces the scale with the provided uniform scale.
* This assumes the matrix is an affine transformation.
*
* @param {Matrix4} matrix The matrix to use.
* @param {number} scale The uniform scale that replaces the scale of the provided matrix.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @see Matrix4.setScale
* @see Matrix4.fromScale
* @see Matrix4.fromUniformScale
* @see Matrix4.multiplyByScale
* @see Matrix4.multiplyByUniformScale
* @see Matrix4.getScale
*/
static setUniformScale(matrix, scale, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.number("scale", scale);
Check_default.typeOf.object("result", result);
const existingScale = _Matrix4.getScale(matrix, scaleScratch22);
const scaleRatioX = scale / existingScale.x;
const scaleRatioY = scale / existingScale.y;
const scaleRatioZ = scale / existingScale.z;
result[0] = matrix[0] * scaleRatioX;
result[1] = matrix[1] * scaleRatioX;
result[2] = matrix[2] * scaleRatioX;
result[3] = matrix[3];
result[4] = matrix[4] * scaleRatioY;
result[5] = matrix[5] * scaleRatioY;
result[6] = matrix[6] * scaleRatioY;
result[7] = matrix[7];
result[8] = matrix[8] * scaleRatioZ;
result[9] = matrix[9] * scaleRatioZ;
result[10] = matrix[10] * scaleRatioZ;
result[11] = matrix[11];
result[12] = matrix[12];
result[13] = matrix[13];
result[14] = matrix[14];
result[15] = matrix[15];
return result;
}
/**
* Extracts the non-uniform scale assuming the matrix is an affine transformation.
*
* @param {Matrix4} matrix The matrix.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter
*
* @see Matrix4.multiplyByScale
* @see Matrix4.multiplyByUniformScale
* @see Matrix4.fromScale
* @see Matrix4.fromUniformScale
* @see Matrix4.setScale
* @see Matrix4.setUniformScale
*/
static getScale(matrix, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.object("result", result);
result.x = Cartesian3_default.magnitude(
Cartesian3_default.fromElements(matrix[0], matrix[1], matrix[2], scratchColumn2)
);
result.y = Cartesian3_default.magnitude(
Cartesian3_default.fromElements(matrix[4], matrix[5], matrix[6], scratchColumn2)
);
result.z = Cartesian3_default.magnitude(
Cartesian3_default.fromElements(matrix[8], matrix[9], matrix[10], scratchColumn2)
);
return result;
}
/**
* Computes the maximum scale assuming the matrix is an affine transformation.
* The maximum scale is the maximum length of the column vectors in the upper-left
* 3x3 matrix.
*
* @param {Matrix4} matrix The matrix.
* @returns {number} The maximum scale.
*/
static getMaximumScale(matrix) {
_Matrix4.getScale(matrix, scaleScratch32);
return Cartesian3_default.maximumComponent(scaleScratch32);
}
/**
* Sets the rotation assuming the matrix is an affine transformation.
*
* @param {Matrix4} matrix The matrix.
* @param {Matrix3} rotation The rotation matrix.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @see Matrix4.fromRotation
* @see Matrix4.getRotation
*/
static setRotation(matrix, rotation, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.object("result", result);
const scale = _Matrix4.getScale(matrix, scaleScratch42);
result[0] = rotation[0] * scale.x;
result[1] = rotation[1] * scale.x;
result[2] = rotation[2] * scale.x;
result[3] = matrix[3];
result[4] = rotation[3] * scale.y;
result[5] = rotation[4] * scale.y;
result[6] = rotation[5] * scale.y;
result[7] = matrix[7];
result[8] = rotation[6] * scale.z;
result[9] = rotation[7] * scale.z;
result[10] = rotation[8] * scale.z;
result[11] = matrix[11];
result[12] = matrix[12];
result[13] = matrix[13];
result[14] = matrix[14];
result[15] = matrix[15];
return result;
}
/**
* Extracts the rotation matrix assuming the matrix is an affine transformation.
*
* @param {Matrix4} matrix The matrix.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*
* @see Matrix4.setRotation
* @see Matrix4.fromRotation
*/
static getRotation(matrix, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.object("result", result);
const scale = _Matrix4.getScale(matrix, scaleScratch52);
result[0] = matrix[0] / scale.x;
result[1] = matrix[1] / scale.x;
result[2] = matrix[2] / scale.x;
result[3] = matrix[4] / scale.y;
result[4] = matrix[5] / scale.y;
result[5] = matrix[6] / scale.y;
result[6] = matrix[8] / scale.z;
result[7] = matrix[9] / scale.z;
result[8] = matrix[10] / scale.z;
return result;
}
/**
* Computes the product of two matrices.
*
* @param {Matrix4} left The first matrix.
* @param {Matrix4} right The second matrix.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*/
static multiply(left, right, result) {
Check_default.typeOf.object("left", left);
Check_default.typeOf.object("right", right);
Check_default.typeOf.object("result", result);
const left0 = left[0];
const left1 = left[1];
const left2 = left[2];
const left3 = left[3];
const left4 = left[4];
const left5 = left[5];
const left6 = left[6];
const left7 = left[7];
const left8 = left[8];
const left9 = left[9];
const left10 = left[10];
const left11 = left[11];
const left12 = left[12];
const left13 = left[13];
const left14 = left[14];
const left15 = left[15];
const right0 = right[0];
const right1 = right[1];
const right2 = right[2];
const right3 = right[3];
const right4 = right[4];
const right5 = right[5];
const right6 = right[6];
const right7 = right[7];
const right8 = right[8];
const right9 = right[9];
const right10 = right[10];
const right11 = right[11];
const right12 = right[12];
const right13 = right[13];
const right14 = right[14];
const right15 = right[15];
const column0Row0 = left0 * right0 + left4 * right1 + left8 * right2 + left12 * right3;
const column0Row1 = left1 * right0 + left5 * right1 + left9 * right2 + left13 * right3;
const column0Row2 = left2 * right0 + left6 * right1 + left10 * right2 + left14 * right3;
const column0Row3 = left3 * right0 + left7 * right1 + left11 * right2 + left15 * right3;
const column1Row0 = left0 * right4 + left4 * right5 + left8 * right6 + left12 * right7;
const column1Row1 = left1 * right4 + left5 * right5 + left9 * right6 + left13 * right7;
const column1Row2 = left2 * right4 + left6 * right5 + left10 * right6 + left14 * right7;
const column1Row3 = left3 * right4 + left7 * right5 + left11 * right6 + left15 * right7;
const column2Row0 = left0 * right8 + left4 * right9 + left8 * right10 + left12 * right11;
const column2Row1 = left1 * right8 + left5 * right9 + left9 * right10 + left13 * right11;
const column2Row2 = left2 * right8 + left6 * right9 + left10 * right10 + left14 * right11;
const column2Row3 = left3 * right8 + left7 * right9 + left11 * right10 + left15 * right11;
const column3Row0 = left0 * right12 + left4 * right13 + left8 * right14 + left12 * right15;
const column3Row1 = left1 * right12 + left5 * right13 + left9 * right14 + left13 * right15;
const column3Row2 = left2 * right12 + left6 * right13 + left10 * right14 + left14 * right15;
const column3Row3 = left3 * right12 + left7 * right13 + left11 * right14 + left15 * right15;
result[0] = column0Row0;
result[1] = column0Row1;
result[2] = column0Row2;
result[3] = column0Row3;
result[4] = column1Row0;
result[5] = column1Row1;
result[6] = column1Row2;
result[7] = column1Row3;
result[8] = column2Row0;
result[9] = column2Row1;
result[10] = column2Row2;
result[11] = column2Row3;
result[12] = column3Row0;
result[13] = column3Row1;
result[14] = column3Row2;
result[15] = column3Row3;
return result;
}
/**
* Computes the sum of two matrices.
*
* @param {Matrix4} left The first matrix.
* @param {Matrix4} right The second matrix.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*/
static add(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];
result[4] = left[4] + right[4];
result[5] = left[5] + right[5];
result[6] = left[6] + right[6];
result[7] = left[7] + right[7];
result[8] = left[8] + right[8];
result[9] = left[9] + right[9];
result[10] = left[10] + right[10];
result[11] = left[11] + right[11];
result[12] = left[12] + right[12];
result[13] = left[13] + right[13];
result[14] = left[14] + right[14];
result[15] = left[15] + right[15];
return result;
}
/**
* Computes the difference of two matrices.
*
* @param {Matrix4} left The first matrix.
* @param {Matrix4} right The second matrix.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*/
static subtract(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];
result[4] = left[4] - right[4];
result[5] = left[5] - right[5];
result[6] = left[6] - right[6];
result[7] = left[7] - right[7];
result[8] = left[8] - right[8];
result[9] = left[9] - right[9];
result[10] = left[10] - right[10];
result[11] = left[11] - right[11];
result[12] = left[12] - right[12];
result[13] = left[13] - right[13];
result[14] = left[14] - right[14];
result[15] = left[15] - right[15];
return result;
}
/**
* Computes the product of two matrices assuming the matrices are affine transformation matrices,
* where the upper left 3x3 elements are any matrix, and
* the upper three elements in the fourth column are the translation.
* The bottom row is assumed to be [0, 0, 0, 1].
* The matrix is not verified to be in the proper form.
* This method is faster than computing the product for general 4x4
* matrices using {@link Matrix4.multiply}.
*
* @param {Matrix4} left The first matrix.
* @param {Matrix4} right The second matrix.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @example
* const m1 = new Cesium.Matrix4(1.0, 6.0, 7.0, 0.0, 2.0, 5.0, 8.0, 0.0, 3.0, 4.0, 9.0, 0.0, 0.0, 0.0, 0.0, 1.0);
* const m2 = Cesium.Transforms.eastNorthUpToFixedFrame(new Cesium.Cartesian3(1.0, 1.0, 1.0));
* const m3 = Cesium.Matrix4.multiplyTransformation(m1, m2, new Cesium.Matrix4());
*/
static multiplyTransformation(left, right, result) {
Check_default.typeOf.object("left", left);
Check_default.typeOf.object("right", right);
Check_default.typeOf.object("result", result);
const left0 = left[0];
const left1 = left[1];
const left2 = left[2];
const left4 = left[4];
const left5 = left[5];
const left6 = left[6];
const left8 = left[8];
const left9 = left[9];
const left10 = left[10];
const left12 = left[12];
const left13 = left[13];
const left14 = left[14];
const right0 = right[0];
const right1 = right[1];
const right2 = right[2];
const right4 = right[4];
const right5 = right[5];
const right6 = right[6];
const right8 = right[8];
const right9 = right[9];
const right10 = right[10];
const right12 = right[12];
const right13 = right[13];
const right14 = right[14];
const column0Row0 = left0 * right0 + left4 * right1 + left8 * right2;
const column0Row1 = left1 * right0 + left5 * right1 + left9 * right2;
const column0Row2 = left2 * right0 + left6 * right1 + left10 * right2;
const column1Row0 = left0 * right4 + left4 * right5 + left8 * right6;
const column1Row1 = left1 * right4 + left5 * right5 + left9 * right6;
const column1Row2 = left2 * right4 + left6 * right5 + left10 * right6;
const column2Row0 = left0 * right8 + left4 * right9 + left8 * right10;
const column2Row1 = left1 * right8 + left5 * right9 + left9 * right10;
const column2Row2 = left2 * right8 + left6 * right9 + left10 * right10;
const column3Row0 = left0 * right12 + left4 * right13 + left8 * right14 + left12;
const column3Row1 = left1 * right12 + left5 * right13 + left9 * right14 + left13;
const column3Row2 = left2 * right12 + left6 * right13 + left10 * right14 + left14;
result[0] = column0Row0;
result[1] = column0Row1;
result[2] = column0Row2;
result[3] = 0;
result[4] = column1Row0;
result[5] = column1Row1;
result[6] = column1Row2;
result[7] = 0;
result[8] = column2Row0;
result[9] = column2Row1;
result[10] = column2Row2;
result[11] = 0;
result[12] = column3Row0;
result[13] = column3Row1;
result[14] = column3Row2;
result[15] = 1;
return result;
}
/**
* Multiplies a transformation matrix (with a bottom row of [0.0, 0.0, 0.0, 1.0])
* by a 3x3 rotation matrix. This is an optimization
* for Matrix4.multiply(m, Matrix4.fromRotationTranslation(rotation), m); with less allocations and arithmetic operations.
*
* @param {Matrix4} matrix The matrix on the left-hand side.
* @param {Matrix3} rotation The 3x3 rotation matrix on the right-hand side.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @example
* // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromRotationTranslation(rotation), m);
* Cesium.Matrix4.multiplyByMatrix3(m, rotation, m);
*/
static multiplyByMatrix3(matrix, rotation, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.object("rotation", rotation);
Check_default.typeOf.object("result", result);
const left0 = matrix[0];
const left1 = matrix[1];
const left2 = matrix[2];
const left4 = matrix[4];
const left5 = matrix[5];
const left6 = matrix[6];
const left8 = matrix[8];
const left9 = matrix[9];
const left10 = matrix[10];
const right0 = rotation[0];
const right1 = rotation[1];
const right2 = rotation[2];
const right4 = rotation[3];
const right5 = rotation[4];
const right6 = rotation[5];
const right8 = rotation[6];
const right9 = rotation[7];
const right10 = rotation[8];
const column0Row0 = left0 * right0 + left4 * right1 + left8 * right2;
const column0Row1 = left1 * right0 + left5 * right1 + left9 * right2;
const column0Row2 = left2 * right0 + left6 * right1 + left10 * right2;
const column1Row0 = left0 * right4 + left4 * right5 + left8 * right6;
const column1Row1 = left1 * right4 + left5 * right5 + left9 * right6;
const column1Row2 = left2 * right4 + left6 * right5 + left10 * right6;
const column2Row0 = left0 * right8 + left4 * right9 + left8 * right10;
const column2Row1 = left1 * right8 + left5 * right9 + left9 * right10;
const column2Row2 = left2 * right8 + left6 * right9 + left10 * right10;
result[0] = column0Row0;
result[1] = column0Row1;
result[2] = column0Row2;
result[3] = 0;
result[4] = column1Row0;
result[5] = column1Row1;
result[6] = column1Row2;
result[7] = 0;
result[8] = column2Row0;
result[9] = column2Row1;
result[10] = column2Row2;
result[11] = 0;
result[12] = matrix[12];
result[13] = matrix[13];
result[14] = matrix[14];
result[15] = matrix[15];
return result;
}
/**
* Multiplies a transformation matrix (with a bottom row of [0.0, 0.0, 0.0, 1.0])
* by an implicit translation matrix defined by a {@link Cartesian3}. This is an optimization
* for Matrix4.multiply(m, Matrix4.fromTranslation(position), m); with less allocations and arithmetic operations.
*
* @param {Matrix4} matrix The matrix on the left-hand side.
* @param {Cartesian3} translation The translation on the right-hand side.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @example
* // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromTranslation(position), m);
* Cesium.Matrix4.multiplyByTranslation(m, position, m);
*/
static multiplyByTranslation(matrix, translation3, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.object("translation", translation3);
Check_default.typeOf.object("result", result);
const x = translation3.x;
const y = translation3.y;
const z2 = translation3.z;
const tx = x * matrix[0] + y * matrix[4] + z2 * matrix[8] + matrix[12];
const ty = x * matrix[1] + y * matrix[5] + z2 * matrix[9] + matrix[13];
const tz = x * matrix[2] + y * matrix[6] + z2 * matrix[10] + matrix[14];
result[0] = matrix[0];
result[1] = matrix[1];
result[2] = matrix[2];
result[3] = matrix[3];
result[4] = matrix[4];
result[5] = matrix[5];
result[6] = matrix[6];
result[7] = matrix[7];
result[8] = matrix[8];
result[9] = matrix[9];
result[10] = matrix[10];
result[11] = matrix[11];
result[12] = tx;
result[13] = ty;
result[14] = tz;
result[15] = matrix[15];
return result;
}
/**
* Multiplies an affine transformation matrix (with a bottom row of [0.0, 0.0, 0.0, 1.0])
* by an implicit non-uniform scale matrix. This is an optimization
* for Matrix4.multiply(m, Matrix4.fromUniformScale(scale), m);, where
* m must be an affine matrix.
* This function performs fewer allocations and arithmetic operations.
*
* @param {Matrix4} matrix The affine matrix on the left-hand side.
* @param {Cartesian3} scale The non-uniform scale on the right-hand side.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
*
* @example
* // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromScale(scale), m);
* Cesium.Matrix4.multiplyByScale(m, scale, m);
*
* @see Matrix4.multiplyByUniformScale
* @see Matrix4.fromScale
* @see Matrix4.fromUniformScale
* @see Matrix4.setScale
* @see Matrix4.setUniformScale
* @see Matrix4.getScale
*/
static multiplyByScale(matrix, scale, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.object("scale", scale);
Check_default.typeOf.object("result", result);
const scaleX = scale.x;
const scaleY = scale.y;
const scaleZ = scale.z;
if (scaleX === 1 && scaleY === 1 && scaleZ === 1) {
return _Matrix4.clone(matrix, result);
}
result[0] = scaleX * matrix[0];
result[1] = scaleX * matrix[1];
result[2] = scaleX * matrix[2];
result[3] = matrix[3];
result[4] = scaleY * matrix[4];
result[5] = scaleY * matrix[5];
result[6] = scaleY * matrix[6];
result[7] = matrix[7];
result[8] = scaleZ * matrix[8];
result[9] = scaleZ * matrix[9];
result[10] = scaleZ * matrix[10];
result[11] = matrix[11];
result[12] = matrix[12];
result[13] = matrix[13];
result[14] = matrix[14];
result[15] = matrix[15];
return result;
}
/**
* Computes the product of a matrix times a uniform scale, as if the scale were a scale matrix.
*
* @param {Matrix4} matrix The matrix on the left-hand side.
* @param {number} scale The uniform scale on the right-hand side.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @example
* // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromUniformScale(scale), m);
* Cesium.Matrix4.multiplyByUniformScale(m, scale, m);
*
* @see Matrix4.multiplyByScale
* @see Matrix4.fromScale
* @see Matrix4.fromUniformScale
* @see Matrix4.setScale
* @see Matrix4.setUniformScale
* @see Matrix4.getScale
*/
static multiplyByUniformScale(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];
result[4] = matrix[4] * scale;
result[5] = matrix[5] * scale;
result[6] = matrix[6] * scale;
result[7] = matrix[7];
result[8] = matrix[8] * scale;
result[9] = matrix[9] * scale;
result[10] = matrix[10] * scale;
result[11] = matrix[11];
result[12] = matrix[12];
result[13] = matrix[13];
result[14] = matrix[14];
result[15] = matrix[15];
return result;
}
/**
* Computes the product of a matrix and a column vector.
*
* @param {Matrix4} matrix The matrix.
* @param {Cartesian4} cartesian The vector.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*/
static multiplyByVector(matrix, cartesian11, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.object("cartesian", cartesian11);
Check_default.typeOf.object("result", result);
const vX = cartesian11.x;
const vY = cartesian11.y;
const vZ = cartesian11.z;
const vW = cartesian11.w;
const x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ + matrix[12] * vW;
const y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ + matrix[13] * vW;
const z2 = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ + matrix[14] * vW;
const w = matrix[3] * vX + matrix[7] * vY + matrix[11] * vZ + matrix[15] * vW;
result.x = x;
result.y = y;
result.z = z2;
result.w = w;
return result;
}
/**
* Computes the product of a matrix and a {@link Cartesian3}. This is equivalent to calling {@link Matrix4.multiplyByVector}
* with a {@link Cartesian4} with a w component of zero.
*
* @param {Matrix4} matrix The matrix.
* @param {Cartesian3} cartesian The point.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*
* @example
* const p = new Cesium.Cartesian3(1.0, 2.0, 3.0);
* const result = Cesium.Matrix4.multiplyByPointAsVector(matrix, p, new Cesium.Cartesian3());
* // A shortcut for
* // Cartesian3 p = ...
* // Cesium.Matrix4.multiplyByVector(matrix, new Cesium.Cartesian4(p.x, p.y, p.z, 0.0), result);
*/
static multiplyByPointAsVector(matrix, cartesian11, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.object("cartesian", cartesian11);
Check_default.typeOf.object("result", result);
const vX = cartesian11.x;
const vY = cartesian11.y;
const vZ = cartesian11.z;
const x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ;
const y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ;
const z2 = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ;
result.x = x;
result.y = y;
result.z = z2;
return result;
}
/**
* Computes the product of a matrix and a {@link Cartesian3}. This is equivalent to calling {@link Matrix4.multiplyByVector}
* with a {@link Cartesian4} with a w component of 1, but returns a {@link Cartesian3} instead of a {@link Cartesian4}.
*
* @param {Matrix4} matrix The matrix.
* @param {Cartesian3} cartesian The point.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*
* @example
* const p = new Cesium.Cartesian3(1.0, 2.0, 3.0);
* const result = Cesium.Matrix4.multiplyByPoint(matrix, p, new Cesium.Cartesian3());
*/
static multiplyByPoint(matrix, cartesian11, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.object("cartesian", cartesian11);
Check_default.typeOf.object("result", result);
const vX = cartesian11.x;
const vY = cartesian11.y;
const vZ = cartesian11.z;
const x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ + matrix[12];
const y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ + matrix[13];
const z2 = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ + matrix[14];
result.x = x;
result.y = y;
result.z = z2;
return result;
}
/**
* Computes the product of a matrix and a scalar.
*
* @param {Matrix4} matrix The matrix.
* @param {number} scalar The number to multiply by.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @example
* //create a Matrix4 instance which is a scaled version of the supplied Matrix4
* // m = [10.0, 11.0, 12.0, 13.0]
* // [14.0, 15.0, 16.0, 17.0]
* // [18.0, 19.0, 20.0, 21.0]
* // [22.0, 23.0, 24.0, 25.0]
*
* const a = Cesium.Matrix4.multiplyByScalar(m, -2, new Cesium.Matrix4());
*
* // m remains the same
* // a = [-20.0, -22.0, -24.0, -26.0]
* // [-28.0, -30.0, -32.0, -34.0]
* // [-36.0, -38.0, -40.0, -42.0]
* // [-44.0, -46.0, -48.0, -50.0]
*/
static multiplyByScalar(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;
result[4] = matrix[4] * scalar;
result[5] = matrix[5] * scalar;
result[6] = matrix[6] * scalar;
result[7] = matrix[7] * scalar;
result[8] = matrix[8] * scalar;
result[9] = matrix[9] * scalar;
result[10] = matrix[10] * scalar;
result[11] = matrix[11] * scalar;
result[12] = matrix[12] * scalar;
result[13] = matrix[13] * scalar;
result[14] = matrix[14] * scalar;
result[15] = matrix[15] * scalar;
return result;
}
/**
* Computes a negated copy of the provided matrix.
*
* @param {Matrix4} matrix The matrix to negate.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @example
* //create a new Matrix4 instance which is a negation of a Matrix4
* // m = [10.0, 11.0, 12.0, 13.0]
* // [14.0, 15.0, 16.0, 17.0]
* // [18.0, 19.0, 20.0, 21.0]
* // [22.0, 23.0, 24.0, 25.0]
*
* const a = Cesium.Matrix4.negate(m, new Cesium.Matrix4());
*
* // m remains the same
* // a = [-10.0, -11.0, -12.0, -13.0]
* // [-14.0, -15.0, -16.0, -17.0]
* // [-18.0, -19.0, -20.0, -21.0]
* // [-22.0, -23.0, -24.0, -25.0]
*/
static negate(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];
result[4] = -matrix[4];
result[5] = -matrix[5];
result[6] = -matrix[6];
result[7] = -matrix[7];
result[8] = -matrix[8];
result[9] = -matrix[9];
result[10] = -matrix[10];
result[11] = -matrix[11];
result[12] = -matrix[12];
result[13] = -matrix[13];
result[14] = -matrix[14];
result[15] = -matrix[15];
return result;
}
/**
* Computes the transpose of the provided matrix.
*
* @param {Matrix4} matrix The matrix to transpose.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @example
* //returns transpose of a Matrix4
* // m = [10.0, 11.0, 12.0, 13.0]
* // [14.0, 15.0, 16.0, 17.0]
* // [18.0, 19.0, 20.0, 21.0]
* // [22.0, 23.0, 24.0, 25.0]
*
* const a = Cesium.Matrix4.transpose(m, new Cesium.Matrix4());
*
* // m remains the same
* // a = [10.0, 14.0, 18.0, 22.0]
* // [11.0, 15.0, 19.0, 23.0]
* // [12.0, 16.0, 20.0, 24.0]
* // [13.0, 17.0, 21.0, 25.0]
*/
static transpose(matrix, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.object("result", result);
const matrix1 = matrix[1];
const matrix2 = matrix[2];
const matrix3 = matrix[3];
const matrix6 = matrix[6];
const matrix7 = matrix[7];
const matrix11 = matrix[11];
result[0] = matrix[0];
result[1] = matrix[4];
result[2] = matrix[8];
result[3] = matrix[12];
result[4] = matrix1;
result[5] = matrix[5];
result[6] = matrix[9];
result[7] = matrix[13];
result[8] = matrix2;
result[9] = matrix6;
result[10] = matrix[10];
result[11] = matrix[14];
result[12] = matrix3;
result[13] = matrix7;
result[14] = matrix11;
result[15] = matrix[15];
return result;
}
/**
* Computes a matrix, which contains the absolute (unsigned) values of the provided matrix's elements.
*
* @param {Matrix4} matrix The matrix with signed elements.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*/
static abs(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]);
result[4] = Math.abs(matrix[4]);
result[5] = Math.abs(matrix[5]);
result[6] = Math.abs(matrix[6]);
result[7] = Math.abs(matrix[7]);
result[8] = Math.abs(matrix[8]);
result[9] = Math.abs(matrix[9]);
result[10] = Math.abs(matrix[10]);
result[11] = Math.abs(matrix[11]);
result[12] = Math.abs(matrix[12]);
result[13] = Math.abs(matrix[13]);
result[14] = Math.abs(matrix[14]);
result[15] = Math.abs(matrix[15]);
return result;
}
/**
* Compares the provided matrices componentwise and returns
* true if they are equal, false otherwise.
*
* @param {Matrix4} [left] The first matrix.
* @param {Matrix4} [right] The second matrix.
* @returns {boolean} true if left and right are equal, false otherwise.
*
* @example
* //compares two Matrix4 instances
*
* // a = [10.0, 14.0, 18.0, 22.0]
* // [11.0, 15.0, 19.0, 23.0]
* // [12.0, 16.0, 20.0, 24.0]
* // [13.0, 17.0, 21.0, 25.0]
*
* // b = [10.0, 14.0, 18.0, 22.0]
* // [11.0, 15.0, 19.0, 23.0]
* // [12.0, 16.0, 20.0, 24.0]
* // [13.0, 17.0, 21.0, 25.0]
*
* if(Cesium.Matrix4.equals(a,b)) {
* console.log("Both matrices are equal");
* } else {
* console.log("They are not equal");
* }
*
* //Prints "Both matrices are equal" on the console
*/
static equals(left, right) {
return left === right || defined_default(left) && defined_default(right) && // Translation
left[12] === right[12] && left[13] === right[13] && left[14] === right[14] && // Rotation/scale
left[0] === right[0] && left[1] === right[1] && left[2] === right[2] && left[4] === right[4] && left[5] === right[5] && left[6] === right[6] && left[8] === right[8] && left[9] === right[9] && left[10] === right[10] && // Bottom row
left[3] === right[3] && left[7] === right[7] && left[11] === right[11] && left[15] === right[15];
}
/**
* Compares the provided matrices componentwise and returns
* true if they are within the provided epsilon,
* false otherwise.
*
* @param {Matrix4} [left] The first matrix.
* @param {Matrix4} [right] The second matrix.
* @param {number} [epsilon=0] The epsilon to use for equality testing.
* @returns {boolean} true if left and right are within the provided epsilon, false otherwise.
*
* @example
* //compares two Matrix4 instances
*
* // a = [10.5, 14.5, 18.5, 22.5]
* // [11.5, 15.5, 19.5, 23.5]
* // [12.5, 16.5, 20.5, 24.5]
* // [13.5, 17.5, 21.5, 25.5]
*
* // b = [10.0, 14.0, 18.0, 22.0]
* // [11.0, 15.0, 19.0, 23.0]
* // [12.0, 16.0, 20.0, 24.0]
* // [13.0, 17.0, 21.0, 25.0]
*
* if(Cesium.Matrix4.equalsEpsilon(a,b,0.1)){
* console.log("Difference between both the matrices is less than 0.1");
* } else {
* console.log("Difference between both the matrices is not less than 0.1");
* }
*
* //Prints "Difference between both the matrices is not less than 0.1" on the console
*/
static equalsEpsilon(left, right, epsilon) {
epsilon = 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 && Math.abs(left[4] - right[4]) <= epsilon && Math.abs(left[5] - right[5]) <= epsilon && Math.abs(left[6] - right[6]) <= epsilon && Math.abs(left[7] - right[7]) <= epsilon && Math.abs(left[8] - right[8]) <= epsilon && Math.abs(left[9] - right[9]) <= epsilon && Math.abs(left[10] - right[10]) <= epsilon && Math.abs(left[11] - right[11]) <= epsilon && Math.abs(left[12] - right[12]) <= epsilon && Math.abs(left[13] - right[13]) <= epsilon && Math.abs(left[14] - right[14]) <= epsilon && Math.abs(left[15] - right[15]) <= epsilon;
}
/**
* Gets the translation portion of the provided matrix, assuming the matrix is an affine transformation matrix.
*
* @param {Matrix4} matrix The matrix to use.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*/
static getTranslation(matrix, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.object("result", result);
result.x = matrix[12];
result.y = matrix[13];
result.z = matrix[14];
return result;
}
/**
* Gets the upper left 3x3 matrix of the provided matrix.
*
* @param {Matrix4} matrix The matrix to use.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*
* @example
* // returns a Matrix3 instance from a Matrix4 instance
*
* // m = [10.0, 14.0, 18.0, 22.0]
* // [11.0, 15.0, 19.0, 23.0]
* // [12.0, 16.0, 20.0, 24.0]
* // [13.0, 17.0, 21.0, 25.0]
*
* const b = new Cesium.Matrix3();
* Cesium.Matrix4.getMatrix3(m,b);
*
* // b = [10.0, 14.0, 18.0]
* // [11.0, 15.0, 19.0]
* // [12.0, 16.0, 20.0]
*/
static getMatrix3(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[4];
result[4] = matrix[5];
result[5] = matrix[6];
result[6] = matrix[8];
result[7] = matrix[9];
result[8] = matrix[10];
return result;
}
/**
* Computes the inverse of the provided matrix using Cramers Rule.
* If the determinant is zero, the matrix can not be inverted, and an exception is thrown.
* If the matrix is a proper rigid transformation, it is more efficient
* to invert it with {@link Matrix4.inverseTransformation}.
*
* @param {Matrix4} matrix The matrix to invert.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @exception {RuntimeError} matrix is not invertible because its determinate is zero.
*/
static inverse(matrix, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.object("result", result);
const src0 = matrix[0];
const src1 = matrix[4];
const src2 = matrix[8];
const src3 = matrix[12];
const src4 = matrix[1];
const src5 = matrix[5];
const src6 = matrix[9];
const src7 = matrix[13];
const src8 = matrix[2];
const src9 = matrix[6];
const src10 = matrix[10];
const src11 = matrix[14];
const src12 = matrix[3];
const src13 = matrix[7];
const src14 = matrix[11];
const src15 = matrix[15];
let tmp0 = src10 * src15;
let tmp1 = src11 * src14;
let tmp2 = src9 * src15;
let tmp3 = src11 * src13;
let tmp4 = src9 * src14;
let tmp5 = src10 * src13;
let tmp6 = src8 * src15;
let tmp7 = src11 * src12;
let tmp8 = src8 * src14;
let tmp9 = src10 * src12;
let tmp10 = src8 * src13;
let tmp11 = src9 * src12;
const dst0 = tmp0 * src5 + tmp3 * src6 + tmp4 * src7 - (tmp1 * src5 + tmp2 * src6 + tmp5 * src7);
const dst1 = tmp1 * src4 + tmp6 * src6 + tmp9 * src7 - (tmp0 * src4 + tmp7 * src6 + tmp8 * src7);
const dst2 = tmp2 * src4 + tmp7 * src5 + tmp10 * src7 - (tmp3 * src4 + tmp6 * src5 + tmp11 * src7);
const dst3 = tmp5 * src4 + tmp8 * src5 + tmp11 * src6 - (tmp4 * src4 + tmp9 * src5 + tmp10 * src6);
const dst4 = tmp1 * src1 + tmp2 * src2 + tmp5 * src3 - (tmp0 * src1 + tmp3 * src2 + tmp4 * src3);
const dst5 = tmp0 * src0 + tmp7 * src2 + tmp8 * src3 - (tmp1 * src0 + tmp6 * src2 + tmp9 * src3);
const dst6 = tmp3 * src0 + tmp6 * src1 + tmp11 * src3 - (tmp2 * src0 + tmp7 * src1 + tmp10 * src3);
const dst7 = tmp4 * src0 + tmp9 * src1 + tmp10 * src2 - (tmp5 * src0 + tmp8 * src1 + tmp11 * src2);
tmp0 = src2 * src7;
tmp1 = src3 * src6;
tmp2 = src1 * src7;
tmp3 = src3 * src5;
tmp4 = src1 * src6;
tmp5 = src2 * src5;
tmp6 = src0 * src7;
tmp7 = src3 * src4;
tmp8 = src0 * src6;
tmp9 = src2 * src4;
tmp10 = src0 * src5;
tmp11 = src1 * src4;
const dst8 = tmp0 * src13 + tmp3 * src14 + tmp4 * src15 - (tmp1 * src13 + tmp2 * src14 + tmp5 * src15);
const dst9 = tmp1 * src12 + tmp6 * src14 + tmp9 * src15 - (tmp0 * src12 + tmp7 * src14 + tmp8 * src15);
const dst10 = tmp2 * src12 + tmp7 * src13 + tmp10 * src15 - (tmp3 * src12 + tmp6 * src13 + tmp11 * src15);
const dst11 = tmp5 * src12 + tmp8 * src13 + tmp11 * src14 - (tmp4 * src12 + tmp9 * src13 + tmp10 * src14);
const dst12 = tmp2 * src10 + tmp5 * src11 + tmp1 * src9 - (tmp4 * src11 + tmp0 * src9 + tmp3 * src10);
const dst13 = tmp8 * src11 + tmp0 * src8 + tmp7 * src10 - (tmp6 * src10 + tmp9 * src11 + tmp1 * src8);
const dst14 = tmp6 * src9 + tmp11 * src11 + tmp3 * src8 - (tmp10 * src11 + tmp2 * src8 + tmp7 * src9);
const dst15 = tmp10 * src10 + tmp4 * src8 + tmp9 * src9 - (tmp8 * src9 + tmp11 * src10 + tmp5 * src8);
let det = src0 * dst0 + src1 * dst1 + src2 * dst2 + src3 * dst3;
if (Math.abs(det) < Math_default.EPSILON21) {
if (Matrix3_default.equalsEpsilon(
_Matrix4.getMatrix3(matrix, scratchInverseRotation),
scratchMatrix3Zero,
Math_default.EPSILON7
) && Cartesian4_default.equals(
_Matrix4.getRow(matrix, 3, scratchBottomRow),
scratchExpectedBottomRow
)) {
result[0] = 0;
result[1] = 0;
result[2] = 0;
result[3] = 0;
result[4] = 0;
result[5] = 0;
result[6] = 0;
result[7] = 0;
result[8] = 0;
result[9] = 0;
result[10] = 0;
result[11] = 0;
result[12] = -matrix[12];
result[13] = -matrix[13];
result[14] = -matrix[14];
result[15] = 1;
return result;
}
throw new RuntimeError_default(
"matrix is not invertible because its determinate is zero."
);
}
det = 1 / det;
result[0] = dst0 * det;
result[1] = dst1 * det;
result[2] = dst2 * det;
result[3] = dst3 * det;
result[4] = dst4 * det;
result[5] = dst5 * det;
result[6] = dst6 * det;
result[7] = dst7 * det;
result[8] = dst8 * det;
result[9] = dst9 * det;
result[10] = dst10 * det;
result[11] = dst11 * det;
result[12] = dst12 * det;
result[13] = dst13 * det;
result[14] = dst14 * det;
result[15] = dst15 * det;
return result;
}
/**
* Computes the inverse of the provided matrix assuming it is a proper rigid matrix,
* where the upper left 3x3 elements are a rotation matrix,
* and the upper three elements in the fourth column are the translation.
* The bottom row is assumed to be [0, 0, 0, 1].
* The matrix is not verified to be in the proper form.
* This method is faster than computing the inverse for a general 4x4
* matrix using {@link Matrix4.inverse}.
*
* @param {Matrix4} matrix The matrix to invert.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*/
static inverseTransformation(matrix, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.object("result", result);
const matrix0 = matrix[0];
const matrix1 = matrix[1];
const matrix2 = matrix[2];
const matrix4 = matrix[4];
const matrix5 = matrix[5];
const matrix6 = matrix[6];
const matrix8 = matrix[8];
const matrix9 = matrix[9];
const matrix10 = matrix[10];
const vX = matrix[12];
const vY = matrix[13];
const vZ = matrix[14];
const x = -matrix0 * vX - matrix1 * vY - matrix2 * vZ;
const y = -matrix4 * vX - matrix5 * vY - matrix6 * vZ;
const z2 = -matrix8 * vX - matrix9 * vY - matrix10 * vZ;
result[0] = matrix0;
result[1] = matrix4;
result[2] = matrix8;
result[3] = 0;
result[4] = matrix1;
result[5] = matrix5;
result[6] = matrix9;
result[7] = 0;
result[8] = matrix2;
result[9] = matrix6;
result[10] = matrix10;
result[11] = 0;
result[12] = x;
result[13] = y;
result[14] = z2;
result[15] = 1;
return result;
}
/**
* Computes the inverse transpose of a matrix.
*
* @param {Matrix4} matrix The matrix to transpose and invert.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*/
static inverseTranspose(matrix, result) {
Check_default.typeOf.object("matrix", matrix);
Check_default.typeOf.object("result", result);
return _Matrix4.inverse(
_Matrix4.transpose(matrix, scratchTransposeMatrix2),
result
);
}
/**
* Gets the number of items in the collection.
*
* @type {number}
*/
get length() {
return _Matrix4.packedLength;
}
/**
* Duplicates the provided Matrix4 instance.
*
* @param {Matrix4} [result] The object onto which to store the result.
* @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
*/
clone(result) {
return _Matrix4.clone(this, result);
}
/**
* Compares this matrix to the provided matrix componentwise and returns
* true if they are equal, false otherwise.
*
* @param {Matrix4} [right] The right hand side matrix.
* @returns {boolean} true if they are equal, false otherwise.
*/
equals(right) {
return _Matrix4.equals(this, right);
}
/**
* Compares provided matrix and array, starting from a given array offset.
*
* @param {Matrix4} matrix
* @param {number[]} array
* @param {number} offset
* @ignore
*/
static equalsArray(matrix, array, offset) {
return matrix[0] === array[offset] && matrix[1] === array[offset + 1] && matrix[2] === array[offset + 2] && matrix[3] === array[offset + 3] && matrix[4] === array[offset + 4] && matrix[5] === array[offset + 5] && matrix[6] === array[offset + 6] && matrix[7] === array[offset + 7] && matrix[8] === array[offset + 8] && matrix[9] === array[offset + 9] && matrix[10] === array[offset + 10] && matrix[11] === array[offset + 11] && matrix[12] === array[offset + 12] && matrix[13] === array[offset + 13] && matrix[14] === array[offset + 14] && matrix[15] === array[offset + 15];
}
/**
* Compares this matrix to the provided matrix componentwise and returns
* true if they are within the provided epsilon,
* false otherwise.
*
* @param {Matrix4} [right] The right hand side matrix.
* @param {number} [epsilon=0] The epsilon to use for equality testing.
* @returns {boolean} true if they are within the provided epsilon, false otherwise.
*/
equalsEpsilon(right, epsilon) {
return _Matrix4.equalsEpsilon(this, right, epsilon);
}
/**
* Computes a string representing this Matrix with each row being
* on a separate line and in the format '(column0, column1, column2, column3)'.
*
* @returns {string} A string representing the provided Matrix with each row being on a separate line and in the format '(column0, column1, column2, column3)'.
*/
toString() {
return `(${this[0]}, ${this[4]}, ${this[8]}, ${this[12]})
(${this[1]}, ${this[5]}, ${this[9]}, ${this[13]})
(${this[2]}, ${this[6]}, ${this[10]}, ${this[14]})
(${this[3]}, ${this[7]}, ${this[11]}, ${this[15]})`;
}
};
Matrix4.packedLength = 16;
Matrix4.fromArray = Matrix4.unpack;
Matrix4.IDENTITY = Object.freeze(
new Matrix4(
1,
0,
0,
0,
0,
1,
0,
0,
0,
0,
1,
0,
0,
0,
0,
1
)
);
Matrix4.ZERO = Object.freeze(
new Matrix4(
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
)
);
Matrix4.COLUMN0ROW0 = 0;
Matrix4.COLUMN0ROW1 = 1;
Matrix4.COLUMN0ROW2 = 2;
Matrix4.COLUMN0ROW3 = 3;
Matrix4.COLUMN1ROW0 = 4;
Matrix4.COLUMN1ROW1 = 5;
Matrix4.COLUMN1ROW2 = 6;
Matrix4.COLUMN1ROW3 = 7;
Matrix4.COLUMN2ROW0 = 8;
Matrix4.COLUMN2ROW1 = 9;
Matrix4.COLUMN2ROW2 = 10;
Matrix4.COLUMN2ROW3 = 11;
Matrix4.COLUMN3ROW0 = 12;
Matrix4.COLUMN3ROW1 = 13;
Matrix4.COLUMN3ROW2 = 14;
Matrix4.COLUMN3ROW3 = 15;
var fromCameraF = new Cartesian3_default();
var fromCameraR = new Cartesian3_default();
var fromCameraU = new Cartesian3_default();
var scaleScratch12 = new Cartesian3_default();
var scaleScratch22 = new Cartesian3_default();
var scratchColumn2 = new Cartesian3_default();
var scaleScratch32 = new Cartesian3_default();
var scaleScratch42 = new Cartesian3_default();
var scaleScratch52 = new Cartesian3_default();
var scratchInverseRotation = new Matrix3_default();
var scratchMatrix3Zero = new Matrix3_default();
var scratchBottomRow = new Cartesian4_default();
var scratchExpectedBottomRow = new Cartesian4_default(0, 0, 0, 1);
var scratchTransposeMatrix2 = new Matrix4();
var Matrix4_default = Matrix4;
// packages/engine/Source/Core/WebGLConstants.js
var WebGLConstants = {
DEPTH_BUFFER_BIT: 256,
STENCIL_BUFFER_BIT: 1024,
COLOR_BUFFER_BIT: 16384,
POINTS: 0,
LINES: 1,
LINE_LOOP: 2,
LINE_STRIP: 3,
TRIANGLES: 4,
TRIANGLE_STRIP: 5,
TRIANGLE_FAN: 6,
ZERO: 0,
ONE: 1,
SRC_COLOR: 768,
ONE_MINUS_SRC_COLOR: 769,
SRC_ALPHA: 770,
ONE_MINUS_SRC_ALPHA: 771,
DST_ALPHA: 772,
ONE_MINUS_DST_ALPHA: 773,
DST_COLOR: 774,
ONE_MINUS_DST_COLOR: 775,
SRC_ALPHA_SATURATE: 776,
FUNC_ADD: 32774,
BLEND_EQUATION: 32777,
BLEND_EQUATION_RGB: 32777,
// same as BLEND_EQUATION
BLEND_EQUATION_ALPHA: 34877,
FUNC_SUBTRACT: 32778,
FUNC_REVERSE_SUBTRACT: 32779,
BLEND_DST_RGB: 32968,
BLEND_SRC_RGB: 32969,
BLEND_DST_ALPHA: 32970,
BLEND_SRC_ALPHA: 32971,
CONSTANT_COLOR: 32769,
ONE_MINUS_CONSTANT_COLOR: 32770,
CONSTANT_ALPHA: 32771,
ONE_MINUS_CONSTANT_ALPHA: 32772,
BLEND_COLOR: 32773,
ARRAY_BUFFER: 34962,
ELEMENT_ARRAY_BUFFER: 34963,
ARRAY_BUFFER_BINDING: 34964,
ELEMENT_ARRAY_BUFFER_BINDING: 34965,
STREAM_DRAW: 35040,
STATIC_DRAW: 35044,
DYNAMIC_DRAW: 35048,
BUFFER_SIZE: 34660,
BUFFER_USAGE: 34661,
CURRENT_VERTEX_ATTRIB: 34342,
FRONT: 1028,
BACK: 1029,
FRONT_AND_BACK: 1032,
CULL_FACE: 2884,
BLEND: 3042,
DITHER: 3024,
STENCIL_TEST: 2960,
DEPTH_TEST: 2929,
SCISSOR_TEST: 3089,
POLYGON_OFFSET_FILL: 32823,
SAMPLE_ALPHA_TO_COVERAGE: 32926,
SAMPLE_COVERAGE: 32928,
NO_ERROR: 0,
INVALID_ENUM: 1280,
INVALID_VALUE: 1281,
INVALID_OPERATION: 1282,
OUT_OF_MEMORY: 1285,
CW: 2304,
CCW: 2305,
LINE_WIDTH: 2849,
ALIASED_POINT_SIZE_RANGE: 33901,
ALIASED_LINE_WIDTH_RANGE: 33902,
CULL_FACE_MODE: 2885,
FRONT_FACE: 2886,
DEPTH_RANGE: 2928,
DEPTH_WRITEMASK: 2930,
DEPTH_CLEAR_VALUE: 2931,
DEPTH_FUNC: 2932,
STENCIL_CLEAR_VALUE: 2961,
STENCIL_FUNC: 2962,
STENCIL_FAIL: 2964,
STENCIL_PASS_DEPTH_FAIL: 2965,
STENCIL_PASS_DEPTH_PASS: 2966,
STENCIL_REF: 2967,
STENCIL_VALUE_MASK: 2963,
STENCIL_WRITEMASK: 2968,
STENCIL_BACK_FUNC: 34816,
STENCIL_BACK_FAIL: 34817,
STENCIL_BACK_PASS_DEPTH_FAIL: 34818,
STENCIL_BACK_PASS_DEPTH_PASS: 34819,
STENCIL_BACK_REF: 36003,
STENCIL_BACK_VALUE_MASK: 36004,
STENCIL_BACK_WRITEMASK: 36005,
VIEWPORT: 2978,
SCISSOR_BOX: 3088,
COLOR_CLEAR_VALUE: 3106,
COLOR_WRITEMASK: 3107,
UNPACK_ALIGNMENT: 3317,
PACK_ALIGNMENT: 3333,
MAX_TEXTURE_SIZE: 3379,
MAX_VIEWPORT_DIMS: 3386,
SUBPIXEL_BITS: 3408,
RED_BITS: 3410,
GREEN_BITS: 3411,
BLUE_BITS: 3412,
ALPHA_BITS: 3413,
DEPTH_BITS: 3414,
STENCIL_BITS: 3415,
POLYGON_OFFSET_UNITS: 10752,
POLYGON_OFFSET_FACTOR: 32824,
TEXTURE_BINDING_2D: 32873,
SAMPLE_BUFFERS: 32936,
SAMPLES: 32937,
SAMPLE_COVERAGE_VALUE: 32938,
SAMPLE_COVERAGE_INVERT: 32939,
COMPRESSED_TEXTURE_FORMATS: 34467,
DONT_CARE: 4352,
FASTEST: 4353,
NICEST: 4354,
GENERATE_MIPMAP_HINT: 33170,
BYTE: 5120,
UNSIGNED_BYTE: 5121,
SHORT: 5122,
UNSIGNED_SHORT: 5123,
INT: 5124,
UNSIGNED_INT: 5125,
FLOAT: 5126,
DEPTH_COMPONENT: 6402,
ALPHA: 6406,
RGB: 6407,
RGBA: 6408,
LUMINANCE: 6409,
LUMINANCE_ALPHA: 6410,
UNSIGNED_SHORT_4_4_4_4: 32819,
UNSIGNED_SHORT_5_5_5_1: 32820,
UNSIGNED_SHORT_5_6_5: 33635,
FRAGMENT_SHADER: 35632,
VERTEX_SHADER: 35633,
MAX_VERTEX_ATTRIBS: 34921,
MAX_VERTEX_UNIFORM_VECTORS: 36347,
MAX_VARYING_VECTORS: 36348,
MAX_COMBINED_TEXTURE_IMAGE_UNITS: 35661,
MAX_VERTEX_TEXTURE_IMAGE_UNITS: 35660,
MAX_TEXTURE_IMAGE_UNITS: 34930,
MAX_FRAGMENT_UNIFORM_VECTORS: 36349,
SHADER_TYPE: 35663,
DELETE_STATUS: 35712,
LINK_STATUS: 35714,
VALIDATE_STATUS: 35715,
ATTACHED_SHADERS: 35717,
ACTIVE_UNIFORMS: 35718,
ACTIVE_ATTRIBUTES: 35721,
SHADING_LANGUAGE_VERSION: 35724,
CURRENT_PROGRAM: 35725,
NEVER: 512,
LESS: 513,
EQUAL: 514,
LEQUAL: 515,
GREATER: 516,
NOTEQUAL: 517,
GEQUAL: 518,
ALWAYS: 519,
KEEP: 7680,
REPLACE: 7681,
INCR: 7682,
DECR: 7683,
INVERT: 5386,
INCR_WRAP: 34055,
DECR_WRAP: 34056,
VENDOR: 7936,
RENDERER: 7937,
VERSION: 7938,
NEAREST: 9728,
LINEAR: 9729,
NEAREST_MIPMAP_NEAREST: 9984,
LINEAR_MIPMAP_NEAREST: 9985,
NEAREST_MIPMAP_LINEAR: 9986,
LINEAR_MIPMAP_LINEAR: 9987,
TEXTURE_MAG_FILTER: 10240,
TEXTURE_MIN_FILTER: 10241,
TEXTURE_WRAP_S: 10242,
TEXTURE_WRAP_T: 10243,
TEXTURE_2D: 3553,
TEXTURE: 5890,
TEXTURE_CUBE_MAP: 34067,
TEXTURE_BINDING_CUBE_MAP: 34068,
TEXTURE_CUBE_MAP_POSITIVE_X: 34069,
TEXTURE_CUBE_MAP_NEGATIVE_X: 34070,
TEXTURE_CUBE_MAP_POSITIVE_Y: 34071,
TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072,
TEXTURE_CUBE_MAP_POSITIVE_Z: 34073,
TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074,
MAX_CUBE_MAP_TEXTURE_SIZE: 34076,
TEXTURE0: 33984,
TEXTURE1: 33985,
TEXTURE2: 33986,
TEXTURE3: 33987,
TEXTURE4: 33988,
TEXTURE5: 33989,
TEXTURE6: 33990,
TEXTURE7: 33991,
TEXTURE8: 33992,
TEXTURE9: 33993,
TEXTURE10: 33994,
TEXTURE11: 33995,
TEXTURE12: 33996,
TEXTURE13: 33997,
TEXTURE14: 33998,
TEXTURE15: 33999,
TEXTURE16: 34e3,
TEXTURE17: 34001,
TEXTURE18: 34002,
TEXTURE19: 34003,
TEXTURE20: 34004,
TEXTURE21: 34005,
TEXTURE22: 34006,
TEXTURE23: 34007,
TEXTURE24: 34008,
TEXTURE25: 34009,
TEXTURE26: 34010,
TEXTURE27: 34011,
TEXTURE28: 34012,
TEXTURE29: 34013,
TEXTURE30: 34014,
TEXTURE31: 34015,
ACTIVE_TEXTURE: 34016,
REPEAT: 10497,
CLAMP_TO_EDGE: 33071,
MIRRORED_REPEAT: 33648,
FLOAT_VEC2: 35664,
FLOAT_VEC3: 35665,
FLOAT_VEC4: 35666,
INT_VEC2: 35667,
INT_VEC3: 35668,
INT_VEC4: 35669,
BOOL: 35670,
BOOL_VEC2: 35671,
BOOL_VEC3: 35672,
BOOL_VEC4: 35673,
FLOAT_MAT2: 35674,
FLOAT_MAT3: 35675,
FLOAT_MAT4: 35676,
SAMPLER_2D: 35678,
SAMPLER_CUBE: 35680,
VERTEX_ATTRIB_ARRAY_ENABLED: 34338,
VERTEX_ATTRIB_ARRAY_SIZE: 34339,
VERTEX_ATTRIB_ARRAY_STRIDE: 34340,
VERTEX_ATTRIB_ARRAY_TYPE: 34341,
VERTEX_ATTRIB_ARRAY_NORMALIZED: 34922,
VERTEX_ATTRIB_ARRAY_POINTER: 34373,
VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: 34975,
IMPLEMENTATION_COLOR_READ_TYPE: 35738,
IMPLEMENTATION_COLOR_READ_FORMAT: 35739,
COMPILE_STATUS: 35713,
LOW_FLOAT: 36336,
MEDIUM_FLOAT: 36337,
HIGH_FLOAT: 36338,
LOW_INT: 36339,
MEDIUM_INT: 36340,
HIGH_INT: 36341,
FRAMEBUFFER: 36160,
RENDERBUFFER: 36161,
RGBA4: 32854,
RGB5_A1: 32855,
RGB565: 36194,
DEPTH_COMPONENT16: 33189,
STENCIL_INDEX: 6401,
STENCIL_INDEX8: 36168,
DEPTH_STENCIL: 34041,
RENDERBUFFER_WIDTH: 36162,
RENDERBUFFER_HEIGHT: 36163,
RENDERBUFFER_INTERNAL_FORMAT: 36164,
RENDERBUFFER_RED_SIZE: 36176,
RENDERBUFFER_GREEN_SIZE: 36177,
RENDERBUFFER_BLUE_SIZE: 36178,
RENDERBUFFER_ALPHA_SIZE: 36179,
RENDERBUFFER_DEPTH_SIZE: 36180,
RENDERBUFFER_STENCIL_SIZE: 36181,
FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: 36048,
FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: 36049,
FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: 36050,
FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: 36051,
COLOR_ATTACHMENT0: 36064,
DEPTH_ATTACHMENT: 36096,
STENCIL_ATTACHMENT: 36128,
DEPTH_STENCIL_ATTACHMENT: 33306,
NONE: 0,
FRAMEBUFFER_COMPLETE: 36053,
FRAMEBUFFER_INCOMPLETE_ATTACHMENT: 36054,
FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: 36055,
FRAMEBUFFER_INCOMPLETE_DIMENSIONS: 36057,
FRAMEBUFFER_UNSUPPORTED: 36061,
FRAMEBUFFER_BINDING: 36006,
RENDERBUFFER_BINDING: 36007,
MAX_RENDERBUFFER_SIZE: 34024,
INVALID_FRAMEBUFFER_OPERATION: 1286,
UNPACK_FLIP_Y_WEBGL: 37440,
UNPACK_PREMULTIPLY_ALPHA_WEBGL: 37441,
CONTEXT_LOST_WEBGL: 37442,
UNPACK_COLORSPACE_CONVERSION_WEBGL: 37443,
BROWSER_DEFAULT_WEBGL: 37444,
// WEBGL_compressed_texture_s3tc
COMPRESSED_RGB_S3TC_DXT1_EXT: 33776,
COMPRESSED_RGBA_S3TC_DXT1_EXT: 33777,
COMPRESSED_RGBA_S3TC_DXT3_EXT: 33778,
COMPRESSED_RGBA_S3TC_DXT5_EXT: 33779,
// WEBGL_compressed_texture_pvrtc
COMPRESSED_RGB_PVRTC_4BPPV1_IMG: 35840,
COMPRESSED_RGB_PVRTC_2BPPV1_IMG: 35841,
COMPRESSED_RGBA_PVRTC_4BPPV1_IMG: 35842,
COMPRESSED_RGBA_PVRTC_2BPPV1_IMG: 35843,
// WEBGL_compressed_texture_astc
COMPRESSED_RGBA_ASTC_4x4_WEBGL: 37808,
// WEBGL_compressed_texture_etc1
COMPRESSED_RGB_ETC1_WEBGL: 36196,
// EXT_texture_compression_bptc
COMPRESSED_RGBA_BPTC_UNORM: 36492,
// EXT_color_buffer_half_float
HALF_FLOAT_OES: 36193,
// Desktop OpenGL
DOUBLE: 5130,
// WebGL 2
READ_BUFFER: 3074,
UNPACK_ROW_LENGTH: 3314,
UNPACK_SKIP_ROWS: 3315,
UNPACK_SKIP_PIXELS: 3316,
PACK_ROW_LENGTH: 3330,
PACK_SKIP_ROWS: 3331,
PACK_SKIP_PIXELS: 3332,
COLOR: 6144,
DEPTH: 6145,
STENCIL: 6146,
RED: 6403,
RGB8: 32849,
RGBA8: 32856,
RGB10_A2: 32857,
TEXTURE_BINDING_3D: 32874,
UNPACK_SKIP_IMAGES: 32877,
UNPACK_IMAGE_HEIGHT: 32878,
TEXTURE_3D: 32879,
TEXTURE_WRAP_R: 32882,
MAX_3D_TEXTURE_SIZE: 32883,
UNSIGNED_INT_2_10_10_10_REV: 33640,
MAX_ELEMENTS_VERTICES: 33e3,
MAX_ELEMENTS_INDICES: 33001,
TEXTURE_MIN_LOD: 33082,
TEXTURE_MAX_LOD: 33083,
TEXTURE_BASE_LEVEL: 33084,
TEXTURE_MAX_LEVEL: 33085,
MIN: 32775,
MAX: 32776,
DEPTH_COMPONENT24: 33190,
MAX_TEXTURE_LOD_BIAS: 34045,
TEXTURE_COMPARE_MODE: 34892,
TEXTURE_COMPARE_FUNC: 34893,
CURRENT_QUERY: 34917,
QUERY_RESULT: 34918,
QUERY_RESULT_AVAILABLE: 34919,
STREAM_READ: 35041,
STREAM_COPY: 35042,
STATIC_READ: 35045,
STATIC_COPY: 35046,
DYNAMIC_READ: 35049,
DYNAMIC_COPY: 35050,
MAX_DRAW_BUFFERS: 34852,
DRAW_BUFFER0: 34853,
DRAW_BUFFER1: 34854,
DRAW_BUFFER2: 34855,
DRAW_BUFFER3: 34856,
DRAW_BUFFER4: 34857,
DRAW_BUFFER5: 34858,
DRAW_BUFFER6: 34859,
DRAW_BUFFER7: 34860,
DRAW_BUFFER8: 34861,
DRAW_BUFFER9: 34862,
DRAW_BUFFER10: 34863,
DRAW_BUFFER11: 34864,
DRAW_BUFFER12: 34865,
DRAW_BUFFER13: 34866,
DRAW_BUFFER14: 34867,
DRAW_BUFFER15: 34868,
MAX_FRAGMENT_UNIFORM_COMPONENTS: 35657,
MAX_VERTEX_UNIFORM_COMPONENTS: 35658,
SAMPLER_3D: 35679,
SAMPLER_2D_SHADOW: 35682,
FRAGMENT_SHADER_DERIVATIVE_HINT: 35723,
PIXEL_PACK_BUFFER: 35051,
PIXEL_UNPACK_BUFFER: 35052,
PIXEL_PACK_BUFFER_BINDING: 35053,
PIXEL_UNPACK_BUFFER_BINDING: 35055,
FLOAT_MAT2x3: 35685,
FLOAT_MAT2x4: 35686,
FLOAT_MAT3x2: 35687,
FLOAT_MAT3x4: 35688,
FLOAT_MAT4x2: 35689,
FLOAT_MAT4x3: 35690,
SRGB: 35904,
SRGB8: 35905,
SRGB8_ALPHA8: 35907,
COMPARE_REF_TO_TEXTURE: 34894,
RGBA32F: 34836,
RGB32F: 34837,
RGBA16F: 34842,
RGB16F: 34843,
VERTEX_ATTRIB_ARRAY_INTEGER: 35069,
MAX_ARRAY_TEXTURE_LAYERS: 35071,
MIN_PROGRAM_TEXEL_OFFSET: 35076,
MAX_PROGRAM_TEXEL_OFFSET: 35077,
MAX_VARYING_COMPONENTS: 35659,
TEXTURE_2D_ARRAY: 35866,
TEXTURE_BINDING_2D_ARRAY: 35869,
R11F_G11F_B10F: 35898,
UNSIGNED_INT_10F_11F_11F_REV: 35899,
RGB9_E5: 35901,
UNSIGNED_INT_5_9_9_9_REV: 35902,
TRANSFORM_FEEDBACK_BUFFER_MODE: 35967,
MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS: 35968,
TRANSFORM_FEEDBACK_VARYINGS: 35971,
TRANSFORM_FEEDBACK_BUFFER_START: 35972,
TRANSFORM_FEEDBACK_BUFFER_SIZE: 35973,
TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN: 35976,
RASTERIZER_DISCARD: 35977,
MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS: 35978,
MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS: 35979,
INTERLEAVED_ATTRIBS: 35980,
SEPARATE_ATTRIBS: 35981,
TRANSFORM_FEEDBACK_BUFFER: 35982,
TRANSFORM_FEEDBACK_BUFFER_BINDING: 35983,
RGBA32UI: 36208,
RGB32UI: 36209,
RGBA16UI: 36214,
RGB16UI: 36215,
RGBA8UI: 36220,
RGB8UI: 36221,
RGBA32I: 36226,
RGB32I: 36227,
RGBA16I: 36232,
RGB16I: 36233,
RGBA8I: 36238,
RGB8I: 36239,
RED_INTEGER: 36244,
RGB_INTEGER: 36248,
RGBA_INTEGER: 36249,
SAMPLER_2D_ARRAY: 36289,
SAMPLER_2D_ARRAY_SHADOW: 36292,
SAMPLER_CUBE_SHADOW: 36293,
UNSIGNED_INT_VEC2: 36294,
UNSIGNED_INT_VEC3: 36295,
UNSIGNED_INT_VEC4: 36296,
INT_SAMPLER_2D: 36298,
INT_SAMPLER_3D: 36299,
INT_SAMPLER_CUBE: 36300,
INT_SAMPLER_2D_ARRAY: 36303,
UNSIGNED_INT_SAMPLER_2D: 36306,
UNSIGNED_INT_SAMPLER_3D: 36307,
UNSIGNED_INT_SAMPLER_CUBE: 36308,
UNSIGNED_INT_SAMPLER_2D_ARRAY: 36311,
DEPTH_COMPONENT32F: 36012,
DEPTH32F_STENCIL8: 36013,
FLOAT_32_UNSIGNED_INT_24_8_REV: 36269,
FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING: 33296,
FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE: 33297,
FRAMEBUFFER_ATTACHMENT_RED_SIZE: 33298,
FRAMEBUFFER_ATTACHMENT_GREEN_SIZE: 33299,
FRAMEBUFFER_ATTACHMENT_BLUE_SIZE: 33300,
FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE: 33301,
FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE: 33302,
FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE: 33303,
FRAMEBUFFER_DEFAULT: 33304,
UNSIGNED_INT_24_8: 34042,
DEPTH24_STENCIL8: 35056,
UNSIGNED_NORMALIZED: 35863,
DRAW_FRAMEBUFFER_BINDING: 36006,
// Same as FRAMEBUFFER_BINDING
READ_FRAMEBUFFER: 36008,
DRAW_FRAMEBUFFER: 36009,
READ_FRAMEBUFFER_BINDING: 36010,
RENDERBUFFER_SAMPLES: 36011,
FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER: 36052,
MAX_COLOR_ATTACHMENTS: 36063,
COLOR_ATTACHMENT1: 36065,
COLOR_ATTACHMENT2: 36066,
COLOR_ATTACHMENT3: 36067,
COLOR_ATTACHMENT4: 36068,
COLOR_ATTACHMENT5: 36069,
COLOR_ATTACHMENT6: 36070,
COLOR_ATTACHMENT7: 36071,
COLOR_ATTACHMENT8: 36072,
COLOR_ATTACHMENT9: 36073,
COLOR_ATTACHMENT10: 36074,
COLOR_ATTACHMENT11: 36075,
COLOR_ATTACHMENT12: 36076,
COLOR_ATTACHMENT13: 36077,
COLOR_ATTACHMENT14: 36078,
COLOR_ATTACHMENT15: 36079,
FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: 36182,
MAX_SAMPLES: 36183,
HALF_FLOAT: 5131,
RG: 33319,
RG_INTEGER: 33320,
R8: 33321,
RG8: 33323,
R16F: 33325,
R32F: 33326,
RG16F: 33327,
RG32F: 33328,
R8I: 33329,
R8UI: 33330,
R16I: 33331,
R16UI: 33332,
R32I: 33333,
R32UI: 33334,
RG8I: 33335,
RG8UI: 33336,
RG16I: 33337,
RG16UI: 33338,
RG32I: 33339,
RG32UI: 33340,
VERTEX_ARRAY_BINDING: 34229,
R8_SNORM: 36756,
RG8_SNORM: 36757,
RGB8_SNORM: 36758,
RGBA8_SNORM: 36759,
SIGNED_NORMALIZED: 36764,
COPY_READ_BUFFER: 36662,
COPY_WRITE_BUFFER: 36663,
COPY_READ_BUFFER_BINDING: 36662,
// Same as COPY_READ_BUFFER
COPY_WRITE_BUFFER_BINDING: 36663,
// Same as COPY_WRITE_BUFFER
UNIFORM_BUFFER: 35345,
UNIFORM_BUFFER_BINDING: 35368,
UNIFORM_BUFFER_START: 35369,
UNIFORM_BUFFER_SIZE: 35370,
MAX_VERTEX_UNIFORM_BLOCKS: 35371,
MAX_FRAGMENT_UNIFORM_BLOCKS: 35373,
MAX_COMBINED_UNIFORM_BLOCKS: 35374,
MAX_UNIFORM_BUFFER_BINDINGS: 35375,
MAX_UNIFORM_BLOCK_SIZE: 35376,
MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS: 35377,
MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS: 35379,
UNIFORM_BUFFER_OFFSET_ALIGNMENT: 35380,
ACTIVE_UNIFORM_BLOCKS: 35382,
UNIFORM_TYPE: 35383,
UNIFORM_SIZE: 35384,
UNIFORM_BLOCK_INDEX: 35386,
UNIFORM_OFFSET: 35387,
UNIFORM_ARRAY_STRIDE: 35388,
UNIFORM_MATRIX_STRIDE: 35389,
UNIFORM_IS_ROW_MAJOR: 35390,
UNIFORM_BLOCK_BINDING: 35391,
UNIFORM_BLOCK_DATA_SIZE: 35392,
UNIFORM_BLOCK_ACTIVE_UNIFORMS: 35394,
UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES: 35395,
UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER: 35396,
UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER: 35398,
INVALID_INDEX: 4294967295,
MAX_VERTEX_OUTPUT_COMPONENTS: 37154,
MAX_FRAGMENT_INPUT_COMPONENTS: 37157,
MAX_SERVER_WAIT_TIMEOUT: 37137,
OBJECT_TYPE: 37138,
SYNC_CONDITION: 37139,
SYNC_STATUS: 37140,
SYNC_FLAGS: 37141,
SYNC_FENCE: 37142,
SYNC_GPU_COMMANDS_COMPLETE: 37143,
UNSIGNALED: 37144,
SIGNALED: 37145,
ALREADY_SIGNALED: 37146,
TIMEOUT_EXPIRED: 37147,
CONDITION_SATISFIED: 37148,
WAIT_FAILED: 37149,
SYNC_FLUSH_COMMANDS_BIT: 1,
VERTEX_ATTRIB_ARRAY_DIVISOR: 35070,
ANY_SAMPLES_PASSED: 35887,
ANY_SAMPLES_PASSED_CONSERVATIVE: 36202,
SAMPLER_BINDING: 35097,
RGB10_A2UI: 36975,
INT_2_10_10_10_REV: 36255,
TRANSFORM_FEEDBACK: 36386,
TRANSFORM_FEEDBACK_PAUSED: 36387,
TRANSFORM_FEEDBACK_ACTIVE: 36388,
TRANSFORM_FEEDBACK_BINDING: 36389,
COMPRESSED_R11_EAC: 37488,
COMPRESSED_SIGNED_R11_EAC: 37489,
COMPRESSED_RG11_EAC: 37490,
COMPRESSED_SIGNED_RG11_EAC: 37491,
COMPRESSED_RGB8_ETC2: 37492,
COMPRESSED_SRGB8_ETC2: 37493,
COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2: 37494,
COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2: 37495,
COMPRESSED_RGBA8_ETC2_EAC: 37496,
COMPRESSED_SRGB8_ALPHA8_ETC2_EAC: 37497,
TEXTURE_IMMUTABLE_FORMAT: 37167,
MAX_ELEMENT_INDEX: 36203,
TEXTURE_IMMUTABLE_LEVELS: 33503,
// Extensions
MAX_TEXTURE_MAX_ANISOTROPY_EXT: 34047
};
Object.freeze(WebGLConstants);
var WebGLConstants_default = WebGLConstants;
// packages/engine/Source/Renderer/AutomaticUniforms.js
var viewerPositionWCScratch = new Cartesian3_default();
function AutomaticUniform(options) {
this._size = options.size;
this._datatype = options.datatype;
this.getValue = options.getValue;
}
var datatypeToGlsl = {};
datatypeToGlsl[WebGLConstants_default.FLOAT] = "float";
datatypeToGlsl[WebGLConstants_default.FLOAT_VEC2] = "vec2";
datatypeToGlsl[WebGLConstants_default.FLOAT_VEC3] = "vec3";
datatypeToGlsl[WebGLConstants_default.FLOAT_VEC4] = "vec4";
datatypeToGlsl[WebGLConstants_default.INT] = "int";
datatypeToGlsl[WebGLConstants_default.INT_VEC2] = "ivec2";
datatypeToGlsl[WebGLConstants_default.INT_VEC3] = "ivec3";
datatypeToGlsl[WebGLConstants_default.INT_VEC4] = "ivec4";
datatypeToGlsl[WebGLConstants_default.BOOL] = "bool";
datatypeToGlsl[WebGLConstants_default.BOOL_VEC2] = "bvec2";
datatypeToGlsl[WebGLConstants_default.BOOL_VEC3] = "bvec3";
datatypeToGlsl[WebGLConstants_default.BOOL_VEC4] = "bvec4";
datatypeToGlsl[WebGLConstants_default.FLOAT_MAT2] = "mat2";
datatypeToGlsl[WebGLConstants_default.FLOAT_MAT3] = "mat3";
datatypeToGlsl[WebGLConstants_default.FLOAT_MAT4] = "mat4";
datatypeToGlsl[WebGLConstants_default.SAMPLER_2D] = "sampler2D";
datatypeToGlsl[WebGLConstants_default.SAMPLER_CUBE] = "samplerCube";
AutomaticUniform.prototype.getDeclaration = function(name) {
let declaration = `uniform ${datatypeToGlsl[this._datatype]} ${name}`;
const size = this._size;
if (size === 1) {
declaration += ";";
} else {
declaration += `[${size.toString()}];`;
}
return declaration;
};
var AutomaticUniforms = {
/**
* An automatic GLSL uniform containing the viewport's 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 texture containing edge IDs
* from the 3D Tiles edge rendering pass. Used for edge detection and
* avoiding z-fighting between edges and surfaces.
*
* @example
* // GLSL declaration
* uniform sampler2D czm_edgeIdTexture;
*
* // Get the edge ID at the current fragment
* vec2 coords = gl_FragCoord.xy / czm_viewport.zw;
* vec4 edgeId = texture(czm_edgeIdTexture, coords);
*/
czm_edgeIdTexture: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.SAMPLER_2D,
getValue: function(uniformState) {
return uniformState.edgeIdTexture;
}
}),
/**
* An automatic GLSL uniform containing the edge color texture.
* This texture contains the edge content rendered during the CESIUM_3D_TILE_EDGES pass.
*
* @example
* // GLSL declaration
* uniform sampler2D czm_edgeColorTexture;
*
* // Sample the edge color at the current fragment
* vec2 coords = gl_FragCoord.xy / czm_viewport.zw;
* vec4 edgeColor = texture(czm_edgeColorTexture, coords);
*/
czm_edgeColorTexture: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.SAMPLER_2D,
getValue: function(uniformState) {
return uniformState.edgeColorTexture;
}
}),
/**
* An automatic GLSL uniform containing the packed depth texture produced by the
* edge visibility pass. The depth is packed via czm_packDepth and should be
* unpacked with czm_unpackDepth.
*
* @example
* // GLSL declaration
* uniform sampler2D czm_edgeDepthTexture;
*
* vec2 coords = gl_FragCoord.xy / czm_viewport.zw;
* float d = czm_unpackDepth(texture(czm_edgeDepthTexture, coords));
*/
czm_edgeDepthTexture: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.SAMPLER_2D,
getValue: function(uniformState) {
return uniformState.edgeDepthTexture;
}
}),
/**
* An automatic GLSL uniform containing the feature-ID texture produced by
* the planar fill pre-pass (BENTLEY_materials_planar_fill). Non-behind
* planar fill geometry writes its per-fragment feature ID here so that
* behind fills can test whether the existing pixel belongs to the same
* logical object.
*
* @example
* // GLSL declaration
* uniform sampler2D czm_planarFillIdTexture;
*
* // Sample
* vec2 coords = gl_FragCoord.xy / czm_viewport.zw;
* float existingFeatureId = texture(czm_planarFillIdTexture, coords).r;
*/
czm_planarFillIdTexture: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.SAMPLER_2D,
getValue: function(uniformState) {
return uniformState.planarFillIdTexture;
}
}),
/**
* 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 ellipsoid surface normal
* at the position below the eye (camera), in eye coordinates.
* This uniform is only valid when the {@link SceneMode} is SCENE3D.
*/
czm_eyeEllipsoidNormalEC: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_VEC3,
getValue: function(uniformState) {
return uniformState.eyeEllipsoidNormalEC;
}
}),
/**
* An automatic GLSL uniform containing the ellipsoid radii of curvature at the camera position.
* The .x component is the prime vertical radius of curvature (east-west direction)
* .y is the meridional radius of curvature (north-south direction)
* This uniform is only valid when the {@link SceneMode} is SCENE3D.
*/
czm_eyeEllipsoidCurvature: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_VEC2,
getValue: function(uniformState) {
return uniformState.eyeEllipsoidCurvature;
}
}),
/**
* An automatic GLSL uniform containing the transform from model coordinates
* to an east-north-up coordinate system centered at the position on the
* ellipsoid below the camera.
* This uniform is only valid when the {@link SceneMode} is SCENE3D.
*/
czm_modelToEnu: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_MAT4,
getValue: function(uniformState) {
return uniformState.modelToEnu;
}
}),
/**
* An automatic GLSL uniform containing the the inverse of
* {@link AutomaticUniforms.czm_modelToEnu}.
* This uniform is only valid when the {@link SceneMode} is SCENE3D.
*/
czm_enuToModel: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_MAT4,
getValue: function(uniformState) {
return uniformState.enuToModel;
}
}),
/**
* 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, 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 cube map used within the scene.
*
* @example
* // GLSL declaration
* uniform samplerCube czm_specularEnvironmentMaps;
*/
czm_specularEnvironmentMaps: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.SAMPLER_CUBE,
getValue: function(uniformState) {
return uniformState.specularEnvironmentMaps;
}
}),
/**
* An automatic GLSL uniform containing the maximum valid level-of-detail of the specular environment cube map 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 scalar used to mix a color with the fog color based on the distance to the camera.
*
* @see czm_fog
*/
czm_fogVisualDensityScalar: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT,
getValue: function(uniformState) {
return uniformState.fogVisualDensityScalar;
}
}),
/**
* An automatic GLSL uniform scalar used to set a minimum brightness when dynamic lighting is applied to fog.
*
* @see czm_fog
*/
czm_fogMinimumBrightness: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT,
getValue: function(uniformState) {
return uniformState.fogMinimumBrightness;
}
}),
/**
* An automatic uniform representing the color shift for the atmosphere in HSB color space
*
* @example
* uniform vec3 czm_atmosphereHsbShift;
*/
czm_atmosphereHsbShift: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_VEC3,
getValue: function(uniformState) {
return uniformState.atmosphereHsbShift;
}
}),
/**
* An automatic uniform representing the intensity of the light that is used for computing the atmosphere color
*
* @example
* uniform float czm_atmosphereLightIntensity;
*/
czm_atmosphereLightIntensity: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT,
getValue: function(uniformState) {
return uniformState.atmosphereLightIntensity;
}
}),
/**
* An automatic uniform representing the Rayleigh scattering coefficient used when computing the atmosphere scattering
*
* @example
* uniform vec3 czm_atmosphereRayleighCoefficient;
*/
czm_atmosphereRayleighCoefficient: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_VEC3,
getValue: function(uniformState) {
return uniformState.atmosphereRayleighCoefficient;
}
}),
/**
* An automatic uniform representing the Rayleigh scale height in meters used for computing atmosphere scattering.
*
* @example
* uniform vec3 czm_atmosphereRayleighScaleHeight;
*/
czm_atmosphereRayleighScaleHeight: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT,
getValue: function(uniformState) {
return uniformState.atmosphereRayleighScaleHeight;
}
}),
/**
* An automatic uniform representing the Mie scattering coefficient used when computing atmosphere scattering.
*
* @example
* uniform vec3 czm_atmosphereMieCoefficient;
*/
czm_atmosphereMieCoefficient: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT_VEC3,
getValue: function(uniformState) {
return uniformState.atmosphereMieCoefficient;
}
}),
/**
* An automatic uniform storign the Mie scale height used when computing atmosphere scattering.
*
* @example
* uniform float czm_atmosphereMieScaleHeight;
*/
czm_atmosphereMieScaleHeight: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT,
getValue: function(uniformState) {
return uniformState.atmosphereMieScaleHeight;
}
}),
/**
* An automatic uniform representing the anisotropy of the medium to consider for Mie scattering.
*
* @example
* uniform float czm_atmosphereAnisotropy;
*/
czm_atmosphereMieAnisotropy: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT,
getValue: function(uniformState) {
return uniformState.atmosphereMieAnisotropy;
}
}),
/**
* An automatic uniform representing which light source to use for dynamic lighting
*
* @example
* uniform float czm_atmosphereDynamicLighting
*/
czm_atmosphereDynamicLighting: new AutomaticUniform({
size: 1,
datatype: WebGLConstants_default.FLOAT,
getValue: function(uniformState) {
return uniformState.atmosphereDynamicLighting;
}
}),
/**
* 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(c14) {
const r2 = Math.random() * 16 | 0;
const v3 = c14 === "x" ? r2 : r2 & 3 | 8;
return v3.toString(16);
});
}
var createGuid_default = createGuid;
// packages/engine/Source/Core/destroyObject.js
function returnTrue() {
return true;
}
function destroyObject(object2, message) {
message = 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;
//>>includeStart('debug', pragmas.debug);
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, length2) {
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, length2);
}
return new Uint16Array(sourceArray, byteOffset, length2);
};
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."
);
};
Object.freeze(IndexDatatype);
var IndexDatatype_default = 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,
DYNAMIC_READ: WebGLConstants_default.DYNAMIC_READ
};
BufferUsage.validate = function(bufferUsage) {
return bufferUsage === BufferUsage.STREAM_DRAW || bufferUsage === BufferUsage.STATIC_DRAW || bufferUsage === BufferUsage.DYNAMIC_DRAW || bufferUsage === BufferUsage.DYNAMIC_READ;
};
Object.freeze(BufferUsage);
var BufferUsage_default = BufferUsage;
// packages/engine/Source/Renderer/Buffer.js
function Buffer2(options) {
options = options ?? Frozen_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 buffer2 = gl.createBuffer();
gl.bindBuffer(bufferTarget, buffer2);
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 = buffer2;
this.vertexArrayDestroyable = true;
}
Buffer2.createPixelBuffer = function(options) {
Check_default.defined("options.context", options.context);
if (!options.context._webgl2) {
throw new DeveloperError_default(
"A WebGL 2 context is required to create PixelBuffers."
);
}
return new Buffer2({
context: options.context,
bufferTarget: WebGLConstants_default.PIXEL_PACK_BUFFER,
typedArray: options.typedArray,
sizeInBytes: options.sizeInBytes,
usage: options.usage
});
};
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 buffer2 = new Buffer2({
context,
bufferTarget: WebGLConstants_default.ELEMENT_ARRAY_BUFFER,
typedArray: options.typedArray,
sizeInBytes: options.sizeInBytes,
usage: options.usage
});
const numberOfIndices = buffer2.sizeInBytes / bytesPerIndex;
Object.defineProperties(buffer2, {
indexDatatype: {
get: function() {
return indexDatatype;
}
},
bytesPerIndex: {
get: function() {
return bytesPerIndex;
}
},
numberOfIndices: {
get: function() {
return numberOfIndices;
}
}
});
return buffer2;
};
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._bind = function() {
const gl = this._gl;
const target = this._bufferTarget;
gl.bindBuffer(target, this._buffer);
};
Buffer2.prototype._unBind = function() {
const gl = this._gl;
const target = this._bufferTarget;
gl.bindBuffer(target, null);
};
Buffer2.prototype.copyFromArrayView = function(arrayView, offsetInBytes) {
offsetInBytes = 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, length2) {
sourceOffset = sourceOffset ?? 0;
destinationOffset = 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(length2)) {
if (defined_default(arrayLength)) {
copyLength = arrayLength - destinationOffset;
elementSize = 1;
} else {
arrayLength = arrayView.length;
copyLength = arrayLength - destinationOffset;
elementSize = arrayView.BYTES_PER_ELEMENT;
}
} else {
copyLength = length2;
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,
length2
);
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 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,
isEdge,
edgeVersion,
isFirefox,
firefoxVersion,
isWindows,
isIPadOrIOS,
hardwareConcurrency: 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;
};
FeatureDetection.supportsEsmWebWorkers = function() {
return !isFirefox() || parseInt(firefoxVersionResult) >= 114;
};
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;
}
var Color = class _Color {
/**
* @param {number} [red=1.0] The red component.
* @param {number} [green=1.0] The green component.
* @param {number} [blue=1.0] The blue component.
* @param {number} [alpha=1.0] The alpha component.
*/
constructor(red, green, blue, alpha) {
this.red = red ?? 1;
this.green = green ?? 1;
this.blue = blue ?? 1;
this.alpha = alpha ?? 1;
}
/**
* Creates a Color instance from a {@link Cartesian4}. x, y, z,
* and w map to red, green, blue, and alpha, respectively.
*
* @param {Cartesian4} cartesian The source cartesian.
* @param {Color} [result] The object onto which to store the result.
* @returns {Color} The modified result parameter or a new Color instance if one was not provided.
*/
static fromCartesian4(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;
}
/**
* Creates a new Color specified using red, green, blue, and alpha values
* that are in the range of 0 to 255, converting them internally to a range of 0.0 to 1.0.
*
* @param {number} [red=255] The red component.
* @param {number} [green=255] The green component.
* @param {number} [blue=255] The blue component.
* @param {number} [alpha=255] The alpha component.
* @param {Color} [result] The object onto which to store the result.
* @returns {Color} The modified result parameter or a new Color instance if one was not provided.
*/
static fromBytes(red, green, blue, alpha, result) {
red = _Color.byteToFloat(red ?? 255);
green = _Color.byteToFloat(green ?? 255);
blue = _Color.byteToFloat(blue ?? 255);
alpha = _Color.byteToFloat(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;
}
/**
* Creates a new Color that has the same red, green, and blue components
* of the specified color, but with the specified alpha value.
*
* @param {Color} color The base color
* @param {number} alpha The new alpha component.
* @param {Color} [result] The object onto which to store the result.
* @returns {Color} The modified result parameter or a new Color instance if one was not provided.
*
* @example const translucentRed = Cesium.Color.fromAlpha(Cesium.Color.RED, 0.9);
*/
static fromAlpha(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;
}
/**
* Creates a new Color from a single numeric unsigned 32-bit RGBA value, using the endianness
* of the system.
*
* @param {number} rgba A single numeric unsigned 32-bit RGBA value.
* @param {Color} [result] The object to store the result in, if undefined a new instance will be created.
* @returns {Color} The color object.
*
* @example
* const color = Cesium.Color.fromRgba(0x67ADDFFF);
*
* @see Color#toRgba
*/
static fromRgba(rgba, result) {
scratchUint32Array[0] = rgba;
return _Color.fromBytes(
scratchUint8Array[0],
scratchUint8Array[1],
scratchUint8Array[2],
scratchUint8Array[3],
result
);
}
/**
* Creates a Color instance from hue, saturation, and lightness.
*
* @param {number} [hue=0] The hue angle 0...1
* @param {number} [saturation=0] The saturation value 0...1
* @param {number} [lightness=0] The lightness value 0...1
* @param {number} [alpha=1.0] The alpha component 0...1
* @param {Color} [result] The object to store the result in, if undefined a new instance will be created.
* @returns {Color} The color object.
*
* @see {@link http://www.w3.org/TR/css3-color/#hsl-color|CSS color values}
*/
static fromHsl(hue, saturation, lightness, alpha, result) {
hue = (hue ?? 0) % 1;
saturation = saturation ?? 0;
lightness = lightness ?? 0;
alpha = 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;
}
/**
* Creates a random color using the provided options. For reproducible random colors, you should
* call {@link CesiumMath#setRandomNumberSeed} once at the beginning of your application.
*
* @param {object} [options] Object with the following properties:
* @param {number} [options.red] If specified, the red component to use instead of a randomized value.
* @param {number} [options.minimumRed=0.0] The maximum red value to generate if none was specified.
* @param {number} [options.maximumRed=1.0] The minimum red value to generate if none was specified.
* @param {number} [options.green] If specified, the green component to use instead of a randomized value.
* @param {number} [options.minimumGreen=0.0] The maximum green value to generate if none was specified.
* @param {number} [options.maximumGreen=1.0] The minimum green value to generate if none was specified.
* @param {number} [options.blue] If specified, the blue component to use instead of a randomized value.
* @param {number} [options.minimumBlue=0.0] The maximum blue value to generate if none was specified.
* @param {number} [options.maximumBlue=1.0] The minimum blue value to generate if none was specified.
* @param {number} [options.alpha] If specified, the alpha component to use instead of a randomized value.
* @param {number} [options.minimumAlpha=0.0] The maximum alpha value to generate if none was specified.
* @param {number} [options.maximumAlpha=1.0] The minimum alpha value to generate if none was specified.
* @param {Color} [result] The object to store the result in, if undefined a new instance will be created.
* @returns {Color} The modified result parameter or a new instance if result was undefined.
*
* @exception {DeveloperError} minimumRed must be less than or equal to maximumRed.
* @exception {DeveloperError} minimumGreen must be less than or equal to maximumGreen.
* @exception {DeveloperError} minimumBlue must be less than or equal to maximumBlue.
* @exception {DeveloperError} minimumAlpha must be less than or equal to maximumAlpha.
*
* @example
* //Create a completely random color
* const color = Cesium.Color.fromRandom();
*
* //Create a random shade of yellow.
* const color1 = Cesium.Color.fromRandom({
* red : 1.0,
* green : 1.0,
* alpha : 1.0
* });
*
* //Create a random bright color.
* const color2 = Cesium.Color.fromRandom({
* minimumRed : 0.75,
* minimumGreen : 0.75,
* minimumBlue : 0.75,
* alpha : 1.0
* });
*/
static fromRandom(options, result) {
options = options ?? Frozen_default.EMPTY_OBJECT;
let red = options.red;
if (!defined_default(red)) {
const minimumRed = options.minimumRed ?? 0;
const maximumRed = 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 = options.minimumGreen ?? 0;
const maximumGreen = 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 = options.minimumBlue ?? 0;
const maximumBlue = 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 = options.minimumAlpha ?? 0;
const maximumAlpha = options.maximumAlpha ?? 1;
Check_default.typeOf.number.lessThanOrEquals(
"minimumAlpha",
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;
}
/**
* Creates a Color instance from a CSS color value.
*
* @param {string} color The CSS color value in #rgb, #rgba, #rrggbb, #rrggbbaa, rgb(), rgba(), hsl(), or hsla() format.
* @param {Color} [result] The object to store the result in, if undefined a new instance will be created.
* @returns {Color} The color object, or undefined if the string was not a valid CSS color.
*
*
* @example
* const cesiumBlue = Cesium.Color.fromCssColorString('#67ADDF');
* const green = Cesium.Color.fromCssColorString('green');
*
* @see {@link http://www.w3.org/TR/css3-color|CSS color values}
*/
static fromCssColorString(color, result) {
Check_default.typeOf.string("color", color);
if (!defined_default(result)) {
result = new _Color();
}
color = color.trim();
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(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(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(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(matches[4] ?? "1.0"),
result
);
}
result = void 0;
return result;
}
/**
* Stores the provided instance into the provided array.
*
* @param {Color} value The value to pack.
* @param {number[]|TypedArray} array The array to pack into.
* @param {number} [startingIndex=0] The index into the array at which to start packing the elements.
*
* @returns {number[]|TypedArray} The array that was packed into
*/
static pack(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
Check_default.defined("array", array);
startingIndex = startingIndex ?? 0;
array[startingIndex++] = value.red;
array[startingIndex++] = value.green;
array[startingIndex++] = value.blue;
array[startingIndex] = value.alpha;
return array;
}
/**
* Retrieves an instance from a packed array.
*
* @param {number[]|TypedArray} array The packed array.
* @param {number} [startingIndex=0] The starting index of the element to be unpacked.
* @param {Color} [result] The object into which to store the result.
* @returns {Color} The modified result parameter or a new Color instance if one was not provided.
*/
static unpack(array, startingIndex, result) {
Check_default.defined("array", array);
startingIndex = 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;
}
/**
* Converts a 'byte' color component in the range of 0 to 255 into
* a 'float' color component in the range of 0 to 1.0.
*
* @param {number} number The number to be converted.
* @returns {number} The converted number.
*/
static byteToFloat(number) {
return number / 255;
}
/**
* Converts a 'float' color component in the range of 0 to 1.0 into
* a 'byte' color component in the range of 0 to 255.
*
* @param {number} number The number to be converted.
* @returns {number} The converted number.
*/
static floatToByte(number) {
return number === 1 ? 255 : number * 256 | 0;
}
/**
* Duplicates a Color.
*
* @param {Color} color The Color to duplicate.
* @param {Color} [result] The object to store the result in, if undefined a new instance will be created.
* @returns {Color} The modified result parameter or a new instance if result was undefined. (Returns undefined if color is undefined)
*/
static clone(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;
}
/**
* Returns true if the first Color equals the second color.
*
* @param {Color} [left] The first Color to compare for equality.
* @param {Color} [right] The second Color to compare for equality.
* @returns {boolean} true if the Colors are equal; otherwise, false.
*/
static equals(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;
}
/**
* @private
*/
static equalsArray(color, array, offset) {
return color.red === array[offset] && color.green === array[offset + 1] && color.blue === array[offset + 2] && color.alpha === array[offset + 3];
}
/**
* Returns a duplicate of a Color instance.
*
* @param {Color} [result] The object to store the result in, if undefined a new instance will be created.
* @returns {Color} The modified result parameter or a new instance if result was undefined.
*/
clone(result) {
return _Color.clone(this, result);
}
/**
* Returns true if this Color equals other.
*
* @param {Color} [other] The Color to compare for equality.
* @returns {boolean} true if the Colors are equal; otherwise, false.
*/
equals(other) {
return _Color.equals(this, other);
}
/**
* Returns true if this Color equals other componentwise within the specified epsilon.
*
* @param {Color} other The Color to compare for equality.
* @param {number} [epsilon=0.0] The epsilon to use for equality testing.
* @returns {boolean} true if the Colors are equal within the specified epsilon; otherwise, false.
*/
equalsEpsilon(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;
}
/**
* Creates a string representing this Color in the format '(red, green, blue, alpha)'.
*
* @returns {string} A string representing this Color in the format '(red, green, blue, alpha)'.
*/
toString() {
return `(${this.red}, ${this.green}, ${this.blue}, ${this.alpha})`;
}
/**
* Creates a string containing the CSS color value for this color.
*
* @returns {string} The CSS equivalent of this color.
*
* @see {@link http://www.w3.org/TR/css3-color/#rgba-color|CSS RGB or RGBA color values}
*/
toCssColorString() {
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})`;
}
/**
* Creates a string containing CSS hex string color value for this color.
*
* @returns {string} The CSS hex string equivalent of this color.
*/
toCssHexString() {
let r2 = _Color.floatToByte(this.red).toString(16);
if (r2.length < 2) {
r2 = `0${r2}`;
}
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 `#${r2}${g}${b}${hexAlpha}`;
}
return `#${r2}${g}${b}`;
}
/**
* Converts this color to an array of red, green, blue, and alpha values
* that are in the range of 0 to 255.
*
* @param {number[]} [result] The array to store the result in, if undefined a new instance will be created.
* @returns {number[]} The modified result parameter or a new instance if result was undefined.
*/
toBytes(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;
}
/**
* Converts RGBA values in bytes to a single numeric unsigned 32-bit RGBA value, using the endianness
* of the system.
*
* @returns {number} A single numeric unsigned 32-bit RGBA value.
*
* @see Color.toRgba
*/
static bytesToRgba(red, green, blue, alpha) {
scratchUint8Array[0] = red;
scratchUint8Array[1] = green;
scratchUint8Array[2] = blue;
scratchUint8Array[3] = alpha;
return scratchUint32Array[0];
}
/**
* Converts this color to a single numeric unsigned 32-bit RGBA value, using the endianness
* of the system.
*
* @returns {number} A single numeric unsigned 32-bit RGBA value.
*
*
* @example
* const rgba = Cesium.Color.BLUE.toRgba();
*
* @see Color.fromRgba
*/
toRgba() {
return _Color.bytesToRgba(
_Color.floatToByte(this.red),
_Color.floatToByte(this.green),
_Color.floatToByte(this.blue),
_Color.floatToByte(this.alpha)
);
}
/**
* Brightens this color by the provided magnitude.
*
* @param {number} magnitude A positive number indicating the amount to brighten.
* @param {Color} result The object onto which to store the result.
* @returns {Color} The modified result parameter.
*
* @example
* const brightBlue = Cesium.Color.BLUE.brighten(0.5, new Cesium.Color());
*/
brighten(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;
}
/**
* Darkens this color by the provided magnitude.
*
* @param {number} magnitude A positive number indicating the amount to darken.
* @param {Color} result The object onto which to store the result.
* @returns {Color} The modified result parameter.
*
* @example
* const darkBlue = Cesium.Color.BLUE.darken(0.5, new Cesium.Color());
*/
darken(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;
}
/**
* Creates a new Color that has the same red, green, and blue components
* as this Color, but with the specified alpha value.
*
* @param {number} alpha The new alpha component.
* @param {Color} [result] The object onto which to store the result.
* @returns {Color} The modified result parameter or a new Color instance if one was not provided.
*
* @example const translucentRed = Cesium.Color.RED.withAlpha(0.9);
*/
withAlpha(alpha, result) {
return _Color.fromAlpha(this, alpha, result);
}
/**
* Computes the componentwise sum of two Colors.
*
* @param {Color} left The first Color.
* @param {Color} right The second Color.
* @param {Color} result The object onto which to store the result.
* @returns {Color} The modified result parameter.
*/
static add(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;
}
/**
* Computes the componentwise difference of two Colors.
*
* @param {Color} left The first Color.
* @param {Color} right The second Color.
* @param {Color} result The object onto which to store the result.
* @returns {Color} The modified result parameter.
*/
static subtract(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;
}
/**
* Computes the componentwise product of two Colors.
*
* @param {Color} left The first Color.
* @param {Color} right The second Color.
* @param {Color} result The object onto which to store the result.
* @returns {Color} The modified result parameter.
*/
static multiply(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;
}
/**
* Computes the componentwise quotient of two Colors.
*
* @param {Color} left The first Color.
* @param {Color} right The second Color.
* @param {Color} result The object onto which to store the result.
* @returns {Color} The modified result parameter.
*/
static divide(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;
}
/**
* Computes the componentwise modulus of two Colors.
*
* @param {Color} left The first Color.
* @param {Color} right The second Color.
* @param {Color} result The object onto which to store the result.
* @returns {Color} The modified result parameter.
*/
static mod(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;
}
/**
* Computes the linear interpolation or extrapolation at t between the provided colors.
*
* @param {Color} start The color corresponding to t at 0.0.
* @param {Color} end The color corresponding to t at 1.0.
* @param {number} t The point along t at which to interpolate.
* @param {Color} result The object onto which to store the result.
* @returns {Color} The modified result parameter.
*/
static lerp(start, end, t2, result) {
Check_default.typeOf.object("start", start);
Check_default.typeOf.object("end", end);
Check_default.typeOf.number("t", t2);
Check_default.typeOf.object("result", result);
result.red = Math_default.lerp(start.red, end.red, t2);
result.green = Math_default.lerp(start.green, end.green, t2);
result.blue = Math_default.lerp(start.blue, end.blue, t2);
result.alpha = Math_default.lerp(start.alpha, end.alpha, t2);
return result;
}
/**
* Multiplies the provided Color componentwise by the provided scalar.
*
* @param {Color} color The Color to be scaled.
* @param {number} scalar The scalar to multiply with.
* @param {Color} result The object onto which to store the result.
* @returns {Color} The modified result parameter.
*/
static multiplyByScalar(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;
}
/**
* Divides the provided Color componentwise by the provided scalar.
*
* @param {Color} color The Color to be divided.
* @param {number} scalar The scalar to divide with.
* @param {Color} result The object onto which to store the result.
* @returns {Color} The modified result parameter.
*/
static divideByScalar(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;
}
};
var scratchArrayBuffer;
var scratchUint32Array;
var scratchUint8Array;
if (FeatureDetection_default.supportsTypedArrays()) {
scratchArrayBuffer = new ArrayBuffer(4);
scratchUint32Array = new Uint32Array(scratchArrayBuffer);
scratchUint8Array = new Uint8Array(scratchArrayBuffer);
}
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*\(\s*([0-9.]+%?)\s*[,\s]+\s*([0-9.]+%?)\s*[,\s]+\s*([0-9.]+%?)(?:\s*[,\s/]+\s*([0-9.]+))?\s*\)$/i;
var hslParenthesesMatcher = /^hsla?\s*\(\s*([0-9.]+)\s*[,\s]+\s*([0-9.]+%)\s*[,\s]+\s*([0-9.]+%)(?:\s*[,\s/]+\s*([0-9.]+))?\s*\)$/i;
Color.packedLength = 4;
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 = options ?? Frozen_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_EDGES: 4,
CESIUM_3D_TILE_PLANAR_FILL_ID: 5,
CESIUM_3D_TILE: 6,
CESIUM_3D_TILE_CLASSIFICATION: 7,
CESIUM_3D_TILE_CLASSIFICATION_IGNORE_SHOW: 8,
OPAQUE: 9,
TRANSLUCENT: 10,
VOXELS: 11,
GAUSSIAN_SPLATS: 12,
CESIUM_3D_TILE_EDGES_DIRECT: 13,
OVERLAY: 14,
NUMBER_OF_PASSES: 15
};
Object.freeze(Pass);
var Pass_default = Pass;
// packages/engine/Source/Renderer/ComputeCommand.js
function ComputeCommand(options) {
options = options ?? Frozen_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 = 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
var Cartesian2 = class _Cartesian2 {
/**
* @param {number} [x=0.0] The X component.
* @param {number} [y=0.0] The Y component.
*/
constructor(x, y) {
this.x = x ?? 0;
this.y = y ?? 0;
}
/**
* Creates a Cartesian2 instance from x and y coordinates.
*
* @param {number} x The x coordinate.
* @param {number} y The y coordinate.
* @param {Cartesian2} [result] The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
*/
static fromElements(x, y, result) {
if (!defined_default(result)) {
return new _Cartesian2(x, y);
}
result.x = x;
result.y = y;
return result;
}
/**
* Duplicates a Cartesian2 instance.
*
* @param {Cartesian2} cartesian The Cartesian to duplicate.
* @param {Cartesian2} [result] The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided. (Returns undefined if cartesian is undefined)
*/
static clone(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;
}
/**
* Stores the provided instance into the provided array.
*
* @param {Cartesian2} value The value to pack.
* @param {number[]} array The array to pack into.
* @param {number} [startingIndex=0] The index into the array at which to start packing the elements.
*
* @returns {number[]} The array that was packed into
*/
static pack(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
Check_default.defined("array", array);
startingIndex = startingIndex ?? 0;
array[startingIndex++] = value.x;
array[startingIndex] = value.y;
return array;
}
/**
* Retrieves an instance from a packed array.
*
* @param {number[]} array The packed array.
* @param {number} [startingIndex=0] The starting index of the element to be unpacked.
* @param {Cartesian2} [result] The object into which to store the result.
* @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
*/
static unpack(array, startingIndex, result) {
Check_default.defined("array", array);
startingIndex = startingIndex ?? 0;
if (!defined_default(result)) {
result = new _Cartesian2();
}
result.x = array[startingIndex++];
result.y = array[startingIndex];
return result;
}
/**
* Flattens an array of Cartesian2s into an array of components.
*
* @param {Cartesian2[]} array The array of cartesians to pack.
* @param {number[]} [result] The array onto which to store the result. If this is a typed array, it must have array.length * 2 components, else a {@link DeveloperError} will be thrown. If it is a regular array, it will be resized to have (array.length * 2) elements.
* @returns {number[]} The packed array.
*/
static packArray(array, result) {
Check_default.defined("array", array);
const length2 = array.length;
const resultLength = length2 * 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 < length2; ++i) {
_Cartesian2.pack(array[i], result, i * 2);
}
return result;
}
/**
* Unpacks an array of cartesian components into an array of Cartesian2s.
*
* @param {number[]} array The array of components to unpack.
* @param {Cartesian2[]} [result] The array onto which to store the result.
* @returns {Cartesian2[]} The unpacked array.
*/
static unpackArray(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 length2 = array.length;
if (!defined_default(result)) {
result = new Array(length2 / 2);
} else {
result.length = length2 / 2;
}
for (let i = 0; i < length2; i += 2) {
const index = i / 2;
result[index] = _Cartesian2.unpack(array, i, result[index]);
}
return result;
}
/**
* Computes the value of the maximum component for the supplied Cartesian.
*
* @param {Cartesian2} cartesian The cartesian to use.
* @returns {number} The value of the maximum component.
*/
static maximumComponent(cartesian11) {
Check_default.typeOf.object("cartesian", cartesian11);
return Math.max(cartesian11.x, cartesian11.y);
}
/**
* Computes the value of the minimum component for the supplied Cartesian.
*
* @param {Cartesian2} cartesian The cartesian to use.
* @returns {number} The value of the minimum component.
*/
static minimumComponent(cartesian11) {
Check_default.typeOf.object("cartesian", cartesian11);
return Math.min(cartesian11.x, cartesian11.y);
}
/**
* Compares two Cartesians and computes a Cartesian which contains the minimum components of the supplied Cartesians.
*
* @param {Cartesian2} first A cartesian to compare.
* @param {Cartesian2} second A cartesian to compare.
* @param {Cartesian2} result The object into which to store the result.
* @returns {Cartesian2} A cartesian with the minimum components.
*/
static minimumByComponent(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;
}
/**
* Compares two Cartesians and computes a Cartesian which contains the maximum components of the supplied Cartesians.
*
* @param {Cartesian2} first A cartesian to compare.
* @param {Cartesian2} second A cartesian to compare.
* @param {Cartesian2} result The object into which to store the result.
* @returns {Cartesian2} A cartesian with the maximum components.
*/
static maximumByComponent(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;
}
/**
* Constrain a value to lie between two values.
*
* @param {Cartesian2} value The value to clamp.
* @param {Cartesian2} min The minimum bound.
* @param {Cartesian2} max The maximum bound.
* @param {Cartesian2} result The object into which to store the result.
* @returns {Cartesian2} The clamped value such that min <= result <= max.
*/
static clamp(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;
}
/**
* Computes the provided Cartesian's squared magnitude.
*
* @param {Cartesian2} cartesian The Cartesian instance whose squared magnitude is to be computed.
* @returns {number} The squared magnitude.
*/
static magnitudeSquared(cartesian11) {
Check_default.typeOf.object("cartesian", cartesian11);
return cartesian11.x * cartesian11.x + cartesian11.y * cartesian11.y;
}
/**
* Computes the Cartesian's magnitude (length).
*
* @param {Cartesian2} cartesian The Cartesian instance whose magnitude is to be computed.
* @returns {number} The magnitude.
*/
static magnitude(cartesian11) {
return Math.sqrt(_Cartesian2.magnitudeSquared(cartesian11));
}
/**
* Computes the distance between two points.
*
* @param {Cartesian2} left The first point to compute the distance from.
* @param {Cartesian2} right The second point to compute the distance to.
* @returns {number} The distance between two points.
*
* @example
* // Returns 1.0
* const d = Cesium.Cartesian2.distance(new Cesium.Cartesian2(1.0, 0.0), new Cesium.Cartesian2(2.0, 0.0));
*/
static distance(left, right) {
Check_default.typeOf.object("left", left);
Check_default.typeOf.object("right", right);
_Cartesian2.subtract(left, right, distanceScratch3);
return _Cartesian2.magnitude(distanceScratch3);
}
/**
* Computes the squared distance between two points. Comparing squared distances
* using this function is more efficient than comparing distances using {@link Cartesian2#distance}.
*
* @param {Cartesian2} left The first point to compute the distance from.
* @param {Cartesian2} right The second point to compute the distance to.
* @returns {number} The distance between two points.
*
* @example
* // Returns 4.0, not 2.0
* const d = Cesium.Cartesian2.distance(new Cesium.Cartesian2(1.0, 0.0), new Cesium.Cartesian2(3.0, 0.0));
*/
static distanceSquared(left, right) {
Check_default.typeOf.object("left", left);
Check_default.typeOf.object("right", right);
_Cartesian2.subtract(left, right, distanceScratch3);
return _Cartesian2.magnitudeSquared(distanceScratch3);
}
/**
* Computes the normalized form of the supplied Cartesian.
*
* @param {Cartesian2} cartesian The Cartesian to be normalized.
* @param {Cartesian2} result The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter.
*/
static normalize(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;
}
/**
* Computes the dot (scalar) product of two Cartesians.
*
* @param {Cartesian2} left The first Cartesian.
* @param {Cartesian2} right The second Cartesian.
* @returns {number} The dot product.
*/
static dot(left, right) {
Check_default.typeOf.object("left", left);
Check_default.typeOf.object("right", right);
return left.x * right.x + left.y * right.y;
}
/**
* Computes the magnitude of the cross product that would result from implicitly setting the Z coordinate of the input vectors to 0
*
* @param {Cartesian2} left The first Cartesian.
* @param {Cartesian2} right The second Cartesian.
* @returns {number} The cross product.
*/
static cross(left, right) {
Check_default.typeOf.object("left", left);
Check_default.typeOf.object("right", right);
return left.x * right.y - left.y * right.x;
}
/**
* Computes the componentwise product of two Cartesians.
*
* @param {Cartesian2} left The first Cartesian.
* @param {Cartesian2} right The second Cartesian.
* @param {Cartesian2} result The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter.
*/
static multiplyComponents(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;
}
/**
* Computes the componentwise quotient of two Cartesians.
*
* @param {Cartesian2} left The first Cartesian.
* @param {Cartesian2} right The second Cartesian.
* @param {Cartesian2} result The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter.
*/
static divideComponents(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;
}
/**
* Computes the componentwise sum of two Cartesians.
*
* @param {Cartesian2} left The first Cartesian.
* @param {Cartesian2} right The second Cartesian.
* @param {Cartesian2} result The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter.
*/
static add(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;
}
/**
* Computes the componentwise difference of two Cartesians.
*
* @param {Cartesian2} left The first Cartesian.
* @param {Cartesian2} right The second Cartesian.
* @param {Cartesian2} result The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter.
*/
static subtract(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;
}
/**
* Multiplies the provided Cartesian componentwise by the provided scalar.
*
* @param {Cartesian2} cartesian The Cartesian to be scaled.
* @param {number} scalar The scalar to multiply with.
* @param {Cartesian2} result The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter.
*/
static multiplyByScalar(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;
}
/**
* Divides the provided Cartesian componentwise by the provided scalar.
*
* @param {Cartesian2} cartesian The Cartesian to be divided.
* @param {number} scalar The scalar to divide by.
* @param {Cartesian2} result The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter.
*/
static divideByScalar(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;
}
/**
* Negates the provided Cartesian.
*
* @param {Cartesian2} cartesian The Cartesian to be negated.
* @param {Cartesian2} result The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter.
*/
static negate(cartesian11, result) {
Check_default.typeOf.object("cartesian", cartesian11);
Check_default.typeOf.object("result", result);
result.x = -cartesian11.x;
result.y = -cartesian11.y;
return result;
}
/**
* Computes the absolute value of the provided Cartesian.
*
* @param {Cartesian2} cartesian The Cartesian whose absolute value is to be computed.
* @param {Cartesian2} result The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter.
*/
static abs(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;
}
/**
* Computes the linear interpolation or extrapolation at t using the provided cartesians.
*
* @param {Cartesian2} start The value corresponding to t at 0.0.
* @param {Cartesian2} end The value corresponding to t at 1.0.
* @param {number} t The point along t at which to interpolate.
* @param {Cartesian2} result The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter.
*/
static lerp(start, end, t2, result) {
Check_default.typeOf.object("start", start);
Check_default.typeOf.object("end", end);
Check_default.typeOf.number("t", t2);
Check_default.typeOf.object("result", result);
_Cartesian2.multiplyByScalar(end, t2, lerpScratch3);
result = _Cartesian2.multiplyByScalar(start, 1 - t2, result);
return _Cartesian2.add(lerpScratch3, result, result);
}
/**
* Returns the angle, in radians, between the provided Cartesians.
*
* @param {Cartesian2} left The first Cartesian.
* @param {Cartesian2} right The second Cartesian.
* @returns {number} The angle between the Cartesians.
*/
static angleBetween(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)
);
}
/**
* Returns the axis that is most orthogonal to the provided Cartesian.
*
* @param {Cartesian2} cartesian The Cartesian on which to find the most orthogonal axis.
* @param {Cartesian2} result The object onto which to store the result.
* @returns {Cartesian2} The most orthogonal axis.
*/
static mostOrthogonalAxis(cartesian11, result) {
Check_default.typeOf.object("cartesian", cartesian11);
Check_default.typeOf.object("result", result);
const f2 = _Cartesian2.normalize(cartesian11, mostOrthogonalAxisScratch3);
_Cartesian2.abs(f2, f2);
if (f2.x <= f2.y) {
result = _Cartesian2.clone(_Cartesian2.UNIT_X, result);
} else {
result = _Cartesian2.clone(_Cartesian2.UNIT_Y, result);
}
return result;
}
/**
* Compares the provided Cartesians componentwise and returns
* true if they are equal, false otherwise.
*
* @param {Cartesian2} [left] The first Cartesian.
* @param {Cartesian2} [right] The second Cartesian.
* @returns {boolean} true if left and right are equal, false otherwise.
*/
static equals(left, right) {
return left === right || defined_default(left) && defined_default(right) && left.x === right.x && left.y === right.y;
}
/**
* @param {Cartesian2} cartesian
* @param {number[]} array
* @param {number} offset
* @ignore
*/
static equalsArray(cartesian11, array, offset) {
return cartesian11.x === array[offset] && cartesian11.y === array[offset + 1];
}
/**
* Compares the provided Cartesians componentwise and returns
* true if they pass an absolute or relative tolerance test,
* false otherwise.
*
* @param {Cartesian2} [left] The first Cartesian.
* @param {Cartesian2} [right] The second Cartesian.
* @param {number} [relativeEpsilon=0] The relative epsilon tolerance to use for equality testing.
* @param {number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
* @returns {boolean} true if left and right are within the provided epsilon, false otherwise.
*/
static equalsEpsilon(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
);
}
/**
* Duplicates this Cartesian2 instance.
*
* @param {Cartesian2} [result] The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
*/
clone(result) {
return _Cartesian2.clone(this, result);
}
/**
* Compares this Cartesian against the provided Cartesian componentwise and returns
* true if they are equal, false otherwise.
*
* @param {Cartesian2} [right] The right hand side Cartesian.
* @returns {boolean} true if they are equal, false otherwise.
*/
equals(right) {
return _Cartesian2.equals(this, right);
}
/**
* Compares this Cartesian against the provided Cartesian componentwise and returns
* true if they pass an absolute or relative tolerance test,
* false otherwise.
*
* @param {Cartesian2} [right] The right hand side Cartesian.
* @param {number} [relativeEpsilon=0] The relative epsilon tolerance to use for equality testing.
* @param {number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
* @returns {boolean} true if they are within the provided epsilon, false otherwise.
*/
equalsEpsilon(right, relativeEpsilon, absoluteEpsilon) {
return _Cartesian2.equalsEpsilon(
this,
right,
relativeEpsilon,
absoluteEpsilon
);
}
/**
* Creates a string representing this Cartesian in the format '(x, y)'.
*
* @returns {string} A string representing the provided Cartesian in the format '(x, y)'.
*/
toString() {
return `(${this.x}, ${this.y})`;
}
};
Cartesian2.fromCartesian3 = Cartesian2.clone;
Cartesian2.fromCartesian4 = Cartesian2.clone;
Cartesian2.packedLength = 2;
Cartesian2.fromArray = Cartesian2.unpack;
var distanceScratch3 = new Cartesian2();
var lerpScratch3 = new Cartesian2();
var angleBetweenScratch3 = new Cartesian2();
var angleBetweenScratch22 = new Cartesian2();
var mostOrthogonalAxisScratch3 = new Cartesian2();
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));
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
var _Cartographic = class _Cartographic {
/**
* @param {number} [longitude=0.0] The longitude, in radians.
* @param {number} [latitude=0.0] The latitude, in radians.
* @param {number} [height=0.0] The height, in meters, above the ellipsoid.
*/
constructor(longitude, latitude, height) {
this.longitude = longitude ?? 0;
this.latitude = latitude ?? 0;
this.height = height ?? 0;
}
/**
* Creates a new Cartographic instance from longitude and latitude
* specified in radians.
*
* @param {number} longitude The longitude, in radians.
* @param {number} latitude The latitude, in radians.
* @param {number} [height=0.0] The height, in meters, above the ellipsoid.
* @param {Cartographic} [result] The object onto which to store the result.
* @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided.
*/
static fromRadians(longitude, latitude, height, result) {
Check_default.typeOf.number("longitude", longitude);
Check_default.typeOf.number("latitude", latitude);
height = height ?? 0;
if (!defined_default(result)) {
return new _Cartographic(longitude, latitude, height);
}
result.longitude = longitude;
result.latitude = latitude;
result.height = height;
return result;
}
/**
* Creates a new Cartographic instance from longitude and latitude
* specified in degrees. The values in the resulting object will
* be in radians.
*
* @param {number} longitude The longitude, in degrees.
* @param {number} latitude The latitude, in degrees.
* @param {number} [height=0.0] The height, in meters, above the ellipsoid.
* @param {Cartographic} [result] The object onto which to store the result.
* @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided.
*/
static fromDegrees(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);
}
/**
* Creates a new Cartographic instance from a Cartesian position. The values in the
* resulting object will be in radians.
*
* @param {Cartesian3} cartesian The Cartesian position to convert to cartographic representation.
* @param {Ellipsoid} [ellipsoid=Ellipsoid.default] The ellipsoid on which the position lies.
* @param {Cartographic} [result] The object onto which to store the result.
* @returns {Cartographic} The modified result parameter, new Cartographic instance if none was provided, or undefined if the cartesian is at the center of the ellipsoid.
*/
static fromCartesian(cartesian11, ellipsoid, result) {
const oneOverRadii = defined_default(ellipsoid) ? ellipsoid.oneOverRadii : _Cartographic._ellipsoidOneOverRadii;
const oneOverRadiiSquared = defined_default(ellipsoid) ? ellipsoid.oneOverRadiiSquared : _Cartographic._ellipsoidOneOverRadiiSquared;
const centerToleranceSquared = defined_default(ellipsoid) ? ellipsoid._centerToleranceSquared : _Cartographic._ellipsoidCenterToleranceSquared;
const p = scaleToGeodeticSurface_default(
cartesian11,
oneOverRadii,
oneOverRadiiSquared,
centerToleranceSquared,
cartesianToCartographicP
);
if (!defined_default(p)) {
return void 0;
}
let n2 = Cartesian3_default.multiplyComponents(
p,
oneOverRadiiSquared,
cartesianToCartographicN
);
n2 = Cartesian3_default.normalize(n2, n2);
const h = Cartesian3_default.subtract(cartesian11, p, cartesianToCartographicH);
const longitude = Math.atan2(n2.y, n2.x);
const latitude = Math.asin(n2.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;
}
/**
* Creates a new Cartesian3 instance from a Cartographic input. The values in the inputted
* object should be in radians.
*
* @param {Cartographic} cartographic Input to be converted into a Cartesian3 output.
* @param {Ellipsoid} [ellipsoid=Ellipsoid.default] The ellipsoid on which the position lies.
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The position
*/
static toCartesian(cartographic2, ellipsoid, result) {
Check_default.defined("cartographic", cartographic2);
return Cartesian3_default.fromRadians(
cartographic2.longitude,
cartographic2.latitude,
cartographic2.height,
ellipsoid,
result
);
}
/**
* Duplicates a Cartographic instance.
*
* @param {Cartographic} cartographic The cartographic to duplicate.
* @param {Cartographic} [result] The object onto which to store the result.
* @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided. (Returns undefined if cartographic is undefined)
*/
static clone(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;
}
/**
* Compares the provided cartographics componentwise and returns
* true if they are equal, false otherwise.
*
* @param {Cartographic} [left] The first cartographic.
* @param {Cartographic} [right] The second cartographic.
* @returns {boolean} true if left and right are equal, false otherwise.
*/
static equals(left, right) {
return left === right || defined_default(left) && defined_default(right) && left.longitude === right.longitude && left.latitude === right.latitude && left.height === right.height;
}
/**
* Compares the provided cartographics componentwise and returns
* true if they are within the provided epsilon,
* false otherwise.
*
* @param {Cartographic} [left] The first cartographic.
* @param {Cartographic} [right] The second cartographic.
* @param {number} [epsilon=0] The epsilon to use for equality testing.
* @returns {boolean} true if left and right are within the provided epsilon, false otherwise.
*/
static equalsEpsilon(left, right, epsilon) {
epsilon = 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;
}
/**
* Duplicates this instance.
*
* @param {Cartographic} [result] The object onto which to store the result.
* @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided.
*/
clone(result) {
return _Cartographic.clone(this, result);
}
/**
* Compares the provided against this cartographic componentwise and returns
* true if they are equal, false otherwise.
*
* @param {Cartographic} [right] The second cartographic.
* @returns {boolean} true if left and right are equal, false otherwise.
*/
equals(right) {
return _Cartographic.equals(this, right);
}
/**
* Compares the provided against this cartographic componentwise and returns
* true if they are within the provided epsilon,
* false otherwise.
*
* @param {Cartographic} [right] The second cartographic.
* @param {number} [epsilon=0] The epsilon to use for equality testing.
* @returns {boolean} true if left and right are within the provided epsilon, false otherwise.
*/
equalsEpsilon(right, epsilon) {
return _Cartographic.equalsEpsilon(this, right, epsilon);
}
/**
* Creates a string representing this cartographic in the format '(longitude, latitude, height)'.
*
* @returns {string} A string representing the provided cartographic in the format '(longitude, latitude, height)'.
*/
toString() {
return `(${this.longitude}, ${this.latitude}, ${this.height})`;
}
};
// To avoid circular dependencies, these are set by Ellipsoid when Ellipsoid.default is set.
__publicField(_Cartographic, "_ellipsoidOneOverRadii", new Cartesian3_default(
1 / 6378137,
1 / 6378137,
1 / 6356752314245179e-9
));
__publicField(_Cartographic, "_ellipsoidOneOverRadiiSquared", new Cartesian3_default(
1 / (6378137 * 6378137),
1 / (6378137 * 6378137),
1 / (6356752314245179e-9 * 6356752314245179e-9)
));
__publicField(_Cartographic, "_ellipsoidCenterToleranceSquared", Math_default.EPSILON1);
var Cartographic = _Cartographic;
Cartographic.ZERO = Object.freeze(new Cartographic(0, 0, 0));
var cartesianToCartographicN = new Cartesian3_default();
var cartesianToCartographicP = new Cartesian3_default();
var cartesianToCartographicH = new Cartesian3_default();
var Cartographic_default = Cartographic;
// packages/engine/Source/Core/Ellipsoid.js
function initialize(ellipsoid, x, y, z2) {
x = x ?? 0;
y = y ?? 0;
z2 = z2 ?? 0;
Check_default.typeOf.number.greaterThanOrEquals("x", x, 0);
Check_default.typeOf.number.greaterThanOrEquals("y", y, 0);
Check_default.typeOf.number.greaterThanOrEquals("z", z2, 0);
ellipsoid._radii = new Cartesian3_default(x, y, z2);
ellipsoid._radiiSquared = new Cartesian3_default(x * x, y * y, z2 * z2);
ellipsoid._radiiToTheFourth = new Cartesian3_default(
x * x * x * x,
y * y * y * y,
z2 * z2 * z2 * z2
);
ellipsoid._oneOverRadii = new Cartesian3_default(
x === 0 ? 0 : 1 / x,
y === 0 ? 0 : 1 / y,
z2 === 0 ? 0 : 1 / z2
);
ellipsoid._oneOverRadiiSquared = new Cartesian3_default(
x === 0 ? 0 : 1 / (x * x),
y === 0 ? 0 : 1 / (y * y),
z2 === 0 ? 0 : 1 / (z2 * z2)
);
ellipsoid._minimumRadius = Math.min(x, y, z2);
ellipsoid._maximumRadius = Math.max(x, y, z2);
ellipsoid._centerToleranceSquared = Math_default.EPSILON1;
if (ellipsoid._radiiSquared.z !== 0) {
ellipsoid._squaredXOverSquaredZ = ellipsoid._radiiSquared.x / ellipsoid._radiiSquared.z;
}
}
var Ellipsoid = class _Ellipsoid {
/**
* @param {number} [x=0] The radius in the x direction.
* @param {number} [y=0] The radius in the y direction.
* @param {number} [z=0] The radius in the z direction.
*
* @exception {DeveloperError} All radii components must be greater than or equal to zero.
*/
constructor(x, y, z2) {
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, z2);
}
/**
* Gets the radii of the ellipsoid.
* @type {Cartesian3}
* @readonly
*/
get radii() {
return this._radii;
}
/**
* Gets the squared radii of the ellipsoid.
* @type {Cartesian3}
* @readonly
*/
get radiiSquared() {
return this._radiiSquared;
}
/**
* Gets the radii of the ellipsoid raise to the fourth power.
* @type {Cartesian3}
* @readonly
*/
get radiiToTheFourth() {
return this._radiiToTheFourth;
}
/**
* Gets one over the radii of the ellipsoid.
* @type {Cartesian3}
* @readonly
*/
get oneOverRadii() {
return this._oneOverRadii;
}
/**
* Gets one over the squared radii of the ellipsoid.
* @type {Cartesian3}
* @readonly
*/
get oneOverRadiiSquared() {
return this._oneOverRadiiSquared;
}
/**
* Gets the minimum radius of the ellipsoid.
* @type {number}
* @readonly
*/
get minimumRadius() {
return this._minimumRadius;
}
/**
* Gets the maximum radius of the ellipsoid.
* @type {number}
* @readonly
*/
get maximumRadius() {
return this._maximumRadius;
}
/**
* Duplicates an Ellipsoid instance.
*
* @param {Ellipsoid} ellipsoid The ellipsoid to duplicate.
* @param {Ellipsoid} [result] The object onto which to store the result, or undefined if a new
* instance should be created.
* @returns {Ellipsoid} The cloned Ellipsoid. (Returns undefined if ellipsoid is undefined)
*/
static clone(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;
}
/**
* Computes an Ellipsoid from a Cartesian specifying the radii in x, y, and z directions.
*
* @param {Cartesian3} [cartesian=Cartesian3.ZERO] The ellipsoid's radius in the x, y, and z directions.
* @param {Ellipsoid} [result] The object onto which to store the result, or undefined if a new
* instance should be created.
* @returns {Ellipsoid} A new Ellipsoid instance.
*
* @exception {DeveloperError} All radii components must be greater than or equal to zero.
*
* @see Ellipsoid.WGS84
* @see Ellipsoid.UNIT_SPHERE
*/
static fromCartesian3(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;
}
/**
* The default ellipsoid used when not otherwise specified.
* @type {Ellipsoid}
* @example
* Cesium.Ellipsoid.default = Cesium.Ellipsoid.MOON;
*
* // Apollo 11 landing site
* const position = Cesium.Cartesian3.fromRadians(
* 0.67416,
* 23.47315,
* );
*/
static get default() {
return _Ellipsoid._default;
}
static set default(value) {
Check_default.typeOf.object("value", value);
_Ellipsoid._default = value;
Cartesian3_default._ellipsoidRadiiSquared = value.radiiSquared;
Cartographic_default._ellipsoidOneOverRadii = value.oneOverRadii;
Cartographic_default._ellipsoidOneOverRadiiSquared = value.oneOverRadiiSquared;
Cartographic_default._ellipsoidCenterToleranceSquared = value._centerToleranceSquared;
}
/**
* Duplicates an Ellipsoid instance.
*
* @param {Ellipsoid} [result] The object onto which to store the result, or undefined if a new
* instance should be created.
* @returns {Ellipsoid} The cloned Ellipsoid.
*/
clone(result) {
return _Ellipsoid.clone(this, result);
}
/**
* Stores the provided instance into the provided array.
*
* @param {Ellipsoid} value The value to pack.
* @param {number[]} array The array to pack into.
* @param {number} [startingIndex=0] The index into the array at which to start packing the elements.
*
* @returns {number[]} The array that was packed into
*/
static pack(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
Check_default.defined("array", array);
startingIndex = startingIndex ?? 0;
Cartesian3_default.pack(value._radii, array, startingIndex);
return array;
}
/**
* Retrieves an instance from a packed array.
*
* @param {number[]} array The packed array.
* @param {number} [startingIndex=0] The starting index of the element to be unpacked.
* @param {Ellipsoid} [result] The object into which to store the result.
* @returns {Ellipsoid} The modified result parameter or a new Ellipsoid instance if one was not provided.
*/
static unpack(array, startingIndex, result) {
Check_default.defined("array", array);
startingIndex = startingIndex ?? 0;
const radii = Cartesian3_default.unpack(array, startingIndex);
return _Ellipsoid.fromCartesian3(radii, result);
}
/**
* Computes the normal of the plane tangent to the surface of the ellipsoid at the provided position.
*
* @param {Cartographic} cartographic The cartographic position for which to to determine the geodetic normal.
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
*/
geodeticSurfaceNormalCartographic(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 z2 = Math.sin(latitude);
if (!defined_default(result)) {
result = new Cartesian3_default();
}
result.x = x;
result.y = y;
result.z = z2;
return Cartesian3_default.normalize(result, result);
}
/**
* Computes the normal of the plane tangent to the surface of the ellipsoid at the provided position.
*
* @param {Cartesian3} cartesian The Cartesian position for which to to determine the surface normal.
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided, or undefined if a normal cannot be found.
*/
geodeticSurfaceNormal(cartesian11, result) {
Check_default.typeOf.object("cartesian", cartesian11);
if (isNaN(cartesian11.x) || isNaN(cartesian11.y) || isNaN(cartesian11.z)) {
throw new DeveloperError_default("cartesian has a NaN component");
}
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);
}
/**
* Converts the provided cartographic to Cartesian representation.
*
* @param {Cartographic} cartographic The cartographic position.
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
*
* @example
* //Create a Cartographic and determine it's Cartesian representation on a WGS84 ellipsoid.
* const position = new Cesium.Cartographic(Cesium.Math.toRadians(21), Cesium.Math.toRadians(78), 5000);
* const cartesianPosition = Cesium.Ellipsoid.WGS84.cartographicToCartesian(position);
*/
cartographicToCartesian(cartographic2, result) {
const n2 = cartographicToCartesianNormal;
const k = cartographicToCartesianK;
this.geodeticSurfaceNormalCartographic(cartographic2, n2);
Cartesian3_default.multiplyComponents(this._radiiSquared, n2, k);
const gamma = Math.sqrt(Cartesian3_default.dot(n2, k));
Cartesian3_default.divideByScalar(k, gamma, k);
Cartesian3_default.multiplyByScalar(n2, cartographic2.height, n2);
if (!defined_default(result)) {
result = new Cartesian3_default();
}
return Cartesian3_default.add(k, n2, result);
}
/**
* Converts the provided array of cartographics to an array of Cartesians.
*
* @param {Cartographic[]} cartographics An array of cartographic positions.
* @param {Cartesian3[]} [result] The object onto which to store the result.
* @returns {Cartesian3[]} The modified result parameter or a new Array instance if none was provided.
*
* @example
* //Convert an array of Cartographics and determine their Cartesian representation on a WGS84 ellipsoid.
* const positions = [new Cesium.Cartographic(Cesium.Math.toRadians(21), Cesium.Math.toRadians(78), 0),
* new Cesium.Cartographic(Cesium.Math.toRadians(21.321), Cesium.Math.toRadians(78.123), 100),
* new Cesium.Cartographic(Cesium.Math.toRadians(21.645), Cesium.Math.toRadians(78.456), 250)];
* const cartesianPositions = Cesium.Ellipsoid.WGS84.cartographicArrayToCartesianArray(positions);
*/
cartographicArrayToCartesianArray(cartographics, result) {
Check_default.defined("cartographics", cartographics);
const length2 = cartographics.length;
if (!defined_default(result)) {
result = new Array(length2);
} else {
result.length = length2;
}
for (let i = 0; i < length2; i++) {
result[i] = this.cartographicToCartesian(cartographics[i], result[i]);
}
return result;
}
/**
* Converts the provided cartesian to cartographic representation.
* The cartesian is undefined at the center of the ellipsoid.
*
* @param {Cartesian3} cartesian The Cartesian position to convert to cartographic representation.
* @param {Cartographic} [result] The object onto which to store the result.
* @returns {Cartographic} The modified result parameter, new Cartographic instance if none was provided, or undefined if the cartesian is at the center of the ellipsoid.
*
* @example
* //Create a Cartesian and determine it's Cartographic representation on a WGS84 ellipsoid.
* const position = new Cesium.Cartesian3(17832.12, 83234.52, 952313.73);
* const cartographicPosition = Cesium.Ellipsoid.WGS84.cartesianToCartographic(position);
*/
cartesianToCartographic(cartesian11, result) {
const p = this.scaleToGeodeticSurface(cartesian11, cartesianToCartographicP2);
if (!defined_default(p)) {
return void 0;
}
const n2 = this.geodeticSurfaceNormal(p, cartesianToCartographicN2);
const h = Cartesian3_default.subtract(cartesian11, p, cartesianToCartographicH2);
const longitude = Math.atan2(n2.y, n2.x);
const latitude = Math.asin(n2.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;
}
/**
* Converts the provided array of cartesians to an array of cartographics.
*
* @param {Cartesian3[]} cartesians An array of Cartesian positions.
* @param {Cartographic[]} [result] The object onto which to store the result.
* @returns {Cartographic[]} The modified result parameter or a new Array instance if none was provided.
*
* @example
* //Create an array of Cartesians and determine their Cartographic representation on a WGS84 ellipsoid.
* const positions = [new Cesium.Cartesian3(17832.12, 83234.52, 952313.73),
* new Cesium.Cartesian3(17832.13, 83234.53, 952313.73),
* new Cesium.Cartesian3(17832.14, 83234.54, 952313.73)]
* const cartographicPositions = Cesium.Ellipsoid.WGS84.cartesianArrayToCartographicArray(positions);
*/
cartesianArrayToCartographicArray(cartesians, result) {
Check_default.defined("cartesians", cartesians);
const length2 = cartesians.length;
if (!defined_default(result)) {
result = new Array(length2);
} else {
result.length = length2;
}
for (let i = 0; i < length2; ++i) {
result[i] = this.cartesianToCartographic(cartesians[i], result[i]);
}
return result;
}
/**
* Scales the provided Cartesian position along the geodetic surface normal
* so that it is on the surface of this ellipsoid. If the position is
* at the center of the ellipsoid, this function returns undefined.
*
* @param {Cartesian3} cartesian The Cartesian position to scale.
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter, a new Cartesian3 instance if none was provided, or undefined if the position is at the center.
*/
scaleToGeodeticSurface(cartesian11, result) {
return scaleToGeodeticSurface_default(
cartesian11,
this._oneOverRadii,
this._oneOverRadiiSquared,
this._centerToleranceSquared,
result
);
}
/**
* Scales the provided Cartesian position along the geocentric surface normal
* so that it is on the surface of this ellipsoid.
*
* @param {Cartesian3} cartesian The Cartesian position to scale.
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
*/
scaleToGeocentricSurface(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);
}
/**
* Transforms a Cartesian X, Y, Z position to the ellipsoid-scaled space by multiplying
* its components by the result of {@link Ellipsoid#oneOverRadii}.
*
* @param {Cartesian3} position The position to transform.
* @param {Cartesian3} [result] The position to which to copy the result, or undefined to create and
* return a new instance.
* @returns {Cartesian3} The position expressed in the scaled space. The returned instance is the
* one passed as the result parameter if it is not undefined, or a new instance of it is.
*/
transformPositionToScaledSpace(position, result) {
if (!defined_default(result)) {
result = new Cartesian3_default();
}
return Cartesian3_default.multiplyComponents(position, this._oneOverRadii, result);
}
/**
* Transforms a Cartesian X, Y, Z position from the ellipsoid-scaled space by multiplying
* its components by the result of {@link Ellipsoid#radii}.
*
* @param {Cartesian3} position The position to transform.
* @param {Cartesian3} [result] The position to which to copy the result, or undefined to create and
* return a new instance.
* @returns {Cartesian3} The position expressed in the unscaled space. The returned instance is the
* one passed as the result parameter if it is not undefined, or a new instance of it is.
*/
transformPositionFromScaledSpace(position, result) {
if (!defined_default(result)) {
result = new Cartesian3_default();
}
return Cartesian3_default.multiplyComponents(position, this._radii, result);
}
/**
* Compares this Ellipsoid against the provided Ellipsoid componentwise and returns
* true if they are equal, false otherwise.
*
* @param {Ellipsoid} [right] The other Ellipsoid.
* @returns {boolean} true if they are equal, false otherwise.
*/
equals(right) {
return this === right || defined_default(right) && Cartesian3_default.equals(this._radii, right._radii);
}
/**
* Creates a string representing this Ellipsoid in the format '(radii.x, radii.y, radii.z)'.
*
* @returns {string} A string representing this ellipsoid in the format '(radii.x, radii.y, radii.z)'.
*/
toString() {
return this._radii.toString();
}
/**
* Computes a point which is the intersection of the surface normal with the z-axis.
*
* @param {Cartesian3} position the position. must be on the surface of the ellipsoid.
* @param {number} [buffer = 0.0] A buffer to subtract from the ellipsoid size when checking if the point is inside the ellipsoid.
* In earth case, with common earth datums, there is no need for this buffer since the intersection point is always (relatively) very close to the center.
* In WGS84 datum, intersection point is at max z = +-42841.31151331382 (0.673% of z-axis).
* Intersection point could be outside the ellipsoid if the ratio of MajorAxis / AxisOfRotation is bigger than the square root of 2
* @param {Cartesian3} [result] The cartesian to which to copy the result, or undefined to create and
* return a new instance.
* @returns {Cartesian3 | undefined} the intersection point if it's inside the ellipsoid, undefined otherwise
*
* @exception {DeveloperError} position is required.
* @exception {DeveloperError} Ellipsoid must be an ellipsoid of revolution (radii.x == radii.y).
* @exception {DeveloperError} Ellipsoid.radii.z must be greater than 0.
*/
getSurfaceNormalIntersectionWithZAxis(position, buffer2, 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);
buffer2 = buffer2 ?? 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 - buffer2) {
return void 0;
}
return result;
}
/**
* Computes the ellipsoid curvatures at a given position on the surface.
*
* @param {Cartesian3} surfacePosition The position on the ellipsoid surface where curvatures will be calculated.
* @param {Cartesian2} [result] The cartesian to which to copy the result, or undefined to create and return a new instance.
* @returns {Cartesian2} The local curvature of the ellipsoid surface at the provided position, in east and north directions.
*
* @exception {DeveloperError} position is required.
*/
getLocalCurvature(surfacePosition, result) {
Check_default.typeOf.object("surfacePosition", surfacePosition);
if (!defined_default(result)) {
result = new Cartesian2_default();
}
const primeVerticalEndpoint = this.getSurfaceNormalIntersectionWithZAxis(
surfacePosition,
0,
scratchEndpoint
);
const primeVerticalRadius = Cartesian3_default.distance(
surfacePosition,
primeVerticalEndpoint
);
const radiusRatio = this.minimumRadius * primeVerticalRadius / this.maximumRadius ** 2;
const meridionalRadius = primeVerticalRadius * radiusRatio ** 2;
return Cartesian2_default.fromElements(
1 / primeVerticalRadius,
1 / meridionalRadius,
result
);
}
/**
* Computes an approximation of the surface area of a rectangle on the surface of an ellipsoid using
* Gauss-Legendre 10th order quadrature.
*
* @param {Rectangle} rectangle The rectangle used for computing the surface area.
* @returns {number} The approximate area of the rectangle on the surface of this ellipsoid.
*/
surfaceArea(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
);
});
});
}
};
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.MARS = Object.freeze(new Ellipsoid(3396190, 3396190, 3376200));
Ellipsoid._default = Ellipsoid.WGS84;
Ellipsoid.packedLength = Cartesian3_default.packedLength;
Ellipsoid.prototype.geocentricSurfaceNormal = Cartesian3_default.normalize;
var cartographicToCartesianNormal = new Cartesian3_default();
var cartographicToCartesianK = new Cartesian3_default();
var cartesianToCartographicN2 = new Cartesian3_default();
var cartesianToCartographicP2 = new Cartesian3_default();
var cartesianToCartographicH2 = new Cartesian3_default();
var scratchEndpoint = new Cartesian3_default();
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;
}
var Ellipsoid_default = Ellipsoid;
// packages/engine/Source/Core/GeographicProjection.js
var GeographicProjection = class {
/**
* @param {Ellipsoid} [ellipsoid=Ellipsoid.default] The ellipsoid.
*/
constructor(ellipsoid) {
this._ellipsoid = ellipsoid ?? Ellipsoid_default.default;
this._semimajorAxis = this._ellipsoid.maximumRadius;
this._oneOverSemimajorAxis = 1 / this._semimajorAxis;
}
/**
* Gets the {@link Ellipsoid}.
*
* @type {Ellipsoid}
* @readonly
*/
get ellipsoid() {
return this._ellipsoid;
}
/**
* Projects a set of {@link Cartographic} coordinates, in radians, to map coordinates, in meters.
* X and Y are the longitude and latitude, respectively, multiplied by the maximum radius of the
* ellipsoid. Z is the unmodified height.
*
* @param {Cartographic} cartographic The coordinates to project.
* @param {Cartesian3} [result] An instance into which to copy the result. If this parameter is
* undefined, a new instance is created and returned.
* @returns {Cartesian3} The projected coordinates. If the result parameter is not undefined, the
* coordinates are copied there and that instance is returned. Otherwise, a new instance is
* created and returned.
*/
project(cartographic2, result) {
const semimajorAxis = this._semimajorAxis;
const x = cartographic2.longitude * semimajorAxis;
const y = cartographic2.latitude * semimajorAxis;
const z2 = cartographic2.height;
if (!defined_default(result)) {
return new Cartesian3_default(x, y, z2);
}
result.x = x;
result.y = y;
result.z = z2;
return result;
}
/**
* Unprojects a set of projected {@link Cartesian3} coordinates, in meters, to {@link Cartographic}
* coordinates, in radians. Longitude and Latitude are the X and Y coordinates, respectively,
* divided by the maximum radius of the ellipsoid. Height is the unmodified Z coordinate.
*
* @param {Cartesian3} cartesian The Cartesian position to unproject with height (z) in meters.
* @param {Cartographic} [result] An instance into which to copy the result. If this parameter is
* undefined, a new instance is created and returned.
* @returns {Cartographic} The unprojected coordinates. If the result parameter is not undefined, the
* coordinates are copied there and that instance is returned. Otherwise, a new instance is
* created and returned.
*/
unproject(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
};
Object.freeze(Intersect);
var Intersect_default = Intersect;
// 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/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/GregorianDate.js
var daysInYear = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
function GregorianDate(year, month, day, hour, minute, second, millisecond, isLeapSecond) {
const minimumYear = 1;
const minimumMonth = 1;
const minimumDay = 1;
const minimumHour = 0;
const minimumMinute = 0;
const minimumSecond = 0;
const minimumMillisecond = 0;
year = year ?? minimumYear;
month = month ?? minimumMonth;
day = day ?? minimumDay;
hour = hour ?? minimumHour;
minute = minute ?? minimumMinute;
second = second ?? minimumSecond;
millisecond = millisecond ?? minimumMillisecond;
isLeapSecond = isLeapSecond ?? false;
validateRange();
validateDate();
this.year = year;
this.month = month;
this.day = day;
this.hour = hour;
this.minute = minute;
this.second = second;
this.millisecond = millisecond;
this.isLeapSecond = isLeapSecond;
function validateRange() {
const maximumYear = 9999;
const maximumMonth = 12;
const maximumDay = 31;
const maximumHour = 23;
const maximumMinute = 59;
const maximumSecond = 59;
const excludedMaximumMilisecond = 1e3;
Check_default.typeOf.number.greaterThanOrEquals("Year", year, minimumYear);
Check_default.typeOf.number.lessThanOrEquals("Year", year, maximumYear);
Check_default.typeOf.number.greaterThanOrEquals("Month", month, minimumMonth);
Check_default.typeOf.number.lessThanOrEquals("Month", month, maximumMonth);
Check_default.typeOf.number.greaterThanOrEquals("Day", day, minimumDay);
Check_default.typeOf.number.lessThanOrEquals("Day", day, maximumDay);
Check_default.typeOf.number.greaterThanOrEquals("Hour", hour, minimumHour);
Check_default.typeOf.number.lessThanOrEquals("Hour", hour, maximumHour);
Check_default.typeOf.number.greaterThanOrEquals("Minute", minute, minimumMinute);
Check_default.typeOf.number.lessThanOrEquals("Minute", minute, maximumMinute);
Check_default.typeOf.bool("IsLeapSecond", isLeapSecond);
Check_default.typeOf.number.greaterThanOrEquals("Second", second, minimumSecond);
Check_default.typeOf.number.lessThanOrEquals(
"Second",
second,
isLeapSecond ? maximumSecond + 1 : maximumSecond
);
Check_default.typeOf.number.greaterThanOrEquals(
"Millisecond",
millisecond,
minimumMillisecond
);
Check_default.typeOf.number.lessThan(
"Millisecond",
millisecond,
excludedMaximumMilisecond
);
}
function validateDate() {
const daysInMonth2 = month === 2 && isLeapYear_default(year) ? daysInYear[month - 1] + 1 : daysInYear[month - 1];
if (day > daysInMonth2) {
throw new DeveloperError_default("Month and Day represents invalid date");
}
}
}
var GregorianDate_default = GregorianDate;
// packages/engine/Source/Core/LeapSecond.js
function LeapSecond(date, offset) {
this.julianDate = date;
this.offset = offset;
}
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
};
Object.freeze(TimeConstants);
var TimeConstants_default = 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
};
Object.freeze(TimeStandard);
var TimeStandard_default = 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 daysInLeapFebruary = 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 offset = leapSeconds[index].offset;
if (index > 0) {
const difference = JulianDate.secondsDifference(
leapSeconds[index].julianDate,
julianDate
);
if (difference > offset) {
index--;
offset = leapSeconds[index].offset;
}
}
JulianDate.addSeconds(julianDate, offset, 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 - 1].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.";
var JulianDate = class _JulianDate {
/**
* @param {number} [julianDayNumber=0.0] The Julian Day Number representing the number of whole days. Fractional days will also be handled correctly.
* @param {number} [secondsOfDay=0.0] The number of seconds into the current Julian Day Number. Fractional seconds, negative seconds and seconds greater than a day will be handled correctly.
* @param {TimeStandard} [timeStandard=TimeStandard.UTC] The time standard in which the first two parameters are defined.
*/
constructor(julianDayNumber, secondsOfDay, timeStandard) {
this.dayNumber = void 0;
this.secondsOfDay = void 0;
julianDayNumber = julianDayNumber ?? 0;
secondsOfDay = secondsOfDay ?? 0;
timeStandard = 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);
}
}
/**
* Creates a new instance from a GregorianDate.
*
* @param {GregorianDate} date A GregorianDate.
* @param {JulianDate} [result] An existing instance to use for the result.
* @returns {JulianDate} The modified result parameter or a new instance if none was provided.
*
* @exception {DeveloperError} date must be a valid GregorianDate.
*/
static fromGregorianDate(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;
}
/**
* Creates a new instance from a JavaScript Date.
*
* @param {Date} date A JavaScript Date.
* @param {JulianDate} [result] An existing instance to use for the result.
* @returns {JulianDate} The modified result parameter or a new instance if none was provided.
*
* @exception {DeveloperError} date must be a valid JavaScript Date.
*/
static fromDate(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;
}
/**
* Creates a new instance from a from an {@link http://en.wikipedia.org/wiki/ISO_8601|ISO 8601} date.
* This method is superior to Date.parse because it will handle all valid formats defined by the ISO 8601
* specification, including leap seconds and sub-millisecond times, which discarded by most JavaScript implementations.
*
* @param {string} iso8601String An ISO 8601 date.
* @param {JulianDate} [result] An existing instance to use for the result.
* @returns {JulianDate} The modified result parameter or a new instance if none was provided.
*
* @exception {DeveloperError} Invalid ISO 8601 date.
*/
static fromIso8601(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 > daysInLeapFebruary) {
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 offset = tokens[offsetIndex];
const offsetHours = +tokens[offsetIndex + 1];
const offsetMinutes = +(tokens[offsetIndex + 2] || 0);
switch (offset) {
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 ? daysInLeapFebruary : daysInMonth[month - 1];
while (day > tmp2) {
day -= tmp2;
month++;
if (month > 12) {
month -= 12;
year++;
}
tmp2 = inLeapYear && month === 2 ? daysInLeapFebruary : 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 ? daysInLeapFebruary : 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;
}
/**
* Creates a new instance that represents the current system time.
* This is equivalent to calling JulianDate.fromDate(new Date());.
*
* @param {JulianDate} [result] An existing instance to use for the result.
* @returns {JulianDate} The modified result parameter or a new instance if none was provided.
*/
static now(result) {
return _JulianDate.fromDate(/* @__PURE__ */ new Date(), result);
}
/**
* Creates a {@link GregorianDate} from the provided instance.
*
* @param {JulianDate} julianDate The date to be converted.
* @param {GregorianDate} [result] An existing instance to use for the result.
* @returns {GregorianDate} The modified result parameter or a new instance if none was provided.
*/
static toGregorianDate(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 J2 = 80 * L / 2447 | 0;
const day = L - (2447 * J2 / 80 | 0) | 0;
L = J2 / 11 | 0;
const month = J2 + 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;
}
/**
* Creates a JavaScript Date from the provided instance.
* Since JavaScript dates are only accurate to the nearest millisecond and
* cannot represent a leap second, consider using {@link JulianDate.toGregorianDate} instead.
* If the provided JulianDate is during a leap second, the previous second is used.
*
* @param {JulianDate} julianDate The date to be converted.
* @returns {Date} A new instance representing the provided date.
*/
static toDate(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
)
);
}
/**
* Creates an ISO8601 representation of the provided date.
*
* @param {JulianDate} julianDate The date to be converted.
* @param {number} [precision] The number of fractional digits used to represent the seconds component. By default, the most precise representation is used.
* @returns {string} The ISO8601 representation of the provided date.
*/
static toIso8601(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) {
const millisecondHundreds = millisecond * 0.01;
millisecondStr = millisecondHundreds < 1e-6 ? millisecondHundreds.toFixed(20).replace(".", "").replace(/0+$/, "") : millisecondHundreds.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`;
}
/**
* Duplicates a JulianDate instance.
*
* @param {JulianDate} julianDate The date to duplicate.
* @param {JulianDate} [result] An existing instance to use for the result.
* @returns {JulianDate} The modified result parameter or a new instance if none was provided. Returns undefined if julianDate is undefined.
*/
static clone(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;
}
/**
* Compares two instances.
*
* @param {JulianDate} left The first instance.
* @param {JulianDate} right The second instance.
* @returns {number} A negative value if left is less than right, a positive value if left is greater than right, or zero if left and right are equal.
*/
static compare(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;
}
/**
* Compares two instances and returns true if they are equal, false otherwise.
*
* @param {JulianDate} [left] The first instance.
* @param {JulianDate} [right] The second instance.
* @returns {boolean} true if the dates are equal; otherwise, false.
*/
static equals(left, right) {
return left === right || defined_default(left) && defined_default(right) && left.dayNumber === right.dayNumber && left.secondsOfDay === right.secondsOfDay;
}
/**
* Compares two instances and returns true if they are within epsilon seconds of
* each other. That is, in order for the dates to be considered equal (and for
* this function to return true), the absolute value of the difference between them, in
* seconds, must be less than epsilon.
*
* @param {JulianDate} [left] The first instance.
* @param {JulianDate} [right] The second instance.
* @param {number} [epsilon=0] The maximum number of seconds that should separate the two instances.
* @returns {boolean} true if the two dates are within epsilon seconds of each other; otherwise false.
*/
static equalsEpsilon(left, right, epsilon) {
epsilon = epsilon ?? 0;
return left === right || defined_default(left) && defined_default(right) && Math.abs(_JulianDate.secondsDifference(left, right)) <= epsilon;
}
/**
* Computes the total number of whole and fractional days represented by the provided instance.
*
* @param {JulianDate} julianDate The date.
* @returns {number} The Julian date as single floating point number.
*/
static totalDays(julianDate) {
if (!defined_default(julianDate)) {
throw new DeveloperError_default("julianDate is required.");
}
return julianDate.dayNumber + julianDate.secondsOfDay / TimeConstants_default.SECONDS_PER_DAY;
}
/**
* Computes the difference in seconds between the provided instance.
*
* @param {JulianDate} left The first instance.
* @param {JulianDate} right The second instance.
* @returns {number} The difference, in seconds, when subtracting right from left.
*/
static secondsDifference(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);
}
/**
* Computes the difference in days between the provided instance.
*
* @param {JulianDate} left The first instance.
* @param {JulianDate} right The second instance.
* @returns {number} The difference, in days, when subtracting right from left.
*/
static daysDifference(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;
}
/**
* Computes the number of seconds the provided instance is ahead of UTC.
*
* @param {JulianDate} julianDate The date.
* @returns {number} The number of seconds the provided instance is ahead of UTC
*/
static computeTaiMinusUtc(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;
}
/**
* Adds the provided number of seconds to the provided date instance.
*
* @param {JulianDate} julianDate The date.
* @param {number} seconds The number of seconds to add or subtract.
* @param {JulianDate} result An existing instance to use for the result.
* @returns {JulianDate} The modified result parameter.
*/
static addSeconds(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
);
}
/**
* Adds the provided number of minutes to the provided date instance.
*
* @param {JulianDate} julianDate The date.
* @param {number} minutes The number of minutes to add or subtract.
* @param {JulianDate} result An existing instance to use for the result.
* @returns {JulianDate} The modified result parameter.
*/
static addMinutes(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);
}
/**
* Adds the provided number of hours to the provided date instance.
*
* @param {JulianDate} julianDate The date.
* @param {number} hours The number of hours to add or subtract.
* @param {JulianDate} result An existing instance to use for the result.
* @returns {JulianDate} The modified result parameter.
*/
static addHours(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);
}
/**
* Adds the provided number of days to the provided date instance.
*
* @param {JulianDate} julianDate The date.
* @param {number} days The number of days to add or subtract.
* @param {JulianDate} result An existing instance to use for the result.
* @returns {JulianDate} The modified result parameter.
*/
static addDays(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);
}
/**
* Compares the provided instances and returns true if left is earlier than right, false otherwise.
*
* @param {JulianDate} left The first instance.
* @param {JulianDate} right The second instance.
* @returns {boolean} true if left is earlier than right, false otherwise.
*/
static lessThan(left, right) {
return _JulianDate.compare(left, right) < 0;
}
/**
* Compares the provided instances and returns true if left is earlier than or equal to right, false otherwise.
*
* @param {JulianDate} left The first instance.
* @param {JulianDate} right The second instance.
* @returns {boolean} true if left is earlier than or equal to right, false otherwise.
*/
static lessThanOrEquals(left, right) {
return _JulianDate.compare(left, right) <= 0;
}
/**
* Compares the provided instances and returns true if left is later than right, false otherwise.
*
* @param {JulianDate} left The first instance.
* @param {JulianDate} right The second instance.
* @returns {boolean} true if left is later than right, false otherwise.
*/
static greaterThan(left, right) {
return _JulianDate.compare(left, right) > 0;
}
/**
* Compares the provided instances and returns true if left is later than or equal to right, false otherwise.
*
* @param {JulianDate} left The first instance.
* @param {JulianDate} right The second instance.
* @returns {boolean} true if left is later than or equal to right, false otherwise.
*/
static greaterThanOrEquals(left, right) {
return _JulianDate.compare(left, right) >= 0;
}
/**
* Duplicates this instance.
*
* @param {JulianDate} [result] An existing instance to use for the result.
* @returns {JulianDate} The modified result parameter or a new instance if none was provided.
*/
clone(result) {
return _JulianDate.clone(this, result);
}
/**
* Compares this and the provided instance and returns true if they are equal, false otherwise.
*
* @param {JulianDate} [right] The second instance.
* @returns {boolean} true if the dates are equal; otherwise, false.
*/
equals(right) {
return _JulianDate.equals(this, right);
}
/**
* Compares this and the provided instance and returns true if they are within epsilon seconds of
* each other. That is, in order for the dates to be considered equal (and for
* this function to return true), the absolute value of the difference between them, in
* seconds, must be less than epsilon.
*
* @param {JulianDate} [right] The second instance.
* @param {number} [epsilon=0] The maximum number of seconds that should separate the two instances.
* @returns {boolean} true if the two dates are within epsilon seconds of each other; otherwise false.
*/
equalsEpsilon(right, epsilon) {
return _JulianDate.equalsEpsilon(this, right, epsilon);
}
/**
* Creates a string representing this date in ISO8601 format.
*
* @returns {string} A string representing this date in ISO8601 format.
*/
toString() {
return _JulianDate.toIso8601(this);
}
};
var toGregorianDateScratch = new JulianDate(0, 0, TimeStandard_default.TAI);
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 = 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 = 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 = 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
};
Object.freeze(RequestState);
var RequestState_default = 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
};
Object.freeze(RequestType);
var RequestType_default = RequestType;
// packages/engine/Source/Core/Request.js
function Request(options) {
options = options ?? Frozen_default.EMPTY_OBJECT;
const throttleByServer = options.throttleByServer ?? false;
const throttle = options.throttle ?? false;
this.url = options.url;
this.requestFunction = options.requestFunction;
this.cancelFunction = options.cancelFunction;
this.priorityFunction = options.priorityFunction;
this.priority = options.priority ?? 0;
this.throttle = throttle;
this.throttleByServer = throttleByServer;
this.type = 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 = /* @__PURE__ */ new Map();
this._toRemove = /* @__PURE__ */ new Map();
this._toAdd = /* @__PURE__ */ new Map();
this._invokingListeners = false;
this._listenerCount = 0;
}
Object.defineProperties(Event.prototype, {
/**
* The number of listeners currently subscribed to the event.
* @memberof Event.prototype
* @type {number}
* @readonly
*/
numberOfListeners: {
get: function() {
return this._listenerCount;
}
}
});
Event.prototype.addEventListener = function(listener, scope) {
Check_default.typeOf.func("listener", listener);
const event = this;
const listenerMap = event._invokingListeners ? event._toAdd : event._listeners;
const added = addEventListener(this, listenerMap, listener, scope);
if (added) {
event._listenerCount++;
}
return function() {
event.removeEventListener(listener, scope);
};
};
function addEventListener(event, listenerMap, listener, scope) {
if (!listenerMap.has(listener)) {
listenerMap.set(listener, /* @__PURE__ */ new Set());
}
const scopes = listenerMap.get(listener);
if (!scopes.has(scope)) {
scopes.add(scope);
return true;
}
return false;
}
Event.prototype.removeEventListener = function(listener, scope) {
Check_default.typeOf.func("listener", listener);
const removedFromListeners = removeEventListener(
this,
this._listeners,
listener,
scope
);
const removedFromToAdd = removeEventListener(
this,
this._toAdd,
listener,
scope
);
const removed = removedFromListeners || removedFromToAdd;
if (removed) {
this._listenerCount--;
}
return removed;
};
function removeEventListener(event, listenerMap, listener, scope) {
const scopes = listenerMap.get(listener);
if (!scopes || !scopes.has(scope)) {
return false;
}
if (event._invokingListeners) {
if (!addEventListener(event, event._toRemove, listener, scope)) {
return false;
}
} else {
scopes.delete(scope);
if (scopes.size === 0) {
listenerMap.delete(listener);
}
}
return true;
}
Event.prototype.raiseEvent = function() {
this._invokingListeners = true;
for (const [listener, scopes] of this._listeners.entries()) {
if (!defined_default(listener)) {
continue;
}
for (const scope of scopes) {
listener.apply(scope, arguments);
}
}
this._invokingListeners = false;
for (const [listener, scopes] of this._toAdd.entries()) {
for (const scope of scopes) {
addEventListener(this, this._listeners, listener, scope);
}
}
this._toAdd.clear();
for (const [listener, scopes] of this._toRemove.entries()) {
for (const scope of scopes) {
removeEventListener(this, this._listeners, listener, scope);
}
}
this._toRemove.clear();
};
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(length2) {
length2 = length2 ?? this._length;
this._array.length = length2;
};
Heap.prototype.heapify = function(index) {
index = index ?? 0;
const length2 = this._length;
const comparator = this._comparator;
const array = this._array;
let candidate;
let inserting = true;
while (inserting) {
const right = 2 * (index + 1);
const left = right - 1;
if (left < length2 && comparator(array[left], array[index]) < 0) {
candidate = left;
} else {
candidate = index;
}
if (right < length2 && 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 length2 = this._length;
for (let i = Math.ceil(length2 / 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 = 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 = 18;
RequestScheduler.requestsByServer = {};
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 = desiredRequests ?? 1;
const maxRequests = 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;
deferred.promise.catch(() => {
});
request.deferred = void 0;
deferred.reject(new RuntimeError_default(`Request cancelled: "${request.url}"`));
}
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 length2 = numberOfActiveRequestsByServer[serverKey];
if (!defined_default(length2)) {
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 length2 = activeRequests.length;
for (let i = 0; i < length2; ++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 = options ?? Frozen_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 = options.request ?? new Request_default();
this.proxy = options.proxy;
this.retryCallback = options.retryCallback;
this.retryAttempts = options.retryAttempts ?? 0;
this._retryCount = 0;
const parseUrl2 = options.parseUrl ?? true;
if (parseUrl2) {
this.parseUrl(options.url, true, true);
} else {
this._url = options.url;
}
this._credits = options.credits;
}
function defaultClone(value, defaultValue) {
return defined_default(value) ? clone_default(value) : defaultValue;
}
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 = {
// 'from-image' is deprecated, new option is 'none'. However, we still need to support older browsers,
// and there's no good way to detect support for these options. For now, continue to use 'from-image'. See: https://github.com/CesiumGS/cesium/issues/12846
imageOrientation: "flipY",
// default is "from-image"
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;
}
},
/**
* Gets the credits required for attribution of an asset.
* @private
*/
credits: {
get: function() {
return this._credits;
}
}
});
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 = 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,
credits: defined_default(this.credits) ? this.credits.slice() : void 0
});
}
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 = options ?? Frozen_default.EMPTY_OBJECT;
const preferImageBitmap = options.preferImageBitmap ?? false;
const preferBlob = options.preferBlob ?? false;
const flipY = options.flipY ?? false;
const skipColorSpaceConversion = options.skipColorSpaceConversion ?? false;
checkAndResetRequest(this.request);
if (!xhrBlobSupported || this.isDataUri || this.isBlobUri || !this.hasHeaders && !preferBlob) {
return this._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 generatedBlobResource._fetchImage({
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);
});
};
Resource.prototype._fetchImage = function(options) {
const resource = this;
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 resource._fetchImage({
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 = 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 buffer2 = new ArrayBuffer(byteString.length);
const view = new Uint8Array(buffer2);
for (let i = 0; i < byteString.length; i++) {
view[i] = byteString.charCodeAt(i);
}
return buffer2;
}
function decodeDataUri(dataUriRegexResult, responseType) {
responseType = responseType ?? "";
const mimeType = dataUriRegexResult[1];
const isBase64 = !!dataUriRegexResult[2];
const data = dataUriRegexResult[3];
let buffer2;
let parser3;
switch (responseType) {
case "":
case "text":
return decodeDataUriText(isBase64, data);
case "arraybuffer":
return decodeDataUriArrayBuffer(isBase64, data);
case "blob":
buffer2 = decodeDataUriArrayBuffer(isBase64, data);
return new Blob([buffer2], {
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, headers) {
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,
headers,
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, {
// 'from-image' is deprecated, new option is 'none'. However, we still need to support older browsers,
// and there's no good way to detect support for these options. For now, continue to use 'from-image'. See: https://github.com/CesiumGS/cesium/issues/12846
imageOrientation: options.flipY ? "flipY" : "none",
premultiplyAlpha: options.premultiplyAlpha ? "premultiply" : "none",
colorSpaceConversion: options.skipColorSpaceConversion ? "none" : "default"
});
};
function loadWithHttpRequest(url2, responseType, method, data, headers, deferred, overrideMimeType) {
fetch(url2, {
method,
headers
}).then(async (response) => {
if (!response.ok) {
const responseHeaders = {};
response.headers.forEach((value, key) => {
responseHeaders[key] = value;
});
deferred.reject(
new RequestErrorEvent_default(response.status, response, responseHeaders)
);
return;
}
switch (responseType) {
case "text":
deferred.resolve(response.text());
break;
case "json":
deferred.resolve(response.json());
break;
default:
deferred.resolve(new Uint8Array(await response.arrayBuffer()).buffer);
break;
}
}).catch(() => {
deferred.reject(new RequestErrorEvent_default());
});
}
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(void 0);
} 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 = options ?? Frozen_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 = 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 = options ?? Frozen_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;
let after;
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 = heading ?? 0;
this.pitch = pitch ?? 0;
this.roll = 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;
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 (defined_default(import.meta?.url)) {
baseUrlString = getAbsoluteUri_default(".", import.meta.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, s2) {
this.x = x;
this.y = y;
this.s = s2;
}
var Iau2006XysSample_default = Iau2006XysSample;
// packages/engine/Source/Core/Iau2006XysData.js
function Iau2006XysData(options) {
options = options ?? Frozen_default.EMPTY_OBJECT;
this._xysFileUrlTemplate = Resource_default.createIfNeeded(
options.xysFileUrlTemplate
);
this._interpolationOrder = options.interpolationOrder ?? 9;
this._sampleZeroJulianEphemerisDate = options.sampleZeroJulianEphemerisDate ?? 24423965e-1;
this._sampleZeroDateTT = new JulianDate_default(
this._sampleZeroJulianEphemerisDate,
0,
TimeStandard_default.TAI
);
this._stepSizeDays = options.stepSizeDays ?? 1;
this._samplesPerXysFile = options.samplesPerXysFile ?? 1e3;
this._totalSamples = 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;
};
Iau2006XysData.prototype._updateChunkData = function(index, { samples }) {
this._chunkDownloadsInProgress[index] = void 0;
const samplesPerFile = this._samplesPerXysFile;
const startIndex = index * samplesPerFile * 3;
for (let i = 0; i < samples.length; ++i) {
this._samples[startIndex + i] = samples[i];
}
};
async function requestXysChunkJson(resource, index, xysData) {
try {
const chunk = await resource.fetchJson();
xysData._updateChunkData(index, chunk);
} catch (e) {
}
}
function requestXysChunk(xysData, chunkIndex) {
if (defined_default(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 = requestXysChunkJson(chunkUrl, chunkIndex, xysData);
xysData._chunkDownloadsInProgress[chunkIndex] = promise;
return promise;
}
var Iau2006XysData_default = Iau2006XysData;
// packages/engine/Source/Core/Quaternion.js
function Quaternion(x, y, z2, w) {
this.x = x ?? 0;
this.y = y ?? 0;
this.z = z2 ?? 0;
this.w = 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 s2 = Math.sin(halfAngle);
fromAxisAngleScratch = Cartesian3_default.normalize(axis, fromAxisAngleScratch);
const x = fromAxisAngleScratch.x * s2;
const y = fromAxisAngleScratch.y * s2;
const z2 = fromAxisAngleScratch.z * s2;
const w = Math.cos(halfAngle);
if (!defined_default(result)) {
return new Quaternion(x, y, z2, w);
}
result.x = x;
result.y = y;
result.z = z2;
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 z2;
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;
z2 = (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];
z2 = -quat[2];
}
if (!defined_default(result)) {
return new Quaternion(x, y, z2, w);
}
result.x = x;
result.y = y;
result.z = z2;
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 = 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 = 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 offset = 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[offset] = sampledQuaternionAxis.x * angle;
result[offset + 1] = sampledQuaternionAxis.y * angle;
result[offset + 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 z2 = quaternion.z * inverseMagnitude;
const w = quaternion.w * inverseMagnitude;
result.x = x;
result.y = y;
result.z = z2;
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 z2 = 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 = z2;
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 || Math.abs(w + 1) < Math_default.EPSILON6) {
result.x = 1;
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, t2, result) {
Check_default.typeOf.object("start", start);
Check_default.typeOf.object("end", end);
Check_default.typeOf.number("t", t2);
Check_default.typeOf.object("result", result);
lerpScratch4 = Quaternion.multiplyByScalar(end, t2, lerpScratch4);
result = Quaternion.multiplyByScalar(start, 1 - t2, result);
return Quaternion.add(lerpScratch4, result, result);
};
var slerpEndNegated = new Quaternion();
var slerpScaledP = new Quaternion();
var slerpScaledR = new Quaternion();
Quaternion.slerp = function(start, end, t2, result) {
Check_default.typeOf.object("start", start);
Check_default.typeOf.object("end", end);
Check_default.typeOf.number("t", t2);
Check_default.typeOf.object("result", result);
let dot2 = Quaternion.dot(start, end);
let r2 = end;
if (dot2 < 0) {
dot2 = -dot2;
r2 = slerpEndNegated = Quaternion.negate(end, slerpEndNegated);
}
if (1 - dot2 < Math_default.EPSILON6) {
return Quaternion.lerp(start, r2, t2, result);
}
const theta = Math.acos(dot2);
slerpScaledP = Quaternion.multiplyByScalar(
start,
Math.sin((1 - t2) * theta),
slerpScaledP
);
slerpScaledR = Quaternion.multiplyByScalar(
r2,
Math.sin(t2 * 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, t2, 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", t2);
Check_default.typeOf.object("result", result);
const slerp0 = Quaternion.slerp(q0, q12, t2, squadScratchQuaternion0);
const slerp1 = Quaternion.slerp(s0, s1, t2, squadScratchQuaternion1);
return Quaternion.slerp(slerp0, slerp1, 2 * t2 * (1 - t2), 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 s2 = i + 1;
const t2 = 2 * s2 + 1;
u[i] = 1 / (s2 * t2);
v[i] = s2 / t2;
}
u[7] = opmu / (8 * 17);
v[7] = opmu * 8 / 17;
Quaternion.fastSlerp = function(start, end, t2, result) {
Check_default.typeOf.object("start", start);
Check_default.typeOf.object("end", end);
Check_default.typeOf.number("t", t2);
Check_default.typeOf.object("result", result);
let x = Quaternion.dot(start, end);
let sign3;
if (x >= 0) {
sign3 = 1;
} else {
sign3 = -1;
x = -x;
}
const xm1 = x - 1;
const d = 1 - t2;
const sqrT = t2 * t2;
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 = sign3 * t2 * (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, t2, 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", t2);
Check_default.typeOf.object("result", result);
const slerp0 = Quaternion.fastSlerp(q0, q12, t2, squadScratchQuaternion0);
const slerp1 = Quaternion.fastSlerp(s0, s1, t2, squadScratchQuaternion1);
return Quaternion.fastSlerp(slerp0, slerp1, 2 * t2 * (1 - t2), 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 = 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/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 (isNaN(origin.x) || isNaN(origin.y) || isNaN(origin.z)) {
throw new DeveloperError_default("origin has a NaN component");
}
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 sign3 = Math_default.sign(origin.z);
Cartesian3_default.unpack(
degeneratePositionLocalFrame[firstAxis],
0,
scratchFirstCartesian
);
if (firstAxis !== "east" && firstAxis !== "west") {
Cartesian3_default.multiplyByScalar(
scratchFirstCartesian,
sign3,
scratchFirstCartesian
);
}
Cartesian3_default.unpack(
degeneratePositionLocalFrame[secondAxis],
0,
scratchSecondCartesian
);
if (secondAxis !== "east" && secondAxis !== "west") {
Cartesian3_default.multiplyByScalar(
scratchSecondCartesian,
sign3,
scratchSecondCartesian
);
}
Cartesian3_default.unpack(
degeneratePositionLocalFrame[thirdAxis],
0,
scratchThirdCartesian
);
if (thirdAxis !== "east" && thirdAxis !== "west") {
Cartesian3_default.multiplyByScalar(
scratchThirdCartesian,
sign3,
scratchThirdCartesian
);
}
} else {
ellipsoid = ellipsoid ?? Ellipsoid_default.default;
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 = 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 = ellipsoid ?? Ellipsoid_default.default;
fixedFrameTransform = 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.computeIcrfToCentralBodyFixedMatrix = function(date, result) {
let transformMatrix2 = Transforms.computeIcrfToFixedMatrix(date, result);
if (!defined_default(transformMatrix2)) {
transformMatrix2 = Transforms.computeTemeToPseudoFixedMatrix(date, result);
}
return transformMatrix2;
};
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 t2;
const diffDays = utcDayNumber - 2451545;
if (utcSecondsIntoDay >= 43200) {
t2 = (diffDays + 0.5) / TimeConstants_default.DAYS_PER_JULIAN_CENTURY;
} else {
t2 = (diffDays - 0.5) / TimeConstants_default.DAYS_PER_JULIAN_CENTURY;
}
const gmst0 = gmstConstant0 + t2 * (gmstConstant1 + t2 * (gmstConstant2 + t2 * 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 TdtMinusTai = 32.184;
var J2000d = 2451545;
var scratchHpr = new HeadingPitchRoll_default();
var scratchRotationMatrix = new Matrix3_default();
var dateScratch = new JulianDate_default();
Transforms.computeMoonFixedToIcrfMatrix = function(date, result) {
if (!defined_default(date)) {
throw new DeveloperError_default("date is required.");
}
if (!defined_default(result)) {
result = new Matrix3_default();
}
const secondsTT = JulianDate_default.addSeconds(date, TdtMinusTai, dateScratch);
const d = JulianDate_default.totalDays(secondsTT) - J2000d;
const e1 = Math_default.toRadians(12.112) - Math_default.toRadians(0.052992) * d;
const e2 = Math_default.toRadians(24.224) - Math_default.toRadians(0.105984) * d;
const e3 = Math_default.toRadians(227.645) + Math_default.toRadians(13.012) * d;
const e4 = Math_default.toRadians(261.105) + Math_default.toRadians(13.340716) * d;
const e5 = Math_default.toRadians(358) + Math_default.toRadians(0.9856) * d;
scratchHpr.pitch = Math_default.toRadians(270 - 90) - Math_default.toRadians(3.878) * Math.sin(e1) - Math_default.toRadians(0.12) * Math.sin(e2) + Math_default.toRadians(0.07) * Math.sin(e3) - Math_default.toRadians(0.017) * Math.sin(e4);
scratchHpr.roll = Math_default.toRadians(66.53 - 90) + Math_default.toRadians(1.543) * Math.cos(e1) + Math_default.toRadians(0.24) * Math.cos(e2) - Math_default.toRadians(0.028) * Math.cos(e3) + Math_default.toRadians(7e-3) * Math.cos(e4);
scratchHpr.heading = Math_default.toRadians(244.375 - 90) + Math_default.toRadians(13.17635831) * d + Math_default.toRadians(3.558) * Math.sin(e1) + Math_default.toRadians(0.121) * Math.sin(e2) - Math_default.toRadians(0.064) * Math.sin(e3) + Math_default.toRadians(0.016) * Math.sin(e4) + Math_default.toRadians(0.025) * Math.sin(e5);
return Matrix3_default.fromHeadingPitchRoll(
scratchHpr,
scratchRotationMatrix,
result
);
};
Transforms.computeIcrfToMoonFixedMatrix = 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.computeMoonFixedToIcrfMatrix(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, point4, result) {
result = Transforms.pointToGLWindowCoordinates(
modelViewProjectionMatrix,
viewportTransformation,
point4,
result
);
result.y = 2 * viewportTransformation[5] - result.y;
return result;
};
Transforms.pointToGLWindowCoordinates = function(modelViewProjectionMatrix, viewportTransformation, point4, 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(point4)) {
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(point4.x, point4.y, point4.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 = (ellipsoid ?? Ellipsoid_default.default).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;
};
Transforms.SWIZZLE_3D_TO_2D_MATRIX = Object.freeze(
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;
let projectedPosition2;
if (Cartesian3_default.equals(rtcCenter, Cartesian3_default.ZERO)) {
projectedPosition2 = Cartesian3_default.clone(
Cartesian3_default.ZERO,
scratchCartesian3Projection
);
} else {
const cartographic2 = ellipsoid.cartesianToCartographic(
rtcCenter,
scratchCartographic
);
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(Transforms.SWIZZLE_3D_TO_2D_MATRIX, local, result);
Matrix4_default.setTranslation(result, projectedPosition2, result);
return result;
};
Transforms.ellipsoidTo2DModelMatrix = 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(Transforms.SWIZZLE_3D_TO_2D_MATRIX, toENU, result);
Matrix4_default.multiply(translation3, result, result);
return result;
};
var Transforms_default = Transforms;
// packages/engine/Source/Core/Rectangle.js
var Rectangle = class _Rectangle {
/**
* @param {number} [west=0.0] The westernmost longitude, in radians, in the range [-Pi, Pi].
* @param {number} [south=0.0] The southernmost latitude, in radians, in the range [-Pi/2, Pi/2].
* @param {number} [east=0.0] The easternmost longitude, in radians, in the range [-Pi, Pi].
* @param {number} [north=0.0] The northernmost latitude, in radians, in the range [-Pi/2, Pi/2].
*/
constructor(west, south, east, north) {
this.west = west ?? 0;
this.south = south ?? 0;
this.east = east ?? 0;
this.north = north ?? 0;
}
/**
* Gets the width of the rectangle in radians.
* @type {number}
* @readonly
*/
get width() {
return _Rectangle.computeWidth(this);
}
/**
* Gets the height of the rectangle in radians.
* @type {number}
* @readonly
*/
get height() {
return _Rectangle.computeHeight(this);
}
/**
* Stores the provided instance into the provided array.
*
* @param {Rectangle} value The value to pack.
* @param {number[]} array The array to pack into.
* @param {number} [startingIndex=0] The index into the array at which to start packing the elements.
*
* @returns {number[]} The array that was packed into
*/
static pack(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
Check_default.defined("array", array);
startingIndex = startingIndex ?? 0;
array[startingIndex++] = value.west;
array[startingIndex++] = value.south;
array[startingIndex++] = value.east;
array[startingIndex] = value.north;
return array;
}
/**
* Retrieves an instance from a packed array.
*
* @param {number[]} array The packed array.
* @param {number} [startingIndex=0] The starting index of the element to be unpacked.
* @param {Rectangle} [result] The object into which to store the result.
* @returns {Rectangle} The modified result parameter or a new Rectangle instance if one was not provided.
*/
static unpack(array, startingIndex, result) {
Check_default.defined("array", array);
startingIndex = 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;
}
/**
* Computes the width of a rectangle in radians.
* @param {Rectangle} rectangle The rectangle to compute the width of.
* @returns {number} The width.
*/
static computeWidth(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;
}
/**
* Computes the height of a rectangle in radians.
* @param {Rectangle} rectangle The rectangle to compute the height of.
* @returns {number} The height.
*/
static computeHeight(rectangle) {
Check_default.typeOf.object("rectangle", rectangle);
return rectangle.north - rectangle.south;
}
/**
* Creates a rectangle given the boundary longitude and latitude in degrees.
*
* @param {number} [west=0.0] The westernmost longitude in degrees in the range [-180.0, 180.0].
* @param {number} [south=0.0] The southernmost latitude in degrees in the range [-90.0, 90.0].
* @param {number} [east=0.0] The easternmost longitude in degrees in the range [-180.0, 180.0].
* @param {number} [north=0.0] The northernmost latitude in degrees in the range [-90.0, 90.0].
* @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
* @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
*
* @example
* const rectangle = Cesium.Rectangle.fromDegrees(0.0, 20.0, 10.0, 30.0);
*/
static fromDegrees(west, south, east, north, result) {
west = Math_default.toRadians(west ?? 0);
south = Math_default.toRadians(south ?? 0);
east = Math_default.toRadians(east ?? 0);
north = Math_default.toRadians(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;
}
/**
* Creates a rectangle given the boundary longitude and latitude in radians.
*
* @param {number} [west=0.0] The westernmost longitude in radians in the range [-Math.PI, Math.PI].
* @param {number} [south=0.0] The southernmost latitude in radians in the range [-Math.PI/2, Math.PI/2].
* @param {number} [east=0.0] The easternmost longitude in radians in the range [-Math.PI, Math.PI].
* @param {number} [north=0.0] The northernmost latitude in radians in the range [-Math.PI/2, Math.PI/2].
* @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
* @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
*
* @example
* const rectangle = Cesium.Rectangle.fromRadians(0.0, Math.PI/4, Math.PI/8, 3*Math.PI/4);
*/
static fromRadians(west, south, east, north, result) {
if (!defined_default(result)) {
return new _Rectangle(west, south, east, north);
}
result.west = west ?? 0;
result.south = south ?? 0;
result.east = east ?? 0;
result.north = north ?? 0;
return result;
}
/**
* Creates the smallest possible Rectangle that encloses all positions in the provided array.
*
* @param {Cartographic[]} cartographics The list of Cartographic instances.
* @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
* @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
*/
static fromCartographicArray(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;
}
/**
* Creates the smallest possible Rectangle that encloses all positions in the provided array.
*
* @param {Cartesian3[]} cartesians The list of Cartesian instances.
* @param {Ellipsoid} [ellipsoid=Ellipsoid.default] The ellipsoid the cartesians are on.
* @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
* @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
*/
static fromCartesianArray(cartesians, ellipsoid, result) {
Check_default.defined("cartesians", cartesians);
ellipsoid = ellipsoid ?? Ellipsoid_default.default;
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;
}
/**
* Create a rectangle from a bounding sphere, ignoring height.
*
*
* @param {BoundingSphere} boundingSphere The bounding sphere.
* @param {Ellipsoid} [ellipsoid=Ellipsoid.default] The ellipsoid.
* @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
* @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
*/
static fromBoundingSphere(boundingSphere, ellipsoid, result) {
Check_default.typeOf.object("boundingSphere", boundingSphere);
const center = boundingSphere.center;
const radius = boundingSphere.radius;
if (!defined_default(ellipsoid)) {
ellipsoid = Ellipsoid_default.default;
}
if (!defined_default(result)) {
result = new _Rectangle();
}
if (Cartesian3_default.equals(center, Cartesian3_default.ZERO)) {
_Rectangle.clone(_Rectangle.MAX_VALUE, result);
return result;
}
const fromENU = Transforms_default.eastNorthUpToFixedFrame(
center,
ellipsoid,
fromBoundingSphereMatrixScratch
);
const east = Matrix4_default.multiplyByPointAsVector(
fromENU,
Cartesian3_default.UNIT_X,
fromBoundingSphereEastScratch
);
Cartesian3_default.normalize(east, east);
const north = Matrix4_default.multiplyByPointAsVector(
fromENU,
Cartesian3_default.UNIT_Y,
fromBoundingSphereNorthScratch
);
Cartesian3_default.normalize(north, north);
Cartesian3_default.multiplyByScalar(north, radius, north);
Cartesian3_default.multiplyByScalar(east, radius, east);
const south = Cartesian3_default.negate(north, fromBoundingSphereSouthScratch);
const west = Cartesian3_default.negate(east, fromBoundingSphereWestScratch);
const positions = fromBoundingSpherePositionsScratch;
let corner = positions[0];
Cartesian3_default.add(center, north, corner);
corner = positions[1];
Cartesian3_default.add(center, west, corner);
corner = positions[2];
Cartesian3_default.add(center, south, corner);
corner = positions[3];
Cartesian3_default.add(center, east, corner);
positions[4] = center;
return _Rectangle.fromCartesianArray(positions, ellipsoid, result);
}
/**
* Duplicates a Rectangle.
*
* @param {Rectangle} rectangle The rectangle to clone.
* @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
* @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided. (Returns undefined if rectangle is undefined)
*/
static clone(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;
}
/**
* Compares the provided Rectangles componentwise and returns
* true if they pass an absolute or relative tolerance test,
* false otherwise.
*
* @param {Rectangle} [left] The first Rectangle.
* @param {Rectangle} [right] The second Rectangle.
* @param {number} [absoluteEpsilon=0] The absolute epsilon tolerance to use for equality testing.
* @returns {boolean} true if left and right are within the provided epsilon, false otherwise.
*/
static equalsEpsilon(left, right, absoluteEpsilon) {
absoluteEpsilon = 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;
}
/**
* Duplicates this Rectangle.
*
* @param {Rectangle} [result] The object onto which to store the result.
* @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
*/
clone(result) {
return _Rectangle.clone(this, result);
}
/**
* Compares the provided Rectangle with this Rectangle componentwise and returns
* true if they are equal, false otherwise.
*
* @param {Rectangle} [other] The Rectangle to compare.
* @returns {boolean} true if the Rectangles are equal, false otherwise.
*/
equals(other) {
return _Rectangle.equals(this, other);
}
/**
* Compares the provided rectangles and returns true if they are equal,
* false otherwise.
*
* @param {Rectangle} [left] The first Rectangle.
* @param {Rectangle} [right] The second Rectangle.
* @returns {boolean} true if left and right are equal; otherwise false.
*/
static equals(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;
}
/**
* Compares the provided Rectangle with this Rectangle componentwise and returns
* true if they are within the provided epsilon,
* false otherwise.
*
* @param {Rectangle} [other] The Rectangle to compare.
* @param {number} [epsilon=0] The epsilon to use for equality testing.
* @returns {boolean} true if the Rectangles are within the provided epsilon, false otherwise.
*/
equalsEpsilon(other, epsilon) {
return _Rectangle.equalsEpsilon(this, other, epsilon);
}
/**
* Checks a Rectangle's properties and throws if they are not in valid ranges.
*
* @param {Rectangle} rectangle The rectangle to validate
*
* @exception {DeveloperError} north must be in the interval [-Pi/2, Pi/2].
* @exception {DeveloperError} south must be in the interval [-Pi/2, Pi/2].
* @exception {DeveloperError} east must be in the interval [-Pi, Pi].
* @exception {DeveloperError} west must be in the interval [-Pi, Pi].
* @private
*/
static _validate(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);
}
/**
* Computes the southwest corner of a rectangle.
*
* @param {Rectangle} rectangle The rectangle for which to find the corner
* @param {Cartographic} [result] The object onto which to store the result.
* @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
*/
static southwest(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;
}
/**
* Computes the northwest corner of a rectangle.
*
* @param {Rectangle} rectangle The rectangle for which to find the corner
* @param {Cartographic} [result] The object onto which to store the result.
* @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
*/
static northwest(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;
}
/**
* Computes the northeast corner of a rectangle.
*
* @param {Rectangle} rectangle The rectangle for which to find the corner
* @param {Cartographic} [result] The object onto which to store the result.
* @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
*/
static northeast(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;
}
/**
* Computes the southeast corner of a rectangle.
*
* @param {Rectangle} rectangle The rectangle for which to find the corner
* @param {Cartographic} [result] The object onto which to store the result.
* @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
*/
static southeast(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;
}
/**
* Computes the center of a rectangle.
*
* @param {Rectangle} rectangle The rectangle for which to find the center
* @param {Cartographic} [result] The object onto which to store the result.
* @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
*/
static center(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;
}
/**
* Computes the intersection of two rectangles. This function assumes that the rectangle's coordinates are
* latitude and longitude in radians and produces a correct intersection, taking into account the fact that
* the same angle can be represented with multiple values as well as the wrapping of longitude at the
* anti-meridian. For a simple intersection that ignores these factors and can be used with projected
* coordinates, see {@link Rectangle.simpleIntersection}.
*
* @param {Rectangle} rectangle On rectangle to find an intersection
* @param {Rectangle} otherRectangle Another rectangle to find an intersection
* @param {Rectangle} [result] The object onto which to store the result.
* @returns {Rectangle|undefined} The modified result parameter, a new Rectangle instance if none was provided or undefined if there is no intersection.
*/
static intersection(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;
}
let west = Math_default.negativePiToPi(
Math.max(rectangleWest, otherRectangleWest)
);
const east = Math_default.negativePiToPi(
Math.min(rectangleEast, otherRectangleEast)
);
if (west === Math_default.PI && east < Math_default.PI) {
west = -Math_default.PI;
}
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;
}
/**
* Computes a simple intersection of two rectangles. Unlike {@link Rectangle.intersection}, this function
* does not attempt to put the angular coordinates into a consistent range or to account for crossing the
* anti-meridian. As such, it can be used for rectangles where the coordinates are not simply latitude
* and longitude (i.e. projected coordinates).
*
* @param {Rectangle} rectangle On rectangle to find an intersection
* @param {Rectangle} otherRectangle Another rectangle to find an intersection
* @param {Rectangle} [result] The object onto which to store the result.
* @returns {Rectangle|undefined} The modified result parameter, a new Rectangle instance if none was provided or undefined if there is no intersection.
*/
static simpleIntersection(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;
}
/**
* Computes a rectangle that is the union of two rectangles.
*
* @param {Rectangle} rectangle A rectangle to enclose in rectangle.
* @param {Rectangle} otherRectangle A rectangle to enclose in a rectangle.
* @param {Rectangle} [result] The object onto which to store the result.
* @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
*/
static union(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;
}
/**
* Computes a rectangle by enlarging the provided rectangle until it contains the provided cartographic.
*
* @param {Rectangle} rectangle A rectangle to expand.
* @param {Cartographic} cartographic A cartographic to enclose in a rectangle.
* @param {Rectangle} [result] The object onto which to store the result.
* @returns {Rectangle} The modified result parameter or a new Rectangle instance if one was not provided.
*/
static expand(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;
}
/**
* Returns true if the cartographic is on or inside the rectangle, false otherwise.
*
* @param {Rectangle} rectangle The rectangle
* @param {Cartographic} cartographic The cartographic to test.
* @returns {boolean} true if the provided cartographic is inside the rectangle, false otherwise.
*/
static contains(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;
}
/**
* Samples a rectangle so that it includes a list of Cartesian points suitable for passing to
* {@link BoundingSphere#fromPoints}. Sampling is necessary to account
* for rectangles that cover the poles or cross the equator.
*
* @param {Rectangle} rectangle The rectangle to subsample.
* @param {Ellipsoid} [ellipsoid=Ellipsoid.default] The ellipsoid to use.
* @param {number} [surfaceHeight=0.0] The height of the rectangle above the ellipsoid.
* @param {Cartesian3[]} [result] The array of Cartesians onto which to store the result.
* @returns {Cartesian3[]} The modified result parameter or a new Array of Cartesians instances if none was provided.
*/
static subsample(rectangle, ellipsoid, surfaceHeight, result) {
Check_default.typeOf.object("rectangle", rectangle);
ellipsoid = ellipsoid ?? Ellipsoid_default.default;
surfaceHeight = surfaceHeight ?? 0;
if (!defined_default(result)) {
result = [];
}
let length2 = 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[length2] = ellipsoid.cartographicToCartesian(lla, result[length2]);
length2++;
lla.longitude = east;
result[length2] = ellipsoid.cartographicToCartesian(lla, result[length2]);
length2++;
lla.latitude = south;
result[length2] = ellipsoid.cartographicToCartesian(lla, result[length2]);
length2++;
lla.longitude = west;
result[length2] = ellipsoid.cartographicToCartesian(lla, result[length2]);
length2++;
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[length2] = ellipsoid.cartographicToCartesian(lla, result[length2]);
length2++;
}
}
if (lla.latitude === 0) {
lla.longitude = west;
result[length2] = ellipsoid.cartographicToCartesian(lla, result[length2]);
length2++;
lla.longitude = east;
result[length2] = ellipsoid.cartographicToCartesian(lla, result[length2]);
length2++;
}
result.length = length2;
return result;
}
/**
* Computes a subsection of a rectangle from normalized coordinates in the range [0.0, 1.0].
*
* @param {Rectangle} rectangle The rectangle to subsection.
* @param {number} westLerp The west interpolation factor in the range [0.0, 1.0]. Must be less than or equal to eastLerp.
* @param {number} southLerp The south interpolation factor in the range [0.0, 1.0]. Must be less than or equal to northLerp.
* @param {number} eastLerp The east interpolation factor in the range [0.0, 1.0]. Must be greater than or equal to westLerp.
* @param {number} northLerp The north interpolation factor in the range [0.0, 1.0]. Must be greater than or equal to southLerp.
* @param {Rectangle} [result] The object onto which to store the result.
* @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
*/
static subsection(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.packedLength = 4;
var fromBoundingSphereMatrixScratch = new Matrix4_default();
var fromBoundingSphereEastScratch = new Cartesian3_default();
var fromBoundingSphereNorthScratch = new Cartesian3_default();
var fromBoundingSphereWestScratch = new Cartesian3_default();
var fromBoundingSphereSouthScratch = new Cartesian3_default();
var fromBoundingSpherePositionsScratch = new Array(5);
for (let n2 = 0; n2 < fromBoundingSpherePositionsScratch.length; ++n2) {
fromBoundingSpherePositionsScratch[n2] = new Cartesian3_default();
}
var subsampleLlaScratch = new Cartographic_default();
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 = x ?? 0;
this.y = y ?? 0;
this.width = width ?? 0;
this.height = height ?? 0;
}
BoundingRectangle.packedLength = 4;
BoundingRectangle.pack = function(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
Check_default.defined("array", array);
startingIndex = 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 = 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 length2 = 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 < length2; 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;
}
defaultProjection._ellipsoid = Ellipsoid_default.default;
projection = 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, point4, result) {
Check_default.typeOf.object("rectangle", rectangle);
Check_default.typeOf.object("point", point4);
result = BoundingRectangle.clone(rectangle, result);
const width = point4.x - result.x;
const height = point4.y - result.y;
if (width > result.width) {
result.width = width;
} else if (width < 0) {
result.width -= width;
result.x = point4.x;
}
if (height > result.height) {
result.height = height;
} else if (height < 0) {
result.height -= height;
result.y = point4.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;
};
Object.freeze(PrimitiveType);
var PrimitiveType_default = 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
};
var DrawCommand = class _DrawCommand {
/**
* @param {DrawCommandOptions} [options]
*/
constructor(options = Frozen_default.EMPTY_OBJECT) {
this._boundingVolume = options.boundingVolume;
this._orientedBoundingBox = options.orientedBoundingBox;
this._modelMatrix = options.modelMatrix;
this._primitiveType = options.primitiveType ?? PrimitiveType_default.TRIANGLES;
this._vertexArray = options.vertexArray;
this._count = options.count;
this._offset = options.offset ?? 0;
this._instanceCount = 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._snapId = options.snapId;
this._pickMetadataAllowed = options.pickMetadataAllowed === true;
this._pickedMetadataInfo = void 0;
this._flags = 0;
this.cull = options.cull ?? true;
this.occlude = options.occlude ?? true;
this.executeInClosestFrustum = options.executeInClosestFrustum ?? false;
this.debugShowBoundingVolume = options.debugShowBoundingVolume ?? false;
this.castShadows = options.castShadows ?? false;
this.receiveShadows = options.receiveShadows ?? false;
this.pickOnly = options.pickOnly ?? false;
this.depthForTranslucentClassification = options.depthForTranslucentClassification ?? false;
this.dirty = true;
this.lastDirtyTime = 0;
this.derivedCommands = {};
}
/**
* 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.
*
* @type {boolean}
* @default true
*/
get cull() {
return hasFlag(this, Flags.CULL);
}
set cull(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.
*
* @type {boolean}
* @default true
*/
get occlude() {
return hasFlag(this, Flags.OCCLUDE);
}
set occlude(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.
*
* @type {boolean}
* @default false
*/
get executeInClosestFrustum() {
return hasFlag(this, Flags.EXECUTE_IN_CLOSEST_FRUSTUM);
}
set executeInClosestFrustum(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}.
*
* @type {object}
* @default undefined
*
* @see Scene#debugCommandFilter
*/
get owner() {
return this._owner;
}
set owner(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.
*
* @type {string|undefined}
* @default undefined
*/
get pickId() {
return this._pickId;
}
set pickId(value) {
if (this._pickId !== value) {
this._pickId = value;
this.dirty = true;
}
}
/**
* A GLSL string that will evaluate to the float snap payload written during
* a snapping pass (see {@link Scene#snap}). When undefined, the
* command does not render during a snapping pass.
*
* @type {string|undefined}
* @default undefined
*/
get snapId() {
return this._snapId;
}
set snapId(value) {
if (this._snapId !== value) {
this._snapId = value;
this.dirty = true;
}
}
/**
* Whether metadata picking is allowed.
*
* This is essentially only set to `true` for draw commands that are
* part of a `ModelDrawCommand`, to check whether a derived command
* for metadata picking has to be created.
*
* @type {boolean}
* @default undefined
* @private
*/
get pickMetadataAllowed() {
return this._pickMetadataAllowed;
}
/**
* Information about picked metadata.
*
* @type {PickedMetadataInfo|undefined}
* @default undefined
*/
get pickedMetadataInfo() {
return this._pickedMetadataInfo;
}
set pickedMetadataInfo(value) {
if (this._pickedMetadataInfo !== value) {
this._pickedMetadataInfo = value;
this.dirty = true;
}
}
/**
* Whether this command should be executed in the pick pass only.
*
* @type {boolean}
* @default false
*/
get pickOnly() {
return hasFlag(this, Flags.PICK_ONLY);
}
set pickOnly(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.
*
* @type {boolean}
* @default false
*/
get depthForTranslucentClassification() {
return hasFlag(this, Flags.DEPTH_FOR_TRANSLUCENT_CLASSIFICATION);
}
set depthForTranslucentClassification(value) {
if (hasFlag(this, Flags.DEPTH_FOR_TRANSLUCENT_CLASSIFICATION) !== value) {
setFlag(this, Flags.DEPTH_FOR_TRANSLUCENT_CLASSIFICATION, value);
this.dirty = true;
}
}
/**
* @param {DrawCommand} command
* @param {DrawCommand} result
* @returns {DrawCommand}
* @private
*/
static shallowClone(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._snapId = command._snapId;
result._pickMetadataAllowed = command._pickMetadataAllowed;
result._pickedMetadataInfo = command._pickedMetadataInfo;
result._flags = command._flags;
result.dirty = true;
result.lastDirtyTime = 0;
return result;
}
/**
* Executes the draw command.
*
* @param {Context} context The renderer context in which to draw.
* @param {PassState} [passState] The state for the current render pass.
*/
execute(context, passState) {
context.draw(this, passState);
}
};
function hasFlag(command, flag) {
return (command._flags & flag) === flag;
}
function setFlag(command, flag, value) {
if (value) {
command._flags |= flag;
} else {
command._flags &= ~flag;
}
}
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;
};
PixelDatatype.getTypedArrayConstructor = function(pixelDatatype) {
const sizeInBytes = PixelDatatype.sizeInBytes(pixelDatatype);
if (sizeInBytes === Uint8Array.BYTES_PER_ELEMENT) {
return Uint8Array;
} else if (sizeInBytes === Uint16Array.BYTES_PER_ELEMENT) {
return Uint16Array;
} else if (sizeInBytes === Float32Array.BYTES_PER_ELEMENT && pixelDatatype === PixelDatatype.FLOAT) {
return Float32Array;
}
return Uint32Array;
};
Object.freeze(PixelDatatype);
var PixelDatatype_default = 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 red channel as an integer.
* @type {number}
* @constant
*/
RED_INTEGER: WebGLConstants_default.RED_INTEGER,
/**
* A pixel format containing red and green channels as integers.
* @type {number}
* @constant
*/
RG_INTEGER: WebGLConstants_default.RG_INTEGER,
/**
* A pixel format containing red, green, and blue channels as integers.
* @type {number}
* @constant
*/
RGB_INTEGER: WebGLConstants_default.RGB_INTEGER,
/**
* A pixel format containing red, green, blue, and alpha channels as integers.
* @type {number}
* @constant
*/
RGBA_INTEGER: WebGLConstants_default.RGBA_INTEGER,
/**
* 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:
case PixelFormat.RGB_INTEGER:
return 3;
case PixelFormat.RGBA:
case PixelFormat.RGBA_INTEGER:
return 4;
case PixelFormat.LUMINANCE_ALPHA:
case PixelFormat.RG:
case PixelFormat.RG_INTEGER:
return 2;
case PixelFormat.ALPHA:
case PixelFormat.RED:
case PixelFormat.RED_INTEGER:
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.RED_INTEGER || pixelFormat === PixelFormat.RG_INTEGER || pixelFormat === PixelFormat.RGB_INTEGER || pixelFormat === PixelFormat.RGBA_INTEGER || 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.RED || 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.texture3DSizeInBytes = function(pixelFormat, pixelDatatype, width, height, depth) {
let componentsLength = PixelFormat.componentsLength(pixelFormat);
if (PixelDatatype_default.isPacked(pixelDatatype)) {
componentsLength = 1;
}
return componentsLength * PixelDatatype_default.sizeInBytes(pixelDatatype) * width * height * depth;
};
PixelFormat.alignmentInBytes = function(pixelFormat, pixelDatatype, width) {
const mod = PixelFormat.textureSizeInBytes(pixelFormat, pixelDatatype, width, 1) % 4;
return mod === 0 ? 4 : mod === 2 ? 2 : 1;
};
PixelFormat.createTypedArray = function(pixelFormat, pixelDatatype, width, height) {
const constructor = PixelDatatype_default.getTypedArrayConstructor(pixelDatatype);
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;
}
}
if (pixelDatatype === PixelDatatype_default.UNSIGNED_BYTE) {
switch (pixelFormat) {
case PixelFormat.RGBA:
return WebGLConstants_default.RGBA8;
case PixelFormat.RGB:
return WebGLConstants_default.RGB8;
case PixelFormat.RG:
return WebGLConstants_default.RG8;
case PixelFormat.RED:
return WebGLConstants_default.R8;
}
}
if (pixelDatatype === PixelDatatype_default.INT) {
switch (pixelFormat) {
case PixelFormat.RGBA_INTEGER:
return WebGLConstants_default.RGBA32I;
case PixelFormat.RGB_INTEGER:
return WebGLConstants_default.RGB32I;
case PixelFormat.RG_INTEGER:
return WebGLConstants_default.RG32I;
case PixelFormat.RED_INTEGER:
return WebGLConstants_default.R32I;
}
}
if (pixelDatatype === PixelDatatype_default.UNSIGNED_INT) {
switch (pixelFormat) {
case PixelFormat.RGBA_INTEGER:
return WebGLConstants_default.RGBA32UI;
case PixelFormat.RGB_INTEGER:
return WebGLConstants_default.RGB32UI;
case PixelFormat.RG_INTEGER:
return WebGLConstants_default.RG32UI;
case PixelFormat.RED_INTEGER:
return WebGLConstants_default.R32UI;
}
}
return pixelFormat;
};
Object.freeze(PixelFormat);
var PixelFormat_default = PixelFormat;
// packages/engine/Source/Renderer/ContextLimits.js
var ContextLimits = {
_maximumCombinedTextureImageUnits: 0,
_maximumCubeMapSize: 0,
_maximumFragmentUniformVectors: 0,
_maximumTextureImageUnits: 0,
_maximumRenderbufferSize: 0,
_maximumTextureSize: 0,
_maximum3DTextureSize: 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.
* If both shaders access the same texture unit, this counts as two texture units.
* The minimum in WebGL2 contexts is 32, or 8 in WebGL1 contexts.
* @memberof ContextLimits
* @type {number}
* @see {@link https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glGet.xhtml|glGet in OpenGL ES 3.0} with MAX_COMBINED_TEXTURE_IMAGE_UNITS.
* @see {@link https://registry.khronos.org/OpenGL-Refpages/es2.0/xhtml/glGet.xml|glGet in OpenGL ES 2.0} for WebGL1 contexts.
*/
maximumCombinedTextureImageUnits: {
get: function() {
return ContextLimits._maximumCombinedTextureImageUnits;
}
},
/**
* The approximate maximum cube map width and height supported by this WebGL implementation.
* The minimum in WebGL2 contexts is 2048, but most desktop and laptop implementations will support much larger sizes like 8192.
* The minimum in WebGL1 contexts is 16.
* @memberof ContextLimits
* @type {number}
* @see {@link https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glGet.xhtml|glGet in OpenGL ES 3.0} with MAX_CUBE_MAP_TEXTURE_SIZE.
* @see {@link https://registry.khronos.org/OpenGL-Refpages/es2.0/xhtml/glGet.xml|glGet in OpenGL ES 2.0} for WebGL1 contexts.
*/
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 in WebGL2 contexts is 224, or 16 in WebGL1 contexts.
* @memberof ContextLimits
* @type {number}
* @see {@link https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glGet.xhtml|glGet in OpenGL ES 3.0} with MAX_FRAGMENT_UNIFORM_VECTORS.
* @see {@link https://registry.khronos.org/OpenGL-Refpages/es2.0/xhtml/glGet.xml|glGet in OpenGL ES 2.0} for WebGL1 contexts.
*/
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 in WebGL2 contexts is 16, or 8 in WebGL1 contexts.
* @memberof ContextLimits
* @type {number}
* @see {@link https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glGet.xhtml|glGet in OpenGL ES 3.0} with MAX_TEXTURE_IMAGE_UNITS.
* @see {@link https://registry.khronos.org/OpenGL-Refpages/es2.0/xhtml/glGet.xml|glGet in OpenGL ES 2.0} for WebGL1 contexts.
*/
maximumTextureImageUnits: {
get: function() {
return ContextLimits._maximumTextureImageUnits;
}
},
/**
* The maximum renderbuffer width and height supported by this WebGL implementation.
* The minimum in WebGL2 contexts is 2048, but most desktop and laptop implementations will support much larger sizes like 8192.
* The minimum in WebGL1 contexts is 1.
* @memberof ContextLimits
* @type {number}
* @see {@link https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glGet.xhtml|glGet in OpenGL ES 3.0} with MAX_RENDERBUFFER_SIZE.
* @see {@link https://registry.khronos.org/OpenGL-Refpages/es2.0/xhtml/glGet.xml|glGet in OpenGL ES 2.0} for WebGL1 contexts.
*/
maximumRenderbufferSize: {
get: function() {
return ContextLimits._maximumRenderbufferSize;
}
},
/**
* The approximate maximum texture width and height supported by this WebGL implementation.
* The minimum in WebGL2 contexts is 2048, but most desktop and laptop implementations will support much larger sizes like 8192.
* The minimum in WebGL1 contexts is 64.
* @memberof ContextLimits
* @type {number}
* @see {@link https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glGet.xhtml|glGet in OpenGL ES 3.0} with MAX_TEXTURE_SIZE.
* @see {@link https://registry.khronos.org/OpenGL-Refpages/es2.0/xhtml/glGet.xml|glGet in OpenGL ES 2.0} for WebGL1 contexts.
*/
maximumTextureSize: {
get: function() {
return ContextLimits._maximumTextureSize;
}
},
/**
* The approximate maximum texture width, height, and depth supported by this WebGL2 implementation.
* The minimum is 256, but most desktop and laptop implementations will support much larger sizes like 2048.
* 3D textures are not supported in WebGL1 contexts.
* @memberof ContextLimits
* @type {number}
* @see {@link https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glGet.xhtml|glGet in OpenGL ES 3.0} with MAX_3D_TEXTURE_SIZE.
*/
maximum3DTextureSize: {
get: function() {
return ContextLimits._maximum3DTextureSize;
}
},
/**
* The maximum number of vec4 varying variables supported by this WebGL implementation.
* The minimum is 15 in WebGL2 contexts, or 8 in WebGL1 contexts. Matrices and arrays count as multiple vec4s.
* @memberof ContextLimits
* @type {number}
* @see {@link https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glGet.xhtml|glGet in OpenGL ES 3.0} with MAX_VARYING_VECTORS.
* @see {@link https://registry.khronos.org/OpenGL-Refpages/es2.0/xhtml/glGet.xml|glGet in OpenGL ES 2.0} for WebGL1 contexts.
*/
maximumVaryingVectors: {
get: function() {
return ContextLimits._maximumVaryingVectors;
}
},
/**
* The maximum number of vec4 vertex attributes supported by this WebGL implementation.
* The minimum is 16 in WebGL2 contexts, or 8 in WebGL1 contexts.
* @memberof ContextLimits
* @type {number}
* @see {@link https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glGet.xhtml|glGet in OpenGL ES 3.0} with MAX_VERTEX_ATTRIBS.
* @see {@link https://registry.khronos.org/OpenGL-Refpages/es2.0/xhtml/glGet.xml|glGet in OpenGL ES 2.0} for WebGL1 contexts.
*/
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 16 in WebGL2 contexts, or 0 in WebGL1 contexts.
* @memberof ContextLimits
* @type {number}
* @see {@link https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glGet.xhtml|glGet in OpenGL ES 3.0} with MAX_VERTEX_TEXTURE_IMAGE_UNITS.
* @see {@link https://registry.khronos.org/OpenGL-Refpages/es2.0/xhtml/glGet.xml|glGet in OpenGL ES 2.0} for WebGL1 contexts.
*/
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 256 in WebGL2 contexts, or 128 in WebGL1 contexts.
* @memberof ContextLimits
* @type {number}
* @see {@link https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glGet.xhtml|glGet in OpenGL ES 3.0} with MAX_VERTEX_UNIFORM_VECTORS.
* @see {@link https://registry.khronos.org/OpenGL-Refpages/es2.0/xhtml/glGet.xml|glGet in OpenGL ES 2.0} for WebGL1 contexts.
*/
maximumVertexUniformVectors: {
get: function() {
return ContextLimits._maximumVertexUniformVectors;
}
},
/**
* The minimum aliased line width, in pixels, supported by this WebGL implementation. It will be at most one.
* @see {@link https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glGet.xhtml|glGet in OpenGL ES 3.0} with ALIASED_LINE_WIDTH_RANGE.
* @memberof ContextLimits
* @type {number}
*/
minimumAliasedLineWidth: {
get: function() {
return ContextLimits._minimumAliasedLineWidth;
}
},
/**
* The maximum aliased line width, in pixels, supported by this WebGL implementation. It will be at least one.
* @see {@link https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glGet.xhtml|glGet in OpenGL ES 3.0} with ALIASED_LINE_WIDTH_RANGE.
* @memberof ContextLimits
* @type {number}
*/
maximumAliasedLineWidth: {
get: function() {
return ContextLimits._maximumAliasedLineWidth;
}
},
/**
* The minimum aliased point size, in pixels, supported by this WebGL implementation. It will be at most one.
* @see {@link https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glGet.xhtml|glGet in OpenGL ES 3.0} with ALIASED_POINT_SIZE_RANGE.
* @memberof ContextLimits
* @type {number}
*/
minimumAliasedPointSize: {
get: function() {
return ContextLimits._minimumAliasedPointSize;
}
},
/**
* The maximum aliased point size, in pixels, supported by this WebGL implementation. It will be at least one.
* @see {@link https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glGet.xhtml|glGet in OpenGL ES 3.0} with ALIASED_POINT_SIZE_RANGE.
* @memberof ContextLimits
* @type {number}
*/
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.
* @see {@link https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glGet.xhtml|glGet in OpenGL ES 3.0} with MAX_VIEWPORT_DIMS.
* @memberof ContextLimits
* @type {number}
*/
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.
* @see {@link https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glGet.xhtml|glGet in OpenGL ES 3.0} with MAX_VIEWPORT_DIMS.
* @memberof ContextLimits
* @type {number}
*/
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 = options ?? Frozen_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 = 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();
if (defined_default(options.colorTextures)) {
const textures = options.colorTextures;
const length2 = this._colorTextures.length = this._activeColorAttachments.length = textures.length;
if (length2 > maximumColorAttachments) {
throw new DeveloperError_default(
"The number of color attachments exceeds the number supported."
);
}
for (let i = 0; i < length2; ++i) {
const 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."
);
}
const 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;
const length2 = this._colorRenderbuffers.length = this._activeColorAttachments.length = renderbuffers.length;
if (length2 > maximumColorAttachments) {
throw new DeveloperError_default(
"The number of color attachments exceeds the number supported."
);
}
for (let i = 0; i < length2; ++i) {
const renderbuffer = renderbuffers[i];
const attachmentEnum = this._gl.COLOR_ATTACHMENT0 + i;
attachRenderbuffer(this, attachmentEnum, renderbuffer);
this._activeColorAttachments[i] = attachmentEnum;
this._colorRenderbuffers[i] = renderbuffer;
}
}
if (defined_default(options.depthTexture)) {
const 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)) {
const renderbuffer = options.depthRenderbuffer;
attachRenderbuffer(this, this._gl.DEPTH_ATTACHMENT, renderbuffer);
this._depthRenderbuffer = renderbuffer;
}
if (defined_default(options.stencilRenderbuffer)) {
const renderbuffer = options.stencilRenderbuffer;
attachRenderbuffer(this, this._gl.STENCIL_ATTACHMENT, renderbuffer);
this._stencilRenderbuffer = renderbuffer;
}
if (defined_default(options.depthStencilTexture)) {
const 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)) {
const renderbuffer = options.depthStencilRenderbuffer;
attachRenderbuffer(this, this._gl.DEPTH_STENCIL_ATTACHMENT, renderbuffer);
this._depthStencilRenderbuffer = renderbuffer;
}
this._unBind();
context._currentFramebuffer = void 0;
}
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) {
const textures = this._colorTextures;
for (let i = 0; i < textures.length; ++i) {
const texture = textures[i];
if (defined_default(texture)) {
texture.destroy();
}
}
const renderbuffers = this._colorRenderbuffers;
for (let i = 0; i < renderbuffers.length; ++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;
};
Object.freeze(WindingOrder);
var WindingOrder_default = 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 = renderState ?? Frozen_default.EMPTY_OBJECT;
const cull = rs.cull ?? Frozen_default.EMPTY_OBJECT;
const polygonOffset = rs.polygonOffset ?? Frozen_default.EMPTY_OBJECT;
const scissorTest = rs.scissorTest ?? Frozen_default.EMPTY_OBJECT;
const scissorTestRectangle = scissorTest.rectangle ?? Frozen_default.EMPTY_OBJECT;
const depthRange = rs.depthRange ?? Frozen_default.EMPTY_OBJECT;
const depthTest = rs.depthTest ?? Frozen_default.EMPTY_OBJECT;
const colorMask = rs.colorMask ?? Frozen_default.EMPTY_OBJECT;
const blending = rs.blending ?? Frozen_default.EMPTY_OBJECT;
const blendingColor = blending.color ?? Frozen_default.EMPTY_OBJECT;
const stencilTest = rs.stencilTest ?? Frozen_default.EMPTY_OBJECT;
const stencilTestFrontOperation = stencilTest.frontOperation ?? Frozen_default.EMPTY_OBJECT;
const stencilTestBackOperation = stencilTest.backOperation ?? Frozen_default.EMPTY_OBJECT;
const sampleCoverage = rs.sampleCoverage ?? Frozen_default.EMPTY_OBJECT;
const viewport = rs.viewport;
this.frontFace = rs.frontFace ?? WindingOrder_default.COUNTER_CLOCKWISE;
this.cull = {
enabled: cull.enabled ?? false,
face: cull.face ?? WebGLConstants_default.BACK
};
this.lineWidth = rs.lineWidth ?? 1;
this.polygonOffset = {
enabled: polygonOffset.enabled ?? false,
factor: polygonOffset.factor ?? 0,
units: polygonOffset.units ?? 0
};
this.scissorTest = {
enabled: scissorTest.enabled ?? false,
rectangle: BoundingRectangle_default.clone(scissorTestRectangle)
};
this.depthRange = {
near: depthRange.near ?? 0,
far: depthRange.far ?? 1
};
this.depthTest = {
enabled: depthTest.enabled ?? false,
func: depthTest.func ?? WebGLConstants_default.LESS
// func, because function is a JavaScript keyword
};
this.colorMask = {
red: colorMask.red ?? true,
green: colorMask.green ?? true,
blue: colorMask.blue ?? true,
alpha: colorMask.alpha ?? true
};
this.depthMask = rs.depthMask ?? true;
this.stencilMask = rs.stencilMask ?? ~0;
this.blending = {
enabled: blending.enabled ?? false,
color: new Color_default(
blendingColor.red ?? 0,
blendingColor.green ?? 0,
blendingColor.blue ?? 0,
blendingColor.alpha ?? 0
),
equationRgb: blending.equationRgb ?? WebGLConstants_default.FUNC_ADD,
equationAlpha: blending.equationAlpha ?? WebGLConstants_default.FUNC_ADD,
functionSourceRgb: blending.functionSourceRgb ?? WebGLConstants_default.ONE,
functionSourceAlpha: blending.functionSourceAlpha ?? WebGLConstants_default.ONE,
functionDestinationRgb: blending.functionDestinationRgb ?? WebGLConstants_default.ZERO,
functionDestinationAlpha: blending.functionDestinationAlpha ?? WebGLConstants_default.ZERO
};
this.stencilTest = {
enabled: stencilTest.enabled ?? false,
frontFunction: stencilTest.frontFunction ?? WebGLConstants_default.ALWAYS,
backFunction: stencilTest.backFunction ?? WebGLConstants_default.ALWAYS,
reference: stencilTest.reference ?? 0,
mask: stencilTest.mask ?? ~0,
frontOperation: {
fail: stencilTestFrontOperation.fail ?? WebGLConstants_default.KEEP,
zFail: stencilTestFrontOperation.zFail ?? WebGLConstants_default.KEEP,
zPass: stencilTestFrontOperation.zPass ?? WebGLConstants_default.KEEP
},
backOperation: {
fail: stencilTestBackOperation.fail ?? WebGLConstants_default.KEEP,
zFail: stencilTestBackOperation.zFail ?? WebGLConstants_default.KEEP,
zPass: stencilTestBackOperation.zPass ?? WebGLConstants_default.KEEP
}
};
this.sampleCoverage = {
enabled: sampleCoverage.enabled ?? false,
value: sampleCoverage.value ?? 1,
invert: 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 = 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
var Matrix2 = class _Matrix2 {
/**
* @param {number} [column0Row0=0.0] The value for column 0, row 0.
* @param {number} [column1Row0=0.0] The value for column 1, row 0.
* @param {number} [column0Row1=0.0] The value for column 0, row 1.
* @param {number} [column1Row1=0.0] The value for column 1, row 1.
*/
constructor(column0Row0, column1Row0, column0Row1, column1Row1) {
this[0] = column0Row0 ?? 0;
this[1] = column0Row1 ?? 0;
this[2] = column1Row0 ?? 0;
this[3] = column1Row1 ?? 0;
}
/**
* Stores the provided instance into the provided array.
*
* @param {Matrix2} value The value to pack.
* @param {number[]} array The array to pack into.
* @param {number} [startingIndex=0] The index into the array at which to start packing the elements.
*
* @returns {number[]} The array that was packed into
*/
static pack(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
Check_default.defined("array", array);
startingIndex = startingIndex ?? 0;
array[startingIndex++] = value[0];
array[startingIndex++] = value[1];
array[startingIndex++] = value[2];
array[startingIndex] = value[3];
return array;
}
/**
* Retrieves an instance from a packed array.
*
* @param {number[]} array The packed array.
* @param {number} [startingIndex=0] The starting index of the element to be unpacked.
* @param {Matrix2} [result] The object into which to store the result.
* @returns {Matrix2} The modified result parameter or a new Matrix2 instance if one was not provided.
*/
static unpack(array, startingIndex, result) {
Check_default.defined("array", array);
startingIndex = 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;
}
/**
* Flattens an array of Matrix2s into an array of components. The components
* are stored in column-major order.
*
* @param {Matrix2[]} array The array of matrices to pack.
* @param {number[]} [result] The array onto which to store the result. If this is a typed array, it must have array.length * 4 components, else a {@link DeveloperError} will be thrown. If it is a regular array, it will be resized to have (array.length * 4) elements.
* @returns {number[]} The packed array.
*/
static packArray(array, result) {
Check_default.defined("array", array);
const length2 = array.length;
const resultLength = length2 * 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 < length2; ++i) {
_Matrix2.pack(array[i], result, i * 4);
}
return result;
}
/**
* Unpacks an array of column-major matrix components into an array of Matrix2s.
*
* @param {number[]} array The array of components to unpack.
* @param {Matrix2[]} [result] The array onto which to store the result.
* @returns {Matrix2[]} The unpacked array.
*/
static unpackArray(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 length2 = array.length;
if (!defined_default(result)) {
result = new Array(length2 / 4);
} else {
result.length = length2 / 4;
}
for (let i = 0; i < length2; i += 4) {
const index = i / 4;
result[index] = _Matrix2.unpack(array, i, result[index]);
}
return result;
}
/**
* Duplicates a Matrix2 instance.
*
* @param {Matrix2} matrix The matrix to duplicate.
* @param {Matrix2} [result] The object onto which to store the result.
* @returns {Matrix2} The modified result parameter or a new Matrix2 instance if one was not provided. (Returns undefined if matrix is undefined)
*/
static clone(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;
}
/**
* Creates a Matrix2 instance from a column-major order array.
*
* @param {number[]} values The column-major order array.
* @param {Matrix2} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix2} The modified result parameter, or a new Matrix2 instance if one was not provided.
*/
static fromColumnMajorArray(values, result) {
Check_default.defined("values", values);
return _Matrix2.clone(values, result);
}
/**
* Creates a Matrix2 instance from a row-major order array.
* The resulting matrix will be in column-major order.
*
* @param {number[]} values The row-major order array.
* @param {Matrix2} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix2} The modified result parameter, or a new Matrix2 instance if one was not provided.
*/
static fromRowMajorArray(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;
}
/**
* Computes a Matrix2 instance representing a non-uniform scale.
*
* @param {Cartesian2} scale The x and y scale factors.
* @param {Matrix2} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix2} The modified result parameter, or a new Matrix2 instance if one was not provided.
*
* @example
* // Creates
* // [7.0, 0.0]
* // [0.0, 8.0]
* const m = Cesium.Matrix2.fromScale(new Cesium.Cartesian2(7.0, 8.0));
*/
static fromScale(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;
}
/**
* Computes a Matrix2 instance representing a uniform scale.
*
* @param {number} scale The uniform scale factor.
* @param {Matrix2} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix2} The modified result parameter, or a new Matrix2 instance if one was not provided.
*
* @example
* // Creates
* // [2.0, 0.0]
* // [0.0, 2.0]
* const m = Cesium.Matrix2.fromUniformScale(2.0);
*/
static fromUniformScale(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;
}
/**
* Creates a rotation matrix.
*
* @param {number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
* @param {Matrix2} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns {Matrix2} The modified result parameter, or a new Matrix2 instance if one was not provided.
*
* @example
* // Rotate a point 45 degrees counterclockwise.
* const p = new Cesium.Cartesian2(5, 6);
* const m = Cesium.Matrix2.fromRotation(Cesium.Math.toRadians(45.0));
* const rotated = Cesium.Matrix2.multiplyByVector(m, p, new Cesium.Cartesian2());
*/
static fromRotation(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;
}
/**
* Creates an Array from the provided Matrix2 instance.
* The array will be in column-major order.
*
* @param {Matrix2} matrix The matrix to use..
* @param {number[]} [result] The Array onto which to store the result.
* @returns {number[]} The modified Array parameter or a new Array instance if one was not provided.
*/
static toArray(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;
}
/**
* Computes the array index of the element at the provided row and column.
*
* @param {number} row The zero-based index of the row.
* @param {number} column The zero-based index of the column.
* @returns {number} The index of the element at the provided row and column.
*
* @exception {DeveloperError} row must be 0 or 1.
* @exception {DeveloperError} column must be 0 or 1.
*
* @example
* const myMatrix = new Cesium.Matrix2();
* const column1Row0Index = Cesium.Matrix2.getElementIndex(1, 0);
* const column1Row0 = myMatrix[column1Row0Index]
* myMatrix[column1Row0Index] = 10.0;
*/
static getElementIndex(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;
}
/**
* Retrieves a copy of the matrix column at the provided index as a Cartesian2 instance.
*
* @param {Matrix2} matrix The matrix to use.
* @param {number} index The zero-based index of the column to retrieve.
* @param {Cartesian2} result The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter.
*
* @exception {DeveloperError} index must be 0 or 1.
*/
static getColumn(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;
}
/**
* Computes a new matrix that replaces the specified column in the provided matrix with the provided Cartesian2 instance.
*
* @param {Matrix2} matrix The matrix to use.
* @param {number} index The zero-based index of the column to set.
* @param {Cartesian2} cartesian The Cartesian whose values will be assigned to the specified column.
* @param {Matrix2} result The object onto which to store the result.
* @returns {Matrix2} The modified result parameter.
*
* @exception {DeveloperError} index must be 0 or 1.
*/
static setColumn(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;
}
/**
* Retrieves a copy of the matrix row at the provided index as a Cartesian2 instance.
*
* @param {Matrix2} matrix The matrix to use.
* @param {number} index The zero-based index of the row to retrieve.
* @param {Cartesian2} result The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter.
*
* @exception {DeveloperError} index must be 0 or 1.
*/
static getRow(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;
}
/**
* Computes a new matrix that replaces the specified row in the provided matrix with the provided Cartesian2 instance.
*
* @param {Matrix2} matrix The matrix to use.
* @param {number} index The zero-based index of the row to set.
* @param {Cartesian2} cartesian The Cartesian whose values will be assigned to the specified row.
* @param {Matrix2} result The object onto which to store the result.
* @returns {Matrix2} The modified result parameter.
*
* @exception {DeveloperError} index must be 0 or 1.
*/
static setRow(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;
}
/**
* Computes a new matrix that replaces the scale with the provided scale.
* This assumes the matrix is an affine transformation.
*
* @param {Matrix2} matrix The matrix to use.
* @param {Cartesian2} scale The scale that replaces the scale of the provided matrix.
* @param {Matrix2} result The object onto which to store the result.
* @returns {Matrix2} The modified result parameter.
*
* @see Matrix2.setUniformScale
* @see Matrix2.fromScale
* @see Matrix2.fromUniformScale
* @see Matrix2.multiplyByScale
* @see Matrix2.multiplyByUniformScale
* @see Matrix2.getScale
*/
static setScale(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;
}
/**
* Computes a new matrix that replaces the scale with the provided uniform scale.
* This assumes the matrix is an affine transformation.
*
* @param {Matrix2} matrix The matrix to use.
* @param {number} scale The uniform scale that replaces the scale of the provided matrix.
* @param {Matrix2} result The object onto which to store the result.
* @returns {Matrix2} The modified result parameter.
*
* @see Matrix2.setScale
* @see Matrix2.fromScale
* @see Matrix2.fromUniformScale
* @see Matrix2.multiplyByScale
* @see Matrix2.multiplyByUniformScale
* @see Matrix2.getScale
*/
static setUniformScale(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;
}
/**
* Extracts the non-uniform scale assuming the matrix is an affine transformation.
*
* @param {Matrix2} matrix The matrix.
* @param {Cartesian2} result The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter.
*
* @see Matrix2.multiplyByScale
* @see Matrix2.multiplyByUniformScale
* @see Matrix2.fromScale
* @see Matrix2.fromUniformScale
* @see Matrix2.setScale
* @see Matrix2.setUniformScale
*/
static getScale(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;
}
/**
* Computes the maximum scale assuming the matrix is an affine transformation.
* The maximum scale is the maximum length of the column vectors.
*
* @param {Matrix2} matrix The matrix.
* @returns {number} The maximum scale.
*/
static getMaximumScale(matrix) {
_Matrix2.getScale(matrix, scaleScratch33);
return Cartesian2_default.maximumComponent(scaleScratch33);
}
/**
* Sets the rotation assuming the matrix is an affine transformation.
*
* @param {Matrix2} matrix The matrix.
* @param {Matrix2} rotation The rotation matrix.
* @param {Matrix2} result The object onto which to store the result.
* @returns {Matrix2} The modified result parameter.
*
* @see Matrix2.fromRotation
* @see Matrix2.getRotation
*/
static setRotation(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;
}
/**
* Extracts the rotation matrix assuming the matrix is an affine transformation.
*
* @param {Matrix2} matrix The matrix.
* @param {Matrix2} result The object onto which to store the result.
* @returns {Matrix2} The modified result parameter.
*
* @see Matrix2.setRotation
* @see Matrix2.fromRotation
*/
static getRotation(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;
}
/**
* Computes the product of two matrices.
*
* @param {Matrix2} left The first matrix.
* @param {Matrix2} right The second matrix.
* @param {Matrix2} result The object onto which to store the result.
* @returns {Matrix2} The modified result parameter.
*/
static multiply(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;
}
/**
* Computes the sum of two matrices.
*
* @param {Matrix2} left The first matrix.
* @param {Matrix2} right The second matrix.
* @param {Matrix2} result The object onto which to store the result.
* @returns {Matrix2} The modified result parameter.
*/
static add(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;
}
/**
* Computes the difference of two matrices.
*
* @param {Matrix2} left The first matrix.
* @param {Matrix2} right The second matrix.
* @param {Matrix2} result The object onto which to store the result.
* @returns {Matrix2} The modified result parameter.
*/
static subtract(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;
}
/**
* Computes the product of a matrix and a column vector.
*
* @param {Matrix2} matrix The matrix.
* @param {Cartesian2} cartesian The column.
* @param {Cartesian2} result The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter.
*/
static multiplyByVector(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;
}
/**
* Computes the product of a matrix and a scalar.
*
* @param {Matrix2} matrix The matrix.
* @param {number} scalar The number to multiply by.
* @param {Matrix2} result The object onto which to store the result.
* @returns {Matrix2} The modified result parameter.
*/
static multiplyByScalar(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;
}
/**
* Computes the product of a matrix times a (non-uniform) scale, as if the scale were a scale matrix.
*
* @param {Matrix2} matrix The matrix on the left-hand side.
* @param {Cartesian2} scale The non-uniform scale on the right-hand side.
* @param {Matrix2} result The object onto which to store the result.
* @returns {Matrix2} The modified result parameter.
*
*
* @example
* // Instead of Cesium.Matrix2.multiply(m, Cesium.Matrix2.fromScale(scale), m);
* Cesium.Matrix2.multiplyByScale(m, scale, m);
*
* @see Matrix2.multiplyByUniformScale
* @see Matrix2.fromScale
* @see Matrix2.fromUniformScale
* @see Matrix2.setScale
* @see Matrix2.setUniformScale
* @see Matrix2.getScale
*/
static multiplyByScale(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;
}
/**
* Computes the product of a matrix times a uniform scale, as if the scale were a scale matrix.
*
* @param {Matrix2} matrix The matrix on the left-hand side.
* @param {number} scale The uniform scale on the right-hand side.
* @param {Matrix2} result The object onto which to store the result.
* @returns {Matrix2} The modified result parameter.
*
* @example
* // Instead of Cesium.Matrix2.multiply(m, Cesium.Matrix2.fromUniformScale(scale), m);
* Cesium.Matrix2.multiplyByUniformScale(m, scale, m);
*
* @see Matrix2.multiplyByScale
* @see Matrix2.fromScale
* @see Matrix2.fromUniformScale
* @see Matrix2.setScale
* @see Matrix2.setUniformScale
* @see Matrix2.getScale
*/
static multiplyByUniformScale(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;
}
/**
* Creates a negated copy of the provided matrix.
*
* @param {Matrix2} matrix The matrix to negate.
* @param {Matrix2} result The object onto which to store the result.
* @returns {Matrix2} The modified result parameter.
*/
static negate(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;
}
/**
* Computes the transpose of the provided matrix.
*
* @param {Matrix2} matrix The matrix to transpose.
* @param {Matrix2} result The object onto which to store the result.
* @returns {Matrix2} The modified result parameter.
*/
static transpose(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;
}
/**
* Computes a matrix, which contains the absolute (unsigned) values of the provided matrix's elements.
*
* @param {Matrix2} matrix The matrix with signed elements.
* @param {Matrix2} result The object onto which to store the result.
* @returns {Matrix2} The modified result parameter.
*/
static abs(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;
}
/**
* Compares the provided matrices componentwise and returns
* true if they are equal, false otherwise.
*
* @param {Matrix2} [left] The first matrix.
* @param {Matrix2} [right] The second matrix.
* @returns {boolean} true if left and right are equal, false otherwise.
*/
static equals(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];
}
/**
* Compares provided matrix and array, starting from a given array offset.
*
* @param {Matrix2} matrix
* @param {number[]} array
* @param {number} offset
* @ignore
*/
static equalsArray(matrix, array, offset) {
return matrix[0] === array[offset] && matrix[1] === array[offset + 1] && matrix[2] === array[offset + 2] && matrix[3] === array[offset + 3];
}
/**
* Compares the provided matrices componentwise and returns
* true if they are within the provided epsilon,
* false otherwise.
*
* @param {Matrix2} [left] The first matrix.
* @param {Matrix2} [right] The second matrix.
* @param {number} [epsilon=0] The epsilon to use for equality testing.
* @returns {boolean} true if left and right are within the provided epsilon, false otherwise.
*/
static equalsEpsilon(left, right, epsilon) {
epsilon = 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;
}
/**
* Gets the number of items in the collection.
*
* @type {number}
*/
get length() {
return _Matrix2.packedLength;
}
/**
* Duplicates the provided Matrix2 instance.
*
* @param {Matrix2} [result] The object onto which to store the result.
* @returns {Matrix2} The modified result parameter or a new Matrix2 instance if one was not provided.
*/
clone(result) {
return _Matrix2.clone(this, result);
}
/**
* Compares this matrix to the provided matrix componentwise and returns
* true if they are equal, false otherwise.
*
* @param {Matrix2} [right] The right hand side matrix.
* @returns {boolean} true if they are equal, false otherwise.
*/
equals(right) {
return _Matrix2.equals(this, right);
}
/**
* Compares this matrix to the provided matrix componentwise and returns
* true if they are within the provided epsilon,
* false otherwise.
*
* @param {Matrix2} [right] The right hand side matrix.
* @param {number} [epsilon=0] The epsilon to use for equality testing.
* @returns {boolean} true if they are within the provided epsilon, false otherwise.
*/
equalsEpsilon(right, epsilon) {
return _Matrix2.equalsEpsilon(this, right, epsilon);
}
/**
* Creates a string representing this Matrix with each row being
* on a separate line and in the format '(column0, column1)'.
*
* @returns {string} A string representing the provided Matrix with each row being on a separate line and in the format '(column0, column1)'.
*/
toString() {
return `(${this[0]}, ${this[2]})
(${this[1]}, ${this[3]})`;
}
};
Matrix2.packedLength = 4;
Matrix2.fromArray = Matrix2.unpack;
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;
var scaleScratch13 = new Cartesian2_default();
var scaleScratch23 = new Cartesian2_default();
var scratchColumn3 = new Cartesian2_default();
var scaleScratch33 = new Cartesian2_default();
var scaleScratch43 = new Cartesian2_default();
var scaleScratch53 = new Cartesian2_default();
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_3D:
case gl.SAMPLER_CUBE:
return new UniformSampler(gl, activeUniform, uniformName, location2);
case gl.UNSIGNED_INT_SAMPLER_2D:
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}".`
);
}
}
var UniformFloat = class {
/**
* @param {WebGL2RenderingContext} gl
* @param {WebGLActiveInfo} activeUniform
* @param {string} uniformName
* @param {WebGLUniformLocation} location
*/
constructor(gl, activeUniform, uniformName, location2) {
this.name = uniformName;
this.value = void 0;
this._value = 0;
this._gl = gl;
this._location = location2;
}
set() {
if (this.value !== this._value) {
this._value = this.value;
this._gl.uniform1f(this._location, this.value);
}
}
};
var UniformFloatVec2 = class {
/**
* @param {WebGL2RenderingContext} gl
* @param {WebGLActiveInfo} activeUniform
* @param {string} uniformName
* @param {WebGLUniformLocation} location
*/
constructor(gl, activeUniform, uniformName, location2) {
this.name = uniformName;
this.value = void 0;
this._value = new Cartesian2_default();
this._gl = gl;
this._location = location2;
}
set() {
const v3 = this.value;
if (!Cartesian2_default.equals(v3, this._value)) {
Cartesian2_default.clone(v3, this._value);
this._gl.uniform2f(this._location, v3.x, v3.y);
}
}
};
var UniformFloatVec3 = class {
/**
* @param {WebGL2RenderingContext} gl
* @param {WebGLActiveInfo} activeUniform
* @param {string} uniformName
* @param {WebGLUniformLocation} location
*/
constructor(gl, activeUniform, uniformName, location2) {
this.name = uniformName;
this.value = void 0;
this._value = void 0;
this._gl = gl;
this._location = location2;
}
set() {
const v3 = this.value;
if (defined_default(v3.red)) {
if (!Color_default.equals(v3, this._value)) {
this._value = Color_default.clone(v3, this._value);
this._gl.uniform3f(this._location, v3.red, v3.green, v3.blue);
}
} else if (defined_default(v3.x)) {
if (!Cartesian3_default.equals(v3, this._value)) {
this._value = Cartesian3_default.clone(v3, this._value);
this._gl.uniform3f(this._location, v3.x, v3.y, v3.z);
}
} else {
throw new DeveloperError_default(
`Invalid vec3 value for uniform "${this.name}".`
);
}
}
};
var UniformFloatVec4 = class {
/**
* @param {WebGL2RenderingContext} gl
* @param {WebGLActiveInfo} activeUniform
* @param {string} uniformName
* @param {WebGLUniformLocation} location
*/
constructor(gl, activeUniform, uniformName, location2) {
this.name = uniformName;
this.value = void 0;
this._value = void 0;
this._gl = gl;
this._location = location2;
}
set() {
const v3 = this.value;
if (defined_default(v3.red)) {
if (!Color_default.equals(v3, this._value)) {
this._value = Color_default.clone(v3, this._value);
this._gl.uniform4f(this._location, v3.red, v3.green, v3.blue, v3.alpha);
}
} else if (defined_default(v3.x)) {
if (!Cartesian4_default.equals(v3, this._value)) {
this._value = Cartesian4_default.clone(v3, this._value);
this._gl.uniform4f(this._location, v3.x, v3.y, v3.z, v3.w);
}
} else {
throw new DeveloperError_default(
`Invalid vec4 value for uniform "${this.name}".`
);
}
}
};
var UniformSampler = class {
/**
* @param {WebGL2RenderingContext} gl
* @param {WebGLActiveInfo} activeUniform
* @param {string} uniformName
* @param {WebGLUniformLocation} location
*/
constructor(gl, activeUniform, uniformName, location2) {
this.name = uniformName;
this.value = void 0;
this._gl = gl;
this._location = location2;
this.textureUnitIndex = void 0;
}
set() {
const gl = this._gl;
gl.activeTexture(gl.TEXTURE0 + this.textureUnitIndex);
const v3 = this.value;
gl.bindTexture(v3._target, v3._texture);
}
/**
* @param {number} textureUnitIndex
* @returns {number}
*/
_setSampler(textureUnitIndex) {
this.textureUnitIndex = textureUnitIndex;
this._gl.uniform1i(this._location, textureUnitIndex);
return textureUnitIndex + 1;
}
};
var UniformInt = class {
/**
* @param {WebGL2RenderingContext} gl
* @param {WebGLActiveInfo} activeUniform
* @param {string} uniformName
* @param {WebGLUniformLocation} location
*/
constructor(gl, activeUniform, uniformName, location2) {
this.name = uniformName;
this.value = void 0;
this._value = 0;
this._gl = gl;
this._location = location2;
}
set() {
if (this.value !== this._value) {
this._value = this.value;
this._gl.uniform1i(this._location, this.value);
}
}
};
var UniformIntVec2 = class {
/**
* @param {WebGL2RenderingContext} gl
* @param {WebGLActiveInfo} activeUniform
* @param {string} uniformName
* @param {WebGLUniformLocation} location
*/
constructor(gl, activeUniform, uniformName, location2) {
this.name = uniformName;
this.value = void 0;
this._value = new Cartesian2_default();
this._gl = gl;
this._location = location2;
}
set() {
const v3 = this.value;
if (!Cartesian2_default.equals(v3, this._value)) {
Cartesian2_default.clone(v3, this._value);
this._gl.uniform2i(this._location, v3.x, v3.y);
}
}
};
var UniformIntVec3 = class {
/**
* @param {WebGL2RenderingContext} gl
* @param {WebGLActiveInfo} activeUniform
* @param {string} uniformName
* @param {WebGLUniformLocation} location
*/
constructor(gl, activeUniform, uniformName, location2) {
this.name = uniformName;
this.value = void 0;
this._value = new Cartesian3_default();
this._gl = gl;
this._location = location2;
}
set() {
const v3 = this.value;
if (!Cartesian3_default.equals(v3, this._value)) {
Cartesian3_default.clone(v3, this._value);
this._gl.uniform3i(this._location, v3.x, v3.y, v3.z);
}
}
};
var UniformIntVec4 = class {
/**
* @param {WebGL2RenderingContext} gl
* @param {WebGLActiveInfo} activeUniform
* @param {string} uniformName
* @param {WebGLUniformLocation} location
*/
constructor(gl, activeUniform, uniformName, location2) {
this.name = uniformName;
this.value = void 0;
this._value = new Cartesian4_default();
this._gl = gl;
this._location = location2;
}
set() {
const v3 = this.value;
if (!Cartesian4_default.equals(v3, this._value)) {
Cartesian4_default.clone(v3, this._value);
this._gl.uniform4i(this._location, v3.x, v3.y, v3.z, v3.w);
}
}
};
var scratchUniformArray = new Float32Array(4);
var UniformMat2 = class {
/**
* @param {WebGL2RenderingContext} gl
* @param {WebGLActiveInfo} activeUniform
* @param {string} uniformName
* @param {WebGLUniformLocation} location
*/
constructor(gl, activeUniform, uniformName, location2) {
this.name = uniformName;
this.value = void 0;
this._value = new Matrix2_default();
this._gl = gl;
this._location = location2;
}
set() {
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);
var UniformMat3 = class {
/**
* @param {WebGL2RenderingContext} gl
* @param {WebGLActiveInfo} activeUniform
* @param {string} uniformName
* @param {WebGLUniformLocation} location
*/
constructor(gl, activeUniform, uniformName, location2) {
this.name = uniformName;
this.value = void 0;
this._value = new Matrix3_default();
this._gl = gl;
this._location = location2;
}
set() {
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);
var UniformMat4 = class {
/**
* @param {WebGL2RenderingContext} gl
* @param {WebGLActiveInfo} activeUniform
* @param {string} uniformName
* @param {WebGLUniformLocation} location
*/
constructor(gl, activeUniform, uniformName, location2) {
this.name = uniformName;
this.value = void 0;
this._value = new Matrix4_default();
this._gl = gl;
this._location = location2;
}
set() {
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_3D:
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}".`
);
}
}
var UniformArrayFloat = class {
/**
* @param {WebGL2RenderingContext} gl
* @param {WebGLActiveInfo} activeUniform
* @param {string} uniformName
* @param {WebGLUniformLocation[]} locations
*/
constructor(gl, activeUniform, uniformName, locations) {
const length2 = locations.length;
this.name = uniformName;
this.value = new Array(length2);
this._value = new Float32Array(length2);
this._gl = gl;
this._location = locations[0];
}
set() {
const value = this.value;
const length2 = value.length;
const arraybuffer = this._value;
let changed = false;
for (let i = 0; i < length2; ++i) {
const v3 = value[i];
if (v3 !== arraybuffer[i]) {
arraybuffer[i] = v3;
changed = true;
}
}
if (changed) {
this._gl.uniform1fv(this._location, arraybuffer);
}
}
};
var UniformArrayFloatVec2 = class {
/**
* @param {WebGL2RenderingContext} gl
* @param {WebGLActiveInfo} activeUniform
* @param {string} uniformName
* @param {WebGLUniformLocation[]} locations
*/
constructor(gl, activeUniform, uniformName, locations) {
const length2 = locations.length;
this.name = uniformName;
this.value = new Array(length2);
this._value = new Float32Array(length2 * 2);
this._gl = gl;
this._location = locations[0];
}
set() {
const value = this.value;
const length2 = value.length;
const arraybuffer = this._value;
let changed = false;
let j = 0;
for (let i = 0; i < length2; ++i) {
const v3 = value[i];
if (!Cartesian2_default.equalsArray(v3, arraybuffer, j)) {
Cartesian2_default.pack(v3, arraybuffer, j);
changed = true;
}
j += 2;
}
if (changed) {
this._gl.uniform2fv(this._location, arraybuffer);
}
}
};
var UniformArrayFloatVec3 = class {
/**
* @param {WebGL2RenderingContext} gl
* @param {WebGLActiveInfo} activeUniform
* @param {string} uniformName
* @param {WebGLUniformLocation[]} locations
*/
constructor(gl, activeUniform, uniformName, locations) {
const length2 = locations.length;
this.name = uniformName;
this.value = new Array(length2);
this._value = new Float32Array(length2 * 3);
this._gl = gl;
this._location = locations[0];
}
set() {
const value = this.value;
const length2 = value.length;
const arraybuffer = this._value;
let changed = false;
let j = 0;
for (let i = 0; i < length2; ++i) {
const v3 = value[i];
if (defined_default(v3.red)) {
if (v3.red !== arraybuffer[j] || v3.green !== arraybuffer[j + 1] || v3.blue !== arraybuffer[j + 2]) {
arraybuffer[j] = v3.red;
arraybuffer[j + 1] = v3.green;
arraybuffer[j + 2] = v3.blue;
changed = true;
}
} else if (defined_default(v3.x)) {
if (!Cartesian3_default.equalsArray(v3, arraybuffer, j)) {
Cartesian3_default.pack(v3, arraybuffer, j);
changed = true;
}
} else {
throw new DeveloperError_default("Invalid vec3 value.");
}
j += 3;
}
if (changed) {
this._gl.uniform3fv(this._location, arraybuffer);
}
}
};
var UniformArrayFloatVec4 = class {
/**
* @param {WebGL2RenderingContext} gl
* @param {WebGLActiveInfo} activeUniform
* @param {string} uniformName
* @param {WebGLUniformLocation[]} locations
*/
constructor(gl, activeUniform, uniformName, locations) {
const length2 = locations.length;
this.name = uniformName;
this.value = new Array(length2);
this._value = new Float32Array(length2 * 4);
this._gl = gl;
this._location = locations[0];
}
set() {
const value = this.value;
const length2 = value.length;
const arraybuffer = this._value;
let changed = false;
let j = 0;
for (let i = 0; i < length2; ++i) {
const v3 = value[i];
if (defined_default(v3.red)) {
if (!Color_default.equalsArray(v3, arraybuffer, j)) {
Color_default.pack(v3, arraybuffer, j);
changed = true;
}
} else if (defined_default(v3.x)) {
if (!Cartesian4_default.equalsArray(v3, arraybuffer, j)) {
Cartesian4_default.pack(v3, arraybuffer, j);
changed = true;
}
} else {
throw new DeveloperError_default("Invalid vec4 value.");
}
j += 4;
}
if (changed) {
this._gl.uniform4fv(this._location, arraybuffer);
}
}
};
var UniformArraySampler = class {
/**
* @param {WebGL2RenderingContext} gl
* @param {WebGLActiveInfo} activeUniform
* @param {string} uniformName
* @param {WebGLUniformLocation[]} locations
*/
constructor(gl, activeUniform, uniformName, locations) {
const length2 = locations.length;
this.name = uniformName;
this.value = new Array(length2);
this._value = new Float32Array(length2);
this._gl = gl;
this._locations = locations;
this.textureUnitIndex = void 0;
}
set() {
const gl = this._gl;
const textureUnitIndex = gl.TEXTURE0 + this.textureUnitIndex;
const value = this.value;
const length2 = value.length;
for (let i = 0; i < length2; ++i) {
const v3 = value[i];
gl.activeTexture(textureUnitIndex + i);
gl.bindTexture(v3._target, v3._texture);
}
}
/**
* @param {number} textureUnitIndex
* @returns {number}
*/
_setSampler(textureUnitIndex) {
this.textureUnitIndex = textureUnitIndex;
const locations = this._locations;
const length2 = locations.length;
for (let i = 0; i < length2; ++i) {
const index = textureUnitIndex + i;
this._gl.uniform1i(locations[i], index);
}
return textureUnitIndex + length2;
}
};
var UniformArrayInt = class {
/**
* @param {WebGL2RenderingContext} gl
* @param {WebGLActiveInfo} activeUniform
* @param {string} uniformName
* @param {WebGLUniformLocation[]} locations
*/
constructor(gl, activeUniform, uniformName, locations) {
const length2 = locations.length;
this.name = uniformName;
this.value = new Array(length2);
this._value = new Int32Array(length2);
this._gl = gl;
this._location = locations[0];
}
set() {
const value = this.value;
const length2 = value.length;
const arraybuffer = this._value;
let changed = false;
for (let i = 0; i < length2; ++i) {
const v3 = value[i];
if (v3 !== arraybuffer[i]) {
arraybuffer[i] = v3;
changed = true;
}
}
if (changed) {
this._gl.uniform1iv(this._location, arraybuffer);
}
}
};
var UniformArrayIntVec2 = class {
/**
* @param {WebGL2RenderingContext} gl
* @param {WebGLActiveInfo} activeUniform
* @param {string} uniformName
* @param {WebGLUniformLocation[]} locations
*/
constructor(gl, activeUniform, uniformName, locations) {
const length2 = locations.length;
this.name = uniformName;
this.value = new Array(length2);
this._value = new Int32Array(length2 * 2);
this._gl = gl;
this._location = locations[0];
}
set() {
const value = this.value;
const length2 = value.length;
const arraybuffer = this._value;
let changed = false;
let j = 0;
for (let i = 0; i < length2; ++i) {
const v3 = value[i];
if (!Cartesian2_default.equalsArray(v3, arraybuffer, j)) {
Cartesian2_default.pack(v3, arraybuffer, j);
changed = true;
}
j += 2;
}
if (changed) {
this._gl.uniform2iv(this._location, arraybuffer);
}
}
};
var UniformArrayIntVec3 = class {
/**
* @param {WebGL2RenderingContext} gl
* @param {WebGLActiveInfo} activeUniform
* @param {string} uniformName
* @param {WebGLUniformLocation[]} locations
*/
constructor(gl, activeUniform, uniformName, locations) {
const length2 = locations.length;
this.name = uniformName;
this.value = new Array(length2);
this._value = new Int32Array(length2 * 3);
this._gl = gl;
this._location = locations[0];
}
set() {
const value = this.value;
const length2 = value.length;
const arraybuffer = this._value;
let changed = false;
let j = 0;
for (let i = 0; i < length2; ++i) {
const v3 = value[i];
if (!Cartesian3_default.equalsArray(v3, arraybuffer, j)) {
Cartesian3_default.pack(v3, arraybuffer, j);
changed = true;
}
j += 3;
}
if (changed) {
this._gl.uniform3iv(this._location, arraybuffer);
}
}
};
var UniformArrayIntVec4 = class {
/**
* @param {WebGL2RenderingContext} gl
* @param {WebGLActiveInfo} activeUniform
* @param {string} uniformName
* @param {WebGLUniformLocation[]} locations
*/
constructor(gl, activeUniform, uniformName, locations) {
const length2 = locations.length;
this.name = uniformName;
this.value = new Array(length2);
this._value = new Int32Array(length2 * 4);
this._gl = gl;
this._location = locations[0];
}
set() {
const value = this.value;
const length2 = value.length;
const arraybuffer = this._value;
let changed = false;
let j = 0;
for (let i = 0; i < length2; ++i) {
const v3 = value[i];
if (!Cartesian4_default.equalsArray(v3, arraybuffer, j)) {
Cartesian4_default.pack(v3, arraybuffer, j);
changed = true;
}
j += 4;
}
if (changed) {
this._gl.uniform4iv(this._location, arraybuffer);
}
}
};
var UniformArrayMat2 = class {
/**
* @param {WebGL2RenderingContext} gl
* @param {WebGLActiveInfo} activeUniform
* @param {string} uniformName
* @param {WebGLUniformLocation[]} locations
*/
constructor(gl, activeUniform, uniformName, locations) {
const length2 = locations.length;
this.name = uniformName;
this.value = new Array(length2);
this._value = new Float32Array(length2 * 4);
this._gl = gl;
this._location = locations[0];
}
set() {
const value = this.value;
const length2 = value.length;
const arraybuffer = this._value;
let changed = false;
let j = 0;
for (let i = 0; i < length2; ++i) {
const v3 = value[i];
if (!Matrix2_default.equalsArray(v3, arraybuffer, j)) {
Matrix2_default.pack(v3, arraybuffer, j);
changed = true;
}
j += 4;
}
if (changed) {
this._gl.uniformMatrix2fv(this._location, false, arraybuffer);
}
}
};
var UniformArrayMat3 = class {
/**
* @param {WebGL2RenderingContext} gl
* @param {WebGLActiveInfo} activeUniform
* @param {string} uniformName
* @param {WebGLUniformLocation[]} locations
*/
constructor(gl, activeUniform, uniformName, locations) {
const length2 = locations.length;
this.name = uniformName;
this.value = new Array(length2);
this._value = new Float32Array(length2 * 9);
this._gl = gl;
this._location = locations[0];
}
set() {
const value = this.value;
const length2 = value.length;
const arraybuffer = this._value;
let changed = false;
let j = 0;
for (let i = 0; i < length2; ++i) {
const v3 = value[i];
if (!Matrix3_default.equalsArray(v3, arraybuffer, j)) {
Matrix3_default.pack(v3, arraybuffer, j);
changed = true;
}
j += 9;
}
if (changed) {
this._gl.uniformMatrix3fv(this._location, false, arraybuffer);
}
}
};
var UniformArrayMat4 = class {
/**
* @param {WebGL2RenderingContext} gl
* @param {WebGLActiveInfo} activeUniform
* @param {string} uniformName
* @param {WebGLUniformLocation[]} locations
*/
constructor(gl, activeUniform, uniformName, locations) {
const length2 = locations.length;
this.name = uniformName;
this.value = new Array(length2);
this._value = new Float32Array(length2 * 16);
this._gl = gl;
this._location = locations[0];
}
set() {
const value = this.value;
const length2 = value.length;
const arraybuffer = this._value;
let changed = false;
let j = 0;
for (let i = 0; i < length2; ++i) {
const v3 = value[i];
if (!Matrix4_default.equalsArray(v3, arraybuffer, j)) {
Matrix4_default.pack(v3, 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 = options ?? Frozen_default.EMPTY_OBJECT;
Check_default.defined("options.context", options.context);
return options.context.shaderCache.getShaderProgram(options);
};
ShaderProgram.replaceCache = function(options) {
options = options ?? Frozen_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 length2 = samplerUniforms.length;
for (let i = 0; i < length2; ++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];
if (!defined_default(uniformMap2[mu.name])) {
throw new DeveloperError_default(`Unknown uniform: ${mu.name}`);
}
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;
//>>includeStart('debug', pragmas.debug);
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);
//>>includeStart('debug', pragmas.debug);
default:
throw new DeveloperError_default("componentDatatype is not a valid value.");
}
};
ComponentDatatype.createArrayBufferView = function(componentDatatype, buffer2, byteOffset, length2) {
if (!defined_default(componentDatatype)) {
throw new DeveloperError_default("componentDatatype is required.");
}
if (!defined_default(buffer2)) {
throw new DeveloperError_default("buffer is required.");
}
byteOffset = byteOffset ?? 0;
length2 = length2 ?? (buffer2.byteLength - byteOffset) / ComponentDatatype.getSizeInBytes(componentDatatype);
switch (componentDatatype) {
case ComponentDatatype.BYTE:
return new Int8Array(buffer2, byteOffset, length2);
case ComponentDatatype.UNSIGNED_BYTE:
return new Uint8Array(buffer2, byteOffset, length2);
case ComponentDatatype.SHORT:
return new Int16Array(buffer2, byteOffset, length2);
case ComponentDatatype.UNSIGNED_SHORT:
return new Uint16Array(buffer2, byteOffset, length2);
case ComponentDatatype.INT:
return new Int32Array(buffer2, byteOffset, length2);
case ComponentDatatype.UNSIGNED_INT:
return new Uint32Array(buffer2, byteOffset, length2);
case ComponentDatatype.FLOAT:
return new Float32Array(buffer2, byteOffset, length2);
case ComponentDatatype.DOUBLE:
return new Float64Array(buffer2, byteOffset, length2);
//>>includeStart('debug', pragmas.debug);
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;
//>>includeStart('debug', pragmas.debug);
default:
throw new DeveloperError_default("name is not a valid value.");
}
};
ComponentDatatype.dequantize = function(value, componentDatatype) {
switch (componentDatatype) {
case ComponentDatatype.BYTE:
return Math.max(value / 127, -1);
case ComponentDatatype.UNSIGNED_BYTE:
return value / 255;
case ComponentDatatype.SHORT:
return Math.max(value / 32767, -1);
case ComponentDatatype.UNSIGNED_SHORT:
return value / 65535;
case ComponentDatatype.INT:
return Math.max(value / 2147483647, -1);
case ComponentDatatype.UNSIGNED_INT:
return value / 4294967295;
//>>includeStart('debug', pragmas.debug);
default:
throw new DeveloperError_default(
"componentDatatype is not a valid integer type for dequantization."
);
}
};
Object.freeze(ComponentDatatype);
var ComponentDatatype_default = ComponentDatatype;
// packages/engine/Source/Core/GeometryType.js
var GeometryType = {
NONE: 0,
TRIANGLES: 1,
LINES: 2,
POLYLINES: 3
};
Object.freeze(GeometryType);
var GeometryType_default = GeometryType;
// packages/engine/Source/Core/Geometry.js
function Geometry(options) {
options = options ?? Frozen_default.EMPTY_OBJECT;
Check_default.typeOf.object("options.attributes", options.attributes);
this.attributes = options.attributes;
this.indices = options.indices;
this.primitiveType = options.primitiveType ?? PrimitiveType_default.TRIANGLES;
this.boundingSphere = options.boundingSphere;
this.geometryType = 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 = options ?? Frozen_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 = options.normalize ?? false;
this.values = options.values;
}
var GeometryAttribute_default = GeometryAttribute;
// packages/engine/Source/Core/CompressedTextureBuffer.js
function CompressedTextureBuffer(internalFormat, pixelDatatype, width, height, buffer2) {
this._format = internalFormat;
this._datatype = pixelDatatype;
this._width = width;
this._height = height;
this._buffer = buffer2;
}
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;
}
},
/**
* The compressed texture buffer. Alias for bufferView.
* @type {Uint8Array}
* @readonly
* @memberof CompressedTextureBuffer.prototype
*/
arrayBufferView: {
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 = createWorker("transferTypedArrayTest");
worker.postMessage = 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;
}
TaskProcessor._canTransferArrayBuffer = new Promise((resolve2) => {
worker.onmessage = function(event) {
const array2 = event.data.array;
const result = defined_default(array2) && array2[0] === value;
resolve2(result);
worker.terminate();
TaskProcessor._canTransferArrayBuffer = result;
};
});
}
return TaskProcessor._canTransferArrayBuffer;
}
var taskCompletedEvent = new Event_default();
function urlFromScript(script) {
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;
return URL2.createObjectURL(blob);
}
function createWorker(url2) {
const uri = new import_urijs7.default(url2);
const isUri = uri.scheme().length !== 0 && uri.fragment().length === 0;
const moduleID = url2.replace(/\.js$/, "");
const options = {};
let workerPath;
let crossOriginUrl;
if (isCrossOriginUrl_default(url2)) {
crossOriginUrl = url2;
} else if (!isUri) {
const moduleAbsoluteUrl = buildModuleUrl_default(
`${TaskProcessor._workerModulePrefix}/${moduleID}.js`
);
if (isCrossOriginUrl_default(moduleAbsoluteUrl)) {
crossOriginUrl = moduleAbsoluteUrl;
}
}
if (crossOriginUrl) {
const script = `import "${crossOriginUrl}";`;
workerPath = urlFromScript(script);
options.type = "module";
return new Worker(workerPath, options);
}
if (!isUri && typeof CESIUM_WORKERS !== "undefined") {
const script = `
importScripts("${urlFromScript(CESIUM_WORKERS)}");
CesiumWorkers["${moduleID}"]();
`;
workerPath = urlFromScript(script);
return new Worker(workerPath, options);
}
workerPath = url2;
if (!isUri) {
workerPath = buildModuleUrl_default(
`${TaskProcessor._workerModulePrefix + moduleID}.js`
);
}
if (!FeatureDetection_default.supportsEsmWebWorkers()) {
throw new RuntimeError_default(
"This browser is not supported. Please update your browser to continue."
);
}
options.type = "module";
return new Worker(workerPath, options);
}
async 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 config2;
}
config2.wasmBinaryFile = buildModuleUrl_default(wasmOptions.wasmBinaryFile);
const arrayBuffer = await Resource_default.fetchArrayBuffer({
url: config2.wasmBinaryFile
});
config2.wasmBinary = arrayBuffer;
return config2;
}
function TaskProcessor(workerPath, maximumActiveTasks) {
this._workerPath = workerPath;
this._maximumActiveTasks = maximumActiveTasks ?? Number.POSITIVE_INFINITY;
this._activeTasks = 0;
this._nextID = 0;
this._webAssemblyPromise = void 0;
}
var createOnmessageHandler = (worker, id, resolve2, reject) => {
const listener = ({ data }) => {
if (data.id !== id) {
return;
}
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;
} else if (error.name === "Error") {
error = new Error(data.error.message);
error.stack = data.error.stack;
}
taskCompletedEvent.raiseEvent(error);
reject(error);
} else {
taskCompletedEvent.raiseEvent();
resolve2(data.result);
}
worker.removeEventListener("message", listener);
};
return listener;
};
var emptyTransferableObjectArray = [];
async function runTask(processor, parameters, transferableObjects) {
const canTransfer = await Promise.resolve(canTransferArrayBuffer());
if (!defined_default(transferableObjects)) {
transferableObjects = emptyTransferableObjectArray;
} else if (!canTransfer) {
transferableObjects.length = 0;
}
const id = processor._nextID++;
const promise = new Promise((resolve2, reject) => {
processor._worker.addEventListener(
"message",
createOnmessageHandler(processor._worker, id, resolve2, reject)
);
});
processor._worker.postMessage(
{
id,
baseUrl: buildModuleUrl_default.getCesiumBaseUrl().url,
parameters,
canTransferArrayBuffer: canTransfer
},
transferableObjects
);
return promise;
}
async function scheduleTask(processor, parameters, transferableObjects) {
++processor._activeTasks;
try {
const result = await runTask(processor, parameters, transferableObjects);
--processor._activeTasks;
return result;
} catch (error) {
--processor._activeTasks;
throw error;
}
}
TaskProcessor.prototype.scheduleTask = function(parameters, transferableObjects) {
if (!defined_default(this._worker)) {
this._worker = createWorker(this._workerPath);
}
if (this._activeTasks >= this._maximumActiveTasks) {
return void 0;
}
return scheduleTask(this, parameters, transferableObjects);
};
TaskProcessor.prototype.initWebAssemblyModule = async function(webAssemblyOptions) {
if (defined_default(this._webAssemblyPromise)) {
return this._webAssemblyPromise;
}
const init = async () => {
const worker = this._worker = createWorker(this._workerPath);
const wasmConfig = await getWebAssemblyLoaderConfig(
this,
webAssemblyOptions
);
const canTransfer = await Promise.resolve(canTransferArrayBuffer());
let transferableObjects;
const binary = wasmConfig.wasmBinary;
if (defined_default(binary) && canTransfer) {
transferableObjects = [binary];
}
const promise = new Promise((resolve2, reject) => {
worker.onmessage = function({ data }) {
if (defined_default(data)) {
resolve2(data.result);
} else {
reject(new RuntimeError_default("Could not configure wasm module"));
}
};
});
worker.postMessage(
{
canTransferArrayBuffer: canTransfer,
parameters: { webAssemblyConfig: wasmConfig }
},
transferableObjects
);
return promise;
};
this._webAssemblyPromise = init();
return this._webAssemblyPromise;
};
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({
wasmBinaryFile: "ThirdParty/basis_transcoder.wasm"
}).then(function(result) {
if (result) {
return KTX2Transcoder._transcodeTaskProcessor;
}
throw new RuntimeError_default("KTX2 transcoder could not be initialized.");
});
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 bufferView = ktx2Buffer;
if (ktx2Buffer instanceof ArrayBuffer) {
bufferView = new Uint8Array(ktx2Buffer);
}
const parameters = {
supportedTargetFormats,
ktx2Buffer: bufferView
};
return taskProcessor3.scheduleTask(parameters, [bufferView.buffer]);
}).then(function(result) {
const levelsLength = result.length;
const faceKeys = Object.keys(result[0]);
for (let i = 0; i < levelsLength; i++) {
const faces2 = result[i];
for (let j = 0; j < faceKeys.length; j++) {
const face = faces2[faceKeys[j]];
faces2[faceKeys[j]] = new CompressedTextureBuffer_default(
face.internalFormat,
face.datatype,
face.width,
face.height,
face.levelBuffer
);
}
}
if (faceKeys.length === 1) {
for (let 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/Core/Interval.js
function Interval(start, stop2) {
this.start = start ?? 0;
this.stop = stop2 ?? 0;
}
var Interval_default = Interval;
// packages/engine/Source/Core/BoundingSphere.js
var BoundingSphere = class _BoundingSphere {
/**
* @param {Cartesian3} [center=Cartesian3.ZERO] The center of the bounding sphere.
* @param {number} [radius=0.0] The radius of the bounding sphere.
*/
constructor(center, radius) {
this.center = Cartesian3_default.clone(center ?? Cartesian3_default.ZERO);
this.radius = radius ?? 0;
}
/**
* Computes a tight-fitting bounding sphere enclosing a list of 3D Cartesian points.
* The bounding sphere is computed by running two algorithms, a naive algorithm and
* Ritter's algorithm. The smaller of the two spheres is used to ensure a tight fit.
*
* @param {Cartesian3[]} [positions] An array of points that the bounding sphere will enclose. Each point must have x, y, and z properties.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
*
* @see {@link http://help.agi.com/AGIComponents/html/BlogBoundingSphere.htm|Bounding Sphere computation article}
*/
static fromPoints(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 z2 = 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 (z2 < zMin.z) {
Cartesian3_default.clone(currentPos, zMin);
}
if (z2 > 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) {
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 r2 = Cartesian3_default.magnitude(
Cartesian3_default.subtract(currentPos, naiveCenter, fromPointsScratch)
);
if (r2 > naiveRadius) {
naiveRadius = r2;
}
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;
}
/**
* Computes a bounding sphere from a rectangle projected in 2D.
*
* @param {Rectangle} [rectangle] The rectangle around which to create a bounding sphere.
* @param {MapProjection} [projection=GeographicProjection] The projection used to project the rectangle into 2D.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
static fromRectangle2D(rectangle, projection, result) {
return _BoundingSphere.fromRectangleWithHeights2D(
rectangle,
projection,
0,
0,
result
);
}
/**
* Computes a bounding sphere from a rectangle projected in 2D. The bounding sphere accounts for the
* object's minimum and maximum heights over the rectangle.
*
* @param {Rectangle} [rectangle] The rectangle around which to create a bounding sphere.
* @param {MapProjection} [projection=GeographicProjection] The projection used to project the rectangle into 2D.
* @param {number} [minimumHeight=0.0] The minimum height over the rectangle.
* @param {number} [maximumHeight=0.0] The maximum height over the rectangle.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
static fromRectangleWithHeights2D(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;
}
defaultProjection2._ellipsoid = Ellipsoid_default.default;
projection = 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;
}
/**
* Computes a bounding sphere from a rectangle in 3D. The bounding sphere is created using a subsample of points
* on the ellipsoid and contained in the rectangle. It may not be accurate for all rectangles on all types of ellipsoids.
*
* @param {Rectangle} [rectangle] The valid rectangle used to create a bounding sphere.
* @param {Ellipsoid} [ellipsoid=Ellipsoid.default] The ellipsoid used to determine positions of the rectangle.
* @param {number} [surfaceHeight=0.0] The height above the surface of the ellipsoid.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
static fromRectangle3D(rectangle, ellipsoid, surfaceHeight, result) {
ellipsoid = ellipsoid ?? Ellipsoid_default.default;
surfaceHeight = 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);
}
/**
* Computes a tight-fitting bounding sphere enclosing a list of 3D points, where the points are
* stored in a flat array in X, Y, Z, order. The bounding sphere is computed by running two
* algorithms, a naive algorithm and Ritter's algorithm. The smaller of the two spheres is used to
* ensure a tight fit.
*
* @param {number[]|TypedArray} [positions] An array of points that the bounding sphere will enclose. Each point
* is formed from three elements in the array in the order X, Y, Z.
* @param {Cartesian3} [center=Cartesian3.ZERO] The position to which the positions are relative, which need not be the
* origin of the coordinate system. This is useful when the positions are to be used for
* relative-to-center (RTC) rendering.
* @param {number} [stride=3] The number of array elements per vertex. It must be at least 3, but it may
* be higher. Regardless of the value of this parameter, the X coordinate of the first position
* is at array index 0, the Y coordinate is at array index 1, and the Z coordinate is at array index
* 2. When stride is 3, the X coordinate of the next position then begins at array index 3. If
* the stride is 5, however, two array elements are skipped and the next position begins at array
* index 5.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
*
* @example
* // Compute the bounding sphere from 3 positions, each specified relative to a center.
* // In addition to the X, Y, and Z coordinates, the points array contains two additional
* // elements per point which are ignored for the purpose of computing the bounding sphere.
* const center = new Cesium.Cartesian3(1.0, 2.0, 3.0);
* const points = [1.0, 2.0, 3.0, 0.1, 0.2,
* 4.0, 5.0, 6.0, 0.1, 0.2,
* 7.0, 8.0, 9.0, 0.1, 0.2];
* const sphere = Cesium.BoundingSphere.fromVertices(points, center, 5);
*
* @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
*/
static fromVertices(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 = center ?? Cartesian3_default.ZERO;
stride = 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 z2 = positions[i + 2] + center.z;
currentPos.x = x;
currentPos.y = y;
currentPos.z = z2;
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 (z2 < zMin.z) {
Cartesian3_default.clone(currentPos, zMin);
}
if (z2 > 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) {
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 r2 = Cartesian3_default.magnitude(
Cartesian3_default.subtract(currentPos, naiveCenter, fromPointsScratch)
);
if (r2 > naiveRadius) {
naiveRadius = r2;
}
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;
}
/**
* Computes a tight-fitting bounding sphere enclosing a list of EncodedCartesian3s, where the points are
* stored in parallel flat arrays in X, Y, Z, order. The bounding sphere is computed by running two
* algorithms, a naive algorithm and Ritter's algorithm. The smaller of the two spheres is used to
* ensure a tight fit.
*
* @param {number[]} [positionsHigh] An array of high bits of the encoded cartesians that the bounding sphere will enclose. Each point
* is formed from three elements in the array in the order X, Y, Z.
* @param {number[]} [positionsLow] An array of low bits of the encoded cartesians that the bounding sphere will enclose. Each point
* is formed from three elements in the array in the order X, Y, Z.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
*
* @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
*/
static fromEncodedCartesianVertices(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 z2 = positionsHigh[i + 2] + positionsLow[i + 2];
currentPos.x = x;
currentPos.y = y;
currentPos.z = z2;
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 (z2 < zMin.z) {
Cartesian3_default.clone(currentPos, zMin);
}
if (z2 > 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) {
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 r2 = Cartesian3_default.magnitude(
Cartesian3_default.subtract(currentPos, naiveCenter, fromPointsScratch)
);
if (r2 > naiveRadius) {
naiveRadius = r2;
}
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;
}
/**
* Computes a bounding sphere from the corner points of an axis-aligned bounding box. The sphere
* tightly and fully encompasses the box.
*
* @param {Cartesian3} [corner] The minimum height over the rectangle.
* @param {Cartesian3} [oppositeCorner] The maximum height over the rectangle.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*
* @example
* // Create a bounding sphere around the unit cube
* const sphere = Cesium.BoundingSphere.fromCornerPoints(new Cesium.Cartesian3(-0.5, -0.5, -0.5), new Cesium.Cartesian3(0.5, 0.5, 0.5));
*/
static fromCornerPoints(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;
}
/**
* Creates a bounding sphere encompassing an ellipsoid.
*
* @param {Ellipsoid} ellipsoid The ellipsoid around which to create a bounding sphere.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*
* @example
* const boundingSphere = Cesium.BoundingSphere.fromEllipsoid(ellipsoid);
*/
static fromEllipsoid(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;
}
/**
* Computes a tight-fitting bounding sphere enclosing the provided array of bounding spheres.
*
* @param {BoundingSphere[]} [boundingSpheres] The array of bounding spheres.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
static fromBoundingSpheres(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 length2 = boundingSpheres.length;
if (length2 === 1) {
return _BoundingSphere.clone(boundingSpheres[0], result);
}
if (length2 === 2) {
return _BoundingSphere.union(
boundingSpheres[0],
boundingSpheres[1],
result
);
}
const positions = [];
let i;
for (i = 0; i < length2; i++) {
positions.push(boundingSpheres[i].center);
}
result = _BoundingSphere.fromPoints(positions, result);
const center = result.center;
let radius = result.radius;
for (i = 0; i < length2; i++) {
const tmp2 = boundingSpheres[i];
radius = Math.max(
radius,
Cartesian3_default.distance(center, tmp2.center) + tmp2.radius
);
}
result.radius = radius;
return result;
}
/**
* Computes a tight-fitting bounding sphere enclosing the provided oriented bounding box.
*
* @param {OrientedBoundingBox} orientedBoundingBox The oriented bounding box.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
static fromOrientedBoundingBox(orientedBoundingBox, result) {
Check_default.defined("orientedBoundingBox", orientedBoundingBox);
if (!defined_default(result)) {
result = new _BoundingSphere();
}
const halfAxes = orientedBoundingBox.halfAxes;
const u4 = Matrix3_default.getColumn(halfAxes, 0, fromOrientedBoundingBoxScratchU);
const v3 = Matrix3_default.getColumn(halfAxes, 1, fromOrientedBoundingBoxScratchV);
const w = Matrix3_default.getColumn(halfAxes, 2, fromOrientedBoundingBoxScratchW);
Cartesian3_default.add(u4, v3, u4);
Cartesian3_default.add(u4, w, u4);
result.center = Cartesian3_default.clone(orientedBoundingBox.center, result.center);
result.radius = Cartesian3_default.magnitude(u4);
return result;
}
/**
* Computes a tight-fitting bounding sphere enclosing the provided affine transformation.
*
* @param {Matrix4} transformation The affine transformation.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
static fromTransformation(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;
}
/**
* Duplicates a BoundingSphere instance.
*
* @param {BoundingSphere} sphere The bounding sphere to duplicate.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided. (Returns undefined if sphere is undefined)
*/
static clone(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;
}
/**
* Stores the provided instance into the provided array.
*
* @param {BoundingSphere} value The value to pack.
* @param {number[]} array The array to pack into.
* @param {number} [startingIndex=0] The index into the array at which to start packing the elements.
*
* @returns {number[]} The array that was packed into
*/
static pack(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
Check_default.defined("array", array);
startingIndex = startingIndex ?? 0;
const center = value.center;
array[startingIndex++] = center.x;
array[startingIndex++] = center.y;
array[startingIndex++] = center.z;
array[startingIndex] = value.radius;
return array;
}
/**
* Retrieves an instance from a packed array.
*
* @param {number[]} array The packed array.
* @param {number} [startingIndex=0] The starting index of the element to be unpacked.
* @param {BoundingSphere} [result] The object into which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
*/
static unpack(array, startingIndex, result) {
Check_default.defined("array", array);
startingIndex = 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;
}
/**
* Computes a bounding sphere that contains both the left and right bounding spheres.
*
* @param {BoundingSphere} left A sphere to enclose in a bounding sphere.
* @param {BoundingSphere} right A sphere to enclose in a bounding sphere.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
static union(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;
}
/**
* Computes a bounding sphere by enlarging the provided sphere to contain the provided point.
*
* @param {BoundingSphere} sphere A sphere to expand.
* @param {Cartesian3} point A point to enclose in a bounding sphere.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
static expand(sphere, point4, result) {
Check_default.typeOf.object("sphere", sphere);
Check_default.typeOf.object("point", point4);
result = _BoundingSphere.clone(sphere, result);
const radius = Cartesian3_default.magnitude(
Cartesian3_default.subtract(point4, result.center, expandScratch)
);
if (radius > result.radius) {
result.radius = radius;
}
return result;
}
/**
* Determines which side of a plane a sphere is located.
*
* @param {BoundingSphere} sphere The bounding sphere to test.
* @param {Plane} plane The plane to test against.
* @returns {Intersect} {@link Intersect.INSIDE} if the entire sphere is on the side of the plane
* the normal is pointing, {@link Intersect.OUTSIDE} if the entire sphere is
* on the opposite side, and {@link Intersect.INTERSECTING} if the sphere
* intersects the plane.
*/
static intersectPlane(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;
}
/**
* Applies a 4x4 affine transformation matrix to a bounding sphere.
*
* @param {BoundingSphere} sphere The bounding sphere to apply the transformation to.
* @param {Matrix4} transform The transformation matrix to apply to the bounding sphere.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
static transform(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;
}
/**
* Computes the estimated distance squared from the closest point on a bounding sphere to a point.
*
* @param {BoundingSphere} sphere The sphere.
* @param {Cartesian3} cartesian The point
* @returns {number} The distance squared from the bounding sphere to the point. Returns 0 if the point is inside the sphere.
*
* @example
* // Sort bounding spheres from back to front
* spheres.sort(function(a, b) {
* return Cesium.BoundingSphere.distanceSquaredTo(b, camera.positionWC) - Cesium.BoundingSphere.distanceSquaredTo(a, camera.positionWC);
* });
*/
static distanceSquaredTo(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;
}
/**
* Applies a 4x4 affine transformation matrix to a bounding sphere where there is no scale
* The transformation matrix is not verified to have a uniform scale of 1.
* This method is faster than computing the general bounding sphere transform using {@link BoundingSphere.transform}.
*
* @param {BoundingSphere} sphere The bounding sphere to apply the transformation to.
* @param {Matrix4} transform The transformation matrix to apply to the bounding sphere.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*
* @example
* const modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(positionOnEllipsoid);
* const boundingSphere = new Cesium.BoundingSphere();
* const newBoundingSphere = Cesium.BoundingSphere.transformWithoutScale(boundingSphere, modelMatrix);
*/
static transformWithoutScale(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;
}
/**
* The distances calculated by the vector from the center of the bounding sphere to position projected onto direction
* plus/minus the radius of the bounding sphere.
*
* If you imagine the infinite number of planes with normal direction, this computes the smallest distance to the
* closest and farthest planes from position that intersect the bounding sphere.
*
* @param {BoundingSphere} sphere The bounding sphere to calculate the distance to.
* @param {Cartesian3} position The position to calculate the distance from.
* @param {Cartesian3} direction The direction from position.
* @param {Interval} [result] A Interval to store the nearest and farthest distances.
* @returns {Interval} The nearest and farthest distances on the bounding sphere from position in direction.
*/
static computePlaneDistances(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;
}
/**
* Creates a bounding sphere in 2D from a bounding sphere in 3D world coordinates.
*
* @param {BoundingSphere} sphere The bounding sphere to transform to 2D.
* @param {MapProjection} [projection=GeographicProjection] The projection to 2D.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
static projectTo2D(sphere, projection, result) {
Check_default.typeOf.object("sphere", sphere);
projectTo2DProjection._ellipsoid = Ellipsoid_default.default;
projection = 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 length2 = positions.length;
for (let i = 0; i < length2; ++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 z2 = center.z;
center.x = z2;
center.y = x;
center.z = y;
return result;
}
/**
* Determines whether or not a sphere is hidden from view by the occluder.
*
* @param {BoundingSphere} sphere The bounding sphere surrounding the occluded object.
* @param {Occluder} occluder The occluder.
* @returns {boolean} true if the sphere is not visible; otherwise false.
*/
static isOccluded(sphere, occluder) {
Check_default.typeOf.object("sphere", sphere);
Check_default.typeOf.object("occluder", occluder);
return !occluder.isBoundingSphereVisible(sphere);
}
/**
* Compares the provided BoundingSphere componentwise and returns
* true if they are equal, false otherwise.
*
* @param {BoundingSphere} [left] The first BoundingSphere.
* @param {BoundingSphere} [right] The second BoundingSphere.
* @returns {boolean} true if left and right are equal, false otherwise.
*/
static equals(left, right) {
return left === right || defined_default(left) && defined_default(right) && Cartesian3_default.equals(left.center, right.center) && left.radius === right.radius;
}
/**
* Determines which side of a plane the sphere is located.
*
* @param {Plane} plane The plane to test against.
* @returns {Intersect} {@link Intersect.INSIDE} if the entire sphere is on the side of the plane
* the normal is pointing, {@link Intersect.OUTSIDE} if the entire sphere is
* on the opposite side, and {@link Intersect.INTERSECTING} if the sphere
* intersects the plane.
*/
intersectPlane(plane) {
return _BoundingSphere.intersectPlane(this, plane);
}
/**
* Computes the estimated distance squared from the closest point on a bounding sphere to a point.
*
* @param {Cartesian3} cartesian The point
* @returns {number} The estimated distance squared from the bounding sphere to the point.
*
* @example
* // Sort bounding spheres from back to front
* spheres.sort(function(a, b) {
* return b.distanceSquaredTo(camera.positionWC) - a.distanceSquaredTo(camera.positionWC);
* });
*/
distanceSquaredTo(cartesian11) {
return _BoundingSphere.distanceSquaredTo(this, cartesian11);
}
/**
* The distances calculated by the vector from the center of the bounding sphere to position projected onto direction
* plus/minus the radius of the bounding sphere.
*
* If you imagine the infinite number of planes with normal direction, this computes the smallest distance to the
* closest and farthest planes from position that intersect the bounding sphere.
*
* @param {Cartesian3} position The position to calculate the distance from.
* @param {Cartesian3} direction The direction from position.
* @param {Interval} [result] A Interval to store the nearest and farthest distances.
* @returns {Interval} The nearest and farthest distances on the bounding sphere from position in direction.
*/
computePlaneDistances(position, direction2, result) {
return _BoundingSphere.computePlaneDistances(
this,
position,
direction2,
result
);
}
/**
* Determines whether or not a sphere is hidden from view by the occluder.
*
* @param {Occluder} occluder The occluder.
* @returns {boolean} true if the sphere is not visible; otherwise false.
*/
isOccluded(occluder) {
return _BoundingSphere.isOccluded(this, occluder);
}
/**
* Compares this BoundingSphere against the provided BoundingSphere componentwise and returns
* true if they are equal, false otherwise.
*
* @param {BoundingSphere} [right] The right hand side BoundingSphere.
* @returns {boolean} true if they are equal, false otherwise.
*/
equals(right) {
return _BoundingSphere.equals(this, right);
}
/**
* Duplicates this BoundingSphere instance.
*
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
clone(result) {
return _BoundingSphere.clone(this, result);
}
/**
* Computes the radius of the BoundingSphere.
* @returns {number} The radius of the BoundingSphere.
*/
volume() {
const radius = this.radius;
return volumeConstant * radius * radius * radius;
}
};
BoundingSphere.packedLength = 4;
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;
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();
var fromRectangle3DScratch = (
/** @type {Cartesian3[]} */
[]
);
var fromOrientedBoundingBoxScratchU = new Cartesian3_default();
var fromOrientedBoundingBoxScratchV = new Cartesian3_default();
var fromOrientedBoundingBoxScratchW = new Cartesian3_default();
var scratchFromTransformationCenter = new Cartesian3_default();
var scratchFromTransformationScale = new Cartesian3_default();
var unionScratch = new Cartesian3_default();
var unionScratchCenter = new Cartesian3_default();
var expandScratch = new Cartesian3_default();
var distanceSquaredToScratch = new Cartesian3_default();
var scratchCartesian3 = new Cartesian3_default();
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 n2 = 0; n2 < 8; ++n2) {
projectTo2DPositionsScratch[n2] = new Cartesian3_default();
}
var projectTo2DProjection = new GeographicProjection_default();
var BoundingSphere_default = BoundingSphere;
// packages/engine/Source/Core/GeometryAttributes.js
function GeometryAttributes(options) {
options = options ?? Frozen_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
};
Object.freeze(GeometryOffsetAttribute);
var GeometryOffsetAttribute_default = GeometryOffsetAttribute;
// packages/engine/Source/Core/VertexFormat.js
function VertexFormat(options) {
options = options ?? Frozen_default.EMPTY_OBJECT;
this.position = options.position ?? false;
this.normal = options.normal ?? false;
this.st = options.st ?? false;
this.bitangent = options.bitangent ?? false;
this.tangent = options.tangent ?? false;
this.color = 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 = 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 = 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 = options ?? Frozen_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 = 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 = options ?? Frozen_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 = 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] = 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 = 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 indices;
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
});
}
indices = new Uint16Array(6 * 2 * 3);
indices[0] = 0;
indices[1] = 1;
indices[2] = 2;
indices[3] = 0;
indices[4] = 2;
indices[5] = 3;
indices[6] = 4 + 2;
indices[7] = 4 + 1;
indices[8] = 4 + 0;
indices[9] = 4 + 3;
indices[10] = 4 + 2;
indices[11] = 4 + 0;
indices[12] = 8 + 0;
indices[13] = 8 + 1;
indices[14] = 8 + 2;
indices[15] = 8 + 0;
indices[16] = 8 + 2;
indices[17] = 8 + 3;
indices[18] = 12 + 2;
indices[19] = 12 + 1;
indices[20] = 12 + 0;
indices[21] = 12 + 3;
indices[22] = 12 + 2;
indices[23] = 12 + 0;
indices[24] = 16 + 2;
indices[25] = 16 + 1;
indices[26] = 16 + 0;
indices[27] = 16 + 3;
indices[28] = 16 + 2;
indices[29] = 16 + 0;
indices[30] = 20 + 0;
indices[31] = 20 + 1;
indices[32] = 20 + 2;
indices[33] = 20 + 0;
indices[34] = 20 + 2;
indices[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
});
indices = new Uint16Array(6 * 2 * 3);
indices[0] = 4;
indices[1] = 5;
indices[2] = 6;
indices[3] = 4;
indices[4] = 6;
indices[5] = 7;
indices[6] = 1;
indices[7] = 0;
indices[8] = 3;
indices[9] = 1;
indices[10] = 3;
indices[11] = 2;
indices[12] = 1;
indices[13] = 6;
indices[14] = 5;
indices[15] = 1;
indices[16] = 2;
indices[17] = 6;
indices[18] = 2;
indices[19] = 3;
indices[20] = 7;
indices[21] = 2;
indices[22] = 7;
indices[23] = 6;
indices[24] = 3;
indices[25] = 0;
indices[26] = 4;
indices[27] = 3;
indices[28] = 4;
indices[29] = 7;
indices[30] = 0;
indices[31] = 1;
indices[32] = 5;
indices[33] = 0;
indices[34] = 5;
indices[35] = 4;
}
const diff = Cartesian3_default.subtract(max3, min3, diffScratch);
const radius = Cartesian3_default.magnitude(diff) * 0.5;
if (defined_default(boxGeometry._offsetAttribute)) {
const length2 = positions.length;
const offsetValue = boxGeometry._offsetAttribute === GeometryOffsetAttribute_default.NONE ? 0 : 1;
const applyOffset = new Uint8Array(length2 / 3).fill(offsetValue);
attributes.applyOffset = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentsPerAttribute: 1,
values: applyOffset
});
}
return new Geometry_default({
attributes,
indices,
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/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;
//>>includeStart('debug', pragmas.debug);
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;
//>>includeStart('debug', pragmas.debug);
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;
//>>includeStart('debug', pragmas.debug);
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";
//>>includeStart('debug', pragmas.debug);
default:
throw new DeveloperError_default("attributeType is not a valid value.");
}
};
Object.freeze(AttributeType);
var AttributeType_default = AttributeType;
// packages/engine/Source/Core/AttributeCompression.js
var RIGHT_SHIFT8 = 1 / 256;
var LEFT_SHIFT16 = 65536;
var LEFT_SHIFT8 = 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_SHIFT8);
result.y = forceUint8(octEncodeScratch.x);
result.z = forceUint8(octEncodeScratch.y * RIGHT_SHIFT8);
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 z2 = encoded.z;
const w = encoded.w;
if (x < 0 || x > 255 || y < 0 || y > 255 || z2 < 0 || z2 > 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_SHIFT8 + y;
const yOct16 = z2 * LEFT_SHIFT8 + 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(v12, v22, v3, result) {
Check_default.defined("v1", v12);
Check_default.defined("v2", v22);
Check_default.defined("v3", v3);
Check_default.defined("result", result);
const encoded1 = AttributeCompression.octEncodeFloat(v12);
const encoded2 = AttributeCompression.octEncodeFloat(v22);
const encoded3 = AttributeCompression.octEncode(v3, scratchEncodeCart2);
result.x = 65536 * encoded3.x + encoded1;
result.y = 65536 * encoded3.y + encoded2;
return result;
};
AttributeCompression.octUnpack = function(packed, v12, v22, v3) {
Check_default.defined("packed", packed);
Check_default.defined("v1", v12);
Check_default.defined("v2", v22);
Check_default.defined("v3", v3);
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, v12);
AttributeCompression.octDecodeFloat(encodedFloat2, v22);
AttributeCompression.octDecode(x, y, v3);
};
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 u4 = 0;
let v3 = 0;
let height = 0;
for (let i = 0; i < count; ++i) {
u4 += zigZagDecode(uBuffer[i]);
v3 += zigZagDecode(vBuffer[i]);
uBuffer[i] = u4;
vBuffer[i] = v3;
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;
//>>includeStart('debug', pragmas.debug);
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.encodeRGB8 = function(color) {
Check_default.typeOf.object("color", color);
return Math.round(Math_default.clamp(color.red * 255, 0, 255)) * LEFT_SHIFT16 + Math.round(Math_default.clamp(color.green * 255, 0, 255)) * LEFT_SHIFT8 + Math.round(Math_default.clamp(color.blue * 255, 0, 255));
};
AttributeCompression.decodeRGB8 = function(encoded, result) {
Check_default.typeOf.number("encoded", encoded);
Check_default.typeOf.object("result", result);
encoded = Math.floor(encoded);
result.red = (encoded >> 16 & 255) / 255;
result.green = (encoded >> 8 & 255) / 255;
result.blue = (encoded & 255) / 255;
return result;
};
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 offset = 3 * i;
result[offset] = red * normalize5;
result[offset + 1] = green * normalize6;
result[offset + 2] = blue * normalize5;
}
return result;
};
var AttributeCompression_default = AttributeCompression;
// packages/engine/Source/Core/barycentricCoordinates.js
var scratchCartesian1 = new Cartesian3_default();
var scratchCartesian2 = new Cartesian3_default();
var scratchCartesian32 = new Cartesian3_default();
function barycentricCoordinates(point4, p0, p1, p2, result) {
Check_default.defined("point", point4);
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 v12;
let v22;
let dot00;
let dot01;
let dot02;
let dot11;
let dot12;
if (!defined_default(p0.z)) {
if (Cartesian2_default.equalsEpsilon(point4, p0, Math_default.EPSILON14)) {
return Cartesian3_default.clone(Cartesian3_default.UNIT_X, result);
}
if (Cartesian2_default.equalsEpsilon(point4, p1, Math_default.EPSILON14)) {
return Cartesian3_default.clone(Cartesian3_default.UNIT_Y, result);
}
if (Cartesian2_default.equalsEpsilon(point4, p2, Math_default.EPSILON14)) {
return Cartesian3_default.clone(Cartesian3_default.UNIT_Z, result);
}
v02 = Cartesian2_default.subtract(p1, p0, scratchCartesian1);
v12 = Cartesian2_default.subtract(p2, p0, scratchCartesian2);
v22 = Cartesian2_default.subtract(point4, p0, scratchCartesian32);
dot00 = Cartesian2_default.dot(v02, v02);
dot01 = Cartesian2_default.dot(v02, v12);
dot02 = Cartesian2_default.dot(v02, v22);
dot11 = Cartesian2_default.dot(v12, v12);
dot12 = Cartesian2_default.dot(v12, v22);
} else {
if (Cartesian3_default.equalsEpsilon(point4, p0, Math_default.EPSILON14)) {
return Cartesian3_default.clone(Cartesian3_default.UNIT_X, result);
}
if (Cartesian3_default.equalsEpsilon(point4, p1, Math_default.EPSILON14)) {
return Cartesian3_default.clone(Cartesian3_default.UNIT_Y, result);
}
if (Cartesian3_default.equalsEpsilon(point4, p2, Math_default.EPSILON14)) {
return Cartesian3_default.clone(Cartesian3_default.UNIT_Z, result);
}
v02 = Cartesian3_default.subtract(p1, p0, scratchCartesian1);
v12 = Cartesian3_default.subtract(p2, p0, scratchCartesian2);
v22 = Cartesian3_default.subtract(point4, p0, scratchCartesian32);
dot00 = Cartesian3_default.dot(v02, v02);
dot01 = Cartesian3_default.dot(v02, v12);
dot02 = Cartesian3_default.dot(v02, v22);
dot11 = Cartesian3_default.dot(v12, v12);
dot12 = Cartesian3_default.dot(v12, v22);
}
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/EncodedCartesian3.js
function EncodedCartesian3() {
this.high = Cartesian3_default.clone(Cartesian3_default.ZERO);
this.low = Cartesian3_default.clone(Cartesian3_default.ZERO);
}
EncodedCartesian3.encode = function(value, result) {
Check_default.typeOf.number("value", value);
if (!defined_default(result)) {
result = {
high: 0,
low: 0
};
}
let doubleHigh;
if (value >= 0) {
doubleHigh = Math.floor(value / 65536) * 65536;
result.high = doubleHigh;
result.low = value - doubleHigh;
} else {
doubleHigh = Math.floor(-value / 65536) * 65536;
result.high = -doubleHigh;
result.low = value + doubleHigh;
}
return result;
};
var scratchEncode = {
high: 0,
low: 0
};
EncodedCartesian3.fromCartesian = function(cartesian11, result) {
Check_default.typeOf.object("cartesian", cartesian11);
if (!defined_default(result)) {
result = new EncodedCartesian3();
}
const high = result.high;
const low = result.low;
EncodedCartesian3.encode(cartesian11.x, scratchEncode);
high.x = scratchEncode.high;
low.x = scratchEncode.low;
EncodedCartesian3.encode(cartesian11.y, scratchEncode);
high.y = scratchEncode.high;
low.y = scratchEncode.low;
EncodedCartesian3.encode(cartesian11.z, scratchEncode);
high.z = scratchEncode.high;
low.z = scratchEncode.low;
return result;
};
var encodedP = new EncodedCartesian3();
EncodedCartesian3.writeElements = function(cartesian11, cartesianArray, index) {
Check_default.defined("cartesianArray", cartesianArray);
Check_default.typeOf.number("index", index);
Check_default.typeOf.number.greaterThanOrEquals("index", index, 0);
EncodedCartesian3.fromCartesian(cartesian11, encodedP);
const high = encodedP.high;
const low = encodedP.low;
cartesianArray[index] = high.x;
cartesianArray[index + 1] = high.y;
cartesianArray[index + 2] = high.z;
cartesianArray[index + 3] = low.x;
cartesianArray[index + 4] = low.y;
cartesianArray[index + 5] = low.z;
};
var EncodedCartesian3_default = EncodedCartesian3;
// packages/engine/Source/Core/QuadraticRealPolynomial.js
var QuadraticRealPolynomial = {};
QuadraticRealPolynomial.computeDiscriminant = function(a3, b, c14) {
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 c14 !== "number") {
throw new DeveloperError_default("c is a required number.");
}
const discriminant = b * b - 4 * a3 * c14;
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, c14) {
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 c14 !== "number") {
throw new DeveloperError_default("c is a required number.");
}
let ratio;
if (a3 === 0) {
if (b === 0) {
return [];
}
return [-c14 / b];
} else if (b === 0) {
if (c14 === 0) {
return [0, 0];
}
const cMagnitude = Math.abs(c14);
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 = -c14 / a3;
if (ratio < 0) {
return [];
}
const root = Math.sqrt(ratio);
return [-root, root];
} else if (c14 === 0) {
ratio = -b / a3;
if (ratio < 0) {
return [ratio, 0];
}
return [0, ratio];
}
const b2 = b * b;
const four_ac = 4 * a3 * c14;
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, c14 / q];
}
return [c14 / q, q / a3];
};
var QuadraticRealPolynomial_default = QuadraticRealPolynomial;
// packages/engine/Source/Core/CubicRealPolynomial.js
var CubicRealPolynomial = {};
CubicRealPolynomial.computeDiscriminant = function(a3, b, c14, 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 c14 !== "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 = c14 * c14;
const d2 = d * d;
const discriminant = 18 * a3 * b * c14 * d + b2 * c22 - 27 * a22 * d2 - 4 * (a3 * c22 * c14 + b2 * b * d);
return discriminant;
};
function computeRealRoots(a3, b, c14, d) {
const A = a3;
const B = b / 3;
const C = c14 / 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 s2 = DBar < 0 ? -1 : 1;
const temp0 = -s2 * 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, c14, 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 c14 !== "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, c14, d);
} else if (b === 0) {
if (c14 === 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, c14);
if (roots.Length === 0) {
return [0];
}
return [roots[0], 0, roots[1]];
}
return computeRealRoots(a3, 0, c14, d);
} else if (c14 === 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, c14);
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, c14, d);
};
var CubicRealPolynomial_default = CubicRealPolynomial;
// packages/engine/Source/Core/QuarticRealPolynomial.js
var QuarticRealPolynomial = {};
QuarticRealPolynomial.computeDiscriminant = function(a3, b, c14, 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 c14 !== "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 = c14 * c14;
const c33 = c22 * c14;
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 * c14 * d3 - 27 * a22 * d2 * d2 + 256 * a32 * e3 + e * (18 * b3 * c14 * d - 4 * b2 * c33 + 16 * a3 * c22 * c22 - 80 * a3 * b * c22 * d - 6 * a3 * b2 * d2 + 144 * a22 * c14 * d2) + e2 * (144 * a3 * b2 * c14 - 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 r2 = a0 - a1 * a3 / 4 + a22 * a3Squared / 16 - 3 * a3Squared * a3Squared / 256;
const cubicRoots = CubicRealPolynomial_default.computeRealRoots(
1,
2 * p,
p * p - 4 * r2,
-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, r2);
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 n2 = (p + hSquared + q / h) / 2;
const roots1 = QuadraticRealPolynomial_default.computeRealRoots(1, h, m);
const roots2 = QuadraticRealPolynomial_default.computeRealRoots(1, -h, n2);
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 r2 = a3Squared * a0 - a1 * a22 * a3 + a1Squared;
const cubicRoots = CubicRealPolynomial_default.computeRealRoots(1, p, q, r2);
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 n2 = a3Squared - 4 * y;
const nError = a3Squared + 4 * Math.abs(y);
let g2;
let h2;
if (y < 0 || m * nError < n2 * mError) {
const squareRootOfN = Math.sqrt(n2);
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, c14, 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 c14 !== "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, c14, d, e);
}
const a32 = b / a3;
const a22 = c14 / 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
var Ray = class _Ray {
/**
* @param {Cartesian3} [origin=Cartesian3.ZERO] The origin of the ray.
* @param {Cartesian3} [direction=Cartesian3.ZERO] The direction of the ray.
*/
constructor(origin, direction2) {
direction2 = Cartesian3_default.clone(direction2 ?? Cartesian3_default.ZERO);
if (!Cartesian3_default.equals(direction2, Cartesian3_default.ZERO)) {
Cartesian3_default.normalize(direction2, direction2);
}
this.origin = Cartesian3_default.clone(origin ?? Cartesian3_default.ZERO);
this.direction = direction2;
}
/**
* Duplicates a Ray instance.
*
* @param {Ray} ray The ray to duplicate.
* @param {Ray} [result] The object onto which to store the result.
* @returns {Ray} The modified result parameter or a new Ray instance if one was not provided. (Returns undefined if ray is undefined)
*/
static clone(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;
}
/**
* Computes the point along the ray given by r(t) = o + t*d,
* where o is the origin of the ray and d is the direction.
*
* @param {Ray} ray The ray.
* @param {number} t A scalar value.
* @param {Cartesian3} [result] The object in which the result will be stored.
* @returns {Cartesian3} The modified result parameter, or a new instance if none was provided.
*
* @example
* //Get the first intersection point of a ray and an ellipsoid.
* const intersection = Cesium.IntersectionTests.rayEllipsoid(ray, ellipsoid);
* const point = Cesium.Ray.getPoint(ray, intersection.start);
*/
static getPoint(ray, t2, result) {
Check_default.typeOf.object("ray", ray);
Check_default.typeOf.number("t", t2);
if (!defined_default(result)) {
result = new Cartesian3_default();
}
result = Cartesian3_default.multiplyByScalar(ray.direction, t2, 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 t2 = (-plane.distance - Cartesian3_default.dot(normal2, origin)) / denominator;
if (t2 < 0) {
return void 0;
}
result = Cartesian3_default.multiplyByScalar(direction2, t2, 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 = 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 u4;
let v3;
let t2;
if (cullBackFaces) {
if (det < Math_default.EPSILON6) {
return void 0;
}
tvec = Cartesian3_default.subtract(origin, p0, scratchTVec);
u4 = Cartesian3_default.dot(tvec, p);
if (u4 < 0 || u4 > det) {
return void 0;
}
q = Cartesian3_default.cross(tvec, edge0, scratchQVec);
v3 = Cartesian3_default.dot(direction2, q);
if (v3 < 0 || u4 + v3 > det) {
return void 0;
}
t2 = 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);
u4 = Cartesian3_default.dot(tvec, p) * invDet;
if (u4 < 0 || u4 > 1) {
return void 0;
}
q = Cartesian3_default.cross(tvec, edge0, scratchQVec);
v3 = Cartesian3_default.dot(direction2, q) * invDet;
if (v3 < 0 || u4 + v3 > 1) {
return void 0;
}
t2 = Cartesian3_default.dot(edge1, q) * invDet;
}
return t2;
};
IntersectionTests.rayTriangle = function(ray, p0, p1, p2, cullBackFaces, result) {
const t2 = IntersectionTests.rayTriangleParametric(
ray,
p0,
p1,
p2,
cullBackFaces
);
if (!defined_default(t2) || t2 < 0) {
return void 0;
}
if (!defined_default(result)) {
result = new Cartesian3_default();
}
Cartesian3_default.multiplyByScalar(ray.direction, t2, result);
return Cartesian3_default.add(ray.origin, result, result);
};
var scratchLineSegmentTriangleRay = new Ray_default();
IntersectionTests.lineSegmentTriangle = function(v02, v12, p0, p1, p2, cullBackFaces, result) {
if (!defined_default(v02)) {
throw new DeveloperError_default("v0 is required.");
}
if (!defined_default(v12)) {
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(v12, v02, ray.direction);
Cartesian3_default.normalize(ray.direction, ray.direction);
const t2 = IntersectionTests.rayTriangleParametric(
ray,
p0,
p1,
p2,
cullBackFaces
);
if (!defined_default(t2) || t2 < 0 || t2 > Cartesian3_default.distance(v02, v12)) {
return void 0;
}
if (!defined_default(result)) {
result = new Cartesian3_default();
}
Cartesian3_default.multiplyByScalar(ray.direction, t2, result);
return Cartesian3_default.add(ray.origin, result, result);
};
function solveQuadratic(a3, b, c14, result) {
const det = b * b - 4 * a3 * c14;
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 c14 = Cartesian3_default.magnitudeSquared(diff) - radiusSquared;
const roots = solveQuadratic(a3, b, c14, 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;
};
var scratchRayIntervalX = new Interval_default();
var scratchRayIntervalY = new Interval_default();
var scratchRayIntervalZ = new Interval_default();
IntersectionTests.rayAxisAlignedBoundingBox = function(ray, box, result) {
if (!defined_default(ray)) {
throw new DeveloperError_default("ray is required.");
}
if (!defined_default(box)) {
throw new DeveloperError_default("box is required.");
}
if (!defined_default(result)) {
result = new Interval_default();
}
const tx = rayIntervalAlongAABBAxis(
ray.origin.x,
ray.direction.x,
box.minimum.x,
box.maximum.x,
scratchRayIntervalX
);
const ty = rayIntervalAlongAABBAxis(
ray.origin.y,
ray.direction.y,
box.minimum.y,
box.maximum.y,
scratchRayIntervalY
);
const tz = rayIntervalAlongAABBAxis(
ray.origin.z,
ray.direction.z,
box.minimum.z,
box.maximum.z,
scratchRayIntervalZ
);
result.start = tx.start > ty.start ? tx.start : ty.start;
result.stop = tx.stop < ty.stop ? tx.stop : ty.stop;
if (tx.start > ty.stop || ty.start > tx.stop) {
return void 0;
}
if (result.start > tz.stop || tz.start > result.stop) {
return void 0;
}
if (tz.start > result.start) {
result.start = tz.start;
}
if (tz.stop < result.stop) {
result.stop = tz.stop;
}
return result;
};
function rayIntervalAlongAABBAxis(origin, direction2, min3, max3, result) {
result.start = (min3 - origin) / direction2;
result.stop = (max3 - origin) / direction2;
if (result.stop < result.start) {
const tmp2 = result.stop;
result.stop = result.start;
result.start = tmp2;
}
return result;
}
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;
}
IntersectionTests.quadraticVectorExpression = function(A, b, c14, 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 + c14;
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 c15 = 2 * (l0 * l1 - r0r1);
const c0 = l0 * l0 - r0Squared;
if (c42 === 0 && c33 === 0 && c22 === 0 && c15 === 0) {
return solutions;
}
cosines = QuarticRealPolynomial_default.computeRealRoots(c42, c33, c22, c15, c0);
const length2 = cosines.length;
if (length2 === 0) {
return solutions;
}
for (let i = 0; i < length2; ++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 intersects3 = defined_default(this.rayEllipsoid(ray, ellipsoid));
const f2 = ellipsoid.transformPositionToScaledSpace(
direction2,
firstAxisScratch
);
const firstAxis = Cartesian3_default.normalize(f2, f2);
const reference = Cartesian3_default.mostOrthogonalAxis(f2, 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 = IntersectionTests.quadraticVectorExpression(
A,
Cartesian3_default.negate(b, firstAxisScratch),
0,
0,
1
);
let s2;
let altitude;
const length2 = solutions.length;
if (length2 > 0) {
let closest = Cartesian3_default.clone(Cartesian3_default.ZERO, closestScratch);
let maximumValue = Number.NEGATIVE_INFINITY;
for (let i = 0; i < length2; ++i) {
s2 = Matrix3_default.multiplyByVector(
D_I,
Matrix3_default.multiplyByVector(B, solutions[i], sScratch),
sScratch
);
const v3 = Cartesian3_default.normalize(
Cartesian3_default.subtract(s2, position, referenceScratch),
referenceScratch
);
const dotProduct = Cartesian3_default.dot(v3, direction2);
if (dotProduct > maximumValue) {
maximumValue = dotProduct;
closest = Cartesian3_default.clone(s2, 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 = intersects3 ? -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 t2 = -(plane.distance + nDotP0) / nDotDiff;
if (t2 < 0 || t2 > 1) {
return void 0;
}
Cartesian3_default.multiplyByScalar(difference, t2, 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/Plane.js
function Plane(normal2, distance2) {
Check_default.typeOf.object("normal", normal2);
if (!Math_default.equalsEpsilon(
Cartesian3_default.magnitude(normal2),
1,
Math_default.EPSILON6
)) {
throw new DeveloperError_default("normal must be normalized.");
}
Check_default.typeOf.number("distance", distance2);
this.normal = Cartesian3_default.clone(normal2);
this.distance = distance2;
}
Plane.fromPointNormal = function(point4, normal2, result) {
Check_default.typeOf.object("point", point4);
Check_default.typeOf.object("normal", normal2);
if (!Math_default.equalsEpsilon(
Cartesian3_default.magnitude(normal2),
1,
Math_default.EPSILON6
)) {
throw new DeveloperError_default("normal must be normalized.");
}
const distance2 = -Cartesian3_default.dot(normal2, point4);
if (!defined_default(result)) {
return new Plane(normal2, distance2);
}
Cartesian3_default.clone(normal2, result.normal);
result.distance = distance2;
return result;
};
var scratchNormal = new Cartesian3_default();
Plane.fromCartesian4 = function(coefficients, result) {
Check_default.typeOf.object("coefficients", coefficients);
const normal2 = Cartesian3_default.fromCartesian4(coefficients, scratchNormal);
const distance2 = coefficients.w;
if (!Math_default.equalsEpsilon(
Cartesian3_default.magnitude(normal2),
1,
Math_default.EPSILON6
)) {
throw new DeveloperError_default("normal must be normalized.");
}
if (!defined_default(result)) {
return new Plane(normal2, distance2);
}
Cartesian3_default.clone(normal2, result.normal);
result.distance = distance2;
return result;
};
Plane.getPointDistance = function(plane, point4) {
Check_default.typeOf.object("plane", plane);
Check_default.typeOf.object("point", point4);
return Cartesian3_default.dot(plane.normal, point4) + plane.distance;
};
var scratchCartesian = new Cartesian3_default();
Plane.projectPointOntoPlane = function(plane, point4, result) {
Check_default.typeOf.object("plane", plane);
Check_default.typeOf.object("point", point4);
if (!defined_default(result)) {
result = new Cartesian3_default();
}
const pointDistance = Plane.getPointDistance(plane, point4);
const scaledNormal = Cartesian3_default.multiplyByScalar(
plane.normal,
pointDistance,
scratchCartesian
);
return Cartesian3_default.subtract(point4, scaledNormal, result);
};
var scratchInverseTranspose = new Matrix4_default();
var scratchPlaneCartesian4 = new Cartesian4_default();
var scratchTransformNormal = new Cartesian3_default();
Plane.transform = function(plane, transform3, result) {
Check_default.typeOf.object("plane", plane);
Check_default.typeOf.object("transform", transform3);
const normal2 = plane.normal;
const distance2 = plane.distance;
const inverseTranspose2 = Matrix4_default.inverseTranspose(
transform3,
scratchInverseTranspose
);
let planeAsCartesian4 = Cartesian4_default.fromElements(
normal2.x,
normal2.y,
normal2.z,
distance2,
scratchPlaneCartesian4
);
planeAsCartesian4 = Matrix4_default.multiplyByVector(
inverseTranspose2,
planeAsCartesian4,
planeAsCartesian4
);
const transformedNormal = Cartesian3_default.fromCartesian4(
planeAsCartesian4,
scratchTransformNormal
);
planeAsCartesian4 = Cartesian4_default.divideByScalar(
planeAsCartesian4,
Cartesian3_default.magnitude(transformedNormal),
planeAsCartesian4
);
return Plane.fromCartesian4(planeAsCartesian4, result);
};
Plane.clone = function(plane, result) {
Check_default.typeOf.object("plane", plane);
if (!defined_default(result)) {
return new Plane(plane.normal, plane.distance);
}
Cartesian3_default.clone(plane.normal, result.normal);
result.distance = plane.distance;
return result;
};
Plane.equals = function(left, right) {
Check_default.typeOf.object("left", left);
Check_default.typeOf.object("right", right);
return left.distance === right.distance && Cartesian3_default.equals(left.normal, right.normal);
};
Plane.ORIGIN_XY_PLANE = Object.freeze(new Plane(Cartesian3_default.UNIT_Z, 0));
Plane.ORIGIN_YZ_PLANE = Object.freeze(new Plane(Cartesian3_default.UNIT_X, 0));
Plane.ORIGIN_ZX_PLANE = Object.freeze(new Plane(Cartesian3_default.UNIT_Y, 0));
var Plane_default = Plane;
// packages/engine/Source/Core/Tipsify.js
var Tipsify = {};
Tipsify.calculateACMR = function(options) {
options = options ?? Frozen_default.EMPTY_OBJECT;
const indices = options.indices;
let maximumIndex = options.maximumIndex;
const cacheSize = options.cacheSize ?? 24;
if (!defined_default(indices)) {
throw new DeveloperError_default("indices is required.");
}
const numIndices = indices.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 = indices[currentIndex];
while (currentIndex < numIndices) {
if (intoIndices > maximumIndex) {
maximumIndex = intoIndices;
}
++currentIndex;
intoIndices = indices[currentIndex];
}
}
const vertexTimeStamps = [];
for (let i = 0; i < maximumIndex + 1; i++) {
vertexTimeStamps[i] = 0;
}
let s2 = cacheSize + 1;
for (let j = 0; j < numIndices; ++j) {
if (s2 - vertexTimeStamps[indices[j]] > cacheSize) {
vertexTimeStamps[indices[j]] = s2;
++s2;
}
}
return (s2 - cacheSize + 1) / (numIndices / 3);
};
Tipsify.tipsify = function(options) {
options = options ?? Frozen_default.EMPTY_OBJECT;
const indices = options.indices;
const maximumIndex = options.maximumIndex;
const cacheSize = options.cacheSize ?? 24;
let cursor;
function skipDeadEnd(vertices2, deadEnd2, indices2, 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(indices2, cacheSize2, oneRing2, vertices2, s3, deadEnd2, maximumIndexPlusOne2) {
let n2 = -1;
let p;
let m = -1;
let itOneRing = 0;
while (itOneRing < oneRing2.length) {
const index2 = oneRing2[itOneRing];
if (vertices2[index2].numLiveTriangles) {
p = 0;
if (s3 - vertices2[index2].timeStamp + 2 * vertices2[index2].numLiveTriangles <= cacheSize2) {
p = s3 - vertices2[index2].timeStamp;
}
if (p > m || m === -1) {
m = p;
n2 = index2;
}
}
++itOneRing;
}
if (n2 === -1) {
return skipDeadEnd(vertices2, deadEnd2, indices2, maximumIndexPlusOne2);
}
return n2;
}
if (!defined_default(indices)) {
throw new DeveloperError_default("indices is required.");
}
const numIndices = indices.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 = indices[currentIndex];
const endIndex = numIndices;
if (defined_default(maximumIndex)) {
maximumIndexPlusOne = maximumIndex + 1;
} else {
while (currentIndex < endIndex) {
if (intoIndices > maximumIndexPlusOne) {
maximumIndexPlusOne = intoIndices;
}
++currentIndex;
intoIndices = indices[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[indices[currentIndex]].vertexTriangles.push(triangle);
++vertices[indices[currentIndex]].numLiveTriangles;
vertices[indices[currentIndex + 1]].vertexTriangles.push(triangle);
++vertices[indices[currentIndex + 1]].numLiveTriangles;
vertices[indices[currentIndex + 2]].vertexTriangles.push(triangle);
++vertices[indices[currentIndex + 2]].numLiveTriangles;
++triangle;
currentIndex += 3;
}
let f2 = 0;
let s2 = 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 (f2 !== -1) {
oneRing = [];
intoVertices = vertices[f2];
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 = indices[currentIndex];
oneRing.push(index);
deadEnd.push(index);
outputIndices[currentOutputIndex] = index;
++currentOutputIndex;
vertex = vertices[index];
--vertex.numLiveTriangles;
if (s2 - vertex.timeStamp > cacheSize) {
vertex.timeStamp = s2;
++s2;
}
++currentIndex;
}
}
}
f2 = getNextVertex(
indices,
cacheSize,
oneRing,
vertices,
s2,
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 indices = geometry.indices;
if (defined_default(indices)) {
switch (geometry.primitiveType) {
case PrimitiveType_default.TRIANGLES:
geometry.indices = trianglesToLines(indices);
break;
case PrimitiveType_default.TRIANGLE_STRIP:
geometry.indices = triangleStripToLines(indices);
break;
case PrimitiveType_default.TRIANGLE_FAN:
geometry.indices = triangleFanToLines(indices);
break;
//>>includeStart('debug', pragmas.debug);
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, length2) {
attributeName = 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}.`
);
}
length2 = length2 ?? 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] * length2;
newPositions[j++] = positions[i + 1] + vectors[i + 1] * length2;
newPositions[j++] = positions[i + 2] + vectors[i + 2] * length2;
}
let newBoundingSphere;
const bs = geometry.boundingSphere;
if (defined_default(bs)) {
newBoundingSphere = new BoundingSphere_default(bs.center, bs.radius + length2);
}
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 indices = {};
let j = 0;
let i;
const len = semantics.length;
for (i = 0; i < len; ++i) {
const semantic = semantics[i];
if (defined_default(attributes[semantic])) {
indices[semantic] = j++;
}
}
for (const name in attributes) {
if (attributes.hasOwnProperty(name) && !defined_default(indices[name])) {
indices[name] = j++;
}
}
return indices;
};
GeometryPipeline.reorderForPreVertexCache = function(geometry) {
if (!defined_default(geometry)) {
throw new DeveloperError_default("geometry is required.");
}
const numVertices = Geometry_default.computeNumberOfVertices(geometry);
const indices = geometry.indices;
if (defined_default(indices)) {
const indexCrossReferenceOldToNew = new Int32Array(numVertices);
for (let i = 0; i < numVertices; i++) {
indexCrossReferenceOldToNew[i] = -1;
}
const indicesIn = indices;
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 indices = geometry.indices;
if (geometry.primitiveType === PrimitiveType_default.TRIANGLES && defined_default(indices)) {
const numIndices = indices.length;
let maximumIndex = 0;
for (let j = 0; j < numIndices; j++) {
if (indices[j] > maximumIndex) {
maximumIndex = indices[j];
}
}
geometry.indices = Tipsify_default.tipsify({
indices,
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 length2 = values.length;
const highValues = new Float32Array(length2);
const lowValues = new Float32Array(length2);
for (let i = 0; i < length2; ++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 scratchCartesian33 = new Cartesian3_default();
function transformPoint(matrix, attribute) {
if (defined_default(attribute)) {
const values = attribute.values;
const length2 = values.length;
for (let i = 0; i < length2; i += 3) {
Cartesian3_default.unpack(values, i, scratchCartesian33);
Matrix4_default.multiplyByPoint(matrix, scratchCartesian33, scratchCartesian33);
Cartesian3_default.pack(scratchCartesian33, values, i);
}
}
}
function transformVector(matrix, attribute) {
if (defined_default(attribute)) {
const values = attribute.values;
const length2 = values.length;
for (let i = 0; i < length2; i += 3) {
Cartesian3_default.unpack(values, i, scratchCartesian33);
Matrix3_default.multiplyByVector(matrix, scratchCartesian33, scratchCartesian33);
scratchCartesian33 = Cartesian3_default.normalize(
scratchCartesian33,
scratchCartesian33
);
Cartesian3_default.pack(scratchCartesian33, 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 length2 = 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 < length2; ++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 length2 = 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 < length2; ++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 < length2; ++i) {
sourceValues = instances[i][propertyName].attributes[name].values;
sourceValuesLength = sourceValues.length;
for (j = 0; j < sourceValuesLength; ++j) {
values[k++] = sourceValues[j];
}
}
}
}
let indices;
if (haveIndices) {
let numberOfIndices = 0;
for (i = 0; i < length2; ++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 offset = 0;
for (i = 0; i < length2; ++i) {
const sourceIndices = instances[i][propertyName].indices;
const sourceIndicesLen = sourceIndices.length;
for (k = 0; k < sourceIndicesLen; ++k) {
destIndices[destOffset++] = offset + sourceIndices[k];
}
offset += Geometry_default.computeNumberOfVertices(instances[i][propertyName]);
}
indices = destIndices;
}
let center = new Cartesian3_default();
let radius = 0;
let bs;
for (i = 0; i < length2; ++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, length2, center);
for (i = 0; i < length2; ++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,
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 length2 = instances.length;
for (let i = 0; i < length2; ++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 indices = geometry.indices;
const attributes = geometry.attributes;
const vertices = attributes.position.values;
const numVertices = attributes.position.values.length / 3;
const numIndices = indices.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 = indices[i];
const i1 = indices[i + 1];
const i2 = indices[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[indices[i]];
let index = vertexNormalData.indexOffset + vertexNormalData.currentCount;
normalIndices[index] = j;
vertexNormalData.currentCount++;
vertexNormalData = normalsPerVertex[indices[i + 1]];
index = vertexNormalData.indexOffset + vertexNormalData.currentCount;
normalIndices[index] = j;
vertexNormalData.currentCount++;
vertexNormalData = normalsPerVertex[indices[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 indices = 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(indices)) {
throw new DeveloperError_default("geometry.indices is required.");
}
if (indices.length < 2 || 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 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 = indices.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 = indices[i];
const i1 = indices[i + 1];
const i2 = indices[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 r2 = 1 / ((st[i12] - wx) * t2 - (st[i22] - wx) * t1);
const sdirx = (t2 * (vertices[i13] - ux) - t1 * (vertices[i23] - ux)) * r2;
const sdiry = (t2 * (vertices[i13 + 1] - uy) - t1 * (vertices[i23 + 1] - uy)) * r2;
const sdirz = (t2 * (vertices[i13 + 2] - uz) - t1 * (vertices[i23 + 2] - uz)) * r2;
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 n2 = Cartesian3_default.fromArray(normals, i03, normalScratch2);
const t2 = Cartesian3_default.fromArray(tan1, i03, tScratch);
const scalar = Cartesian3_default.dot(n2, t2);
Cartesian3_default.multiplyByScalar(n2, scalar, normalScale);
Cartesian3_default.normalize(Cartesian3_default.subtract(t2, normalScale, t2), t2);
tangentValues[i03] = t2.x;
tangentValues[i13] = t2.y;
tangentValues[i23] = t2.z;
Cartesian3_default.normalize(Cartesian3_default.cross(n2, t2, t2), t2);
bitangentValues[i03] = t2.x;
bitangentValues[i13] = t2.y;
bitangentValues[i23] = t2.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 scratchCartesian22 = 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 length2 = hasNormal ? normals.length : st.length;
const numComponents = hasNormal ? 3 : 2;
numVertices = length2 / 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, scratchCartesian22);
compressedAttributes[normalIndex++] = AttributeCompression_default.compressTextureCoordinates(scratchCartesian22);
}
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,
scratchCartesian22
);
compressedAttributes[normalIndex++] = scratchCartesian22.x;
compressedAttributes[normalIndex++] = scratchCartesian22.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 indices = IndexDatatype_default.createTypedArray(
numberOfVertices,
numberOfVertices
);
for (let i = 0; i < numberOfVertices; ++i) {
indices[i] = i;
}
geometry.indices = indices;
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 indices = IndexDatatype_default.createTypedArray(
numberOfVertices,
(numberOfVertices - 2) * 3
);
indices[0] = 1;
indices[1] = 0;
indices[2] = 2;
let indicesIndex = 3;
for (let i = 3; i < numberOfVertices; ++i) {
indices[indicesIndex++] = i - 1;
indices[indicesIndex++] = 0;
indices[indicesIndex++] = i;
}
geometry.indices = indices;
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 indices = IndexDatatype_default.createTypedArray(
numberOfVertices,
(numberOfVertices - 2) * 3
);
indices[0] = 0;
indices[1] = 1;
indices[2] = 2;
if (numberOfVertices > 3) {
indices[3] = 0;
indices[4] = 2;
indices[5] = 3;
}
let indicesIndex = 6;
for (let i = 3; i < numberOfVertices - 1; i += 2) {
indices[indicesIndex++] = i;
indices[indicesIndex++] = i - 1;
indices[indicesIndex++] = i + 1;
if (i + 2 < numberOfVertices) {
indices[indicesIndex++] = i;
indices[indicesIndex++] = i + 1;
indices[indicesIndex++] = i + 2;
}
}
geometry.indices = indices;
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 indices = IndexDatatype_default.createTypedArray(
numberOfVertices,
numberOfVertices
);
for (let i = 0; i < numberOfVertices; ++i) {
indices[i] = i;
}
geometry.indices = indices;
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 indices = IndexDatatype_default.createTypedArray(
numberOfVertices,
(numberOfVertices - 1) * 2
);
indices[0] = 0;
indices[1] = 1;
let indicesIndex = 2;
for (let i = 2; i < numberOfVertices; ++i) {
indices[indicesIndex++] = i - 1;
indices[indicesIndex++] = i;
}
geometry.indices = indices;
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 indices = IndexDatatype_default.createTypedArray(
numberOfVertices,
numberOfVertices * 2
);
indices[0] = 0;
indices[1] = 1;
let indicesIndex = 2;
for (let i = 2; i < numberOfVertices; ++i) {
indices[indicesIndex++] = i - 1;
indices[indicesIndex++] = i;
}
indices[indicesIndex++] = numberOfVertices - 1;
indices[indicesIndex] = 0;
geometry.indices = indices;
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 sign3;
if (p0y > p1y) {
if (p0y > p2y) {
sign3 = Math_default.sign(p0.y);
} else {
sign3 = Math_default.sign(p2.y);
}
} else if (p1y > p2y) {
sign3 = Math_default.sign(p1.y);
} else {
sign3 = Math_default.sign(p2.y);
}
const isBehind = sign3 < 0;
offsetPointFromXZPlane(p0, isBehind);
offsetPointFromXZPlane(p1, isBehind);
offsetPointFromXZPlane(p2, isBehind);
}
var c3 = new Cartesian3_default();
function getXZIntersectionOffsetPoints(p, p1, u12, v12) {
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, v12);
offsetPointFromXZPlane(u12, true);
offsetPointFromXZPlane(v12, 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 indices = splitTriangleResult.indices;
if (numBehind === 1) {
indices[1] = 3;
indices[2] = 4;
indices[5] = 6;
indices[7] = 6;
indices[8] = 5;
if (p0Behind) {
getXZIntersectionOffsetPoints(p0, p1, u1, q1);
getXZIntersectionOffsetPoints(p0, p2, u2, q2);
indices[0] = 0;
indices[3] = 1;
indices[4] = 2;
indices[6] = 1;
} else if (p1Behind) {
getXZIntersectionOffsetPoints(p1, p2, u1, q1);
getXZIntersectionOffsetPoints(p1, p0, u2, q2);
indices[0] = 1;
indices[3] = 2;
indices[4] = 0;
indices[6] = 2;
} else if (p2Behind) {
getXZIntersectionOffsetPoints(p2, p0, u1, q1);
getXZIntersectionOffsetPoints(p2, p1, u2, q2);
indices[0] = 2;
indices[3] = 0;
indices[4] = 1;
indices[6] = 0;
}
} else if (numBehind === 2) {
indices[2] = 4;
indices[4] = 4;
indices[5] = 3;
indices[7] = 5;
indices[8] = 6;
if (!p0Behind) {
getXZIntersectionOffsetPoints(p0, p1, u1, q1);
getXZIntersectionOffsetPoints(p0, p2, u2, q2);
indices[0] = 1;
indices[1] = 2;
indices[3] = 1;
indices[6] = 0;
} else if (!p1Behind) {
getXZIntersectionOffsetPoints(p1, p2, u1, q1);
getXZIntersectionOffsetPoints(p1, p0, u2, q2);
indices[0] = 2;
indices[1] = 0;
indices[3] = 2;
indices[6] = 1;
} else if (!p2Behind) {
getXZIntersectionOffsetPoints(p2, p0, u1, q1);
getXZIntersectionOffsetPoints(p2, p1, u2, q2);
indices[0] = 0;
indices[1] = 1;
indices[3] = 0;
indices[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 v12 = CartesianType.fromArray(
sourceValues,
i1 * numberOfComponents,
v1Scratch2
);
const v22 = CartesianType.fromArray(
sourceValues,
i2 * numberOfComponents,
v2Scratch2
);
CartesianType.multiplyByScalar(v02, coords.x, v02);
CartesianType.multiplyByScalar(v12, coords.y, v12);
CartesianType.multiplyByScalar(v22, coords.z, v22);
const value = CartesianType.add(v02, v12, v02);
CartesianType.add(value, v22, 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 v12 = sourceValues[i0] * coords.x;
const v22 = sourceValues[i1] * coords.y;
const v3 = sourceValues[i2] * coords.z;
currentValues[insertedIndex] = v12 + v22 + v3 > 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, point4, 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(point4, 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, indices, currentIndex, point4) {
const insertIndex = currentAttributes.position.values.length / 3;
if (currentIndex !== -1) {
const prevIndex = indices[currentIndex];
const newIndex = currentIndexMap[prevIndex];
if (newIndex === -1) {
currentIndexMap[prevIndex] = insertIndex;
currentAttributes.position.values.push(point4.x, point4.y, point4.z);
currentIndices.push(insertIndex);
return insertIndex;
}
currentIndices.push(newIndex);
return newIndex;
}
currentAttributes.position.values.push(point4.x, point4.y, point4.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 indices = 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 = indices.length;
for (i = 0; i < len; i += 3) {
const i0 = indices[i];
const i1 = indices[i + 1];
const i2 = indices[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 point4 = resultPositions[resultIndex];
if (point4.y < 0) {
currentAttributes = westGeometry.attributes;
currentIndices = westGeometry.indices;
currentIndexMap = westGeometryIndexMap;
} else {
currentAttributes = eastGeometry.attributes;
currentIndices = eastGeometry.indices;
currentIndexMap = eastGeometryIndexMap;
}
insertedIndex = insertSplitPoint(
currentAttributes,
currentIndices,
currentIndexMap,
indices,
resultIndex < 3 ? i + resultIndex : -1,
point4
);
computeTriangleAttributes(
i0,
i1,
i2,
point4,
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,
indices,
i,
p0
);
computeTriangleAttributes(
i0,
i1,
i2,
p0,
positions,
normals,
tangents,
bitangents,
texCoords,
extrudeDirections,
applyOffset,
currentAttributes,
customAttributeNames,
customAttributesLength,
attributes,
insertedIndex
);
insertedIndex = insertSplitPoint(
currentAttributes,
currentIndices,
currentIndexMap,
indices,
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,
indices,
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, point4, positions, insertIndex, currentAttributes, applyOffset) {
if (!defined_default(applyOffset)) {
return;
}
const p0 = Cartesian3_default.fromArray(positions, i0 * 3, p0Scratch);
if (Cartesian3_default.equalsEpsilon(p0, point4, 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 indices = geometry.indices;
const eastGeometry = copyGeometryForSplit(geometry);
const westGeometry = copyGeometryForSplit(geometry);
let i;
const length2 = indices.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 < length2; i += 2) {
const i0 = indices[i];
const i1 = indices[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 offset = Cartesian3_default.multiplyByScalar(
Cartesian3_default.UNIT_Y,
5 * Math_default.EPSILON9,
offsetScratch
);
if (p0.y < 0) {
Cartesian3_default.negate(offset, offset);
p0Attributes = westGeometry.attributes;
p0Indices = westGeometry.indices;
p0IndexMap = westGeometryIndexMap;
p1Attributes = eastGeometry.attributes;
p1Indices = eastGeometry.indices;
p1IndexMap = eastGeometryIndexMap;
}
const offsetPoint = Cartesian3_default.add(
intersection,
offset,
offsetPointScratch
);
insertIndex = insertSplitPoint(
p0Attributes,
p0Indices,
p0IndexMap,
indices,
i,
p0
);
computeLineAttributes(
i0,
i1,
p0,
positions,
insertIndex,
p0Attributes,
applyOffset
);
insertIndex = insertSplitPoint(
p0Attributes,
p0Indices,
p0IndexMap,
indices,
-1,
offsetPoint
);
computeLineAttributes(
i0,
i1,
offsetPoint,
positions,
insertIndex,
p0Attributes,
applyOffset
);
Cartesian3_default.negate(offset, offset);
Cartesian3_default.add(intersection, offset, offsetPoint);
insertIndex = insertSplitPoint(
p1Attributes,
p1Indices,
p1IndexMap,
indices,
-1,
offsetPoint
);
computeLineAttributes(
i0,
i1,
offsetPoint,
positions,
insertIndex,
p1Attributes,
applyOffset
);
insertIndex = insertSplitPoint(
p1Attributes,
p1Indices,
p1IndexMap,
indices,
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,
indices,
i,
p0
);
computeLineAttributes(
i0,
i1,
p0,
positions,
insertIndex,
currentAttributes,
applyOffset
);
insertIndex = insertSplitPoint(
currentAttributes,
currentIndices,
currentIndexMap,
indices,
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 length2 = positions.length;
for (let j = 0; j < length2; 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 < length2) {
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 length2 = positions.length / 3;
for (i = 0; i < length2; 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 offset = Cartesian3_default.multiplyByScalar(
Cartesian3_default.UNIT_Y,
offsetScalar,
cartesian3Scratch5
);
if (p0.y < 0) {
Cartesian3_default.negate(offset, offset);
p0Attributes = westGeometry.attributes;
p0Indices = westGeometry.indices;
p2Attributes = eastGeometry.attributes;
p2Indices = eastGeometry.indices;
}
const offsetPoint = Cartesian3_default.add(
intersection,
offset,
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(offset, offset);
Cartesian3_default.add(intersection, offset, 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 t2 = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(intersection, p0, cartesian3Scratch3)
);
t2 /= 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 r2 = Math_default.lerp(c0.x, c22.x, t2);
const g = Math_default.lerp(c0.y, c22.y, t2);
const b = Math_default.lerp(c0.z, c22.z, t2);
const a3 = Math_default.lerp(c0.w, c22.w, t2);
for (j = i0 * 4; j < i0 * 4 + 2 * 4; ++j) {
p0Attributes.color.values.push(colors[j]);
}
p0Attributes.color.values.push(r2, g, b, a3);
p0Attributes.color.values.push(r2, g, b, a3);
p2Attributes.color.values.push(r2, g, b, a3);
p2Attributes.color.values.push(r2, 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, t2);
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/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 = 0,
yOffset = 0,
source,
skipColorSpaceConversion = false
} = options;
Check_default.defined("options.source", source);
Check_default.typeOf.number.greaterThanOrEquals("xOffset", xOffset, 0);
Check_default.typeOf.number.greaterThanOrEquals("yOffset", yOffset, 0);
if (xOffset + source.width > this._size) {
throw new DeveloperError_default(
"xOffset + options.source.width must be less than or equal to width."
);
}
if (yOffset + source.height > this._size) {
throw new DeveloperError_default(
"yOffset + options.source.height must be less than or equal to height."
);
}
const { width, height } = source;
const gl = this._context._gl;
const target = this._textureTarget;
const targetFace = this._targetFace;
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(target, this._texture);
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;
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) {
let pixels;
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
);
}
pixels = arrayBufferView;
} else {
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, preMultiplyAlpha);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY);
pixels = source;
}
uploaded = true;
} else {
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
pixels = PixelFormat_default.createTypedArray(
pixelFormat,
pixelDatatype,
size,
size
);
}
gl.texImage2D(
targetFace,
0,
internalFormat,
size,
size,
0,
pixelFormat,
PixelDatatype_default.toWebGLConstant(pixelDatatype, this._context),
pixels
);
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 = xOffset ?? 0;
yOffset = yOffset ?? 0;
framebufferXOffset = framebufferXOffset ?? 0;
framebufferYOffset = framebufferYOffset ?? 0;
width = width ?? this._size;
height = 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;
};
CubeMapFace.prototype.copyMipmapFromFramebuffer = function(xOffset, yOffset, width, height, level) {
xOffset = xOffset ?? 0;
yOffset = yOffset ?? 0;
width = width ?? this._size;
height = height ?? this._size;
level = level ?? 0;
Check_default.typeOf.number.greaterThanOrEquals("xOffset", xOffset, 0);
Check_default.typeOf.number.greaterThanOrEquals("yOffset", yOffset, 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.copyTexImage2D(
this._targetFace,
level,
this._internalFormat,
xOffset,
yOffset,
width,
height,
0
);
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;
}
};
Object.freeze(MipmapHint);
var MipmapHint_default = 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;
};
Object.freeze(TextureMagnificationFilter);
var TextureMagnificationFilter_default = 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 = 6.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 = 7.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 = 8.0;\n";
// packages/engine/Source/Shaders/Builtin/Constants/passCesium3DTileEdges.js
var passCesium3DTileEdges_default = "/**\n * The automatic GLSL constant for {@link Pass#CESIUM_3D_TILE_EDGES}\n *\n * @name czm_passCesium3DTileEdges\n * @glslConstant\n *\n * @see czm_pass\n */\nconst float czm_passCesium3DTileEdges = 4.0;\n\n";
// packages/engine/Source/Shaders/Builtin/Constants/passCesium3DTileEdgesDirect.js
var passCesium3DTileEdgesDirect_default = "/**\n * The automatic GLSL constant for {@link Pass#CESIUM_3D_TILE_EDGES_DIRECT}\n *\n * @name czm_passCesium3DTileEdgesDirect\n * @glslConstant\n *\n * @see czm_pass\n */\nconst float czm_passCesium3DTileEdgesDirect = 12.0;\n";
// packages/engine/Source/Shaders/Builtin/Constants/passCesium3DTilePlanarFillId.js
var passCesium3DTilePlanarFillId_default = "/**\n * The automatic GLSL constant for {@link Pass#CESIUM_3D_TILE_PLANAR_FILL_ID}\n *\n * @name czm_passCesium3DTilePlanarFillId\n * @glslConstant\n *\n * @see czm_pass\n */\nconst float czm_passCesium3DTilePlanarFillId = 5.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 = 8.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/passGaussianSplats.js
var passGaussianSplats_default = "/**\n * The automatic GLSL constant for {@link Pass#GAUSSIAN_SPLATS}\n *\n * @name czm_passGaussianSplats\n * @glslConstant\n *\n * @see czm_pass\n */\nconst float czm_passGaussianSplats = 12.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 = 9.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 = 13.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 = 10.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 = 11.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 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* @property {float} waterMask The value of the water mask. 0 is land, 1 is water. 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 float waterMask;\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/applyHSBShift.js
var applyHSBShift_default = "/**\n * Apply a HSB color shift to an RGB color.\n *\n * @param {vec3} rgb The color in RGB space.\n * @param {vec3} hsbShift The amount to shift each component. The xyz components correspond to hue, saturation, and brightness. Shifting the hue by +/- 1.0 corresponds to shifting the hue by a full cycle. Saturation and brightness are clamped between 0 and 1 after the adjustment\n * @param {bool} ignoreBlackPixels If true, black pixels will be unchanged. This is necessary in some shaders such as atmosphere-related effects.\n *\n * @return {vec3} The RGB color after shifting in HSB space and clamping saturation and brightness to a valid range.\n */\nvec3 czm_applyHSBShift(vec3 rgb, vec3 hsbShift, bool ignoreBlackPixels) {\n // Convert rgb color to hsb\n vec3 hsb = czm_RGBToHSB(rgb);\n\n // Perform hsb shift\n // Hue cycles around so no clamp is needed.\n hsb.x += hsbShift.x; // hue\n hsb.y = clamp(hsb.y + hsbShift.y, 0.0, 1.0); // saturation\n\n // brightness\n //\n // Some shaders such as atmosphere-related effects need to leave black\n // pixels unchanged\n if (ignoreBlackPixels) {\n hsb.z = hsb.z > czm_epsilon7 ? hsb.z + hsbShift.z : 0.0;\n } else {\n hsb.z = hsb.z + hsbShift.z;\n }\n hsb.z = clamp(hsb.z, 0.0, 1.0);\n\n // Convert shifted hsb back to rgb\n return czm_HSBToRGB(hsb);\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/approximateTanh.js
var approximateTanh_default = "/**\n * Compute a rational approximation to tanh(x)\n *\n * @param {float} x A real number input\n * @returns {float} An approximation for tanh(x)\n*/\nfloat czm_approximateTanh(float x) {\n float x2 = x * x;\n return max(-1.0, min(1.0, x * (27.0 + x2) / (27.0 + 9.0 * x2)));\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/clipPolygons.js
var clipPolygons_default = "float getSignedDistance(vec2 uv, highp sampler2D clippingDistance) {\n float signedDistance = texture(clippingDistance, uv).r;\n return (signedDistance - 0.5) * 2.0;\n}\n\nvoid czm_clipPolygons(highp sampler2D clippingDistance, int extentsLength, vec2 clippingPosition, int regionIndex) {\n // Position is completely outside of polygons bounds\n vec2 rectUv = clippingPosition;\n if (regionIndex < 0 || rectUv.x <= 0.0 || rectUv.y <= 0.0 || rectUv.x >= 1.0 || rectUv.y >= 1.0) {\n #ifdef CLIPPING_INVERSE \n discard;\n #endif\n return;\n }\n\n vec2 clippingDistanceTextureDimensions = vec2(textureSize(clippingDistance, 0));\n vec2 sampleOffset = max(1.0 / clippingDistanceTextureDimensions, vec2(0.005));\n float dimension = float(extentsLength);\n if (extentsLength > 2) {\n dimension = ceil(log2(float(extentsLength)));\n }\n\n vec2 textureOffset = vec2(mod(float(regionIndex), dimension), floor(float(regionIndex) / dimension)) / dimension;\n vec2 uv = textureOffset + rectUv / dimension;\n\n float signedDistance = getSignedDistance(uv, clippingDistance);\n\n #ifdef CLIPPING_INVERSE\n if (signedDistance > 0.0) {\n discard;\n }\n #else\n if (signedDistance < 0.0) {\n discard;\n }\n #endif\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 // We're manually doing the equivalent of a `mix` here because, some GPUs\n // (NVidia GeForce 3070 Ti and Intel Arc A750, to name two), `mix` seems to\n // use an alternate formulation that introduces jitter even when `time` is\n // 0.0 or 1.0. That is, the value of `p` won't be exactly `position2D.xyz`\n // when `time` is 0.0 and it won't be exactly `position3D.xyz` when `time` is\n // 1.0. The \"textbook\" formulation here, while probably a bit slower,\n // does not have this problem.\n vec3 p = position2D.xyz * (1.0 - time) + position3D.xyz * time;\n return vec4(p, 1.0);\n}\n";
// packages/engine/Source/Shaders/Builtin/Functions/computeAtmosphereColor.js
var computeAtmosphereColor_default = "/**\n * Compute the atmosphere color, applying Rayleigh and Mie scattering. This\n * builtin uses automatic uniforms so the atmophere settings are synced with the\n * state of the Scene, even in other contexts like Model.\n *\n * @name czm_computeAtmosphereColor\n * @glslFunction\n *\n * @param {vec3} positionWC Position of the fragment in world coords (low precision)\n * @param {vec3} lightDirection Light direction from the sun or other light source.\n * @param {vec3} rayleighColor The Rayleigh scattering color computed by a scattering function\n * @param {vec3} mieColor The Mie scattering color computed by a scattering function\n * @param {float} opacity The opacity computed by a scattering function.\n */\nvec4 czm_computeAtmosphereColor(\n vec3 positionWC,\n vec3 lightDirection,\n vec3 rayleighColor,\n vec3 mieColor,\n float opacity\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\n float cosAngle = dot(cameraToPositionWCDirection, lightDirection);\n float cosAngleSq = cosAngle * cosAngle;\n\n float G = czm_atmosphereMieAnisotropy;\n float GSq = G * G;\n\n // The Rayleigh phase function.\n float rayleighPhase = 3.0 / (50.2654824574) * (1.0 + cosAngleSq);\n // The Mie phase function.\n float miePhase = 3.0 / (25.1327412287) * ((1.0 - GSq) * (cosAngleSq + 1.0)) / (pow(1.0 + GSq - 2.0 * cosAngle * G, 1.5) * (2.0 + GSq));\n\n // The final color is generated by combining the effects of the Rayleigh and Mie scattering.\n vec3 rayleigh = rayleighPhase * rayleighColor;\n vec3 mie = miePhase * mieColor;\n\n vec3 color = (rayleigh + mie) * czm_atmosphereLightIntensity;\n\n return vec4(color, opacity);\n}\n\n/**\n * Compute the atmosphere color, applying Rayleigh and Mie scattering. This\n * builtin uses automatic uniforms so the atmophere settings are synced with the\n * state of the Scene, even in other contexts like Model.\n *\n * @name czm_computeAtmosphereColor\n * @glslFunction\n *\n * @param {czm_ray} primaryRay Ray from the origin to sky fragment to in world coords (low precision)\n * @param {vec3} lightDirection Light direction from the sun or other light source.\n * @param {vec3} rayleighColor The Rayleigh scattering color computed by a scattering function\n * @param {vec3} mieColor The Mie scattering color computed by a scattering function\n * @param {float} opacity The opacity computed by a scattering function.\n */\nvec4 czm_computeAtmosphereColor(\n czm_ray primaryRay,\n vec3 lightDirection,\n vec3 rayleighColor,\n vec3 mieColor,\n float opacity\n) {\n vec3 direction = normalize(primaryRay.direction);\n\n float cosAngle = dot(direction, lightDirection);\n float cosAngleSq = cosAngle * cosAngle;\n\n float G = czm_atmosphereMieAnisotropy;\n float GSq = G * G;\n\n // The Rayleigh phase function.\n float rayleighPhase = 3.0 / (50.2654824574) * (1.0 + cosAngleSq);\n // The Mie phase function.\n float miePhase = 3.0 / (25.1327412287) * ((1.0 - GSq) * (cosAngleSq + 1.0)) / (pow(1.0 + GSq - 2.0 * cosAngle * G, 1.5) * (2.0 + GSq));\n\n // The final color is generated by combining the effects of the Rayleigh and Mie scattering.\n vec3 rayleigh = rayleighPhase * rayleighColor;\n vec3 mie = miePhase * mieColor;\n\n vec3 color = (rayleigh + mie) * czm_atmosphereLightIntensity;\n\n return vec4(color, opacity);\n}\n\n";
// packages/engine/Source/Shaders/Builtin/Functions/computeGroundAtmosphereScattering.js
var computeGroundAtmosphereScattering_default = "/**\n * Compute atmosphere scattering for the ground atmosphere and fog. This method\n * uses automatic uniforms so it is always synced with the scene settings.\n *\n * @name czm_computeGroundAtmosphereScattering\n * @glslfunction\n *\n * @param {vec3} positionWC The position of the fragment in world coordinates.\n * @param {vec3} lightDirection The direction of the light to calculate the scattering from.\n * @param {vec3} rayleighColor The variable the Rayleigh scattering will be written to.\n * @param {vec3} mieColor The variable the Mie scattering will be written to.\n * @param {float} opacity The variable the transmittance will be written to.\n */\nvoid czm_computeGroundAtmosphereScattering(vec3 positionWC, vec3 lightDirection, out vec3 rayleighColor, out vec3 mieColor, out float opacity) {\n vec3 cameraToPositionWC = positionWC - czm_viewerPositionWC;\n vec3 cameraToPositionWCDirection = normalize(cameraToPositionWC);\n czm_ray primaryRay = czm_ray(czm_viewerPositionWC, cameraToPositionWCDirection);\n\n float atmosphereInnerRadius = length(positionWC);\n\n czm_computeScattering(\n primaryRay,\n length(cameraToPositionWC),\n lightDirection,\n atmosphereInnerRadius,\n rayleighColor,\n mieColor,\n opacity\n );\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 coordinates\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/ellipsoidTextureCoordinates.js
var ellipsoidTextureCoordinates_default = "/**\n * Approximate uv coordinates based on the ellipsoid normal.\n *\n * @name czm_ellipsoidTextureCoordinates\n * @glslFunction\n */\nvec2 czm_ellipsoidTextureCoordinates(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 floats, vec2s,\n * vec3s, or vec4s.\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/getDynamicAtmosphereLightDirection.js
var getDynamicAtmosphereLightDirection_default = "/**\n * Select which direction vector to use for dynamic atmosphere lighting based on an enum value\n *\n * @name czm_getDynamicAtmosphereLightDirection\n * @glslfunction\n * @see DynamicAtmosphereLightingType.js\n *\n * @param {vec3} positionWC the position of the vertex/fragment in world coordinates. This is normalized and returned when dynamic lighting is turned off.\n * @param {float} lightEnum The enum value for selecting between light sources.\n * @return {vec3} The normalized light direction vector. Depending on the enum value, it is either positionWC, czm_lightDirectionWC or czm_sunDirectionWC\n */\nvec3 czm_getDynamicAtmosphereLightDirection(vec3 positionWC, float lightEnum) {\n const float NONE = 0.0;\n const float SCENE_LIGHT = 1.0;\n const float SUNLIGHT = 2.0;\n\n vec3 lightDirection =\n positionWC * float(lightEnum == NONE) +\n czm_lightDirectionWC * float(lightEnum == SCENE_LIGHT) +\n czm_sunDirectionWC * float(lightEnum == SUNLIGHT);\n return normalize(lightDirection);\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/maximumComponent.js
var maximumComponent_default = "/**\n * Find the maximum component of a vector.\n *\n * @name czm_maximumComponent\n * @glslFunction\n *\n * @param {vec2|vec3|vec4} v The input vector.\n * @returns {float} The value of the largest component.\n */\nfloat czm_maximumComponent(vec2 v)\n{\n return max(v.x, v.y);\n}\nfloat czm_maximumComponent(vec3 v)\n{\n return max(max(v.x, v.y), v.z);\n}\nfloat czm_maximumComponent(vec4 v)\n{\n return max(max(max(v.x, v.y), v.z), v.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 positionEC = czm_modelView * position;\n vec4 q = czm_projection * positionEC;\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 vec4 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 {vec4} 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 float versine = 1.0 - VdotH;\n // pow(versine, 5.0) is slow. See https://stackoverflow.com/a/68793086/10082269\n float versineSquared = versine * versine;\n return f0 + (f90 - f0) * versineSquared * versineSquared * versine;\n}\n\n#ifdef USE_ANISOTROPY\n/**\n * @param {float} bitangentRoughness Material roughness (along the anisotropy bitangent)\n * @param {float} tangentialRoughness Anisotropic roughness (along the anisotropy tangent)\n * @param {vec3} lightDirection The direction from the fragment to the light source, transformed to tangent-bitangent-normal coordinates\n * @param {vec3} viewDirection The direction from the fragment to the camera, transformed to tangent-bitangent-normal coordinates\n */\nfloat smithVisibilityGGX_anisotropic(float bitangentRoughness, float tangentialRoughness, vec3 lightDirection, vec3 viewDirection)\n{\n vec3 roughnessScale = vec3(tangentialRoughness, bitangentRoughness, 1.0);\n float GGXV = lightDirection.z * length(roughnessScale * viewDirection);\n float GGXL = viewDirection.z * length(roughnessScale * lightDirection);\n float v = 0.5 / (GGXV + GGXL);\n return clamp(v, 0.0, 1.0);\n}\n\n/**\n * @param {float} bitangentRoughness Material roughness (along the anisotropy bitangent)\n * @param {float} tangentialRoughness Anisotropic roughness (along the anisotropy tangent)\n * @param {vec3} halfwayDirection The unit vector halfway between light and view directions, transformed to tangent-bitangent-normal coordinates\n */\nfloat GGX_anisotropic(float bitangentRoughness, float tangentialRoughness, vec3 halfwayDirection)\n{\n float roughnessSquared = bitangentRoughness * tangentialRoughness;\n vec3 f = halfwayDirection * vec3(bitangentRoughness, tangentialRoughness, roughnessSquared);\n float w2 = roughnessSquared / dot(f, f);\n return roughnessSquared * w2 * w2 / czm_pi;\n}\n#endif\n\n/**\n * Estimate the geometric self-shadowing of the microfacets in a surface,\n * using the Smith Joint GGX visibility function.\n * Note: Vis = G / (4 * NdotL * NdotV)\n * see Eric Heitz. 2014. Understanding the Masking-Shadowing Function in Microfacet-Based BRDFs. Journal of Computer Graphics Techniques, 3\n * see Real-Time Rendering. Page 331 to 336.\n * see https://google.github.io/filament/Filament.md.html#materialsystem/specularbrdf/geometricshadowing(specularg)\n *\n * @param {float} alphaRoughness The roughness of the material, expressed as the square of perceptual roughness.\n * @param {float} NdotL The cosine of the angle between the surface normal and the direction to the light source.\n * @param {float} NdotV The cosine of the angle between the surface normal and the direction to the camera.\n */\nfloat smithVisibilityGGX(float alphaRoughness, float NdotL, float NdotV)\n{\n float alphaRoughnessSq = alphaRoughness * alphaRoughness;\n\n float GGXV = NdotL * sqrt(NdotV * NdotV * (1.0 - alphaRoughnessSq) + alphaRoughnessSq);\n float GGXL = NdotV * sqrt(NdotL * NdotL * (1.0 - alphaRoughnessSq) + alphaRoughnessSq);\n\n float GGX = GGXV + GGXL;\n if (GGX > 0.0)\n {\n return 0.5 / GGX;\n }\n return 0.0;\n}\n\n/**\n * Estimate the fraction of the microfacets in a surface that are aligned with \n * the halfway vector, which is aligned halfway between the directions from\n * the fragment to the camera and from the fragment to the light source.\n *\n * @param {float} alphaRoughness The roughness of the material, expressed as the square of perceptual roughness.\n * @param {float} NdotH The cosine of the angle between the surface normal and the halfway vector.\n * @return {float} The fraction of microfacets aligned to the halfway vector.\n */\nfloat GGX(float alphaRoughness, float NdotH)\n{\n float alphaRoughnessSquared = alphaRoughness * alphaRoughness;\n float f = (NdotH * alphaRoughnessSquared - NdotH) * NdotH + 1.0;\n return alphaRoughnessSquared / (czm_pi * f * f);\n}\n\n/**\n * Compute the strength of the specular reflection due to direct lighting.\n *\n * @param {vec3} normal The surface normal.\n * @param {vec3} lightDirection The unit vector pointing from the fragment to the light source.\n * @param {vec3} viewDirection The unit vector pointing from the fragment to the camera.\n * @param {vec3} halfwayDirection The unit vector pointing from the fragment to halfway between the light source and the camera.\n * @param {float} alphaRoughness The roughness of the material, expressed as the square of perceptual roughness.\n * @return {float} The strength of the specular reflection.\n */\nfloat computeDirectSpecularStrength(vec3 normal, vec3 lightDirection, vec3 viewDirection, vec3 halfwayDirection, float alphaRoughness)\n{\n float NdotL = clamp(dot(normal, lightDirection), 0.0, 1.0);\n float NdotV = clamp(dot(normal, viewDirection), 0.0, 1.0);\n float G = smithVisibilityGGX(alphaRoughness, NdotL, NdotV);\n float NdotH = clamp(dot(normal, halfwayDirection), 0.0, 1.0);\n float D = GGX(alphaRoughness, NdotH);\n return G * D;\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 = exp2(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/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/unpackClippingExtents.js
var unpackClippingExtents_default = "vec2 getLookupUv(vec2 dimensions, int i) {\n int pixY = i / int(dimensions.x);\n int pixX = i - (pixY * int(dimensions.x));\n float pixelWidth = 1.0 / dimensions.x;\n float pixelHeight = 1.0 / dimensions.y;\n float u = (float(pixX) + 0.5) * pixelWidth; // sample from center of pixel\n float v = (float(pixY) + 0.5) * pixelHeight;\n return vec2(u, v);\n}\n\nvec4 czm_unpackClippingExtents(highp sampler2D extentsTexture, int index) {\n vec2 textureDimensions = vec2(textureSize(extentsTexture, 0));\n return texture(extentsTexture, getLookupUv(textureDimensions, index));\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 */\nfloat 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/unpackTexture.js
var unpackTexture_default = "/**\n * Useful for reinterpreting texture data as higher-precision values.\n * Only works correctly in WebGL 2, which supports the uint type and bitwise operations.\n *\n * @param {float|vec2|vec3|vec4} 1-4 values from a texture lookup (RGBA channels), normalized to [0.0, 1.0].\n * @return {uint} Raw bits as an unsigned integer.\n*/\nuint czm_unpackTexture(float packedValue) {\n float rounded = czm_round(packedValue * 255.0);\n return uint(rounded);\n}\n\nuint czm_unpackTexture(vec2 packedValue) {\n vec2 rounded = czm_round(packedValue * 255.0);\n uint byte0 = uint(rounded.x);\n uint byte1 = uint(rounded.y);\n return byte0 | (byte1 << 8);\n}\n\nuint czm_unpackTexture(vec3 packedValue) {\n vec3 rounded = czm_round(packedValue * 255.0);\n uint byte0 = uint(rounded.x);\n uint byte1 = uint(rounded.y);\n uint byte2 = uint(rounded.z);\n return byte0 | (byte1 << 8) | (byte2 << 16);\n}\n\nuint czm_unpackTexture(vec4 packedValue) {\n vec4 rounded = czm_round(packedValue * 255.0);\n uint byte0 = uint(rounded.x);\n uint byte1 = uint(rounded.y);\n uint byte2 = uint(rounded.z);\n uint byte3 = uint(rounded.w);\n return byte0 | (byte1 << 8) | (byte2 << 16) | (byte3 << 24);\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 = exp2(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#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#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 ellipsoid surface normal at the camera position, in model coordinates.
* @memberof UniformState.prototype
* @type {Cartesian3}
*/
eyeEllipsoidNormalEC: {
get: function() {
return this._eyeEllipsoidNormalEC;
}
},
/**
* The ellipsoid radii of curvature at the camera position.
* The .x component is the prime vertical radius, .y is the meridional.
* @memberof UniformState.prototype
* @type {Cartesian2}
*/
eyeEllipsoidCurvature: {
get: function() {
return this._eyeEllipsoidCurvature;
}
},
/**
* A transform from model coordinates to an east-north-up coordinate system
* centered at the position on the ellipsoid below the camera
* @memberof UniformState.prototype
* @type {Matrix4}
*/
modelToEnu: {
get: function() {
return this._modelToEnu;
}
},
/**
* The inverse of {@link UniformState.prototype.modelToEnu}
* @memberof UniformState.prototype
* @type {Matrix4}
*/
enuToModel: {
get: function() {
return this._enuToModel;
}
},
/**
* 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 used to mix a color with the fog color based on the distance to the camera.
* @memberof UniformState.prototype
* @type {number}
*/
fogVisualDensityScalar: {
get: function() {
return this._fogVisualDensityScalar;
}
},
/**
* A scalar used as a minimum value when brightening fog
* @memberof UniformState.prototype
* @type {number}
*/
fogMinimumBrightness: {
get: function() {
return this._fogMinimumBrightness;
}
},
/**
* A color shift to apply to the atmosphere color in HSB.
* @memberof UniformState.prototype
* @type {Cartesian3}
*/
atmosphereHsbShift: {
get: function() {
return this._atmosphereHsbShift;
}
},
/**
* The intensity of the light that is used for computing the atmosphere color
* @memberof UniformState.prototype
* @type {number}
*/
atmosphereLightIntensity: {
get: function() {
return this._atmosphereLightIntensity;
}
},
/**
* The Rayleigh scattering coefficient used in the atmospheric scattering equations for the sky atmosphere.
* @memberof UniformState.prototype
* @type {Cartesian3}
*/
atmosphereRayleighCoefficient: {
get: function() {
return this._atmosphereRayleighCoefficient;
}
},
/**
* The Rayleigh scale height used in the atmospheric scattering equations for the sky atmosphere, in meters.
* @memberof UniformState.prototype
* @type {number}
*/
atmosphereRayleighScaleHeight: {
get: function() {
return this._atmosphereRayleighScaleHeight;
}
},
/**
* The Mie scattering coefficient used in the atmospheric scattering equations for the sky atmosphere.
* @memberof UniformState.prototype
* @type {Cartesian3}
*/
atmosphereMieCoefficient: {
get: function() {
return this._atmosphereMieCoefficient;
}
},
/**
* The Mie scale height used in the atmospheric scattering equations for the sky atmosphere, in meters.
* @memberof UniformState.prototype
* @type {number}
*/
atmosphereMieScaleHeight: {
get: function() {
return this._atmosphereMieScaleHeight;
}
},
/**
* The anisotropy of the medium to consider for Mie scattering.
* @memberof UniformState.prototype
* @type {number}
*/
atmosphereMieAnisotropy: {
get: function() {
return this._atmosphereMieAnisotropy;
}
},
/**
* Which light source to use for dynamically lighting the atmosphere
*
* @memberof UniformState.prototype
* @type {DynamicAtmosphereLightingType}
*/
atmosphereDynamicLighting: {
get: function() {
return this._atmosphereDynamicLighting;
}
},
/**
* 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 cube map of the scene.
* @memberof UniformState.prototype
* @type {Texture}
*/
specularEnvironmentMaps: {
get: function() {
return this._specularEnvironmentMaps;
}
},
/**
* The maximum level-of-detail of the specular environment cube map 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 this._ellipsoid ?? Ellipsoid_default.default;
}
}
});
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;
}
var surfacePositionScratch = new Cartesian3_default();
var enuTransformScratch = new Matrix4_default();
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 ellipsoid = uniformState._ellipsoid;
let surfacePosition;
const positionCartographic = camera.positionCartographic;
if (!defined_default(positionCartographic)) {
uniformState._eyeHeight = -ellipsoid.maximumRadius;
if (Cartesian3_default.magnitude(camera.positionWC) > 0) {
uniformState._eyeEllipsoidNormalEC = Cartesian3_default.normalize(
camera.positionWC,
uniformState._eyeEllipsoidNormalEC
);
}
surfacePosition = ellipsoid.scaleToGeodeticSurface(
camera.positionWC,
surfacePositionScratch
);
} else {
uniformState._eyeHeight = positionCartographic.height;
uniformState._eyeEllipsoidNormalEC = ellipsoid.geodeticSurfaceNormalCartographic(
positionCartographic,
uniformState._eyeEllipsoidNormalEC
);
surfacePosition = Cartesian3_default.fromRadians(
positionCartographic.longitude,
positionCartographic.latitude,
0,
ellipsoid,
surfacePositionScratch
);
}
uniformState._encodedCameraPositionMCDirty = true;
if (!defined_default(surfacePosition)) {
return;
}
uniformState._eyeEllipsoidNormalEC = Matrix3_default.multiplyByVector(
uniformState._viewRotation,
uniformState._eyeEllipsoidNormalEC,
uniformState._eyeEllipsoidNormalEC
);
const enuToWorld = Transforms_default.eastNorthUpToFixedFrame(
surfacePosition,
ellipsoid,
enuTransformScratch
);
uniformState._enuToModel = Matrix4_default.multiplyTransformation(
uniformState.inverseModel,
enuToWorld,
uniformState._enuToModel
);
uniformState._modelToEnu = Matrix4_default.inverseTransformation(
uniformState._enuToModel,
uniformState._modelToEnu
);
if (!Math_default.equalsEpsilon(
ellipsoid._radii.x,
ellipsoid._radii.y,
Math_default.EPSILON15
)) {
return;
}
uniformState._eyeEllipsoidCurvature = ellipsoid.getLocalCurvature(
surfacePosition,
uniformState._eyeEllipsoidCurvature
);
}
var transformMatrix = new Matrix3_default();
var sunCartographicScratch = new Cartographic_default();
function setSunAndMoonDirections(uniformState, frameState) {
Transforms_default.computeIcrfToCentralBodyFixedMatrix(
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 = 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 = frameState.environmentMap ?? frameState.context.defaultCubeMap;
this._sphericalHarmonicCoefficients = frameState.sphericalHarmonicCoefficients ?? EMPTY_ARRAY;
this._specularEnvironmentMaps = frameState.specularEnvironmentMaps;
this._specularEnvironmentMapsMaximumLOD = frameState.specularEnvironmentMapsMaximumLOD;
this._fogDensity = frameState.fog.density;
this._fogVisualDensityScalar = frameState.fog.visualDensityScalar;
this._fogMinimumBrightness = frameState.fog.minimumBrightness;
const atmosphere = frameState.atmosphere;
if (defined_default(atmosphere)) {
this._atmosphereHsbShift = Cartesian3_default.fromElements(
atmosphere.hueShift,
atmosphere.saturationShift,
atmosphere.brightnessShift,
this._atmosphereHsbShift
);
this._atmosphereLightIntensity = atmosphere.lightIntensity;
this._atmosphereRayleighCoefficient = Cartesian3_default.clone(
atmosphere.rayleighCoefficient,
this._atmosphereRayleighCoefficient
);
this._atmosphereRayleighScaleHeight = atmosphere.rayleighScaleHeight;
this._atmosphereMieCoefficient = Cartesian3_default.clone(
atmosphere.mieCoefficient,
this._atmosphereMieCoefficient
);
this._atmosphereMieScaleHeight = atmosphere.mieScaleHeight;
this._atmosphereMieAnisotropy = atmosphere.mieAnisotropy;
this._atmosphereDynamicLighting = atmosphere.dynamicLighting;
}
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 v3 = uniformState._viewport;
Matrix4_default.computeOrthographicOffCenter(
v3.x,
v3.x + v3.width,
v3.y,
v3.y + v3.height,
0,
1,
uniformState._viewportOrthographicMatrix
);
Matrix4_default.computeViewportTransformation(
v3,
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.transpose(m, m);
}
}
function cleanNormal3D(uniformState) {
if (uniformState._normal3DDirty) {
uniformState._normal3DDirty = false;
const m = uniformState._normal3D;
Matrix4_default.getMatrix3(uniformState.inverseModelView3D, m);
Matrix3_default.transpose(m, m);
}
}
function cleanInverseNormal(uniformState) {
if (uniformState._inverseNormalDirty) {
uniformState._inverseNormalDirty = false;
const m = uniformState._inverseNormal;
Matrix4_default.getMatrix3(uniformState.modelView, m);
Matrix3_default.transpose(m, m);
}
}
function cleanInverseNormal3D(uniformState) {
if (uniformState._inverseNormal3DDirty) {
uniformState._inverseNormal3DDirty = false;
const m = uniformState._inverseNormal3D;
Matrix4_default.getMatrix3(uniformState.modelView3D, m);
Matrix3_default.transpose(m, m);
}
}
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 r2 = view2Dto3DRScratch;
r2.x = right2D.y;
r2.y = right2D.z;
r2.z = right2D.x;
const u4 = view2Dto3DUScratch;
u4.x = up2D.y;
u4.y = up2D.z;
u4.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, r2, r2);
Matrix4_default.multiplyByPointAsVector(enuToFixed, u4, u4);
Matrix4_default.multiplyByPointAsVector(enuToFixed, d, d);
if (!defined_default(result)) {
result = new Matrix4_default();
}
result[0] = r2.x;
result[1] = u4.x;
result[2] = -d.x;
result[3] = 0;
result[4] = r2.y;
result[5] = u4.y;
result[6] = -d.y;
result[7] = 0;
result[8] = r2.z;
result[9] = u4.z;
result[10] = -d.z;
result[11] = 0;
result[12] = -Cartesian3_default.dot(r2, position3D);
result[13] = -Cartesian3_default.dot(u4, 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/Context.js
function Context(canvas, options) {
Check_default.defined("canvas", canvas);
const {
getWebGLStub,
requestWebgl1,
webgl: webglOptions = {},
allowTextureFilterAnisotropic = true
} = options ?? {};
webglOptions.alpha = webglOptions.alpha ?? false;
webglOptions.stencil = webglOptions.stencil ?? true;
webglOptions.powerPreference = 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._maximum3DTextureSize = gl.getParameter(gl.MAX_3D_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._supportsTextureLod = !!getExtension(gl, ["EXT_shader_texture_lod"]);
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, offset, instanceCount) {
gl.drawElementsInstanced(mode2, count, type, offset, 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, offset, instanceCount) {
instancedArrays.drawElementsInstancedANGLE(
mode2,
count,
type,
offset,
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 = /* @__PURE__ */ new Map();
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 length2 = names.length;
for (let i = 0; i < length2; ++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_shader_texture_lod is supported. This extension provides
* access to explicit LOD selection in texture sampling functions.
* @memberof Context.prototype
* @type {boolean}
* @see {@link https://registry.khronos.org/webgl/extensions/EXT_shader_texture_lod/}
*/
supportsTextureLod: {
get: function() {
return this._webgl2 || this._supportsTextureLod;
}
},
/**
* 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 the color defined by {@link Texture.defaultColor}.
* 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) {
const color = Texture_default.defaultColor;
this._defaultTexture = new Texture_default({
context: this,
source: {
width: 1,
height: 1,
arrayBufferView: new Uint8Array([
color.red * 255,
color.green * 255,
color.blue * 255,
color.alpha * 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 = clearCommand ?? defaultClearCommand;
passState = passState ?? this._defaultPassState;
const gl = this._gl;
let bitmask = 0;
const c14 = clearCommand.color;
const d = clearCommand.depth;
const s2 = clearCommand.stencil;
if (defined_default(c14)) {
if (!Color_default.equals(this._clearColor, c14)) {
Color_default.clone(c14, this._clearColor);
gl.clearColor(c14.red, c14.green, c14.blue, c14.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(s2)) {
if (s2 !== this._clearStencil) {
this._clearStencil = s2;
gl.clearStencil(s2);
}
bitmask |= gl.STENCIL_BUFFER_BIT;
}
const rs = clearCommand.renderState ?? this._defaultRenderState;
applyRenderState(this, rs, passState, true);
const framebuffer = 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 offset = 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", offset, 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 = drawCommand._modelMatrix ?? Matrix4_default.IDENTITY;
shaderProgram._setUniforms(
uniformMap2,
context._us,
context.validateShaderProgram
);
va._bind();
const indexBuffer = va.indexBuffer;
if (defined_default(indexBuffer)) {
offset = offset * indexBuffer.bytesPerIndex;
if (defined_default(count)) {
count = Math.min(count, indexBuffer.numberOfIndices);
} else {
count = indexBuffer.numberOfIndices;
}
if (instanceCount === 0) {
context._gl.drawElements(
primitiveType,
count,
indexBuffer.indexDatatype,
offset
);
} else {
context.glDrawElementsInstanced(
primitiveType,
count,
indexBuffer.indexDatatype,
offset,
instanceCount
);
}
} else {
if (defined_default(count)) {
count = Math.min(count, va.numberOfVertices);
} else {
count = va.numberOfVertices;
}
if (instanceCount === 0) {
context._gl.drawArrays(primitiveType, offset, count);
} else {
context.glDrawArraysInstanced(
primitiveType,
offset,
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 = passState ?? this._defaultPassState;
const framebuffer = drawCommand._framebuffer ?? passState.framebuffer;
const renderState = drawCommand._renderState ?? this._defaultRenderState;
shaderProgram = shaderProgram ?? drawCommand._shaderProgram;
uniformMap2 = uniformMap2 ?? drawCommand._uniformMap;
beginDraw(this, framebuffer, passState, shaderProgram, renderState);
continueDraw(this, drawCommand, shaderProgram, uniformMap2);
};
Context.prototype.beginFrame = function() {
};
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 length2 = this._maxFrameTextureUnitIndex;
this._maxFrameTextureUnitIndex = 0;
for (let i = 0; i < length2; ++i) {
gl.activeTexture(gl.TEXTURE0 + i);
gl.bindTexture(gl.TEXTURE_2D, null);
gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
}
};
Context.prototype.readPixelsToPBO = function(readState) {
const gl = this._gl;
readState = readState ?? Frozen_default.EMPTY_OBJECT;
const x = Math.max(readState.x ?? 0, 0);
const y = Math.max(readState.y ?? 0, 0);
const width = readState.width ?? this.drawingBufferWidth;
const height = readState.height ?? this.drawingBufferHeight;
const framebuffer = readState.framebuffer;
if (!this._webgl2) {
throw new DeveloperError_default(
"A WebGL 2 context is required to read pixels using a PBO."
);
}
Check_default.typeOf.number.greaterThan("readState.width", width, 0);
Check_default.typeOf.number.greaterThan("readState.height", height, 0);
let pixelDatatype = PixelDatatype_default.UNSIGNED_BYTE;
let pixelFormat = PixelFormat_default.RGBA;
if (defined_default(framebuffer) && framebuffer.numberOfColorAttachments > 0) {
pixelDatatype = framebuffer.getColorTexture(0).pixelDatatype;
pixelFormat = framebuffer.getColorTexture(0).pixelFormat;
}
const pixels = Buffer_default.createPixelBuffer({
context: this,
sizeInBytes: PixelFormat_default.textureSizeInBytes(
pixelFormat,
pixelDatatype,
width,
height
),
usage: BufferUsage_default.DYNAMIC_READ
});
bindFramebuffer(this, framebuffer);
pixels._bind();
gl.readPixels(
x,
y,
width,
height,
pixelFormat,
PixelDatatype_default.toWebGLConstant(pixelDatatype, this),
0
);
pixels._unBind();
return pixels;
};
Context.prototype.readPixels = function(readState) {
const gl = this._gl;
readState = readState ?? Frozen_default.EMPTY_OBJECT;
const x = Math.max(readState.x ?? 0, 0);
const y = Math.max(readState.y ?? 0, 0);
const width = readState.width ?? this.drawingBufferWidth;
const height = readState.height ?? this.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;
let pixelFormat = PixelFormat_default.RGBA;
if (defined_default(framebuffer) && framebuffer.numberOfColorAttachments > 0) {
pixelDatatype = framebuffer.getColorTexture(0).pixelDatatype;
pixelFormat = framebuffer.getColorTexture(0).pixelFormat;
}
const pixels = PixelFormat_default.createTypedArray(
pixelFormat,
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 = overrides ?? Frozen_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(pickColor4) {
Check_default.defined("pickColor", pickColor4);
return this._pickObjects.get(pickColor4);
};
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.set(key, object2);
return new PickId_default(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);
};
var Context_default = Context;
// packages/engine/Source/Renderer/MultisampleFramebuffer.js
function MultisampleFramebuffer(options) {
options = options ?? Frozen_default.EMPTY_OBJECT;
const {
context,
width,
height,
colorRenderbuffers,
colorTextures,
depthStencilRenderbuffer,
depthStencilTexture,
destroyAttachments
} = options;
Check_default.defined("options.context", context);
Check_default.defined("options.width", width);
Check_default.defined("options.height", height);
this._width = width;
this._height = height;
if (defined_default(colorRenderbuffers) !== defined_default(colorTextures)) {
throw new DeveloperError_default(
"Both color renderbuffer and texture attachments must be provided."
);
}
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
});
this._colorFramebuffer = new Framebuffer_default({
context,
colorTextures,
depthStencilTexture,
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;
}
};
Object.freeze(RenderbufferFormat);
var RenderbufferFormat_default = RenderbufferFormat;
// packages/engine/Source/Renderer/Renderbuffer.js
function Renderbuffer(options) {
options = options ?? Frozen_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 = options.format ?? RenderbufferFormat_default.RGBA4;
const width = defined_default(options.width) ? options.width : context.drawingBufferWidth;
const height = defined_default(options.height) ? options.height : context.drawingBufferHeight;
const numSamples = 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 = options ?? Frozen_default.EMPTY_OBJECT;
this._numSamples = options.numSamples ?? 1;
this._colorAttachmentsLength = options.colorAttachmentsLength ?? 1;
this._color = options.color ?? true;
this._depth = options.depth ?? false;
this._depthStencil = options.depthStencil ?? false;
this._supportsDepthTexture = 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 = options.createColorAttachments ?? true;
this._createDepthAttachments = 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 = 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 ? numSamples ?? 1 : 1;
pixelDatatype = pixelDatatype ?? (this._color ? this._pixelDatatype ?? PixelDatatype_default.UNSIGNED_BYTE : void 0);
pixelFormat = pixelFormat ?? (this._color ? 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 = 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 = 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 = 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 = 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) {
const colorTextures = this._colorTextures;
const colorRenderbuffers = this._colorRenderbuffers;
for (let i = 0; i < colorTextures.length; ++i) {
const texture = colorTextures[i];
if (this._createColorAttachments) {
if (defined_default(texture) && !texture.isDestroyed()) {
texture.destroy();
}
}
if (defined_default(texture) && texture.isDestroyed()) {
colorTextures[i] = void 0;
}
const renderbuffer = colorRenderbuffers[i];
if (this._createColorAttachments) {
if (defined_default(renderbuffer) && !renderbuffer.isDestroyed()) {
renderbuffer.destroy();
}
}
if (defined_default(renderbuffer) && renderbuffer.isDestroyed()) {
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 = {
NONE: 0,
VERTEX: 1,
FRAGMENT: 2,
BOTH: 3
};
ShaderDestination.includesVertexShader = function(destination) {
Check_default.typeOf.number("destination", destination);
return (destination & ShaderDestination.VERTEX) !== 0;
};
ShaderDestination.includesFragmentShader = function(destination) {
Check_default.typeOf.number("destination", destination);
return (destination & ShaderDestination.FRAGMENT) !== 0;
};
ShaderDestination.union = function(...destinations) {
if (destinations.length === 0) {
throw new DeveloperError_default(
"ShaderDestination.union requires at least one destination."
);
}
let result = 0;
for (let i = 0; i < destinations.length; i++) {
result |= destinations[i];
}
return result;
};
ShaderDestination.intersection = function(...destinations) {
if (destinations.length === 0) {
throw new DeveloperError_default(
"ShaderDestination.intersection requires at least one destination."
);
}
let result = destinations[0];
for (let i = 1; i < destinations.length; i++) {
result &= destinations[i];
}
return result;
};
Object.freeze(ShaderDestination);
var ShaderDestination_default = 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 length2 = lines.length;
for (let i = 0; i < length2; 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/Core/addAllToArray.js
function addAllToArray(target, source) {
if (!defined_default(source)) {
return;
}
const sourceLength = source.length;
if (sourceLength === 0) {
return;
}
const targetLength = target.length;
target.length += sourceLength;
for (let i = 0; i < sourceLength; i++) {
target[targetLength + i] = source[i];
}
}
var addAllToArray_default = addAllToArray;
// 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 {Objectundefined until the first update.
* @memberof TextureAtlas.prototype
* @type {Texture|undefined}
* @readonly
* @private
*/
texture: {
get: function() {
return this._texture;
}
},
/**
* The pixel format of the texture.
* @memberof TextureAtlas.prototype
* @type {PixelFormat}
* @readonly
* @private
*/
pixelFormat: {
get: function() {
return this._pixelFormat;
}
},
/**
* The sampler to use when sampling this texture. If undefined, the default sampler is used.
* @memberof TextureAtlas.prototype
* @type {Sampler|undefined}
* @readonly
* @private
*/
sampler: {
get: function() {
return this._sampler;
}
},
/**
* The number of images in the texture atlas. This value increases
* every time addImage or addImageSubRegion is called.
* Texture coordinates are subject to change if the texture atlas resizes, so it is
* important to check {@link TextureAtlas#guid} before using old values.
* @memberof TextureAtlas.prototype
* @type {number}
* @readonly
* @private
*/
numberOfImages: {
get: function() {
return this._nextIndex;
}
},
/**
* 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}
* @readonly
* @private
*/
guid: {
get: function() {
return this._guid;
}
},
/**
* Returns the size in bytes of the texture.
* @memberof TextureAtlas.prototype
* @type {number}
* @readonly
* @private
*/
sizeInBytes: {
get: function() {
if (!defined_default(this._texture)) {
return 0;
}
return this._texture.sizeInBytes;
}
}
});
TextureAtlas.prototype.computeTextureCoordinates = function(index, result) {
Check_default.typeOf.number.greaterThanOrEquals("index", index, 0);
const texture = this._texture;
const rectangle = this._rectangles[index];
if (!defined_default(result)) {
result = new BoundingRectangle_default();
}
if (!defined_default(rectangle)) {
result.x = 0;
result.y = 0;
result.width = 0;
result.height = 0;
return result;
}
const atlasWidth = texture.width;
const atlasHeight = texture.height;
const width = rectangle.width;
const height = rectangle.height;
let x = rectangle.x;
let y = rectangle.y;
const parentIndex = this._subRegions.get(index);
if (defined_default(parentIndex)) {
const parentRectangle = this._rectangles[parentIndex];
x += parentRectangle.x;
y += parentRectangle.y;
}
result.x = x / atlasWidth;
result.y = y / atlasHeight;
result.width = width / atlasWidth;
result.height = height / atlasHeight;
return result;
};
TextureAtlas.prototype._copyFromTexture = function(context, width, height, rectangles) {
const pixelFormat = this._pixelFormat;
const sampler = this._sampler;
const newTexture = new Texture_default({
context,
height,
width,
pixelFormat,
sampler
});
const gl = context._gl;
const target = newTexture._textureTarget;
const oldTexture = this._texture;
const framebuffer = new Framebuffer_default({
context,
colorTextures: [oldTexture],
destroyAttachments: false
});
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(target, newTexture._texture);
framebuffer._bind();
const oldRectangles = this.rectangles;
const subRegions = this._subRegions;
for (let index = 0; index < oldRectangles.length; ++index) {
const rectangle = rectangles[index];
const frameBufferOffset = oldRectangles[index];
if (!defined_default(rectangle) || !defined_default(frameBufferOffset) || defined_default(subRegions.get(index))) {
continue;
}
const { x, y, width: width2, height: height2 } = rectangle;
gl.copyTexSubImage2D(
target,
0,
x,
y,
frameBufferOffset.x,
frameBufferOffset.y,
width2,
height2
);
}
gl.bindTexture(target, null);
newTexture._initialized = true;
framebuffer._unBind();
framebuffer.destroy();
return newTexture;
};
TextureAtlas.prototype._resize = function(context, queueOffset = 0) {
const borderPadding = this._borderWidthInPixels;
const oldRectangles = this._rectangles;
const queue = this._imagesToAddQueue;
const oldTexture = this._texture;
let width = oldTexture.width;
let height = oldTexture.height;
const subRegions = this._subRegions;
const toPack = oldRectangles.map((image, index) => {
return new AddImageRequest({ index, image });
}).filter(
(request, index) => defined_default(request.image) && !defined_default(subRegions.get(index))
);
let maxWidth = 0;
let maxHeight = 0;
let areaQueued = 0;
for (let i = queueOffset; i < queue.length; ++i) {
const { width: width2, height: height2 } = queue[i].image;
maxWidth = Math.max(maxWidth, width2);
maxHeight = Math.max(maxHeight, height2);
areaQueued += width2 * height2;
toPack.push(queue[i]);
}
width = Math_default.nextPowerOfTwo(Math.max(maxWidth, width));
height = Math_default.nextPowerOfTwo(Math.max(maxHeight, height));
while (areaQueued >= width * height) {
if (width > height) {
height *= 2;
} else {
width *= 2;
}
}
toPack.sort(
({ image: imageA }, { image: imageB }) => imageB.height * imageB.width - imageA.height * imageA.width
);
const newRectangles = new Array(this._nextIndex);
for (const index of this._subRegions.keys()) {
if (defined_default(subRegions.get(index))) {
newRectangles[index] = oldRectangles[index];
}
}
let texturePacker, packed = false;
while (!packed) {
texturePacker = new TexturePacker_default({ height, width, borderPadding });
let i;
for (i = 0; i < toPack.length; ++i) {
const { index, image } = toPack[i];
if (!defined_default(image)) {
continue;
}
const repackedNode = texturePacker.pack(index, image);
if (!defined_default(repackedNode)) {
if (width > height) {
height *= 2;
} else {
width *= 2;
}
break;
}
newRectangles[index] = repackedNode.rectangle;
}
packed = i === toPack.length;
}
this._texturePacker = texturePacker;
this._texture = this._copyFromTexture(context, width, height, newRectangles);
oldTexture.destroy();
this._rectangles = newRectangles;
this._guid = createGuid_default();
};
TextureAtlas.prototype.getImageIndex = function(id) {
Check_default.typeOf.string("id", id);
return this._indexById.get(id);
};
TextureAtlas.prototype._copyImageToTexture = function({
index,
image,
resolve: resolve2,
reject
}) {
const texture = this._texture;
const rectangle = this._rectangles[index];
try {
texture.copyFrom({
source: image,
xOffset: rectangle.x,
yOffset: rectangle.y
});
if (defined_default(resolve2)) {
resolve2(index);
}
} catch (e) {
if (defined_default(reject)) {
reject(e);
return;
}
}
};
function AddImageRequest({ index, image, resolve: resolve2, reject }) {
this.index = index;
this.image = image;
this.resolve = resolve2;
this.reject = reject;
this.rectangle = void 0;
}
TextureAtlas.prototype._addImage = function(index, image) {
Check_default.typeOf.number.greaterThanOrEquals("index", index, 0);
Check_default.defined("image", image);
return new Promise((resolve2, reject) => {
this._imagesToAddQueue.push(
new AddImageRequest({
index,
image,
resolve: resolve2,
reject
})
);
this._imagesToAddQueue.sort(
({ image: imageA }, { image: imageB }) => imageB.height * imageB.width - imageA.height * imageA.width
);
});
};
TextureAtlas.prototype._processImageQueue = function(context) {
const queue = this._imagesToAddQueue;
if (queue.length === 0) {
return false;
}
this._rectangles.length = this._nextIndex;
let i, error;
for (i = 0; i < queue.length; ++i) {
const imageRequest = queue[i];
const { image, index } = imageRequest;
const node = this._texturePacker.pack(index, image);
if (!defined_default(node)) {
try {
this._resize(context, i);
} catch (e) {
error = e;
if (defined_default(imageRequest.reject)) {
imageRequest.reject(error);
}
}
break;
}
this._rectangles[index] = node.rectangle;
}
if (defined_default(error)) {
for (i = i + 1; i < queue.length; ++i) {
const { resolve: resolve2 } = queue[i];
if (defined_default(resolve2)) {
resolve2(-1);
}
}
queue.length = 0;
return false;
}
for (let i2 = 0; i2 < queue.length; ++i2) {
this._copyImageToTexture(queue[i2]);
}
queue.length = 0;
return true;
};
TextureAtlas.prototype.update = function(context) {
if (!defined_default(this._texture)) {
const width = this._initialSize.x;
const height = this._initialSize.y;
const pixelFormat = this._pixelFormat;
const sampler = this._sampler;
const borderPadding = this._borderWidthInPixels;
this._texture = new Texture_default({
context,
width,
height,
pixelFormat,
sampler
});
this._texturePacker = new TexturePacker_default({
height,
width,
borderPadding
});
}
return this._processImageQueue(context);
};
async function resolveImage(image, id) {
if (typeof image === "function") {
image = image(id);
}
if (typeof image === "string" || image instanceof Resource_default) {
const resource = Resource_default.createIfNeeded(image);
image = resource.fetchImage();
}
return image;
}
TextureAtlas.prototype.addImage = function(id, image, width, height) {
Check_default.typeOf.string("id", id);
Check_default.defined("image", image);
let promise = this._indexPromiseById.get(id);
let index = this._indexById.get(id);
if (defined_default(promise)) {
return promise;
}
if (defined_default(index)) {
return index;
}
index = this._nextIndex++;
this._indexById.set(id, index);
const resolveAndAddImage = async () => {
const resolvedImage = await resolveImage(image, id);
Check_default.defined("image", resolvedImage);
if (this.isDestroyed() || !defined_default(resolvedImage)) {
this._indexPromiseById.delete(id);
return -1;
}
if (defined_default(width)) {
resolvedImage.width = width;
}
if (defined_default(height)) {
resolvedImage.height = height;
}
const imageIndex = await this._addImage(index, resolvedImage);
this._indexPromiseById.delete(id);
return imageIndex;
};
promise = resolveAndAddImage();
this._indexPromiseById.set(id, promise);
return promise;
};
TextureAtlas.prototype.getCachedImageSubRegion = function(id, subRegion, imageIndex) {
const imagePromise = this._indexPromiseById.get(id);
for (const [index, parentIndex] of this._subRegions.entries()) {
if (imageIndex === parentIndex) {
const boundingRegion = this._rectangles[index];
if (boundingRegion.equals(subRegion)) {
if (imagePromise) {
return imagePromise.then(
(resolvedImageIndex) => resolvedImageIndex === -1 ? -1 : index
);
}
return index;
}
}
}
};
TextureAtlas.prototype.addImageSubRegion = function(id, subRegion) {
Check_default.typeOf.string("id", id);
Check_default.defined("subRegion", subRegion);
const imageIndex = this._indexById.get(id);
if (!defined_default(imageIndex)) {
throw new RuntimeError_default(`image with id "${id}" not found in the atlas.`);
}
let index = this.getCachedImageSubRegion(id, subRegion, imageIndex);
if (defined_default(index)) {
return index;
}
index = this._nextIndex++;
this._subRegions.set(index, imageIndex);
this._rectangles[index] = subRegion.clone();
const indexPromise = this._indexPromiseById.get(id) ?? Promise.resolve(imageIndex);
return indexPromise.then((imageIndex2) => {
if (imageIndex2 === -1) {
return -1;
}
const rectangle = this._rectangles[imageIndex2];
Check_default.typeOf.number.lessThanOrEquals(
"subRegion.x",
subRegion.x,
rectangle.width
);
Check_default.typeOf.number.lessThanOrEquals(
"subRegion.x + subRegion.width",
subRegion.x + subRegion.width,
rectangle.width
);
Check_default.typeOf.number.lessThanOrEquals(
"subRegion.y",
subRegion.y,
rectangle.height
);
Check_default.typeOf.number.lessThanOrEquals(
"subRegion.y + subRegion.height",
subRegion.y + subRegion.height,
rectangle.height
);
return index;
});
};
TextureAtlas.prototype.isDestroyed = function() {
return false;
};
TextureAtlas.prototype.destroy = function() {
this._texture = this._texture && this._texture.destroy();
this._imagesToAddQueue.forEach(({ resolve: resolve2 }) => {
if (defined_default(resolve2)) {
resolve2(-1);
}
});
return destroyObject_default(this);
};
var TextureAtlas_default = TextureAtlas;
// packages/engine/Source/Renderer/VertexArrayFacade.js
function VertexArrayFacade(context, attributes, sizeInVertices, instanced) {
Check_default.defined("context", context);
if (!attributes || attributes.length === 0) {
throw new DeveloperError_default("At least one attribute is required.");
}
const attrs = VertexArrayFacade._verifyAttributes(attributes);
sizeInVertices = sizeInVertices ?? 0;
const precreatedAttributes = [];
const attributesByUsage = {};
let attributesForUsage;
let usage;
const length2 = attrs.length;
for (let i = 0; i < length2; ++i) {
const attribute = attrs[i];
if (attribute.vertexBuffer) {
precreatedAttributes.push(attribute);
continue;
}
usage = attribute.usage;
attributesForUsage = attributesByUsage[usage];
if (!defined_default(attributesForUsage)) {
attributesForUsage = attributesByUsage[usage] = [];
}
attributesForUsage.push(attribute);
}
function compare(left, right) {
return ComponentDatatype_default.getSizeInBytes(right.componentDatatype) - ComponentDatatype_default.getSizeInBytes(left.componentDatatype);
}
this._allBuffers = [];
for (usage in attributesByUsage) {
if (attributesByUsage.hasOwnProperty(usage)) {
attributesForUsage = attributesByUsage[usage];
attributesForUsage.sort(compare);
const vertexSizeInBytes = VertexArrayFacade._vertexSizeInBytes(attributesForUsage);
const bufferUsage = attributesForUsage[0].usage;
const buffer2 = {
vertexSizeInBytes,
vertexBuffer: void 0,
usage: bufferUsage,
needsCommit: false,
arrayBuffer: void 0,
arrayViews: VertexArrayFacade._createArrayViews(
attributesForUsage,
vertexSizeInBytes
)
};
this._allBuffers.push(buffer2);
}
}
this._size = 0;
this._instanced = instanced ?? false;
this._precreated = precreatedAttributes;
this._context = context;
this.writers = void 0;
this.va = void 0;
this.resize(sizeInVertices);
}
VertexArrayFacade._verifyAttributes = function(attributes) {
const attrs = [];
for (let i = 0; i < attributes.length; ++i) {
const attribute = attributes[i];
const attr = {
index: attribute.index ?? i,
enabled: attribute.enabled ?? true,
componentsPerAttribute: attribute.componentsPerAttribute,
componentDatatype: attribute.componentDatatype ?? ComponentDatatype_default.FLOAT,
normalize: attribute.normalize ?? false,
// There will be either a vertexBuffer or an [optional] usage.
vertexBuffer: attribute.vertexBuffer,
usage: attribute.usage ?? BufferUsage_default.STATIC_DRAW
};
attrs.push(attr);
if (attr.componentsPerAttribute !== 1 && attr.componentsPerAttribute !== 2 && attr.componentsPerAttribute !== 3 && attr.componentsPerAttribute !== 4) {
throw new DeveloperError_default(
"attribute.componentsPerAttribute must be in the range [1, 4]."
);
}
const datatype = attr.componentDatatype;
if (!ComponentDatatype_default.validate(datatype)) {
throw new DeveloperError_default(
"Attribute must have a valid componentDatatype or not specify it."
);
}
if (!BufferUsage_default.validate(attr.usage)) {
throw new DeveloperError_default(
"Attribute must have a valid usage or not specify it."
);
}
}
const uniqueIndices = new Array(attrs.length);
for (let j = 0; j < attrs.length; ++j) {
const currentAttr = attrs[j];
const index = currentAttr.index;
if (uniqueIndices[index]) {
throw new DeveloperError_default(
`Index ${index} is used by more than one attribute.`
);
}
uniqueIndices[index] = true;
}
return attrs;
};
VertexArrayFacade._vertexSizeInBytes = function(attributes) {
let sizeInBytes = 0;
const length2 = attributes.length;
for (let i = 0; i < length2; ++i) {
const attribute = attributes[i];
sizeInBytes += attribute.componentsPerAttribute * ComponentDatatype_default.getSizeInBytes(attribute.componentDatatype);
}
const maxComponentSizeInBytes = length2 > 0 ? ComponentDatatype_default.getSizeInBytes(attributes[0].componentDatatype) : 0;
const remainder = maxComponentSizeInBytes > 0 ? sizeInBytes % maxComponentSizeInBytes : 0;
const padding = remainder === 0 ? 0 : maxComponentSizeInBytes - remainder;
sizeInBytes += padding;
return sizeInBytes;
};
VertexArrayFacade._createArrayViews = function(attributes, vertexSizeInBytes) {
const views = [];
let offsetInBytes = 0;
const length2 = attributes.length;
for (let i = 0; i < length2; ++i) {
const attribute = attributes[i];
const componentDatatype = attribute.componentDatatype;
views.push({
index: attribute.index,
enabled: attribute.enabled,
componentsPerAttribute: attribute.componentsPerAttribute,
componentDatatype,
normalize: attribute.normalize,
offsetInBytes,
vertexSizeInComponentType: vertexSizeInBytes / ComponentDatatype_default.getSizeInBytes(componentDatatype),
view: void 0
});
offsetInBytes += attribute.componentsPerAttribute * ComponentDatatype_default.getSizeInBytes(componentDatatype);
}
return views;
};
VertexArrayFacade.prototype.resize = function(sizeInVertices) {
this._size = sizeInVertices;
const allBuffers = this._allBuffers;
this.writers = [];
for (let i = 0, len = allBuffers.length; i < len; ++i) {
const buffer2 = allBuffers[i];
VertexArrayFacade._resize(buffer2, this._size);
VertexArrayFacade._appendWriters(this.writers, buffer2);
}
destroyVA(this);
};
VertexArrayFacade._resize = function(buffer2, size) {
if (buffer2.vertexSizeInBytes > 0) {
const arrayBuffer = new ArrayBuffer(size * buffer2.vertexSizeInBytes);
if (defined_default(buffer2.arrayBuffer)) {
const destView = new Uint8Array(arrayBuffer);
const sourceView = new Uint8Array(buffer2.arrayBuffer);
const sourceLength = sourceView.length;
for (let j = 0; j < sourceLength; ++j) {
destView[j] = sourceView[j];
}
}
const views = buffer2.arrayViews;
const length2 = views.length;
for (let i = 0; i < length2; ++i) {
const view = views[i];
view.view = ComponentDatatype_default.createArrayBufferView(
view.componentDatatype,
arrayBuffer,
view.offsetInBytes
);
}
buffer2.arrayBuffer = arrayBuffer;
}
};
var createWriters = [
// 1 component per attribute
function(buffer2, view, vertexSizeInComponentType) {
return function(index, attribute) {
view[index * vertexSizeInComponentType] = attribute;
buffer2.needsCommit = true;
};
},
// 2 component per attribute
function(buffer2, view, vertexSizeInComponentType) {
return function(index, component0, component1) {
const i = index * vertexSizeInComponentType;
view[i] = component0;
view[i + 1] = component1;
buffer2.needsCommit = true;
};
},
// 3 component per attribute
function(buffer2, view, vertexSizeInComponentType) {
return function(index, component0, component1, component2) {
const i = index * vertexSizeInComponentType;
view[i] = component0;
view[i + 1] = component1;
view[i + 2] = component2;
buffer2.needsCommit = true;
};
},
// 4 component per attribute
function(buffer2, view, vertexSizeInComponentType) {
return function(index, component0, component1, component2, component3) {
const i = index * vertexSizeInComponentType;
view[i] = component0;
view[i + 1] = component1;
view[i + 2] = component2;
view[i + 3] = component3;
buffer2.needsCommit = true;
};
}
];
VertexArrayFacade._appendWriters = function(writers, buffer2) {
const arrayViews = buffer2.arrayViews;
const length2 = arrayViews.length;
for (let i = 0; i < length2; ++i) {
const arrayView = arrayViews[i];
writers[arrayView.index] = createWriters[arrayView.componentsPerAttribute - 1](buffer2, arrayView.view, arrayView.vertexSizeInComponentType);
}
};
VertexArrayFacade.prototype.commit = function(indexBuffer) {
let recreateVA = false;
const allBuffers = this._allBuffers;
let buffer2;
let i;
let length2;
for (i = 0, length2 = allBuffers.length; i < length2; ++i) {
buffer2 = allBuffers[i];
recreateVA = commit(this, buffer2) || recreateVA;
}
if (recreateVA || !defined_default(this.va)) {
destroyVA(this);
const va = this.va = [];
const chunkSize = Math_default.SIXTY_FOUR_KILOBYTES - 4;
const numberOfVertexArrays = defined_default(indexBuffer) && !this._instanced ? Math.ceil(this._size / chunkSize) : 1;
for (let k = 0; k < numberOfVertexArrays; ++k) {
let attributes = [];
for (i = 0, length2 = allBuffers.length; i < length2; ++i) {
buffer2 = allBuffers[i];
const offset = k * (buffer2.vertexSizeInBytes * chunkSize);
VertexArrayFacade._appendAttributes(
attributes,
buffer2,
offset,
this._instanced
);
}
attributes = attributes.concat(this._precreated);
va.push({
va: new VertexArray_default({
context: this._context,
attributes,
indexBuffer
}),
indicesCount: 1.5 * (k !== numberOfVertexArrays - 1 ? chunkSize : this._size % chunkSize)
// TODO: not hardcode 1.5, this assumes 6 indices per 4 vertices (as for Billboard quads).
});
}
}
};
function commit(vertexArrayFacade, buffer2) {
if (buffer2.needsCommit && buffer2.vertexSizeInBytes > 0) {
buffer2.needsCommit = false;
const vertexBuffer = buffer2.vertexBuffer;
const vertexBufferSizeInBytes = vertexArrayFacade._size * buffer2.vertexSizeInBytes;
const vertexBufferDefined = defined_default(vertexBuffer);
if (!vertexBufferDefined || vertexBuffer.sizeInBytes < vertexBufferSizeInBytes) {
if (vertexBufferDefined) {
vertexBuffer.destroy();
}
buffer2.vertexBuffer = Buffer_default.createVertexBuffer({
context: vertexArrayFacade._context,
typedArray: buffer2.arrayBuffer,
usage: buffer2.usage
});
buffer2.vertexBuffer.vertexArrayDestroyable = false;
return true;
}
buffer2.vertexBuffer.copyFromArrayView(buffer2.arrayBuffer);
}
return false;
}
VertexArrayFacade._appendAttributes = function(attributes, buffer2, vertexBufferOffset, instanced) {
const arrayViews = buffer2.arrayViews;
const length2 = arrayViews.length;
for (let i = 0; i < length2; ++i) {
const view = arrayViews[i];
attributes.push({
index: view.index,
enabled: view.enabled,
componentsPerAttribute: view.componentsPerAttribute,
componentDatatype: view.componentDatatype,
normalize: view.normalize,
vertexBuffer: buffer2.vertexBuffer,
offsetInBytes: vertexBufferOffset + view.offsetInBytes,
strideInBytes: buffer2.vertexSizeInBytes,
instanceDivisor: instanced ? 1 : 0
});
}
};
VertexArrayFacade.prototype.subCommit = function(offsetInVertices, lengthInVertices) {
if (offsetInVertices < 0 || offsetInVertices >= this._size) {
throw new DeveloperError_default(
"offsetInVertices must be greater than or equal to zero and less than the vertex array size."
);
}
if (offsetInVertices + lengthInVertices > this._size) {
throw new DeveloperError_default(
"offsetInVertices + lengthInVertices cannot exceed the vertex array size."
);
}
const allBuffers = this._allBuffers;
for (let i = 0, len = allBuffers.length; i < len; ++i) {
subCommit(allBuffers[i], offsetInVertices, lengthInVertices);
}
};
function subCommit(buffer2, offsetInVertices, lengthInVertices) {
if (buffer2.needsCommit && buffer2.vertexSizeInBytes > 0) {
const byteOffset = buffer2.vertexSizeInBytes * offsetInVertices;
const byteLength = buffer2.vertexSizeInBytes * lengthInVertices;
buffer2.vertexBuffer.copyFromArrayView(
new Uint8Array(buffer2.arrayBuffer, byteOffset, byteLength),
byteOffset
);
}
}
VertexArrayFacade.prototype.endSubCommits = function() {
const allBuffers = this._allBuffers;
for (let i = 0, len = allBuffers.length; i < len; ++i) {
allBuffers[i].needsCommit = false;
}
};
function destroyVA(vertexArrayFacade) {
const va = vertexArrayFacade.va;
if (!defined_default(va)) {
return;
}
const length2 = va.length;
for (let i = 0; i < length2; ++i) {
va[i].va.destroy();
}
vertexArrayFacade.va = void 0;
}
VertexArrayFacade.prototype.isDestroyed = function() {
return false;
};
VertexArrayFacade.prototype.destroy = function() {
const allBuffers = this._allBuffers;
for (let i = 0, len = allBuffers.length; i < len; ++i) {
const buffer2 = allBuffers[i];
buffer2.vertexBuffer = buffer2.vertexBuffer && buffer2.vertexBuffer.destroy();
}
destroyVA(this);
return destroyObject_default(this);
};
var VertexArrayFacade_default = VertexArrayFacade;
// packages/engine/Source/Renderer/loadCubeMap.js
function loadCubeMap(context, urls, skipColorSpaceConversion) {
Check_default.defined("context", context);
Check_default.defined("urls", urls);
if (Object.values(CubeMap_default.FaceName).some((faceName) => !defined_default(urls[faceName]))) {
throw new DeveloperError_default(
"urls must have positiveX, negativeX, positiveY, negativeY, positiveZ, and negativeZ properties."
);
}
const flipOptions = {
flipY: true,
skipColorSpaceConversion,
preferImageBitmap: true
};
const facePromises = [
Resource_default.createIfNeeded(urls.positiveX).fetchImage(flipOptions),
Resource_default.createIfNeeded(urls.negativeX).fetchImage(flipOptions),
Resource_default.createIfNeeded(urls.positiveY).fetchImage(flipOptions),
Resource_default.createIfNeeded(urls.negativeY).fetchImage(flipOptions),
Resource_default.createIfNeeded(urls.positiveZ).fetchImage(flipOptions),
Resource_default.createIfNeeded(urls.negativeZ).fetchImage(flipOptions)
];
return Promise.all(facePromises).then(function(images) {
return new CubeMap_default({
context,
source: {
positiveX: images[0],
negativeX: images[1],
positiveY: images[2],
negativeY: images[3],
positiveZ: images[4],
negativeZ: images[5]
}
});
});
}
var loadCubeMap_default = loadCubeMap;
// packages/engine/Source/DataSources/ConstantProperty.js
function ConstantProperty(value) {
this._value = void 0;
this._hasClone = false;
this._hasEquals = false;
this._definitionChanged = new Event_default();
this.setValue(value);
}
Object.defineProperties(ConstantProperty.prototype, {
/**
* Gets a value indicating if this property is constant.
* This property always returns true.
* @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`,
configurable ?? false,
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._splitDirection = void 0;
this._splitDirectionSubscription = void 0;
this.merge(options ?? Frozen_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"
),
/**
* Gets or sets the Property specifying the {@link SplitDirection} of this billboard.
* @memberof BillboardGraphics.prototype
* @type {Property|undefined}
* @default SplitDirection.NONE
*/
splitDirection: createPropertyDescriptor_default("splitDirection")
});
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;
result.splitDirection = this._splitDirection;
return result;
};
BillboardGraphics.prototype.merge = function(source) {
if (!defined_default(source)) {
throw new DeveloperError_default("source is required.");
}
this.show = this._show ?? source.show;
this.image = this._image ?? source.image;
this.scale = this._scale ?? source.scale;
this.pixelOffset = this._pixelOffset ?? source.pixelOffset;
this.eyeOffset = this._eyeOffset ?? source.eyeOffset;
this.horizontalOrigin = this._horizontalOrigin ?? source.horizontalOrigin;
this.verticalOrigin = this._verticalOrigin ?? source.verticalOrigin;
this.heightReference = this._heightReference ?? source.heightReference;
this.color = this._color ?? source.color;
this.rotation = this._rotation ?? source.rotation;
this.alignedAxis = this._alignedAxis ?? source.alignedAxis;
this.sizeInMeters = this._sizeInMeters ?? source.sizeInMeters;
this.width = this._width ?? source.width;
this.height = this._height ?? source.height;
this.scaleByDistance = this._scaleByDistance ?? source.scaleByDistance;
this.translucencyByDistance = this._translucencyByDistance ?? source.translucencyByDistance;
this.pixelOffsetScaleByDistance = this._pixelOffsetScaleByDistance ?? source.pixelOffsetScaleByDistance;
this.imageSubRegion = this._imageSubRegion ?? source.imageSubRegion;
this.distanceDisplayCondition = this._distanceDisplayCondition ?? source.distanceDisplayCondition;
this.disableDepthTestDistance = this._disableDepthTestDistance ?? source.disableDepthTestDistance;
this.splitDirection = this.splitDirection ?? source.splitDirection;
};
var BillboardGraphics_default = BillboardGraphics;
// packages/engine/Source/Core/AssociativeArray.js
var AssociativeArray = class {
constructor() {
this._array = [];
this._hash = {};
}
/**
* Gets the number of items in the collection.
*
* @type {number}
*/
get length() {
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.
*
* @type {Arraytrue if the key is in the array, false otherwise.
*/
contains(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]);
}
/**
* Associates the provided key with the provided value. If the key already
* exists, it is overwritten with the new value.
*
* @param {string|number} key A unique identifier.
* @param {T} value The value to associate with the provided key.
*/
set(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);
}
}
/**
* Retrieves the value associated with the provided key.
*
* @param {string|number} key The key whose value is to be retrieved.
* @returns {T} The associated value, or undefined if the key does not exist in the collection.
*/
get(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];
}
/**
* Removes a key-value pair from the collection.
*
* @param {string|number} key The key to be removed.
* @returns {boolean} True if it was removed, false if the key was not in the collection.
*/
remove(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;
}
/**
* Clears the collection.
*/
removeAll() {
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 = near ?? 0;
this._near = near;
far = 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 = 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 = 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 = near ?? 0;
this.nearValue = nearValue ?? 0;
this.far = far ?? 1;
this.farValue = 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 = 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 = 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 and 3D Tiles. When clamping to 3D Tilesets such as photorealistic 3D Tiles, ensure the tileset has {@link Cesium3DTileset#enableCollision} set to true. Otherwise, the entity may not be correctly clamped to the tileset surface.
* @type {number}
* @constant
*/
CLAMP_TO_GROUND: 1,
/**
* The position height is the height above the terrain and 3D Tiles.
* @type {number}
* @constant
*/
RELATIVE_TO_GROUND: 2,
/**
* The position is clamped to terain.
* @type {number}
* @constant
*/
CLAMP_TO_TERRAIN: 3,
/**
* The position height is the height above terrain.
* @type {number}
* @constant
*/
RELATIVE_TO_TERRAIN: 4,
/**
* The position is clamped to 3D Tiles.
* @type {number}
* @constant
*/
CLAMP_TO_3D_TILE: 5,
/**
* The position height is the height above 3D Tiles.
* @type {number}
* @constant
*/
RELATIVE_TO_3D_TILE: 6
};
Object.freeze(HeightReference);
var HeightReference_default = HeightReference;
function isHeightReferenceClamp(heightReference) {
return heightReference === HeightReference.CLAMP_TO_GROUND || heightReference === HeightReference.CLAMP_TO_3D_TILE || heightReference === HeightReference.CLAMP_TO_TERRAIN;
}
function isHeightReferenceRelative(heightReference) {
return heightReference === HeightReference.RELATIVE_TO_GROUND || heightReference === HeightReference.RELATIVE_TO_3D_TILE || heightReference === HeightReference.RELATIVE_TO_TERRAIN;
}
// 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
};
Object.freeze(HorizontalOrigin);
var HorizontalOrigin_default = 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
};
Object.freeze(VerticalOrigin);
var VerticalOrigin_default = VerticalOrigin;
// packages/engine/Source/DataSources/BoundingSphereState.js
var BoundingSphereState = Object.freeze({
/**
* 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 = 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 length2 = left.length;
for (let i = 0; i < length2; 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) ? 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/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
};
Object.freeze(SplitDirection);
var SplitDirection_default = SplitDirection;
// 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 defaultSplitDirection = SplitDirection_default.NONE;
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;
item.billboard = billboard;
item.textureValue = void 0;
}
billboard.show = show;
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
);
billboard.splitDirection = Property_default.getValueOrDefault(
billboardGraphics._splitDirection,
time,
defaultSplitDirection
);
if (item.textureValue !== textureValue) {
billboard.image = textureValue;
item.textureValue = textureValue;
}
const subRegion = Property_default.getValueOrUndefined(
billboardGraphics._imageSubRegion,
time,
boundingRectangleScratch
);
if (defined_default(subRegion)) {
billboard.setImageSubRegion(billboard.image, 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/BoxOutlineGeometry.js
var diffScratch2 = new Cartesian3_default();
function BoxOutlineGeometry(options) {
options = options ?? Frozen_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 = options ?? Frozen_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 = 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] = 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 = 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 indices = 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
});
indices[0] = 4;
indices[1] = 5;
indices[2] = 5;
indices[3] = 6;
indices[4] = 6;
indices[5] = 7;
indices[6] = 7;
indices[7] = 4;
indices[8] = 0;
indices[9] = 1;
indices[10] = 1;
indices[11] = 2;
indices[12] = 2;
indices[13] = 3;
indices[14] = 3;
indices[15] = 0;
indices[16] = 0;
indices[17] = 4;
indices[18] = 1;
indices[19] = 5;
indices[20] = 2;
indices[21] = 6;
indices[22] = 3;
indices[23] = 7;
const diff = Cartesian3_default.subtract(max3, min3, diffScratch2);
const radius = Cartesian3_default.magnitude(diff) * 0.5;
if (defined_default(boxGeometry._offsetAttribute)) {
const length2 = positions.length;
const offsetValue = boxGeometry._offsetAttribute === GeometryOffsetAttribute_default.NONE ? 0 : 1;
const applyOffset = new Uint8Array(length2 / 3).fill(offsetValue);
attributes.applyOffset = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentsPerAttribute: 1,
values: applyOffset
});
}
return new Geometry_default({
attributes,
indices,
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 = red ?? 1;
green = green ?? 1;
blue = blue ?? 1;
alpha = 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 = near ?? 0;
far = 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 = options ?? Frozen_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(options.modelMatrix ?? Matrix4_default.IDENTITY);
this.id = options.id;
this.pickPrimitive = options.pickPrimitive;
this.attributes = options.attributes ?? {};
this.westHemisphereGeometry = void 0;
this.eastHemisphereGeometry = void 0;
}
var GeometryInstance_default = GeometryInstance;
// packages/engine/Source/Core/TimeInterval.js
function TimeInterval(options) {
options = options ?? Frozen_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 = options.isStartIncluded ?? true;
this.isStopIncluded = 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 = options.isStartIncluded ?? true;
const isStopIncluded = 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 = 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, z2) {
x = x ?? 0;
y = y ?? 0;
z2 = z2 ?? 0;
this.value = new Float32Array([x, y, z2]);
}
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(offset) {
Check_default.defined("offset", offset);
return new OffsetGeometryInstanceAttribute(offset.x, offset.y, offset.z);
};
OffsetGeometryInstanceAttribute.toValue = function(offset, result) {
Check_default.defined("offset", offset);
if (!defined_default(result)) {
result = new Float32Array([offset.x, offset.y, offset.z]);
}
result[0] = offset.x;
result[1] = offset.y;
result[2] = offset.z;
return result;
};
var OffsetGeometryInstanceAttribute_default = OffsetGeometryInstanceAttribute;
// packages/engine/Source/Core/ShowGeometryInstanceAttribute.js
function ShowGeometryInstanceAttribute(show) {
show = 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
};
Object.freeze(BlendEquation);
var BlendEquation_default = 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
};
Object.freeze(BlendFunction);
var BlendFunction_default = 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
})
};
Object.freeze(BlendingState);
var BlendingState_default = 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
};
Object.freeze(CullFace);
var CullFace_default = CullFace;
// packages/engine/Source/Scene/Appearance.js
function Appearance(options) {
options = options ?? Frozen_default.EMPTY_OBJECT;
this.material = options.material;
this.translucent = options.translucent ?? true;
this._vertexShaderSource = options.vertexShaderSource;
this._fragmentShaderSource = options.fragmentShaderSource;
this._renderState = options.renderState;
this._closed = 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 = "uniform 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 = 'uniform 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 = "uniform 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(glow, 0.0, 1.0) * 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/WaterMaskMaterial.js
var WaterMaskMaterial_default = "uniform vec4 waterColor;\nuniform vec4 landColor;\n\nczm_material czm_getMaterial(czm_materialInput materialInput)\n{\n czm_material material = czm_getDefaultMaterial(materialInput);\n\n vec4 outColor = mix(landColor, waterColor, materialInput.waterMask);\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/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 = options.minificationFilter ?? TextureMinificationFilter_default.LINEAR;
this._magnificationFilter = 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;
this._initializationPromises = [];
this._initializationError = void 0;
initializeMaterial(options, this);
Object.defineProperties(this, {
type: {
value: this.type,
writable: false
},
/**
* The {@link TextureMinificationFilter} to apply to this material's textures.
* @memberof Material.prototype
* @type {TextureMinificationFilter}
* @default TextureMinificationFilter.LINEAR
*/
minificationFilter: {
get: function() {
return this._minificationFilter;
},
set: function(value) {
this._minificationFilter = value;
}
},
/**
* The {@link TextureMagnificationFilter} to apply to this material's textures.
* @memberof Material.prototype
* @type {TextureMagnificationFilter}
* @default TextureMagnificationFilter.LINEAR
*/
magnificationFilter: {
get: function() {
return this._magnificationFilter;
},
set: function(value) {
this._magnificationFilter = value;
}
}
});
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 material4 = new Material({
fabric: {
type
}
});
if (defined_default(uniforms)) {
for (const name in uniforms) {
if (uniforms.hasOwnProperty(name)) {
material4.uniforms[name] = uniforms[name];
}
}
}
return material4;
};
Material.fromTypeAsync = async function(type, uniforms) {
if (!defined_default(Material._materialCache.getMaterial(type))) {
throw new DeveloperError_default(`material with type '${type}' does not exist.`);
}
const initializationPromises = [];
const material4 = new Material({
fabric: {
type,
uniforms
}
});
getInitializationPromises(material4, initializationPromises);
await Promise.all(initializationPromises);
initializationPromises.length = 0;
if (defined_default(material4._initializationError)) {
throw material4._initializationError;
}
return material4;
};
function getInitializationPromises(material4, initializationPromises) {
initializationPromises.push(...material4._initializationPromises);
const submaterials = material4.materials;
for (const name in submaterials) {
if (submaterials.hasOwnProperty(name)) {
const submaterial = submaterials[name];
getInitializationPromises(submaterial, initializationPromises);
}
}
}
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 length2 = funcs.length;
for (let i = 0; i < length2; ++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 length2 = loadedImages.length;
for (i = 0; i < length2; ++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;
length2 = loadedCubeMaps.length;
for (i = 0; i < length2; ++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;
length2 = updateFunctions2.length;
for (i = 0; i < length2; ++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 material4 in materials) {
if (materials.hasOwnProperty(material4)) {
materials[material4].destroy();
}
}
return destroyObject_default(this);
};
function initializeMaterial(options, result) {
options = options ?? Frozen_default.EMPTY_OBJECT;
result._strict = options.strict ?? false;
result._count = options.count ?? 0;
result._template = clone_default(options.fabric ?? Frozen_default.EMPTY_OBJECT);
result.fabric = clone_default(options.fabric ?? Frozen_default.EMPTY_OBJECT);
result._template.uniforms = clone_default(
result._template.uniforms ?? Frozen_default.EMPTY_OBJECT
);
result._template.materials = clone_default(
result._template.materials ?? Frozen_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);
createMethodDefinition(result);
createUniforms(result);
createSubMaterials(result);
if (!defined_default(cachedMaterial)) {
Material._materialCache.addMaterial(result.type, result);
}
const defaultTranslucent = result._translucentFunctions.length === 0 ? true : void 0;
translucent = translucent ?? defaultTranslucent;
translucent = 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(material4) {
const template = material4._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, material4) {
const materials = material4._template.materials;
for (const subMaterialId in materials) {
if (materials.hasOwnProperty(subMaterialId)) {
if (shaderComponent.indexOf(subMaterialId) > -1) {
return true;
}
}
}
return false;
}
function createMethodDefinition(material4) {
const components = material4._template.components;
const source = material4._template.source;
if (defined_default(source)) {
material4.shaderSource += `${source}
`;
} else {
material4.shaderSource += "czm_material czm_getMaterial(czm_materialInput materialInput)\n{\n";
material4.shaderSource += "czm_material material = czm_getDefaultMaterial(materialInput);\n";
if (defined_default(components)) {
const isMultiMaterial = Object.keys(material4._template.materials).length > 0;
for (const component in components) {
if (components.hasOwnProperty(component)) {
if (component === "diffuse" || component === "emission") {
const isFusion = isMultiMaterial && isMaterialFused(components[component], material4);
const componentSource = isFusion ? components[component] : `czm_gammaCorrect(${components[component]})`;
material4.shaderSource += `material.${component} = ${componentSource};
`;
} else if (component === "alpha") {
material4.shaderSource += `material.alpha = ${components.alpha};
`;
} else {
material4.shaderSource += `material.${component} = ${components[component]};
`;
}
}
}
}
material4.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(material4, context) {
const uniforms = material4.uniforms;
const uniformValue = uniforms[uniformId];
const uniformChanged = oldUniformValue !== uniformValue;
const uniformValueIsDefaultImage = !defined_default(uniformValue) || uniformValue === Material.DefaultImageId;
oldUniformValue = uniformValue;
let texture = material4._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: material4._minificationFilter,
magnificationFilter: material4._magnificationFilter
});
texture = new Texture_default({
context,
source: uniformValue,
sampler
});
material4._textures[uniformId] = texture;
return;
}
texture.copyFrom({
source: uniformValue
});
} else if (!defined_default(texture)) {
material4._textures[uniformId] = context.defaultTexture;
}
return;
}
if (uniformValue instanceof Texture_default && uniformValue !== texture) {
material4._texturePaths[uniformId] = void 0;
const tmp2 = material4._textures[uniformId];
if (defined_default(tmp2) && tmp2 !== material4._defaultTexture) {
tmp2.destroy();
}
material4._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 !== material4._defaultTexture) {
texture.destroy();
}
texture = void 0;
material4._texturePaths[uniformId] = void 0;
}
if (!defined_default(texture)) {
texture = material4._textures[uniformId] = material4._defaultTexture;
uniformDimensionsName = `${uniformId}Dimensions`;
if (uniforms.hasOwnProperty(uniformDimensionsName)) {
uniformDimensions = uniforms[uniformDimensionsName];
uniformDimensions.x = texture._width;
uniformDimensions.y = texture._height;
}
}
if (uniformValueIsDefaultImage) {
return;
}
if ((uniformValue instanceof HTMLCanvasElement || uniformValue instanceof HTMLImageElement || uniformValue instanceof ImageBitmap || uniformValue instanceof OffscreenCanvas) && uniformValue !== material4._texturePaths[uniformId]) {
material4._loadedImages.push({
id: uniformId,
image: uniformValue
});
material4._texturePaths[uniformId] = uniformValue;
return;
}
loadTexture2DImageForUniform(material4, uniformId);
};
}
function loadTexture2DImageForUniform(material4, uniformId) {
const uniforms = material4.uniforms;
const uniformValue = uniforms[uniformId];
if (uniformValue === Material.DefaultImageId) {
return Promise.resolve();
}
const resource = Resource_default.createIfNeeded(uniformValue);
if (!(resource instanceof Resource_default)) {
return Promise.resolve();
}
const oldResource = Resource_default.createIfNeeded(
material4._texturePaths[uniformId]
);
const uniformHasChanged = !defined_default(oldResource) || oldResource.url !== resource.url;
if (!uniformHasChanged) {
return Promise.resolve();
}
let promise;
if (ktx2Regex.test(resource.url)) {
promise = loadKTX2_default(resource.url);
} else {
promise = resource.fetchImage();
}
Promise.resolve(promise).then(function(image) {
material4._loadedImages.push({
id: uniformId,
image
});
}).catch(function(error) {
material4._initializationError = error;
const texture = material4._textures[uniformId];
if (defined_default(texture) && texture !== material4._defaultTexture) {
texture.destroy();
}
material4._textures[uniformId] = material4._defaultTexture;
});
material4._texturePaths[uniformId] = uniformValue;
return promise;
}
function createCubeMapUpdateFunction(uniformId) {
return function(material4, context) {
const uniformValue = material4.uniforms[uniformId];
if (uniformValue instanceof CubeMap_default) {
const tmp2 = material4._textures[uniformId];
if (tmp2 !== material4._defaultTexture) {
tmp2.destroy();
}
material4._texturePaths[uniformId] = void 0;
material4._textures[uniformId] = uniformValue;
return;
}
if (!defined_default(material4._textures[uniformId])) {
material4._textures[uniformId] = context.defaultCubeMap;
}
loadCubeMapImagesForUniform(material4, uniformId);
};
}
function loadCubeMapImagesForUniform(material4, uniformId) {
const uniforms = material4.uniforms;
const uniformValue = uniforms[uniformId];
if (uniformValue === Material.DefaultCubeMapId) {
return Promise.resolve();
}
const path = uniformValue.positiveX + uniformValue.negativeX + uniformValue.positiveY + uniformValue.negativeY + uniformValue.positiveZ + uniformValue.negativeZ;
if (path === material4._texturePaths[uniformId]) {
return Promise.resolve();
}
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()
];
const allPromise = Promise.all(promises);
allPromise.then(function(images) {
material4._loadedCubeMaps.push({
id: uniformId,
images
});
}).catch(function(error) {
material4._initializationError = error;
});
material4._texturePaths[uniformId] = path;
return allPromise;
}
function createUniforms(material4) {
const uniforms = material4._template.uniforms;
for (const uniformId in uniforms) {
if (uniforms.hasOwnProperty(uniformId)) {
createUniform2(material4, uniformId);
}
}
}
function createUniform2(material4, uniformId) {
const strict = material4._strict;
const materialUniforms = material4._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(material4, 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(material4, imageDimensionsUniformName) > 0) {
materialUniforms[imageDimensionsUniformName] = {
type: "ivec3",
x: 1,
y: 1
};
createUniform2(material4, imageDimensionsUniformName);
}
}
const uniformDeclarationRegex = new RegExp(
`uniform\\s+${uniformType}\\s+${uniformId}\\s*;`
);
if (!uniformDeclarationRegex.test(material4.shaderSource)) {
const uniformDeclaration = `uniform ${uniformType} ${uniformId};`;
material4.shaderSource = uniformDeclaration + material4.shaderSource;
}
const newUniformId = `${uniformId}_${material4._count++}`;
replacedTokenCount = replaceToken(material4, uniformId, newUniformId);
if (replacedTokenCount === 1 && strict) {
throw new DeveloperError_default(
`strict: shader source does not use uniform '${uniformId}'.`
);
}
material4.uniforms[uniformId] = uniformValue;
if (uniformType === "sampler2D") {
material4._uniforms[newUniformId] = function() {
return material4._textures[uniformId];
};
material4._updateFunctions.push(createTexture2DUpdateFunction(uniformId));
material4._initializationPromises.push(
loadTexture2DImageForUniform(material4, uniformId)
);
} else if (uniformType === "samplerCube") {
material4._uniforms[newUniformId] = function() {
return material4._textures[uniformId];
};
material4._updateFunctions.push(createCubeMapUpdateFunction(uniformId));
material4._initializationPromises.push(
loadCubeMapImagesForUniform(material4, uniformId)
);
} else if (uniformType.indexOf("mat") !== -1) {
const scratchMatrix8 = new matrixMap[uniformType]();
material4._uniforms[newUniformId] = function() {
return matrixMap[uniformType].fromColumnMajorArray(
material4.uniforms[uniformId],
scratchMatrix8
);
};
} else {
material4._uniforms[newUniformId] = function() {
return material4.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 || uniformValue instanceof ImageBitmap || uniformValue instanceof OffscreenCanvas) {
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(material4) {
const strict = material4._strict;
const subMaterialTemplates = material4._template.materials;
for (const subMaterialId in subMaterialTemplates) {
if (subMaterialTemplates.hasOwnProperty(subMaterialId)) {
const subMaterial = new Material({
strict,
fabric: subMaterialTemplates[subMaterialId],
count: material4._count
});
material4._count = subMaterial._count;
material4._uniforms = combine_default(
material4._uniforms,
subMaterial._uniforms,
true
);
material4.materials[subMaterialId] = subMaterial;
material4._translucentFunctions = material4._translucentFunctions.concat(
subMaterial._translucentFunctions
);
const originalMethodName = "czm_getMaterial";
const newMethodName = `${originalMethodName}_${material4._count++}`;
replaceToken(subMaterial, originalMethodName, newMethodName);
material4.shaderSource = subMaterial.shaderSource + material4.shaderSource;
const materialMethodCall = `${newMethodName}(materialInput)`;
const tokensReplacedCount = replaceToken(
material4,
subMaterialId,
materialMethodCall
);
if (tokensReplacedCount === 0 && strict) {
throw new DeveloperError_default(
`strict: shader source does not use material '${subMaterialId}'.`
);
}
}
}
}
function replaceToken(material4, token, newToken, excludePeriod) {
excludePeriod = excludePeriod ?? true;
let count = 0;
const suffixChars = "([\\w])?";
const prefixChars = `([\\w${excludePeriod ? "." : ""}])?`;
const regExp = new RegExp(prefixChars + token + suffixChars, "g");
material4.shaderSource = material4.shaderSource.replace(
regExp,
function($0, $1, $2) {
if ($1 || $2) {
return $0;
}
count += 1;
return newToken;
}
);
return count;
}
function getNumberOfTokens(material4, token, excludePeriod) {
return replaceToken(material4, 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(material4) {
return material4.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(material4) {
return material4.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(material4) {
const uniforms = material4.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(material4) {
const uniforms = material4.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(material4) {
const uniforms = material4.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(material4) {
const uniforms = material4.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(material4) {
const uniforms = material4.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(material4) {
const uniforms = material4.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(material4) {
const uniforms = material4.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(material4) {
const uniforms = material4.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
});
Material.WaterMaskType = "WaterMask";
Material._materialCache.addMaterial(Material.WaterMaskType, {
fabric: {
type: Material.WaterMaskType,
source: WaterMaskMaterial_default,
uniforms: {
waterColor: new Color_default(1, 1, 1, 1),
landColor: new Color_default(0, 0, 0, 0)
}
},
translucent: false
});
var Material_default = Material;
// packages/engine/Source/Scene/MaterialAppearance.js
function MaterialAppearance(options) {
options = options ?? Frozen_default.EMPTY_OBJECT;
const translucent = options.translucent ?? true;
const closed = options.closed ?? false;
const materialSupport = options.materialSupport ?? MaterialAppearance.MaterialSupport.TEXTURED;
this.material = defined_default(options.material) ? options.material : Material_default.fromType(Material_default.ColorType);
this.translucent = translucent;
this._vertexShaderSource = options.vertexShaderSource ?? materialSupport.vertexShaderSource;
this._fragmentShaderSource = 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 = options.flat ?? false;
this._faceForward = 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 = options ?? Frozen_default.EMPTY_OBJECT;
const translucent = options.translucent ?? true;
const closed = options.closed ?? false;
const flat = 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 = options.vertexShaderSource ?? vs;
this._fragmentShaderSource = options.fragmentShaderSource ?? fs;
this._renderState = Appearance_default.getDefaultRenderState(
translucent,
closed,
options.renderState
);
this._closed = closed;
this._vertexFormat = vertexFormat;
this._flat = flat;
this._faceForward = 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";
};
var timeScratch = new JulianDate_default();
ColorMaterialProperty.prototype.getValue = function(time, result) {
if (!defined_default(time)) {
time = JulianDate_default.now(timeScratch);
}
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
var GeographicTilingScheme = class {
/**
* @param {object} [options] Object with the following properties:
* @param {Ellipsoid} [options.ellipsoid=Ellipsoid.default] The ellipsoid whose surface is being tiled. Defaults to
* the default ellipsoid.
* @param {Rectangle} [options.rectangle=Rectangle.MAX_VALUE] The rectangle, in radians, covered by the tiling scheme.
* @param {number} [options.numberOfLevelZeroTilesX=2] The number of tiles in the X direction at level zero of
* the tile tree.
* @param {number} [options.numberOfLevelZeroTilesY=1] The number of tiles in the Y direction at level zero of
* the tile tree.
*/
constructor(options) {
options = options ?? Frozen_default.EMPTY_OBJECT;
this._ellipsoid = options.ellipsoid ?? Ellipsoid_default.default;
this._rectangle = options.rectangle ?? Rectangle_default.MAX_VALUE;
this._projection = new GeographicProjection_default(this._ellipsoid);
this._numberOfLevelZeroTilesX = options.numberOfLevelZeroTilesX ?? 2;
this._numberOfLevelZeroTilesY = options.numberOfLevelZeroTilesY ?? 1;
}
/**
* Gets the ellipsoid that is tiled by this tiling scheme.
* @type {Ellipsoid}
*/
get ellipsoid() {
return this._ellipsoid;
}
/**
* Gets the rectangle, in radians, covered by this tiling scheme.
* @type {Rectangle}
*/
get rectangle() {
return this._rectangle;
}
/**
* Gets the map projection used by this tiling scheme.
* @type {MapProjection}
*/
get projection() {
return this._projection;
}
/**
* Gets the total number of tiles in the X direction at a specified level-of-detail.
*
* @param {number} level The level-of-detail.
* @returns {number} The number of tiles in the X direction at the given level.
*/
getNumberOfXTilesAtLevel(level) {
return this._numberOfLevelZeroTilesX << level;
}
/**
* Gets the total number of tiles in the Y direction at a specified level-of-detail.
*
* @param {number} level The level-of-detail.
* @returns {number} The number of tiles in the Y direction at the given level.
*/
getNumberOfYTilesAtLevel(level) {
return this._numberOfLevelZeroTilesY << level;
}
/**
* Transforms a rectangle specified in geodetic radians to the native coordinate system
* of this tiling scheme.
*
* @param {Rectangle} rectangle The rectangle to transform.
* @param {Rectangle} [result] The instance to which to copy the result, or undefined if a new instance
* should be created.
* @returns {Rectangle} The specified 'result', or a new object containing the native rectangle if 'result'
* is undefined.
*/
rectangleToNativeRectangle(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;
}
/**
* Converts tile x, y coordinates and level to a rectangle expressed in the native coordinates
* of the tiling scheme.
*
* @param {number} x The integer x coordinate of the tile.
* @param {number} y The integer y coordinate of the tile.
* @param {number} level The tile level-of-detail. Zero is the least detailed.
* @param {Rectangle} [result] The instance to which to copy the result, or undefined if a new instance
* should be created.
* @returns {Rectangle} The specified 'result', or a new object containing the rectangle
* if 'result' is undefined.
*/
tileXYToNativeRectangle(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;
}
/**
* Converts tile x, y coordinates and level to a cartographic rectangle in radians.
*
* @param {number} x The integer x coordinate of the tile.
* @param {number} y The integer y coordinate of the tile.
* @param {number} level The tile level-of-detail. Zero is the least detailed.
* @param {Rectangle} [result] The instance to which to copy the result, or undefined if a new instance
* should be created.
* @returns {Rectangle} The specified 'result', or a new object containing the rectangle
* if 'result' is undefined.
*/
tileXYToRectangle(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;
}
/**
* Calculates the tile x, y coordinates of the tile containing
* a given cartographic position.
*
* @param {Cartographic} position The position.
* @param {number} level The tile level-of-detail. Zero is the least detailed.
* @param {Cartesian2} [result] The instance to which to copy the result, or undefined if a new instance
* should be created.
* @returns {Cartesian2} The specified 'result', or a new object containing the tile x, y coordinates
* if 'result' is undefined.
*/
positionToTileXY(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 = ellipsoid ?? Ellipsoid_default.default;
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 = ellipsoid ?? Ellipsoid_default.default;
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(minimum ?? Cartesian3_default.ZERO);
this.maximum = Cartesian3_default.clone(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 length2 = positions.length;
for (let i = 1; i < length2; i++) {
const p = positions[i];
const x = p.x;
const y = p.y;
const z2 = 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(z2, minimumZ);
maximumZ = Math.max(z2, 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 s2 = Cartesian3_default.dot(box.center, normal2) + plane.distance;
if (s2 - e > 0) {
return Intersect_default.INSIDE;
}
if (s2 + e < 0) {
return Intersect_default.OUTSIDE;
}
return Intersect_default.INTERSECTING;
};
AxisAlignedBoundingBox.intersectAxisAlignedBoundingBox = function(box, other) {
Check_default.defined("box", box);
Check_default.defined("other", other);
return box.minimum.x <= other.maximum.x && box.maximum.x >= other.minimum.x && box.minimum.y <= other.maximum.y && box.maximum.y >= other.minimum.y && box.minimum.z <= other.maximum.z && box.maximum.z >= other.minimum.z;
};
AxisAlignedBoundingBox.prototype.clone = function(result) {
return AxisAlignedBoundingBox.clone(this, result);
};
AxisAlignedBoundingBox.prototype.intersectPlane = function(plane) {
return AxisAlignedBoundingBox.intersectPlane(this, plane);
};
AxisAlignedBoundingBox.prototype.intersectAxisAlignedBoundingBox = function(other) {
return AxisAlignedBoundingBox.intersectAxisAlignedBoundingBox(this, other);
};
AxisAlignedBoundingBox.prototype.equals = function(right) {
return AxisAlignedBoundingBox.equals(this, right);
};
var AxisAlignedBoundingBox_default = AxisAlignedBoundingBox;
// packages/engine/Source/Core/EllipsoidTangentPlane.js
var scratchCart4 = new Cartesian4_default();
function EllipsoidTangentPlane(origin, ellipsoid) {
Check_default.defined("origin", origin);
ellipsoid = ellipsoid ?? Ellipsoid_default.default;
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 v3 = Cartesian3_default.subtract(
intersectionPoint,
this._origin,
intersectionPoint
);
const x = Cartesian3_default.dot(this._xAxis, v3);
const y = Cartesian3_default.dot(this._yAxis, v3);
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 length2 = cartesians.length;
for (let i = 0; i < length2; 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 v3 = Cartesian3_default.subtract(
intersectionPoint,
this._origin,
intersectionPoint
);
const x = Cartesian3_default.dot(this._xAxis, v3);
const y = Cartesian3_default.dot(this._yAxis, v3);
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 length2 = cartesians.length;
result.length = length2;
for (let i = 0; i < length2; 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 length2 = cartesians.length;
if (!defined_default(result)) {
result = new Array(length2);
} else {
result.length = length2;
}
for (let i = 0; i < length2; ++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(center ?? Cartesian3_default.ZERO);
this.halfAxes = Matrix3_default.clone(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 = 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 = 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 scratchCartesian12 = new Cartesian3_default();
var scratchCartesian23 = new Cartesian3_default();
var scratchCartesian34 = 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 length2 = positions.length;
const meanPoint = Cartesian3_default.clone(positions[0], scratchCartesian12);
for (i = 1; i < length2; i++) {
Cartesian3_default.add(meanPoint, positions[i], meanPoint);
}
const invLength = 1 / length2;
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 < length2; i++) {
p = Cartesian3_default.subtract(positions[i], meanPoint, scratchCartesian23);
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 v12 = Matrix3_default.getColumn(rotation, 0, scratchCartesian4);
let v22 = Matrix3_default.getColumn(rotation, 1, scratchCartesian5);
let v3 = Matrix3_default.getColumn(rotation, 2, scratchCartesian6);
let u12 = -Number.MAX_VALUE;
let u22 = -Number.MAX_VALUE;
let u32 = -Number.MAX_VALUE;
let l1 = Number.MAX_VALUE;
let l2 = Number.MAX_VALUE;
let l3 = Number.MAX_VALUE;
for (i = 0; i < length2; i++) {
p = positions[i];
u12 = Math.max(Cartesian3_default.dot(v12, p), u12);
u22 = Math.max(Cartesian3_default.dot(v22, p), u22);
u32 = Math.max(Cartesian3_default.dot(v3, p), u32);
l1 = Math.min(Cartesian3_default.dot(v12, p), l1);
l2 = Math.min(Cartesian3_default.dot(v22, p), l2);
l3 = Math.min(Cartesian3_default.dot(v3, p), l3);
}
v12 = Cartesian3_default.multiplyByScalar(v12, 0.5 * (l1 + u12), v12);
v22 = Cartesian3_default.multiplyByScalar(v22, 0.5 * (l2 + u22), v22);
v3 = Cartesian3_default.multiplyByScalar(v3, 0.5 * (l3 + u32), v3);
const center = Cartesian3_default.add(v12, v22, result.center);
Cartesian3_default.add(center, v3, center);
const scale = scratchCartesian34;
scale.x = u12 - l1;
scale.y = u22 - l2;
scale.z = u32 - 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 = minimumHeight ?? 0;
maximumHeight = maximumHeight ?? 0;
ellipsoid = ellipsoid ?? Ellipsoid_default.default;
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 offset = Cartesian3_default.subtract(cartesian11, box.center, scratchOffset);
const halfAxes = box.halfAxes;
let u4 = Matrix3_default.getColumn(halfAxes, 0, scratchCartesianU);
let v3 = Matrix3_default.getColumn(halfAxes, 1, scratchCartesianV);
let w = Matrix3_default.getColumn(halfAxes, 2, scratchCartesianW);
const uHalf = Cartesian3_default.magnitude(u4);
const vHalf = Cartesian3_default.magnitude(v3);
const wHalf = Cartesian3_default.magnitude(w);
let uValid = true;
let vValid = true;
let wValid = true;
if (uHalf > 0) {
Cartesian3_default.divideByScalar(u4, uHalf, u4);
} else {
uValid = false;
}
if (vHalf > 0) {
Cartesian3_default.divideByScalar(v3, vHalf, v3);
} 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 = u4;
validAxis1 = v3;
validAxis2 = w;
if (!vValid) {
degenerateAxis = v3;
validAxis1 = u4;
} else if (!wValid) {
degenerateAxis = w;
validAxis2 = u4;
}
validAxis3 = Cartesian3_default.cross(validAxis1, validAxis2, scratchValidAxis3);
if (degenerateAxis === u4) {
u4 = validAxis3;
} else if (degenerateAxis === v3) {
v3 = validAxis3;
} else if (degenerateAxis === w) {
w = validAxis3;
}
} else if (numberOfDegenerateAxes === 2) {
validAxis1 = u4;
if (vValid) {
validAxis1 = v3;
} 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 === u4) {
v3 = validAxis2;
w = validAxis3;
} else if (validAxis1 === v3) {
w = validAxis2;
u4 = validAxis3;
} else if (validAxis1 === w) {
u4 = validAxis2;
v3 = validAxis3;
}
} else if (numberOfDegenerateAxes === 3) {
u4 = Cartesian3_default.UNIT_X;
v3 = Cartesian3_default.UNIT_Y;
w = Cartesian3_default.UNIT_Z;
}
const pPrime = scratchPPrime;
pPrime.x = Cartesian3_default.dot(offset, u4);
pPrime.y = Cartesian3_default.dot(offset, v3);
pPrime.z = Cartesian3_default.dot(offset, 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 u4 = Matrix3_default.getColumn(halfAxes, 0, scratchCartesianU);
const v3 = Matrix3_default.getColumn(halfAxes, 1, scratchCartesianV);
const w = Matrix3_default.getColumn(halfAxes, 2, scratchCartesianW);
const corner = Cartesian3_default.add(u4, v3, 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, u4, corner);
Cartesian3_default.add(corner, v3, 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, u4, corner);
Cartesian3_default.subtract(corner, v3, 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, u4, corner);
Cartesian3_default.subtract(corner, v3, 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, u4, corner);
Cartesian3_default.add(corner, v3, 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, u4, corner);
Cartesian3_default.add(corner, v3, 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, u4, corner);
Cartesian3_default.subtract(corner, v3, 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, u4, corner);
Cartesian3_default.subtract(corner, v3, 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/VerticalExaggeration.js
var VerticalExaggeration = {};
VerticalExaggeration.getHeight = function(height, scale, relativeHeight) {
if (!Number.isFinite(scale)) {
throw new DeveloperError_default("scale must be a finite number.");
}
if (!Number.isFinite(relativeHeight)) {
throw new DeveloperError_default("relativeHeight must be a finite number.");
}
return (height - relativeHeight) * scale + relativeHeight;
};
var scratchCartographic2 = new Cartographic_default();
VerticalExaggeration.getPosition = function(position, ellipsoid, verticalExaggeration, verticalExaggerationRelativeHeight, result) {
const cartographic2 = ellipsoid.cartesianToCartographic(
position,
scratchCartographic2
);
if (!defined_default(cartographic2)) {
return Cartesian3_default.clone(position, result);
}
const newHeight = VerticalExaggeration.getHeight(
cartographic2.height,
verticalExaggeration,
verticalExaggerationRelativeHeight
);
return Cartesian3_default.fromRadians(
cartographic2.longitude,
cartographic2.latitude,
newHeight,
ellipsoid,
result
);
};
var VerticalExaggeration_default = VerticalExaggeration;
// 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;
Object.freeze(ClassificationType);
var ClassificationType_default = 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
};
Object.freeze(DepthFunction);
var DepthFunction_default = 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 length2 = attributes.length;
for (let i = 0; i < length2; ++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 length2 = offsets.length;
const lastOffset = offsets[length2 - 1];
const lastAttribute = attributes[length2 - 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 z2 = Cartesian4_default.unpackFloat(packed);
packed = Cartesian4_default.unpack(array, index + 12, scratchPackedFloatCartesian4);
const w = Cartesian4_default.unpackFloat(packed);
return Cartesian4_default.fromElements(x, y, z2, 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 offset = this._offsets[attributeIndex];
const stride = this._stride;
const index = 4 * stride * instanceIndex + 4 * offset;
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 offset = this._offsets[attributeIndex];
const stride = this._stride;
const index = 4 * stride * instanceIndex + 4 * offset;
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 offset = batchTable._offsets[attributeIndex];
let glslFunction = `${functionReturnType} ${functionName}(float batchId)
{
vec2 st = computeSt(batchId);
st.x += batchTextureStep.x * float(${offset});
`;
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 length2 = attributes.length;
for (let i = 0; i < length2; ++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/Core/WebMercatorProjection.js
var WebMercatorProjection = class _WebMercatorProjection {
/**
* @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid.
*/
constructor(ellipsoid) {
this._ellipsoid = ellipsoid ?? Ellipsoid_default.WGS84;
this._semimajorAxis = this._ellipsoid.maximumRadius;
this._oneOverSemimajorAxis = 1 / this._semimajorAxis;
}
/**
* Gets the {@link Ellipsoid}.
*
* @type {Ellipsoid}
* @readonly
*/
get ellipsoid() {
return this._ellipsoid;
}
/**
* Converts a Mercator angle, in the range -PI to PI, to a geodetic latitude
* in the range -PI/2 to PI/2.
*
* @param {number} mercatorAngle The angle to convert.
* @returns {number} The geodetic latitude in radians.
*/
static mercatorAngleToGeodeticLatitude(mercatorAngle) {
return Math_default.PI_OVER_TWO - 2 * Math.atan(Math.exp(-mercatorAngle));
}
/**
* Converts a geodetic latitude in radians, in the range -PI/2 to PI/2, to a Mercator
* angle in the range -PI to PI.
*
* @param {number} latitude The geodetic latitude in radians.
* @returns {number} The Mercator angle.
*/
static geodeticLatitudeToMercatorAngle(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));
}
/**
* Converts geodetic ellipsoid coordinates, in radians, to the equivalent Web Mercator
* X, Y, Z coordinates expressed in meters and returned in a {@link Cartesian3}. The height
* is copied unmodified to the Z coordinate.
*
* @param {Cartographic} cartographic The cartographic coordinates in radians.
* @param {Cartesian3} [result] The instance to which to copy the result, or undefined if a
* new instance should be created.
* @returns {Cartesian3} The equivalent web mercator X, Y, Z coordinates, in meters.
*/
project(cartographic2, result) {
const semimajorAxis = this._semimajorAxis;
const x = cartographic2.longitude * semimajorAxis;
const y = _WebMercatorProjection.geodeticLatitudeToMercatorAngle(
cartographic2.latitude
) * semimajorAxis;
const z2 = cartographic2.height;
if (!defined_default(result)) {
return new Cartesian3_default(x, y, z2);
}
result.x = x;
result.y = y;
result.z = z2;
return result;
}
/**
* Converts Web Mercator X, Y coordinates, expressed in meters, to a {@link Cartographic}
* containing geodetic ellipsoid coordinates. The Z coordinate is copied unmodified to the
* height.
*
* @param {Cartesian3} cartesian The web mercator Cartesian position to unrproject with height (z) in meters.
* @param {Cartographic} [result] The instance to which to copy the result, or undefined if a
* new instance should be created.
* @returns {Cartographic} The equivalent cartographic coordinates.
*/
unproject(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;
}
};
WebMercatorProjection.MaximumLatitude = WebMercatorProjection.mercatorAngleToGeodeticLatitude(Math.PI);
var WebMercatorProjection_default = WebMercatorProjection;
// packages/engine/Source/Scene/PrimitivePipeline.js
function transformToWorldCoordinates(instances, primitiveModelMatrix, scene3DOnly) {
let toWorld = !scene3DOnly;
const length2 = instances.length;
let i;
if (!toWorld && length2 > 1) {
const modelMatrix = instances[0].modelMatrix;
for (i = 1; i < length2; ++i) {
if (!Matrix4_default.equals(modelMatrix, instances[i].modelMatrix)) {
toWorld = true;
break;
}
}
}
if (toWorld) {
for (i = 0; i < length2; ++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 length2 = instances.length;
for (let i = 0; i < length2; ++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 length2 = instances.length;
for (i = 0; i < length2; ++i) {
if (defined_default(instances[i].geometry)) {
primitiveType = instances[i].geometry.primitiveType;
break;
}
}
for (i = 1; i < length2; ++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 < length2; ++i) {
if (defined_default(instances[i].geometry)) {
GeometryPipeline_default.splitLongitude(instances[i]);
}
}
}
addBatchIds(instances);
if (vertexCacheOptimize) {
for (i = 0; i < length2; ++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);
length2 = geometries.length;
for (i = 0; i < length2; ++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 = [];
length2 = geometries.length;
for (i = 0; i < length2; ++i) {
geometry = geometries[i];
splitGeometries = splitGeometries.concat(
GeometryPipeline_default.fitToUnsignedShortIndices(geometry)
);
}
geometries = splitGeometries;
}
return geometries;
}
function createPickOffsets(instances, geometryName, geometries, pickOffsets) {
let offset;
let indexCount;
let geometryIndex;
const offsetIndex = pickOffsets.length - 1;
if (offsetIndex >= 0) {
const pickOffset = pickOffsets[offsetIndex];
offset = pickOffset.offset + pickOffset.count;
geometryIndex = pickOffset.index;
indexCount = geometries[geometryIndex].indices.length;
} else {
offset = 0;
geometryIndex = 0;
indexCount = geometries[geometryIndex].indices.length;
}
const length2 = instances.length;
for (let i = 0; i < length2; ++i) {
const instance = instances[i];
const geometry = instance[geometryName];
if (!defined_default(geometry)) {
continue;
}
const count = geometry.indices.length;
if (offset + count > indexCount) {
offset = 0;
indexCount = geometries[++geometryIndex].indices.length;
}
pickOffsets.push({
index: geometryIndex,
offset,
count
});
offset += 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 length2 = instances.length;
let pickOffsets;
let offsetInstanceExtend;
let hasOffset = false;
if (length2 > 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(length2);
hasOffset = true;
}
}
const boundingSpheres = new Array(length2);
const boundingSpheresCV = new Array(length2);
for (let i = 0; i < length2; ++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 length2 = geometries.length;
for (let i = 0; i < length2; ++i) {
transferGeometry(geometries[i], transferableObjects);
}
}
function countCreateGeometryResults(items) {
let count = 1;
const length2 = items.length;
for (let i = 0; i < length2; 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 length2 = items.length;
let count = 0;
packedData[count++] = length2;
for (let i = 0; i < length2; 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++] = 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 length2;
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;
length2 = packedGeometry[packedGeometryIndex++];
values = ComponentDatatype_default.createTypedArray(componentDatatype, length2);
for (let valuesIndex = 0; valuesIndex < length2; valuesIndex++) {
values[valuesIndex] = packedGeometry[packedGeometryIndex++];
}
attributes[name] = new GeometryAttribute_default({
componentDatatype,
componentsPerAttribute,
normalize: normalize2,
values
});
}
let indices;
length2 = packedGeometry[packedGeometryIndex++];
if (length2 > 0) {
const numberOfVertices = values.length / componentsPerAttribute;
indices = IndexDatatype_default.createTypedArray(numberOfVertices, length2);
for (i = 0; i < length2; i++) {
indices[i] = packedGeometry[packedGeometryIndex++];
}
}
result[resultIndex++] = new Geometry_default({
primitiveType,
geometryType,
boundingSphere,
boundingSphereCV,
indices,
attributes,
offsetAttribute
});
}
return result;
};
function packInstancesForCombine(instances, transferableObjects) {
const length2 = instances.length;
const packedData = new Float64Array(1 + length2 * 19);
let count = 0;
packedData[count++] = length2;
for (let i = 0; i < length2; 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 length2 = createGeometryResults.length;
for (let i = 0; i < length2; 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 length2 = createGeometryResults.length;
let instanceIndex = 0;
for (let resultIndex = 0; resultIndex < length2; 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 length2 = boundingSpheres.length;
const bufferLength = 1 + (BoundingSphere_default.packedLength + 1) * length2;
const buffer2 = new Float32Array(bufferLength);
let bufferIndex = 0;
buffer2[bufferIndex++] = length2;
for (let i = 0; i < length2; ++i) {
const bs = boundingSpheres[i];
if (!defined_default(bs)) {
buffer2[bufferIndex++] = 0;
} else {
buffer2[bufferIndex++] = 1;
BoundingSphere_default.pack(boundingSpheres[i], buffer2, bufferIndex);
}
bufferIndex += BoundingSphere_default.packedLength;
}
return buffer2;
}
function unpackBoundingSpheres(buffer2) {
const result = new Array(buffer2[0]);
let count = 0;
let i = 1;
while (i < buffer2.length) {
if (buffer2[i++] === 1) {
result[count] = BoundingSphere_default.unpack(buffer2, 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 = {
/**
* The initial state of a primitive.
*
* Note that this does NOT mean that the primitive is "ready", as indicated
* by the _ready property. It means the opposite: Nothing was
* done with the primitive at all.
*
* For primitives that are created with the asynchronous:true
* setting and that are in this state, the update call starts
* the creation of the geometry using web workers, and the primitive goes
* into the CREATING state.
*
* For synchronously created primitives, this state never matters. They will
* go into the COMBINED (or FAILED) state directly due to a call to the
* update function, if they are not yet FAILED, COMBINED,
* or COMPLETE.
*/
READY: 0,
/**
* The process of creating the primitive geometry is ongoing.
*
* A primitive can only ever be in this state when it was created
* with the asynchronous:true setting.
*
* It means that web workers are currently creating the geometry
* of the primitive.
*
* When the geometry creation succeeds, then the primitive will go
* into the CREATED state. Otherwise, it will go into the FAILED
* state. Both will happen asynchronously.
*
* The update function has to be called regularly
* until either of these states is reached.
*/
CREATING: 1,
/**
* The geometry for the primitive has been created.
*
* A primitive can only ever be in this state when it was created
* with the asynchronous:true setting.
*
* It means that web workers have (asynchronously) finished the
* creation of the geometry, but further (asynchronous) processing
* is necessary: If a primitive is determined to be in this state
* during a call to update, an asynchronous process
* is triggered to "combine" the geometry, meaning that the primitive
* will go into the COMBINING state.
*/
CREATED: 2,
/**
* The asynchronous creation of the geometry has been finished, but the
* asynchronous process of combining the geometry has not finished yet.
*
* A primitive can only ever be in this state when it was created
* with the asynchronous:true setting.
*
* It means that whatever is done with
* PrimitivePipeline.packCombineGeometryParameters has
* not finished yet. When combining the geometry succeeds, the
* primitive will go into the COMBINED state. Otherwise, it will
* go into the FAILED state.
*/
COMBINING: 3,
/**
* The geometry data is in a form that can be uploaded to the GPU.
*
* For synchronous primitives, this means that the geometry
* has been created (synchronously) due to the first call to the
* update function.
*
* For asynchronous primitives, this means that the asynchronous
* creation of the geometry and the asynchronous combination of the
* geometry have both finished.
*
* The update function has to be called regularly until
* this state is reached. When it is reached, the update
* call will cause the transition into the COMPLETE state.
*/
COMBINED: 4,
/**
* The geometry has been created and uploaded to the GPU.
*
* When this state is reached, it eventually causes the _ready
* flag of the primitive to become true.
*
* Note: Setting the ready flag does NOT happen in the
* update call: It only happens after rendering the next
* frame!
*
* Note: This state does not mean that nothing has to be done
* anymore (so the work is not "complete"). When the primitive is in
* this state, the update function still has to be
* called regularly.
*/
COMPLETE: 5,
/**
* The creation of the primitive failed.
*
* When this state is reached, it eventually causes the _ready
* flag of the primitive to become true.
*
* Note: Setting the ready flag does NOT happen in the
* update call: It only happens after rendering the next
* frame!
*
* This state can be reached when the (synchronous or asynchronous)
* creation of the geometry, or the (asynchronous) combination of
* the geometry caused any form of error.
*
* It may or may not imply the presence of the _error property.
* When the _error property is present on a FAILED primitive,
* this error will be thrown during the update call. When it
* is not present for a FAILED primitive, then the update call
* will do nothing.
*/
FAILED: 6
};
Object.freeze(PrimitiveState);
var PrimitiveState_default = 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;
};
Object.freeze(ShadowMode);
var ShadowMode_default = ShadowMode;
// packages/engine/Source/Scene/Primitive.js
function Primitive(options) {
options = options ?? Frozen_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(options.modelMatrix ?? Matrix4_default.IDENTITY);
this._modelMatrix = new Matrix4_default();
this.show = options.show ?? true;
this._vertexCacheOptimize = options.vertexCacheOptimize ?? false;
this._interleave = options.interleave ?? false;
this._releaseGeometryInstances = options.releaseGeometryInstances ?? true;
this._allowPicking = options.allowPicking ?? true;
this._asynchronous = options.asynchronous ?? true;
this._compressVertices = options.compressVertices ?? true;
this.cull = options.cull ?? true;
this.debugShowBoundingVolume = 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 = 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;
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;
}
}
});
function getCommonPerInstanceAttributeNames(instances) {
const length2 = instances.length;
const attributesInAllInstances = [];
const attributes0 = instances[0].attributes;
let name;
for (name in attributes0) {
if (attributes0.hasOwnProperty(name) && defined_default(attributes0[name])) {
const attribute = attributes0[name];
let inAllInstances = true;
for (let i = 1; i < length2; ++i) {
const otherAttribute = instances[i].attributes[name];
if (!defined_default(otherAttribute) || attribute.componentDatatype !== otherAttribute.componentDatatype || attribute.componentsPerAttribute !== otherAttribute.componentsPerAttribute || attribute.normalize !== otherAttribute.normalize) {
inAllInstances = false;
break;
}
}
if (inAllInstances) {
attributesInAllInstances.push(name);
}
}
}
return attributesInAllInstances;
}
var scratchGetAttributeCartesian2 = new Cartesian2_default();
var scratchGetAttributeCartesian3 = new Cartesian3_default();
var scratchGetAttributeCartesian42 = new Cartesian4_default();
function getAttributeValue(value) {
const componentsPerAttribute = value.length;
if (componentsPerAttribute === 1) {
return value[0];
} else if (componentsPerAttribute === 2) {
return Cartesian2_default.unpack(value, 0, scratchGetAttributeCartesian2);
} else if (componentsPerAttribute === 3) {
return Cartesian3_default.unpack(value, 0, scratchGetAttributeCartesian3);
} else if (componentsPerAttribute === 4) {
return Cartesian4_default.unpack(value, 0, scratchGetAttributeCartesian42);
}
}
function createBatchTable(primitive, context) {
const geometryInstances = primitive.geometryInstances;
const instances = Array.isArray(geometryInstances) ? geometryInstances : [geometryInstances];
const numberOfInstances = instances.length;
if (numberOfInstances === 0) {
return;
}
const names = getCommonPerInstanceAttributeNames(instances);
const length2 = names.length;
const attributes = [];
const attributeIndices = {};
const boundingSphereAttributeIndices = {};
let offset2DIndex;
const firstInstance = instances[0];
let instanceAttributes = firstInstance.attributes;
let i;
let name;
let attribute;
for (i = 0; i < length2; ++i) {
name = names[i];
attribute = instanceAttributes[name];
attributeIndices[name] = i;
attributes.push({
functionName: `czm_batchTable_${name}`,
componentDatatype: attribute.componentDatatype,
componentsPerAttribute: attribute.componentsPerAttribute,
normalize: attribute.normalize
});
}
if (names.indexOf("distanceDisplayCondition") !== -1) {
attributes.push(
{
functionName: "czm_batchTable_boundingSphereCenter3DHigh",
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3
},
{
functionName: "czm_batchTable_boundingSphereCenter3DLow",
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3
},
{
functionName: "czm_batchTable_boundingSphereCenter2DHigh",
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3
},
{
functionName: "czm_batchTable_boundingSphereCenter2DLow",
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3
},
{
functionName: "czm_batchTable_boundingSphereRadius",
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 1
}
);
boundingSphereAttributeIndices.center3DHigh = attributes.length - 5;
boundingSphereAttributeIndices.center3DLow = attributes.length - 4;
boundingSphereAttributeIndices.center2DHigh = attributes.length - 3;
boundingSphereAttributeIndices.center2DLow = attributes.length - 2;
boundingSphereAttributeIndices.radius = attributes.length - 1;
}
if (names.indexOf("offset") !== -1) {
attributes.push({
functionName: "czm_batchTable_offset2D",
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3
});
offset2DIndex = attributes.length - 1;
}
attributes.push({
functionName: "czm_batchTable_pickColor",
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentsPerAttribute: 4,
normalize: true
});
const attributesLength = attributes.length;
const batchTable = new BatchTable_default(context, attributes, numberOfInstances);
for (i = 0; i < numberOfInstances; ++i) {
const instance = instances[i];
instanceAttributes = instance.attributes;
for (let j = 0; j < length2; ++j) {
name = names[j];
attribute = instanceAttributes[name];
const value = getAttributeValue(attribute.value);
const attributeIndex = attributeIndices[name];
batchTable.setBatchedAttribute(i, attributeIndex, value);
}
const pickObject = {
primitive: instance.pickPrimitive ?? primitive
};
if (defined_default(instance.id)) {
pickObject.id = instance.id;
}
const pickId = context.createPickId(pickObject);
primitive._pickIds.push(pickId);
const pickColor4 = pickId.color;
const color = scratchGetAttributeCartesian42;
color.x = Color_default.floatToByte(pickColor4.red);
color.y = Color_default.floatToByte(pickColor4.green);
color.z = Color_default.floatToByte(pickColor4.blue);
color.w = Color_default.floatToByte(pickColor4.alpha);
batchTable.setBatchedAttribute(i, attributesLength - 1, color);
}
primitive._batchTable = batchTable;
primitive._batchTableAttributeIndices = attributeIndices;
primitive._batchTableBoundingSphereAttributeIndices = boundingSphereAttributeIndices;
primitive._batchTableOffsetAttribute2DIndex = offset2DIndex;
}
function cloneAttribute(attribute) {
let clonedValues;
if (Array.isArray(attribute.values)) {
clonedValues = attribute.values.slice(0);
} else {
clonedValues = new attribute.values.constructor(attribute.values);
}
return new GeometryAttribute_default({
componentDatatype: attribute.componentDatatype,
componentsPerAttribute: attribute.componentsPerAttribute,
normalize: attribute.normalize,
values: clonedValues
});
}
function cloneGeometry(geometry) {
const attributes = geometry.attributes;
const newAttributes = new GeometryAttributes_default();
for (const property in attributes) {
if (attributes.hasOwnProperty(property) && defined_default(attributes[property])) {
newAttributes[property] = cloneAttribute(attributes[property]);
}
}
let indices;
if (defined_default(geometry.indices)) {
const sourceValues = geometry.indices;
if (Array.isArray(sourceValues)) {
indices = sourceValues.slice(0);
} else {
indices = new sourceValues.constructor(sourceValues);
}
}
return new Geometry_default({
attributes: newAttributes,
indices,
primitiveType: geometry.primitiveType,
boundingSphere: BoundingSphere_default.clone(geometry.boundingSphere)
});
}
function cloneInstance(instance, geometry) {
return {
geometry,
attributes: instance.attributes,
modelMatrix: Matrix4_default.clone(instance.modelMatrix),
pickPrimitive: instance.pickPrimitive,
id: instance.id
};
}
var positionRegex = /in\s+vec(?:3|4)\s+(.*)3DHigh;/g;
Primitive._modifyShaderPosition = function(primitive, vertexShaderSource, scene3DOnly) {
let match;
let forwardDecl = "";
let attributes = "";
let computeFunctions = "";
while ((match = positionRegex.exec(vertexShaderSource)) !== null) {
const name = match[1];
const functionName = `vec4 czm_compute${name[0].toUpperCase()}${name.substr(
1
)}()`;
if (functionName !== "vec4 czm_computePosition()") {
forwardDecl += `${functionName};
`;
}
if (!defined_default(primitive.rtcCenter)) {
if (!scene3DOnly) {
attributes += `in vec3 ${name}2DHigh;
in vec3 ${name}2DLow;
`;
computeFunctions += `${functionName}
{
vec4 p;
if (czm_morphTime == 1.0)
{
p = czm_translateRelativeToEye(${name}3DHigh, ${name}3DLow);
}
else if (czm_morphTime == 0.0)
{
p = czm_translateRelativeToEye(${name}2DHigh.zxy, ${name}2DLow.zxy);
}
else
{
p = czm_columbusViewMorph(
czm_translateRelativeToEye(${name}2DHigh.zxy, ${name}2DLow.zxy),
czm_translateRelativeToEye(${name}3DHigh, ${name}3DLow),
czm_morphTime);
}
return p;
}
`;
} else {
computeFunctions += `${functionName}
{
return czm_translateRelativeToEye(${name}3DHigh, ${name}3DLow);
}
`;
}
} else {
vertexShaderSource = vertexShaderSource.replace(
/in\s+vec(?:3|4)\s+position3DHigh;/g,
""
);
vertexShaderSource = vertexShaderSource.replace(
/in\s+vec(?:3|4)\s+position3DLow;/g,
""
);
forwardDecl += "uniform mat4 u_modifiedModelView;\n";
attributes += "in vec4 position;\n";
computeFunctions += `${functionName}
{
return u_modifiedModelView * position;
}
`;
vertexShaderSource = vertexShaderSource.replace(
/czm_modelViewRelativeToEye\s+\*\s+/g,
""
);
vertexShaderSource = vertexShaderSource.replace(
/czm_modelViewProjectionRelativeToEye/g,
"czm_projection"
);
}
}
return [forwardDecl, attributes, vertexShaderSource, computeFunctions].join(
"\n"
);
};
Primitive._appendShowToShader = function(primitive, vertexShaderSource) {
if (!defined_default(primitive._batchTableAttributeIndices.show)) {
return vertexShaderSource;
}
const renamedVS = ShaderSource_default.replaceMain(
vertexShaderSource,
"czm_non_show_main"
);
const showMain = "void main() \n{ \n czm_non_show_main(); \n gl_Position *= czm_batchTable_show(batchId); \n}";
return `${renamedVS}
${showMain}`;
};
Primitive._updateColorAttribute = function(primitive, vertexShaderSource, isDepthFail) {
if (!defined_default(primitive._batchTableAttributeIndices.color) && !defined_default(primitive._batchTableAttributeIndices.depthFailColor)) {
return vertexShaderSource;
}
if (vertexShaderSource.search(/in\s+vec4\s+color;/g) === -1) {
return vertexShaderSource;
}
if (isDepthFail && !defined_default(primitive._batchTableAttributeIndices.depthFailColor)) {
throw new DeveloperError_default(
"A depthFailColor per-instance attribute is required when using a depth fail appearance that uses a color attribute."
);
}
let modifiedVS = vertexShaderSource;
modifiedVS = modifiedVS.replace(/in\s+vec4\s+color;/g, "");
if (!isDepthFail) {
modifiedVS = modifiedVS.replace(
/(\b)color(\b)/g,
"$1czm_batchTable_color(batchId)$2"
);
} else {
modifiedVS = modifiedVS.replace(
/(\b)color(\b)/g,
"$1czm_batchTable_depthFailColor(batchId)$2"
);
}
return modifiedVS;
};
function appendPickToVertexShader(source) {
const renamedVS = ShaderSource_default.replaceMain(source, "czm_non_pick_main");
const pickMain = "out vec4 v_pickColor; \nvoid main() \n{ \n czm_non_pick_main(); \n v_pickColor = czm_batchTable_pickColor(batchId); \n}";
return `${renamedVS}
${pickMain}`;
}
function appendPickToFragmentShader(source) {
return `in vec4 v_pickColor;
${source}`;
}
Primitive._updatePickColorAttribute = function(source) {
let vsPick = source.replace(/in\s+vec4\s+pickColor;/g, "");
vsPick = vsPick.replace(
/(\b)pickColor(\b)/g,
"$1czm_batchTable_pickColor(batchId)$2"
);
return vsPick;
};
Primitive._appendOffsetToShader = function(primitive, vertexShaderSource) {
if (!defined_default(primitive._batchTableAttributeIndices.offset)) {
return vertexShaderSource;
}
let attr = "in float batchId;\n";
attr += "in float applyOffset;";
let modifiedShader = vertexShaderSource.replace(
/in\s+float\s+batchId;/g,
attr
);
let str = "vec4 $1 = czm_computePosition();\n";
str += " if (czm_sceneMode == czm_sceneMode3D)\n";
str += " {\n";
str += " $1 = $1 + vec4(czm_batchTable_offset(batchId) * applyOffset, 0.0);";
str += " }\n";
str += " else\n";
str += " {\n";
str += " $1 = $1 + vec4(czm_batchTable_offset2D(batchId) * applyOffset, 0.0);";
str += " }\n";
modifiedShader = modifiedShader.replace(
/vec4\s+([A-Za-z0-9_]+)\s+=\s+czm_computePosition\(\);/g,
str
);
return modifiedShader;
};
Primitive._appendDistanceDisplayConditionToShader = function(primitive, vertexShaderSource, scene3DOnly) {
if (!defined_default(primitive._batchTableAttributeIndices.distanceDisplayCondition)) {
return vertexShaderSource;
}
const renamedVS = ShaderSource_default.replaceMain(
vertexShaderSource,
"czm_non_distanceDisplayCondition_main"
);
let distanceDisplayConditionMain = "void main() \n{ \n czm_non_distanceDisplayCondition_main(); \n vec2 distanceDisplayCondition = czm_batchTable_distanceDisplayCondition(batchId);\n vec3 boundingSphereCenter3DHigh = czm_batchTable_boundingSphereCenter3DHigh(batchId);\n vec3 boundingSphereCenter3DLow = czm_batchTable_boundingSphereCenter3DLow(batchId);\n float boundingSphereRadius = czm_batchTable_boundingSphereRadius(batchId);\n";
if (!scene3DOnly) {
distanceDisplayConditionMain += " vec3 boundingSphereCenter2DHigh = czm_batchTable_boundingSphereCenter2DHigh(batchId);\n vec3 boundingSphereCenter2DLow = czm_batchTable_boundingSphereCenter2DLow(batchId);\n vec4 centerRTE;\n if (czm_morphTime == 1.0)\n {\n centerRTE = czm_translateRelativeToEye(boundingSphereCenter3DHigh, boundingSphereCenter3DLow);\n }\n else if (czm_morphTime == 0.0)\n {\n centerRTE = czm_translateRelativeToEye(boundingSphereCenter2DHigh.zxy, boundingSphereCenter2DLow.zxy);\n }\n else\n {\n centerRTE = czm_columbusViewMorph(\n czm_translateRelativeToEye(boundingSphereCenter2DHigh.zxy, boundingSphereCenter2DLow.zxy),\n czm_translateRelativeToEye(boundingSphereCenter3DHigh, boundingSphereCenter3DLow),\n czm_morphTime);\n }\n";
} else {
distanceDisplayConditionMain += " vec4 centerRTE = czm_translateRelativeToEye(boundingSphereCenter3DHigh, boundingSphereCenter3DLow);\n";
}
distanceDisplayConditionMain += " float radiusSq = boundingSphereRadius * boundingSphereRadius; \n float distanceSq; \n if (czm_sceneMode == czm_sceneMode2D) \n { \n distanceSq = czm_eyeHeight2D.y - radiusSq; \n } \n else \n { \n distanceSq = dot(centerRTE.xyz, centerRTE.xyz) - radiusSq; \n } \n distanceSq = max(distanceSq, 0.0); \n float nearSq = distanceDisplayCondition.x * distanceDisplayCondition.x; \n float farSq = distanceDisplayCondition.y * distanceDisplayCondition.y; \n float show = (distanceSq >= nearSq && distanceSq <= farSq) ? 1.0 : 0.0; \n gl_Position *= show; \n}";
return `${renamedVS}
${distanceDisplayConditionMain}`;
};
function modifyForEncodedNormals(primitive, vertexShaderSource) {
if (!primitive.compressVertices) {
return vertexShaderSource;
}
const containsNormal = vertexShaderSource.search(/in\s+vec3\s+normal;/g) !== -1;
const containsSt = vertexShaderSource.search(/in\s+vec2\s+st;/g) !== -1;
if (!containsNormal && !containsSt) {
return vertexShaderSource;
}
const containsTangent = vertexShaderSource.search(/in\s+vec3\s+tangent;/g) !== -1;
const containsBitangent = vertexShaderSource.search(/in\s+vec3\s+bitangent;/g) !== -1;
let numComponents = containsSt && containsNormal ? 2 : 1;
numComponents += containsTangent || containsBitangent ? 1 : 0;
const type = numComponents > 1 ? `vec${numComponents}` : "float";
const attributeName = "compressedAttributes";
const attributeDecl = `in ${type} ${attributeName};`;
let globalDecl = "";
let decode = "";
if (containsSt) {
globalDecl += "vec2 st;\n";
const stComponent = numComponents > 1 ? `${attributeName}.x` : attributeName;
decode += ` st = czm_decompressTextureCoordinates(${stComponent});
`;
}
if (containsNormal && containsTangent && containsBitangent) {
globalDecl += "vec3 normal;\nvec3 tangent;\nvec3 bitangent;\n";
decode += ` czm_octDecode(${attributeName}.${containsSt ? "yz" : "xy"}, normal, tangent, bitangent);
`;
} else {
if (containsNormal) {
globalDecl += "vec3 normal;\n";
decode += ` normal = czm_octDecode(${attributeName}${numComponents > 1 ? `.${containsSt ? "y" : "x"}` : ""});
`;
}
if (containsTangent) {
globalDecl += "vec3 tangent;\n";
decode += ` tangent = czm_octDecode(${attributeName}.${containsSt && containsNormal ? "z" : "y"});
`;
}
if (containsBitangent) {
globalDecl += "vec3 bitangent;\n";
decode += ` bitangent = czm_octDecode(${attributeName}.${containsSt && containsNormal ? "z" : "y"});
`;
}
}
let modifiedVS = vertexShaderSource;
modifiedVS = modifiedVS.replace(/in\s+vec3\s+normal;/g, "");
modifiedVS = modifiedVS.replace(/in\s+vec2\s+st;/g, "");
modifiedVS = modifiedVS.replace(/in\s+vec3\s+tangent;/g, "");
modifiedVS = modifiedVS.replace(/in\s+vec3\s+bitangent;/g, "");
modifiedVS = ShaderSource_default.replaceMain(modifiedVS, "czm_non_compressed_main");
const compressedMain = `${"void main() \n{ \n"}${decode} czm_non_compressed_main();
}`;
return [attributeDecl, globalDecl, modifiedVS, compressedMain].join("\n");
}
function depthClampVS(vertexShaderSource) {
let modifiedVS = ShaderSource_default.replaceMain(
vertexShaderSource,
"czm_non_depth_clamp_main"
);
modifiedVS += "void main() {\n czm_non_depth_clamp_main();\n gl_Position = czm_depthClamp(gl_Position);}\n";
return modifiedVS;
}
function depthClampFS(fragmentShaderSource) {
let modifiedFS = ShaderSource_default.replaceMain(
fragmentShaderSource,
"czm_non_depth_clamp_main"
);
modifiedFS += "void main() {\n czm_non_depth_clamp_main();\n #if defined(LOG_DEPTH)\n czm_writeLogDepth();\n #else\n czm_writeDepthClamp();\n #endif\n}\n";
return modifiedFS;
}
function validateShaderMatching(shaderProgram, attributeLocations8) {
const shaderAttributes = shaderProgram.vertexAttributes;
for (const name in shaderAttributes) {
if (shaderAttributes.hasOwnProperty(name)) {
if (!defined_default(attributeLocations8[name])) {
throw new DeveloperError_default(
`Appearance/Geometry mismatch. The appearance requires vertex shader attribute input '${name}', which was not computed as part of the Geometry. Use the appearance's vertexFormat property when constructing the geometry.`
);
}
}
}
}
function getUniformFunction(uniforms, name) {
return function() {
return uniforms[name];
};
}
var numberOfCreationWorkers = Math.max(
FeatureDetection_default.hardwareConcurrency - 1,
1
);
var createGeometryTaskProcessors;
var combineGeometryTaskProcessor = new TaskProcessor_default("combineGeometry");
function loadAsynchronous(primitive, frameState) {
let instances;
let geometry;
let i;
let j;
const instanceIds = primitive._instanceIds;
if (primitive._state === PrimitiveState_default.READY) {
instances = Array.isArray(primitive.geometryInstances) ? primitive.geometryInstances : [primitive.geometryInstances];
const length2 = primitive._numberOfInstances = instances.length;
const promises = [];
let subTasks = [];
for (i = 0; i < length2; ++i) {
geometry = instances[i].geometry;
instanceIds.push(instances[i].id);
if (defined_default(geometry._workerName) && defined_default(geometry._workerPath) || !defined_default(geometry._workerName) && !defined_default(geometry._workerPath)) {
throw new DeveloperError_default(
"Must define either _workerName or _workerPath for asynchronous geometry."
);
}
subTasks.push({
moduleName: geometry._workerName,
modulePath: geometry._workerPath,
geometry
});
}
if (!defined_default(createGeometryTaskProcessors)) {
createGeometryTaskProcessors = new Array(numberOfCreationWorkers);
for (i = 0; i < numberOfCreationWorkers; i++) {
createGeometryTaskProcessors[i] = new TaskProcessor_default("createGeometry");
}
}
let subTask;
subTasks = subdivideArray_default(subTasks, numberOfCreationWorkers);
for (i = 0; i < subTasks.length; i++) {
let packedLength = 0;
const workerSubTasks = subTasks[i];
const workerSubTasksLength = workerSubTasks.length;
for (j = 0; j < workerSubTasksLength; ++j) {
subTask = workerSubTasks[j];
geometry = subTask.geometry;
if (defined_default(geometry.constructor.pack)) {
subTask.offset = packedLength;
packedLength += geometry.constructor.packedLength ?? geometry.packedLength;
}
}
let subTaskTransferableObjects;
if (packedLength > 0) {
const array = new Float64Array(packedLength);
subTaskTransferableObjects = [array.buffer];
for (j = 0; j < workerSubTasksLength; ++j) {
subTask = workerSubTasks[j];
geometry = subTask.geometry;
if (defined_default(geometry.constructor.pack)) {
geometry.constructor.pack(geometry, array, subTask.offset);
subTask.geometry = array;
}
}
}
promises.push(
createGeometryTaskProcessors[i].scheduleTask(
{
subTasks: subTasks[i]
},
subTaskTransferableObjects
)
);
}
primitive._state = PrimitiveState_default.CREATING;
Promise.all(promises).then(function(results) {
primitive._createGeometryResults = results;
primitive._state = PrimitiveState_default.CREATED;
}).catch(function(error) {
setReady(primitive, frameState, PrimitiveState_default.FAILED, error);
});
} else if (primitive._state === PrimitiveState_default.CREATED) {
const transferableObjects = [];
instances = Array.isArray(primitive.geometryInstances) ? primitive.geometryInstances : [primitive.geometryInstances];
const scene3DOnly = frameState.scene3DOnly;
const projection = frameState.mapProjection;
const promise = combineGeometryTaskProcessor.scheduleTask(
PrimitivePipeline_default.packCombineGeometryParameters(
{
createGeometryResults: primitive._createGeometryResults,
instances,
ellipsoid: projection.ellipsoid,
projection,
elementIndexUintSupported: frameState.context.elementIndexUint,
scene3DOnly,
vertexCacheOptimize: primitive.vertexCacheOptimize,
compressVertices: primitive.compressVertices,
modelMatrix: primitive.modelMatrix,
createPickOffsets: primitive._createPickOffsets
},
transferableObjects
),
transferableObjects
);
primitive._createGeometryResults = void 0;
primitive._state = PrimitiveState_default.COMBINING;
Promise.resolve(promise).then(function(packedResult) {
const result = PrimitivePipeline_default.unpackCombineGeometryResults(packedResult);
primitive._geometries = result.geometries;
primitive._attributeLocations = result.attributeLocations;
primitive.modelMatrix = Matrix4_default.clone(
result.modelMatrix,
primitive.modelMatrix
);
primitive._pickOffsets = result.pickOffsets;
primitive._offsetInstanceExtend = result.offsetInstanceExtend;
primitive._instanceBoundingSpheres = result.boundingSpheres;
primitive._instanceBoundingSpheresCV = result.boundingSpheresCV;
if (defined_default(primitive._geometries) && primitive._geometries.length > 0) {
primitive._recomputeBoundingSpheres = true;
primitive._state = PrimitiveState_default.COMBINED;
} else {
setReady(primitive, frameState, PrimitiveState_default.FAILED, void 0);
}
}).catch(function(error) {
setReady(primitive, frameState, PrimitiveState_default.FAILED, error);
});
}
}
function loadSynchronous(primitive, frameState) {
const instances = Array.isArray(primitive.geometryInstances) ? primitive.geometryInstances : [primitive.geometryInstances];
const length2 = primitive._numberOfInstances = instances.length;
const clonedInstances = new Array(length2);
const instanceIds = primitive._instanceIds;
let instance;
let i;
let geometryIndex = 0;
for (i = 0; i < length2; i++) {
instance = instances[i];
const geometry = instance.geometry;
let createdGeometry;
if (defined_default(geometry.attributes) && defined_default(geometry.primitiveType)) {
createdGeometry = cloneGeometry(geometry);
} else {
createdGeometry = geometry.constructor.createGeometry(geometry);
}
clonedInstances[geometryIndex++] = cloneInstance(instance, createdGeometry);
instanceIds.push(instance.id);
}
clonedInstances.length = geometryIndex;
const scene3DOnly = frameState.scene3DOnly;
const projection = frameState.mapProjection;
const result = PrimitivePipeline_default.combineGeometry({
instances: clonedInstances,
ellipsoid: projection.ellipsoid,
projection,
elementIndexUintSupported: frameState.context.elementIndexUint,
scene3DOnly,
vertexCacheOptimize: primitive.vertexCacheOptimize,
compressVertices: primitive.compressVertices,
modelMatrix: primitive.modelMatrix,
createPickOffsets: primitive._createPickOffsets
});
primitive._geometries = result.geometries;
primitive._attributeLocations = result.attributeLocations;
primitive.modelMatrix = Matrix4_default.clone(
result.modelMatrix,
primitive.modelMatrix
);
primitive._pickOffsets = result.pickOffsets;
primitive._offsetInstanceExtend = result.offsetInstanceExtend;
primitive._instanceBoundingSpheres = result.boundingSpheres;
primitive._instanceBoundingSpheresCV = result.boundingSpheresCV;
if (defined_default(primitive._geometries) && primitive._geometries.length > 0) {
primitive._recomputeBoundingSpheres = true;
primitive._state = PrimitiveState_default.COMBINED;
} else {
setReady(primitive, frameState, PrimitiveState_default.FAILED, void 0);
}
}
function recomputeBoundingSpheres(primitive, frameState) {
const offsetIndex = primitive._batchTableAttributeIndices.offset;
if (!primitive._recomputeBoundingSpheres || !defined_default(offsetIndex)) {
primitive._recomputeBoundingSpheres = false;
return;
}
let i;
const offsetInstanceExtend = primitive._offsetInstanceExtend;
const boundingSpheres = primitive._instanceBoundingSpheres;
const length2 = boundingSpheres.length;
let newBoundingSpheres = primitive._tempBoundingSpheres;
if (!defined_default(newBoundingSpheres)) {
newBoundingSpheres = new Array(length2);
for (i = 0; i < length2; i++) {
newBoundingSpheres[i] = new BoundingSphere_default();
}
primitive._tempBoundingSpheres = newBoundingSpheres;
}
for (i = 0; i < length2; ++i) {
let newBS = newBoundingSpheres[i];
const offset = primitive._batchTable.getBatchedAttribute(
i,
offsetIndex,
new Cartesian3_default()
);
newBS = boundingSpheres[i].clone(newBS);
transformBoundingSphere(newBS, offset, offsetInstanceExtend[i]);
}
const combinedBS = [];
const combinedWestBS = [];
const combinedEastBS = [];
for (i = 0; i < length2; ++i) {
const bs = newBoundingSpheres[i];
const minX = bs.center.x - bs.radius;
if (minX > 0 || BoundingSphere_default.intersectPlane(bs, Plane_default.ORIGIN_ZX_PLANE) !== Intersect_default.INTERSECTING) {
combinedBS.push(bs);
} else {
combinedWestBS.push(bs);
combinedEastBS.push(bs);
}
}
let resultBS1 = combinedBS[0];
let resultBS2 = combinedEastBS[0];
let resultBS3 = combinedWestBS[0];
for (i = 1; i < combinedBS.length; i++) {
resultBS1 = BoundingSphere_default.union(resultBS1, combinedBS[i]);
}
for (i = 1; i < combinedEastBS.length; i++) {
resultBS2 = BoundingSphere_default.union(resultBS2, combinedEastBS[i]);
}
for (i = 1; i < combinedWestBS.length; i++) {
resultBS3 = BoundingSphere_default.union(resultBS3, combinedWestBS[i]);
}
const result = [];
if (defined_default(resultBS1)) {
result.push(resultBS1);
}
if (defined_default(resultBS2)) {
result.push(resultBS2);
}
if (defined_default(resultBS3)) {
result.push(resultBS3);
}
for (i = 0; i < result.length; i++) {
const boundingSphere = result[i].clone(primitive._boundingSpheres[i]);
primitive._boundingSpheres[i] = boundingSphere;
primitive._boundingSphereCV[i] = BoundingSphere_default.projectTo2D(
boundingSphere,
frameState.mapProjection,
primitive._boundingSphereCV[i]
);
}
Primitive._updateBoundingVolumes(
primitive,
frameState,
primitive.modelMatrix,
true
);
primitive._recomputeBoundingSpheres = false;
}
var scratchBoundingSphereCenterEncoded = new EncodedCartesian3_default();
var scratchBoundingSphereCartographic = new Cartographic_default();
var scratchBoundingSphereCenter2D = new Cartesian3_default();
var scratchBoundingSphere3 = new BoundingSphere_default();
function updateBatchTableBoundingSpheres(primitive, frameState) {
const hasDistanceDisplayCondition = defined_default(
primitive._batchTableAttributeIndices.distanceDisplayCondition
);
if (!hasDistanceDisplayCondition || primitive._batchTableBoundingSpheresUpdated) {
return;
}
const indices = primitive._batchTableBoundingSphereAttributeIndices;
const center3DHighIndex = indices.center3DHigh;
const center3DLowIndex = indices.center3DLow;
const center2DHighIndex = indices.center2DHigh;
const center2DLowIndex = indices.center2DLow;
const radiusIndex = indices.radius;
const projection = frameState.mapProjection;
const ellipsoid = projection.ellipsoid;
const batchTable = primitive._batchTable;
const boundingSpheres = primitive._instanceBoundingSpheres;
const length2 = boundingSpheres.length;
for (let i = 0; i < length2; ++i) {
let boundingSphere = boundingSpheres[i];
if (!defined_default(boundingSphere)) {
continue;
}
const modelMatrix = primitive.modelMatrix;
if (defined_default(modelMatrix)) {
boundingSphere = BoundingSphere_default.transform(
boundingSphere,
modelMatrix,
scratchBoundingSphere3
);
}
const center = boundingSphere.center;
const radius = boundingSphere.radius;
let encodedCenter = EncodedCartesian3_default.fromCartesian(
center,
scratchBoundingSphereCenterEncoded
);
batchTable.setBatchedAttribute(i, center3DHighIndex, encodedCenter.high);
batchTable.setBatchedAttribute(i, center3DLowIndex, encodedCenter.low);
if (!frameState.scene3DOnly) {
const cartographic2 = ellipsoid.cartesianToCartographic(
center,
scratchBoundingSphereCartographic
);
const center2D = projection.project(
cartographic2,
scratchBoundingSphereCenter2D
);
encodedCenter = EncodedCartesian3_default.fromCartesian(
center2D,
scratchBoundingSphereCenterEncoded
);
batchTable.setBatchedAttribute(i, center2DHighIndex, encodedCenter.high);
batchTable.setBatchedAttribute(i, center2DLowIndex, encodedCenter.low);
}
batchTable.setBatchedAttribute(i, radiusIndex, radius);
}
primitive._batchTableBoundingSpheresUpdated = true;
}
var offsetScratchCartesian = new Cartesian3_default();
var offsetCenterScratch = new Cartesian3_default();
function updateBatchTableOffsets(primitive, frameState) {
const hasOffset = defined_default(primitive._batchTableAttributeIndices.offset);
if (!hasOffset || primitive._batchTableOffsetsUpdated || frameState.scene3DOnly) {
return;
}
const index2D = primitive._batchTableOffsetAttribute2DIndex;
const projection = frameState.mapProjection;
const ellipsoid = projection.ellipsoid;
const batchTable = primitive._batchTable;
const boundingSpheres = primitive._instanceBoundingSpheres;
const length2 = boundingSpheres.length;
for (let i = 0; i < length2; ++i) {
let boundingSphere = boundingSpheres[i];
if (!defined_default(boundingSphere)) {
continue;
}
const offset = batchTable.getBatchedAttribute(
i,
primitive._batchTableAttributeIndices.offset
);
if (Cartesian3_default.equals(offset, Cartesian3_default.ZERO)) {
batchTable.setBatchedAttribute(i, index2D, Cartesian3_default.ZERO);
continue;
}
const modelMatrix = primitive.modelMatrix;
if (defined_default(modelMatrix)) {
boundingSphere = BoundingSphere_default.transform(
boundingSphere,
modelMatrix,
scratchBoundingSphere3
);
}
let center = boundingSphere.center;
center = ellipsoid.scaleToGeodeticSurface(center, offsetCenterScratch);
let cartographic2 = ellipsoid.cartesianToCartographic(
center,
scratchBoundingSphereCartographic
);
const center2D = projection.project(
cartographic2,
scratchBoundingSphereCenter2D
);
const newPoint = Cartesian3_default.add(offset, center, offsetScratchCartesian);
cartographic2 = ellipsoid.cartesianToCartographic(newPoint, cartographic2);
const newPointProjected = projection.project(
cartographic2,
offsetScratchCartesian
);
const newVector = Cartesian3_default.subtract(
newPointProjected,
center2D,
offsetScratchCartesian
);
const x = newVector.x;
newVector.x = newVector.z;
newVector.z = newVector.y;
newVector.y = x;
batchTable.setBatchedAttribute(i, index2D, newVector);
}
primitive._batchTableOffsetsUpdated = true;
}
function createVertexArray(primitive, frameState) {
const attributeLocations8 = primitive._attributeLocations;
const geometries = primitive._geometries;
const scene3DOnly = frameState.scene3DOnly;
const context = frameState.context;
const va = [];
const length2 = geometries.length;
for (let i = 0; i < length2; ++i) {
const geometry = geometries[i];
va.push(
VertexArray_default.fromGeometry({
context,
geometry,
attributeLocations: attributeLocations8,
bufferUsage: BufferUsage_default.STATIC_DRAW,
interleave: primitive._interleave
})
);
if (defined_default(primitive._createBoundingVolumeFunction)) {
primitive._createBoundingVolumeFunction(frameState, geometry);
} else {
primitive._boundingSpheres.push(
BoundingSphere_default.clone(geometry.boundingSphere)
);
primitive._boundingSphereWC.push(new BoundingSphere_default());
if (!scene3DOnly) {
const center = geometry.boundingSphereCV.center;
const x = center.x;
const y = center.y;
const z2 = center.z;
center.x = z2;
center.y = x;
center.z = y;
primitive._boundingSphereCV.push(
BoundingSphere_default.clone(geometry.boundingSphereCV)
);
primitive._boundingSphere2D.push(new BoundingSphere_default());
primitive._boundingSphereMorph.push(new BoundingSphere_default());
}
}
}
primitive._va = va;
primitive._primitiveType = geometries[0].primitiveType;
if (primitive.releaseGeometryInstances) {
primitive.geometryInstances = void 0;
}
primitive._geometries = void 0;
setReady(primitive, frameState, PrimitiveState_default.COMPLETE, void 0);
}
function createRenderStates(primitive, context, appearance, twoPasses) {
let renderState = appearance.getRenderState();
let rs;
if (twoPasses) {
rs = clone_default(renderState, false);
rs.cull = {
enabled: true,
face: CullFace_default.BACK
};
primitive._frontFaceRS = RenderState_default.fromCache(rs);
rs.cull.face = CullFace_default.FRONT;
primitive._backFaceRS = RenderState_default.fromCache(rs);
} else {
primitive._frontFaceRS = RenderState_default.fromCache(renderState);
primitive._backFaceRS = primitive._frontFaceRS;
}
rs = clone_default(renderState, false);
if (defined_default(primitive._depthFailAppearance)) {
rs.depthTest.enabled = false;
}
if (defined_default(primitive._depthFailAppearance)) {
renderState = primitive._depthFailAppearance.getRenderState();
rs = clone_default(renderState, false);
rs.depthTest.func = DepthFunction_default.GREATER;
if (twoPasses) {
rs.cull = {
enabled: true,
face: CullFace_default.BACK
};
primitive._frontFaceDepthFailRS = RenderState_default.fromCache(rs);
rs.cull.face = CullFace_default.FRONT;
primitive._backFaceDepthFailRS = RenderState_default.fromCache(rs);
} else {
primitive._frontFaceDepthFailRS = RenderState_default.fromCache(rs);
primitive._backFaceDepthFailRS = primitive._frontFaceRS;
}
}
}
function createShaderProgram(primitive, frameState, appearance) {
const context = frameState.context;
const attributeLocations8 = primitive._attributeLocations;
let vs = primitive._batchTable.getVertexShaderCallback()(
appearance.vertexShaderSource
);
vs = Primitive._appendOffsetToShader(primitive, vs);
vs = Primitive._appendShowToShader(primitive, vs);
vs = Primitive._appendDistanceDisplayConditionToShader(
primitive,
vs,
frameState.scene3DOnly
);
vs = appendPickToVertexShader(vs);
vs = Primitive._updateColorAttribute(primitive, vs, false);
vs = modifyForEncodedNormals(primitive, vs);
vs = Primitive._modifyShaderPosition(primitive, vs, frameState.scene3DOnly);
let fs = appearance.getFragmentShaderSource();
fs = appendPickToFragmentShader(fs);
primitive._sp = ShaderProgram_default.replaceCache({
context,
shaderProgram: primitive._sp,
vertexShaderSource: vs,
fragmentShaderSource: fs,
attributeLocations: attributeLocations8
});
validateShaderMatching(primitive._sp, attributeLocations8);
if (defined_default(primitive._depthFailAppearance)) {
vs = primitive._batchTable.getVertexShaderCallback()(
primitive._depthFailAppearance.vertexShaderSource
);
vs = Primitive._appendShowToShader(primitive, vs);
vs = Primitive._appendDistanceDisplayConditionToShader(
primitive,
vs,
frameState.scene3DOnly
);
vs = appendPickToVertexShader(vs);
vs = Primitive._updateColorAttribute(primitive, vs, true);
vs = modifyForEncodedNormals(primitive, vs);
vs = Primitive._modifyShaderPosition(primitive, vs, frameState.scene3DOnly);
vs = depthClampVS(vs);
fs = primitive._depthFailAppearance.getFragmentShaderSource();
fs = appendPickToFragmentShader(fs);
fs = depthClampFS(fs);
primitive._spDepthFail = ShaderProgram_default.replaceCache({
context,
shaderProgram: primitive._spDepthFail,
vertexShaderSource: vs,
fragmentShaderSource: fs,
attributeLocations: attributeLocations8
});
validateShaderMatching(primitive._spDepthFail, attributeLocations8);
}
}
var modifiedModelViewScratch = new Matrix4_default();
var rtcScratch = new Cartesian3_default();
function getUniforms(primitive, appearance, material4, frameState) {
const materialUniformMap = defined_default(material4) ? material4._uniforms : void 0;
const appearanceUniformMap = {};
const appearanceUniforms = appearance.uniforms;
if (defined_default(appearanceUniforms)) {
for (const name in appearanceUniforms) {
if (appearanceUniforms.hasOwnProperty(name)) {
if (defined_default(materialUniformMap) && defined_default(materialUniformMap[name])) {
throw new DeveloperError_default(
`Appearance and material have a uniform with the same name: ${name}`
);
}
appearanceUniformMap[name] = getUniformFunction(
appearanceUniforms,
name
);
}
}
}
let uniforms = combine_default(appearanceUniformMap, materialUniformMap);
uniforms = primitive._batchTable.getUniformMapCallback()(uniforms);
if (defined_default(primitive.rtcCenter)) {
uniforms.u_modifiedModelView = function() {
const viewMatrix = frameState.context.uniformState.view;
Matrix4_default.multiply(
viewMatrix,
primitive._modelMatrix,
modifiedModelViewScratch
);
Matrix4_default.multiplyByPoint(
modifiedModelViewScratch,
primitive.rtcCenter,
rtcScratch
);
Matrix4_default.setTranslation(
modifiedModelViewScratch,
rtcScratch,
modifiedModelViewScratch
);
return modifiedModelViewScratch;
};
}
return uniforms;
}
function createCommands(primitive, appearance, material4, translucent, twoPasses, colorCommands, pickCommands, frameState) {
const uniforms = getUniforms(primitive, appearance, material4, frameState);
let depthFailUniforms;
if (defined_default(primitive._depthFailAppearance)) {
depthFailUniforms = getUniforms(
primitive,
primitive._depthFailAppearance,
primitive._depthFailAppearance.material,
frameState
);
}
const pass = translucent ? Pass_default.TRANSLUCENT : Pass_default.OPAQUE;
let multiplier = twoPasses ? 2 : 1;
multiplier *= defined_default(primitive._depthFailAppearance) ? 2 : 1;
colorCommands.length = primitive._va.length * multiplier;
const length2 = colorCommands.length;
let vaIndex = 0;
for (let i = 0; i < length2; ++i) {
let colorCommand;
if (twoPasses) {
colorCommand = colorCommands[i];
if (!defined_default(colorCommand)) {
colorCommand = colorCommands[i] = new DrawCommand_default({
owner: primitive,
primitiveType: primitive._primitiveType
});
}
colorCommand.vertexArray = primitive._va[vaIndex];
colorCommand.renderState = primitive._backFaceRS;
colorCommand.shaderProgram = primitive._sp;
colorCommand.uniformMap = uniforms;
colorCommand.pass = pass;
++i;
}
colorCommand = colorCommands[i];
if (!defined_default(colorCommand)) {
colorCommand = colorCommands[i] = new DrawCommand_default({
owner: primitive,
primitiveType: primitive._primitiveType
});
}
colorCommand.vertexArray = primitive._va[vaIndex];
colorCommand.renderState = primitive._frontFaceRS;
colorCommand.shaderProgram = primitive._sp;
colorCommand.uniformMap = uniforms;
colorCommand.pass = pass;
if (defined_default(primitive._depthFailAppearance)) {
if (twoPasses) {
++i;
colorCommand = colorCommands[i];
if (!defined_default(colorCommand)) {
colorCommand = colorCommands[i] = new DrawCommand_default({
owner: primitive,
primitiveType: primitive._primitiveType
});
}
colorCommand.vertexArray = primitive._va[vaIndex];
colorCommand.renderState = primitive._backFaceDepthFailRS;
colorCommand.shaderProgram = primitive._spDepthFail;
colorCommand.uniformMap = depthFailUniforms;
colorCommand.pass = pass;
}
++i;
colorCommand = colorCommands[i];
if (!defined_default(colorCommand)) {
colorCommand = colorCommands[i] = new DrawCommand_default({
owner: primitive,
primitiveType: primitive._primitiveType
});
}
colorCommand.vertexArray = primitive._va[vaIndex];
colorCommand.renderState = primitive._frontFaceDepthFailRS;
colorCommand.shaderProgram = primitive._spDepthFail;
colorCommand.uniformMap = depthFailUniforms;
colorCommand.pass = pass;
}
++vaIndex;
}
}
Primitive._updateBoundingVolumes = function(primitive, frameState, modelMatrix, forceUpdate) {
let i;
let length2;
let boundingSphere;
if (forceUpdate || !Matrix4_default.equals(modelMatrix, primitive._modelMatrix)) {
Matrix4_default.clone(modelMatrix, primitive._modelMatrix);
length2 = primitive._boundingSpheres.length;
for (i = 0; i < length2; ++i) {
boundingSphere = primitive._boundingSpheres[i];
if (defined_default(boundingSphere)) {
primitive._boundingSphereWC[i] = BoundingSphere_default.transform(
boundingSphere,
modelMatrix,
primitive._boundingSphereWC[i]
);
if (!frameState.scene3DOnly) {
primitive._boundingSphere2D[i] = BoundingSphere_default.clone(
primitive._boundingSphereCV[i],
primitive._boundingSphere2D[i]
);
primitive._boundingSphereMorph[i] = BoundingSphere_default.union(
primitive._boundingSphereWC[i],
primitive._boundingSphereCV[i]
);
}
}
}
}
const pixelSize = primitive.appearance.pixelSize;
if (defined_default(pixelSize)) {
length2 = primitive._boundingSpheres.length;
for (i = 0; i < length2; ++i) {
boundingSphere = primitive._boundingSpheres[i];
const boundingSphereWC = primitive._boundingSphereWC[i];
const pixelSizeInMeters = frameState.camera.getPixelSize(
boundingSphere,
frameState.context.drawingBufferWidth,
frameState.context.drawingBufferHeight
);
const sizeInMeters = pixelSizeInMeters * pixelSize;
boundingSphereWC.radius = boundingSphere.radius + sizeInMeters;
}
}
};
function updateAndQueueCommands(primitive, frameState, colorCommands, pickCommands, modelMatrix, cull, debugShowBoundingVolume2, twoPasses) {
if (frameState.mode !== SceneMode_default.SCENE3D && !Matrix4_default.equals(modelMatrix, Matrix4_default.IDENTITY)) {
throw new DeveloperError_default(
"Primitive.modelMatrix is only supported in 3D mode."
);
}
Primitive._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 commandList = frameState.commandList;
const passes = frameState.passes;
if (passes.render || passes.pick) {
const allowPicking = primitive.allowPicking;
const castShadows = ShadowMode_default.castShadows(primitive.shadows);
const receiveShadows = ShadowMode_default.receiveShadows(primitive.shadows);
const colorLength = colorCommands.length;
let factor2 = twoPasses ? 2 : 1;
factor2 *= defined_default(primitive._depthFailAppearance) ? 2 : 1;
for (let j = 0; j < colorLength; ++j) {
const sphereIndex = Math.floor(j / factor2);
const colorCommand = colorCommands[j];
colorCommand.modelMatrix = modelMatrix;
colorCommand.boundingVolume = boundingSpheres[sphereIndex];
colorCommand.cull = cull;
colorCommand.debugShowBoundingVolume = debugShowBoundingVolume2;
colorCommand.castShadows = castShadows;
colorCommand.receiveShadows = receiveShadows;
if (allowPicking) {
colorCommand.pickId = "v_pickColor";
} else {
colorCommand.pickId = void 0;
}
commandList.push(colorCommand);
}
}
}
Primitive.prototype.update = function(frameState) {
if (!defined_default(this.geometryInstances) && this._va.length === 0 || defined_default(this.geometryInstances) && Array.isArray(this.geometryInstances) && this.geometryInstances.length === 0 || !defined_default(this.appearance) || frameState.mode !== SceneMode_default.SCENE3D && frameState.scene3DOnly || !frameState.passes.render && !frameState.passes.pick) {
return;
}
if (defined_default(this._error)) {
throw this._error;
}
if (defined_default(this.rtcCenter) && !frameState.scene3DOnly) {
throw new DeveloperError_default(
"RTC rendering is only available for 3D only scenes."
);
}
if (this._state === PrimitiveState_default.FAILED) {
return;
}
const context = frameState.context;
if (!defined_default(this._batchTable)) {
createBatchTable(this, context);
}
if (this._batchTable.attributes.length > 0) {
if (ContextLimits_default.maximumVertexTextureImageUnits === 0) {
throw new RuntimeError_default(
"Vertex texture fetch support is required to render primitives with per-instance attributes. The maximum number of vertex texture image units must be greater than zero."
);
}
this._batchTable.update(frameState);
}
if (this._state !== PrimitiveState_default.COMPLETE && this._state !== PrimitiveState_default.COMBINED) {
if (this.asynchronous) {
loadAsynchronous(this, frameState);
} else {
loadSynchronous(this, frameState);
}
}
if (this._state === PrimitiveState_default.COMBINED) {
updateBatchTableBoundingSpheres(this, frameState);
updateBatchTableOffsets(this, frameState);
createVertexArray(this, frameState);
}
if (!this.show || this._state !== PrimitiveState_default.COMPLETE) {
return;
}
if (!this._batchTableOffsetsUpdated) {
updateBatchTableOffsets(this, frameState);
}
if (this._recomputeBoundingSpheres) {
recomputeBoundingSpheres(this, frameState);
}
const appearance = this.appearance;
const material4 = appearance.material;
let createRS = false;
let createSP = false;
if (this._appearance !== appearance) {
this._appearance = appearance;
this._material = material4;
createRS = true;
createSP = true;
} else if (this._material !== material4) {
this._material = material4;
createSP = true;
}
const depthFailAppearance = this.depthFailAppearance;
const depthFailMaterial = defined_default(depthFailAppearance) ? depthFailAppearance.material : void 0;
if (this._depthFailAppearance !== depthFailAppearance) {
this._depthFailAppearance = depthFailAppearance;
this._depthFailMaterial = depthFailMaterial;
createRS = true;
createSP = true;
} else if (this._depthFailMaterial !== depthFailMaterial) {
this._depthFailMaterial = depthFailMaterial;
createSP = true;
}
const translucent = this._appearance.isTranslucent();
if (this._translucent !== translucent) {
this._translucent = translucent;
createRS = true;
}
if (defined_default(this._material)) {
this._material.update(context);
}
const twoPasses = appearance.closed && translucent;
if (createRS) {
const rsFunc = this._createRenderStatesFunction ?? createRenderStates;
rsFunc(this, context, appearance, twoPasses);
}
if (createSP) {
const spFunc = this._createShaderProgramFunction ?? createShaderProgram;
spFunc(this, frameState, appearance);
}
if (createRS || createSP) {
const commandFunc = this._createCommandsFunction ?? createCommands;
commandFunc(
this,
appearance,
material4,
translucent,
twoPasses,
this._colorCommands,
this._pickCommands,
frameState
);
}
const updateAndQueueCommandsFunc = this._updateAndQueueCommandsFunction ?? updateAndQueueCommands;
updateAndQueueCommandsFunc(
this,
frameState,
this._colorCommands,
this._pickCommands,
this.modelMatrix,
this.cull,
this.debugShowBoundingVolume,
twoPasses
);
};
var offsetBoundingSphereScratch1 = new BoundingSphere_default();
var offsetBoundingSphereScratch2 = new BoundingSphere_default();
function transformBoundingSphere(boundingSphere, offset, offsetAttribute) {
if (offsetAttribute === GeometryOffsetAttribute_default.TOP) {
const origBS = BoundingSphere_default.clone(
boundingSphere,
offsetBoundingSphereScratch1
);
const offsetBS = BoundingSphere_default.clone(
boundingSphere,
offsetBoundingSphereScratch2
);
offsetBS.center = Cartesian3_default.add(offsetBS.center, offset, offsetBS.center);
boundingSphere = BoundingSphere_default.union(origBS, offsetBS, boundingSphere);
} else if (offsetAttribute === GeometryOffsetAttribute_default.ALL) {
boundingSphere.center = Cartesian3_default.add(
boundingSphere.center,
offset,
boundingSphere.center
);
}
return boundingSphere;
}
function createGetFunction(batchTable, instanceIndex, attributeIndex) {
return function() {
const attributeValue = batchTable.getBatchedAttribute(
instanceIndex,
attributeIndex
);
const attribute = batchTable.attributes[attributeIndex];
const componentsPerAttribute = attribute.componentsPerAttribute;
const value = ComponentDatatype_default.createTypedArray(
attribute.componentDatatype,
componentsPerAttribute
);
if (defined_default(attributeValue.constructor.pack)) {
attributeValue.constructor.pack(attributeValue, value, 0);
} else {
value[0] = attributeValue;
}
return value;
};
}
function createSetFunction(batchTable, instanceIndex, attributeIndex, primitive, name) {
return function(value) {
if (!defined_default(value) || !defined_default(value.length) || value.length < 1 || value.length > 4) {
throw new DeveloperError_default(
"value must be and array with length between 1 and 4."
);
}
const attributeValue = getAttributeValue(value);
batchTable.setBatchedAttribute(
instanceIndex,
attributeIndex,
attributeValue
);
if (name === "offset") {
primitive._recomputeBoundingSpheres = true;
primitive._batchTableOffsetsUpdated = false;
}
};
}
var offsetScratch2 = new Cartesian3_default();
function createBoundingSphereProperties(primitive, properties, index) {
properties.boundingSphere = {
get: function() {
let boundingSphere = primitive._instanceBoundingSpheres[index];
if (defined_default(boundingSphere)) {
boundingSphere = boundingSphere.clone();
const modelMatrix = primitive.modelMatrix;
const offset = properties.offset;
if (defined_default(offset)) {
transformBoundingSphere(
boundingSphere,
Cartesian3_default.fromArray(offset.get(), 0, offsetScratch2),
primitive._offsetInstanceExtend[index]
);
}
if (defined_default(modelMatrix)) {
boundingSphere = BoundingSphere_default.transform(
boundingSphere,
modelMatrix
);
}
}
return boundingSphere;
}
};
properties.boundingSphereCV = {
get: function() {
return primitive._instanceBoundingSpheresCV[index];
}
};
}
function createPickIdProperty(primitive, properties, index) {
properties.pickId = {
get: function() {
return primitive._pickIds[index];
}
};
}
Primitive.prototype.getGeometryInstanceAttributes = function(id) {
if (!defined_default(id)) {
throw new DeveloperError_default("id is required");
}
if (!defined_default(this._batchTable)) {
throw new DeveloperError_default(
"must call update before calling getGeometryInstanceAttributes"
);
}
let attributes = this._perInstanceAttributeCache.get(id);
if (defined_default(attributes)) {
return attributes;
}
let index = -1;
const lastIndex = this._lastPerInstanceAttributeIndex;
const ids = this._instanceIds;
const length2 = ids.length;
for (let i = 0; i < length2; ++i) {
const curIndex = (lastIndex + i) % length2;
if (id === ids[curIndex]) {
index = curIndex;
break;
}
}
if (index === -1) {
return void 0;
}
const batchTable = this._batchTable;
const perInstanceAttributeIndices = this._batchTableAttributeIndices;
attributes = {};
const properties = {};
for (const name in perInstanceAttributeIndices) {
if (perInstanceAttributeIndices.hasOwnProperty(name)) {
const attributeIndex = perInstanceAttributeIndices[name];
properties[name] = {
get: createGetFunction(batchTable, index, attributeIndex),
set: createSetFunction(batchTable, index, attributeIndex, this, name)
};
}
}
createBoundingSphereProperties(this, properties, index);
createPickIdProperty(this, properties, index);
Object.defineProperties(attributes, properties);
this._lastPerInstanceAttributeIndex = index;
this._perInstanceAttributeCache.set(id, attributes);
return attributes;
};
Primitive.prototype.isDestroyed = function() {
return false;
};
Primitive.prototype.destroy = function() {
let length2;
let i;
this._sp = this._sp && this._sp.destroy();
this._spDepthFail = this._spDepthFail && this._spDepthFail.destroy();
const va = this._va;
length2 = va.length;
for (i = 0; i < length2; ++i) {
va[i].destroy();
}
this._va = void 0;
const pickIds = this._pickIds;
length2 = pickIds.length;
for (i = 0; i < length2; ++i) {
pickIds[i].destroy();
}
this._pickIds = void 0;
this._batchTable = this._batchTable && this._batchTable.destroy();
this._instanceIds = void 0;
this._perInstanceAttributeCache = void 0;
this._attributeLocations = void 0;
return destroyObject_default(this);
};
function setReady(primitive, frameState, state, error) {
primitive._error = error;
primitive._state = state;
frameState.afterRender.push(function() {
primitive._ready = primitive._state === PrimitiveState_default.COMPLETE || primitive._state === PrimitiveState_default.FAILED;
return true;
});
}
var Primitive_default = Primitive;
// packages/engine/Source/Core/GeometryInstanceAttribute.js
function GeometryInstanceAttribute(options) {
options = options ?? Frozen_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.value)) {
throw new DeveloperError_default("options.value is required.");
}
this.componentDatatype = options.componentDatatype;
this.componentsPerAttribute = options.componentsPerAttribute;
this.normalize = options.normalize ?? false;
this.value = options.value;
}
var GeometryInstanceAttribute_default = GeometryInstanceAttribute;
// packages/engine/Source/Shaders/ShadowVolumeAppearanceFS.js
var ShadowVolumeAppearanceFS_default = "#ifdef TEXTURE_COORDINATES\n#ifdef SPHERICAL\nin vec4 v_sphericalExtents;\n#else // SPHERICAL\nin vec2 v_inversePlaneExtents;\nin vec4 v_westPlane;\nin vec4 v_southPlane;\n#endif // SPHERICAL\nin vec3 v_uvMinAndSphericalLongitudeRotation;\nin vec3 v_uMaxAndInverseDistance;\nin vec3 v_vMaxAndInverseDistance;\n#endif // TEXTURE_COORDINATES\n\n#ifdef PER_INSTANCE_COLOR\nin vec4 v_color;\n#endif\n\n#ifdef NORMAL_EC\nvec3 getEyeCoordinate3FromWindowCoordinate(vec2 fragCoord, float logDepthOrDepth) {\n vec4 eyeCoordinate = czm_windowToEyeCoordinates(fragCoord, logDepthOrDepth);\n return eyeCoordinate.xyz / eyeCoordinate.w;\n}\n\nvec3 vectorFromOffset(vec4 eyeCoordinate, vec2 positiveOffset) {\n vec2 glFragCoordXY = gl_FragCoord.xy;\n // Sample depths at both offset and negative offset\n float upOrRightLogDepth = czm_unpackDepth(texture(czm_globeDepthTexture, (glFragCoordXY + positiveOffset) / czm_viewport.zw));\n float downOrLeftLogDepth = czm_unpackDepth(texture(czm_globeDepthTexture, (glFragCoordXY - positiveOffset) / czm_viewport.zw));\n // Explicitly evaluate both paths\n // Necessary for multifrustum and for edges of the screen\n bvec2 upOrRightInBounds = lessThan(glFragCoordXY + positiveOffset, czm_viewport.zw);\n float useUpOrRight = float(upOrRightLogDepth > 0.0 && upOrRightInBounds.x && upOrRightInBounds.y);\n float useDownOrLeft = float(useUpOrRight == 0.0);\n vec3 upOrRightEC = getEyeCoordinate3FromWindowCoordinate(glFragCoordXY + positiveOffset, upOrRightLogDepth);\n vec3 downOrLeftEC = getEyeCoordinate3FromWindowCoordinate(glFragCoordXY - positiveOffset, downOrLeftLogDepth);\n return (upOrRightEC - (eyeCoordinate.xyz / eyeCoordinate.w)) * useUpOrRight + ((eyeCoordinate.xyz / eyeCoordinate.w) - downOrLeftEC) * useDownOrLeft;\n}\n#endif // NORMAL_EC\n\nvoid main(void)\n{\n#ifdef REQUIRES_EC\n float logDepthOrDepth = czm_unpackDepth(texture(czm_globeDepthTexture, gl_FragCoord.xy / czm_viewport.zw));\n vec4 eyeCoordinate = czm_windowToEyeCoordinates(gl_FragCoord.xy, logDepthOrDepth);\n#endif\n\n#ifdef REQUIRES_WC\n vec4 worldCoordinate4 = czm_inverseView * eyeCoordinate;\n vec3 worldCoordinate = worldCoordinate4.xyz / worldCoordinate4.w;\n#endif\n\n#ifdef TEXTURE_COORDINATES\n vec2 uv;\n#ifdef SPHERICAL\n // Treat world coords as a sphere normal for spherical coordinates\n vec2 sphericalLatLong = czm_approximateSphericalCoordinates(worldCoordinate);\n sphericalLatLong.y += v_uvMinAndSphericalLongitudeRotation.z;\n sphericalLatLong.y = czm_branchFreeTernary(sphericalLatLong.y < czm_pi, sphericalLatLong.y, sphericalLatLong.y - czm_twoPi);\n uv.x = (sphericalLatLong.y - v_sphericalExtents.y) * v_sphericalExtents.w;\n uv.y = (sphericalLatLong.x - v_sphericalExtents.x) * v_sphericalExtents.z;\n#else // SPHERICAL\n // Unpack planes and transform to eye space\n uv.x = czm_planeDistance(v_westPlane, eyeCoordinate.xyz / eyeCoordinate.w) * v_inversePlaneExtents.x;\n uv.y = czm_planeDistance(v_southPlane, eyeCoordinate.xyz / eyeCoordinate.w) * v_inversePlaneExtents.y;\n#endif // SPHERICAL\n#endif // TEXTURE_COORDINATES\n\n#ifdef CULL_FRAGMENTS\n // When classifying translucent geometry, logDepthOrDepth == 0.0\n // indicates a region that should not be classified, possibly due to there\n // being opaque pixels there in another buffer.\n if (uv.x <= 0.0 || 1.0 <= uv.x || uv.y <= 0.0 || 1.0 <= uv.y || logDepthOrDepth == 0.0) {\n discard;\n }\n#endif\n\n#ifdef PICK\n out_FragColor.a = 1.0; // Explicitly set the alpha, otherwise this may be discarded by ShaderSource.createPickFragmentShaderSource\n#ifdef CULL_FRAGMENTS\n czm_writeDepthClamp();\n#endif // CULL_FRAGMENTS\n#else // PICK\n\n#ifdef NORMAL_EC\n // Compute normal by sampling adjacent pixels in 2x2 block in screen space\n vec3 downUp = vectorFromOffset(eyeCoordinate, vec2(0.0, 1.0));\n vec3 leftRight = vectorFromOffset(eyeCoordinate, vec2(1.0, 0.0));\n vec3 normalEC = normalize(cross(leftRight, downUp));\n#endif\n\n\n#ifdef PER_INSTANCE_COLOR\n\n vec4 color = czm_gammaCorrect(v_color);\n#ifdef FLAT\n out_FragColor = color;\n#else // FLAT\n czm_materialInput materialInput;\n materialInput.normalEC = normalEC;\n materialInput.positionToEyeEC = -eyeCoordinate.xyz;\n czm_material material = czm_getDefaultMaterial(materialInput);\n material.diffuse = color.rgb;\n material.alpha = color.a;\n\n out_FragColor = czm_phong(normalize(-eyeCoordinate.xyz), material, czm_lightDirectionEC);\n#endif // FLAT\n\n // Premultiply alpha. Required for classification primitives on translucent globe.\n out_FragColor.rgb *= out_FragColor.a;\n\n#else // PER_INSTANCE_COLOR\n\n // Material support.\n // USES_ is distinct from REQUIRES_, because some things are dependencies of each other or\n // dependencies for culling but might not actually be used by the material.\n\n czm_materialInput materialInput;\n\n#ifdef USES_NORMAL_EC\n materialInput.normalEC = normalEC;\n#endif\n\n#ifdef USES_POSITION_TO_EYE_EC\n materialInput.positionToEyeEC = -eyeCoordinate.xyz;\n#endif\n\n#ifdef USES_TANGENT_TO_EYE\n materialInput.tangentToEyeMatrix = czm_eastNorthUpToEyeCoordinates(worldCoordinate, normalEC);\n#endif\n\n#ifdef USES_ST\n // Remap texture coordinates from computed (approximately aligned with cartographic space) to the desired\n // texture coordinate system, which typically forms a tight oriented bounding box around the geometry.\n // Shader is provided a set of reference points for remapping.\n materialInput.st.x = czm_lineDistance(v_uvMinAndSphericalLongitudeRotation.xy, v_uMaxAndInverseDistance.xy, uv) * v_uMaxAndInverseDistance.z;\n materialInput.st.y = czm_lineDistance(v_uvMinAndSphericalLongitudeRotation.xy, v_vMaxAndInverseDistance.xy, uv) * v_vMaxAndInverseDistance.z;\n#endif\n\n czm_material material = czm_getMaterial(materialInput);\n\n#ifdef FLAT\n out_FragColor = vec4(material.diffuse + material.emission, material.alpha);\n#else // FLAT\n out_FragColor = czm_phong(normalize(-eyeCoordinate.xyz), material, czm_lightDirectionEC);\n#endif // FLAT\n\n // Premultiply alpha. Required for classification primitives on translucent globe.\n out_FragColor.rgb *= out_FragColor.a;\n\n#endif // PER_INSTANCE_COLOR\n czm_writeDepthClamp();\n#endif // PICK\n}\n";
// packages/engine/Source/Scene/ShadowVolumeAppearance.js
function ShadowVolumeAppearance(extentsCulling, planarExtents, appearance) {
Check_default.typeOf.bool("extentsCulling", extentsCulling);
Check_default.typeOf.bool("planarExtents", planarExtents);
Check_default.typeOf.object("appearance", appearance);
this._projectionExtentDefines = {
eastMostYhighDefine: "",
eastMostYlowDefine: "",
westMostYhighDefine: "",
westMostYlowDefine: ""
};
const colorShaderDependencies = new ShaderDependencies();
colorShaderDependencies.requiresTextureCoordinates = extentsCulling;
colorShaderDependencies.requiresEC = !appearance.flat;
const pickShaderDependencies = new ShaderDependencies();
pickShaderDependencies.requiresTextureCoordinates = extentsCulling;
if (appearance instanceof PerInstanceColorAppearance_default) {
colorShaderDependencies.requiresNormalEC = !appearance.flat;
} else {
const materialShaderSource = `${appearance.material.shaderSource}
${appearance.fragmentShaderSource}`;
colorShaderDependencies.normalEC = materialShaderSource.indexOf("materialInput.normalEC") !== -1 || materialShaderSource.indexOf("czm_getDefaultMaterial") !== -1;
colorShaderDependencies.positionToEyeEC = materialShaderSource.indexOf("materialInput.positionToEyeEC") !== -1;
colorShaderDependencies.tangentToEyeMatrix = materialShaderSource.indexOf("materialInput.tangentToEyeMatrix") !== -1;
colorShaderDependencies.st = materialShaderSource.indexOf("materialInput.st") !== -1;
}
this._colorShaderDependencies = colorShaderDependencies;
this._pickShaderDependencies = pickShaderDependencies;
this._appearance = appearance;
this._extentsCulling = extentsCulling;
this._planarExtents = planarExtents;
}
ShadowVolumeAppearance.prototype.createFragmentShader = function(columbusView2D) {
Check_default.typeOf.bool("columbusView2D", columbusView2D);
const appearance = this._appearance;
const dependencies = this._colorShaderDependencies;
const defines = [];
if (!columbusView2D && !this._planarExtents) {
defines.push("SPHERICAL");
}
if (dependencies.requiresEC) {
defines.push("REQUIRES_EC");
}
if (dependencies.requiresWC) {
defines.push("REQUIRES_WC");
}
if (dependencies.requiresTextureCoordinates) {
defines.push("TEXTURE_COORDINATES");
}
if (this._extentsCulling) {
defines.push("CULL_FRAGMENTS");
}
if (dependencies.requiresNormalEC) {
defines.push("NORMAL_EC");
}
if (appearance instanceof PerInstanceColorAppearance_default) {
defines.push("PER_INSTANCE_COLOR");
}
if (dependencies.normalEC) {
defines.push("USES_NORMAL_EC");
}
if (dependencies.positionToEyeEC) {
defines.push("USES_POSITION_TO_EYE_EC");
}
if (dependencies.tangentToEyeMatrix) {
defines.push("USES_TANGENT_TO_EYE");
}
if (dependencies.st) {
defines.push("USES_ST");
}
if (appearance.flat) {
defines.push("FLAT");
}
let materialSource = "";
if (!(appearance instanceof PerInstanceColorAppearance_default)) {
materialSource = appearance.material.shaderSource;
}
return new ShaderSource_default({
defines,
sources: [materialSource, ShadowVolumeAppearanceFS_default]
});
};
ShadowVolumeAppearance.prototype.createPickFragmentShader = function(columbusView2D) {
Check_default.typeOf.bool("columbusView2D", columbusView2D);
const dependencies = this._pickShaderDependencies;
const defines = ["PICK"];
if (!columbusView2D && !this._planarExtents) {
defines.push("SPHERICAL");
}
if (dependencies.requiresEC) {
defines.push("REQUIRES_EC");
}
if (dependencies.requiresWC) {
defines.push("REQUIRES_WC");
}
if (dependencies.requiresTextureCoordinates) {
defines.push("TEXTURE_COORDINATES");
}
if (this._extentsCulling) {
defines.push("CULL_FRAGMENTS");
}
return new ShaderSource_default({
defines,
sources: [ShadowVolumeAppearanceFS_default],
pickColorQualifier: "in"
});
};
ShadowVolumeAppearance.prototype.createVertexShader = function(defines, vertexShaderSource, columbusView2D, mapProjection) {
Check_default.defined("defines", defines);
Check_default.typeOf.string("vertexShaderSource", vertexShaderSource);
Check_default.typeOf.bool("columbusView2D", columbusView2D);
Check_default.defined("mapProjection", mapProjection);
return createShadowVolumeAppearanceVS(
this._colorShaderDependencies,
this._planarExtents,
columbusView2D,
defines,
vertexShaderSource,
this._appearance,
mapProjection,
this._projectionExtentDefines
);
};
ShadowVolumeAppearance.prototype.createPickVertexShader = function(defines, vertexShaderSource, columbusView2D, mapProjection) {
Check_default.defined("defines", defines);
Check_default.typeOf.string("vertexShaderSource", vertexShaderSource);
Check_default.typeOf.bool("columbusView2D", columbusView2D);
Check_default.defined("mapProjection", mapProjection);
return createShadowVolumeAppearanceVS(
this._pickShaderDependencies,
this._planarExtents,
columbusView2D,
defines,
vertexShaderSource,
void 0,
mapProjection,
this._projectionExtentDefines
);
};
var longitudeExtentsCartesianScratch = new Cartesian3_default();
var longitudeExtentsCartographicScratch = new Cartographic_default();
var longitudeExtentsEncodeScratch = {
high: 0,
low: 0
};
function createShadowVolumeAppearanceVS(shaderDependencies, planarExtents, columbusView2D, defines, vertexShaderSource, appearance, mapProjection, projectionExtentDefines) {
const allDefines = defines.slice();
if (projectionExtentDefines.eastMostYhighDefine === "") {
const eastMostCartographic = longitudeExtentsCartographicScratch;
eastMostCartographic.longitude = Math_default.PI;
eastMostCartographic.latitude = 0;
eastMostCartographic.height = 0;
const eastMostCartesian = mapProjection.project(
eastMostCartographic,
longitudeExtentsCartesianScratch
);
let encoded = EncodedCartesian3_default.encode(
eastMostCartesian.x,
longitudeExtentsEncodeScratch
);
projectionExtentDefines.eastMostYhighDefine = `EAST_MOST_X_HIGH ${encoded.high.toFixed(
`${encoded.high}`.length + 1
)}`;
projectionExtentDefines.eastMostYlowDefine = `EAST_MOST_X_LOW ${encoded.low.toFixed(
`${encoded.low}`.length + 1
)}`;
const westMostCartographic = longitudeExtentsCartographicScratch;
westMostCartographic.longitude = -Math_default.PI;
westMostCartographic.latitude = 0;
westMostCartographic.height = 0;
const westMostCartesian = mapProjection.project(
westMostCartographic,
longitudeExtentsCartesianScratch
);
encoded = EncodedCartesian3_default.encode(
westMostCartesian.x,
longitudeExtentsEncodeScratch
);
projectionExtentDefines.westMostYhighDefine = `WEST_MOST_X_HIGH ${encoded.high.toFixed(
`${encoded.high}`.length + 1
)}`;
projectionExtentDefines.westMostYlowDefine = `WEST_MOST_X_LOW ${encoded.low.toFixed(
`${encoded.low}`.length + 1
)}`;
}
if (columbusView2D) {
allDefines.push(projectionExtentDefines.eastMostYhighDefine);
allDefines.push(projectionExtentDefines.eastMostYlowDefine);
allDefines.push(projectionExtentDefines.westMostYhighDefine);
allDefines.push(projectionExtentDefines.westMostYlowDefine);
}
if (defined_default(appearance) && appearance instanceof PerInstanceColorAppearance_default) {
allDefines.push("PER_INSTANCE_COLOR");
}
if (shaderDependencies.requiresTextureCoordinates) {
allDefines.push("TEXTURE_COORDINATES");
if (!(planarExtents || columbusView2D)) {
allDefines.push("SPHERICAL");
}
if (columbusView2D) {
allDefines.push("COLUMBUS_VIEW_2D");
}
}
return new ShaderSource_default({
defines: allDefines,
sources: [vertexShaderSource]
});
}
function ShaderDependencies() {
this._requiresEC = false;
this._requiresWC = false;
this._requiresNormalEC = false;
this._requiresTextureCoordinates = false;
this._usesNormalEC = false;
this._usesPositionToEyeEC = false;
this._usesTangentToEyeMat = false;
this._usesSt = false;
}
Object.defineProperties(ShaderDependencies.prototype, {
// Set when assessing final shading (flat vs. phong) and culling using computed texture coordinates
requiresEC: {
get: function() {
return this._requiresEC;
},
set: function(value) {
this._requiresEC = value || this._requiresEC;
}
},
requiresWC: {
get: function() {
return this._requiresWC;
},
set: function(value) {
this._requiresWC = value || this._requiresWC;
this.requiresEC = this._requiresWC;
}
},
requiresNormalEC: {
get: function() {
return this._requiresNormalEC;
},
set: function(value) {
this._requiresNormalEC = value || this._requiresNormalEC;
this.requiresEC = this._requiresNormalEC;
}
},
requiresTextureCoordinates: {
get: function() {
return this._requiresTextureCoordinates;
},
set: function(value) {
this._requiresTextureCoordinates = value || this._requiresTextureCoordinates;
this.requiresWC = this._requiresTextureCoordinates;
}
},
// Get/Set when assessing material hookups
normalEC: {
set: function(value) {
this.requiresNormalEC = value;
this._usesNormalEC = value;
},
get: function() {
return this._usesNormalEC;
}
},
tangentToEyeMatrix: {
set: function(value) {
this.requiresWC = value;
this.requiresNormalEC = value;
this._usesTangentToEyeMat = value;
},
get: function() {
return this._usesTangentToEyeMat;
}
},
positionToEyeEC: {
set: function(value) {
this.requiresEC = value;
this._usesPositionToEyeEC = value;
},
get: function() {
return this._usesPositionToEyeEC;
}
},
st: {
set: function(value) {
this.requiresTextureCoordinates = value;
this._usesSt = value;
},
get: function() {
return this._usesSt;
}
}
});
function pointLineDistance(point1, point22, point4) {
return Math.abs(
(point22.y - point1.y) * point4.x - (point22.x - point1.x) * point4.y + point22.x * point1.y - point22.y * point1.x
) / Cartesian2_default.distance(point22, point1);
}
var points2DScratch2 = [
new Cartesian2_default(),
new Cartesian2_default(),
new Cartesian2_default(),
new Cartesian2_default()
];
function addTextureCoordinateRotationAttributes(attributes, textureCoordinateRotationPoints4) {
const points2D = points2DScratch2;
const minXYCorner = Cartesian2_default.unpack(
textureCoordinateRotationPoints4,
0,
points2D[0]
);
const maxYCorner = Cartesian2_default.unpack(
textureCoordinateRotationPoints4,
2,
points2D[1]
);
const maxXCorner = Cartesian2_default.unpack(
textureCoordinateRotationPoints4,
4,
points2D[2]
);
attributes.uMaxVmax = new GeometryInstanceAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 4,
normalize: false,
value: [maxYCorner.x, maxYCorner.y, maxXCorner.x, maxXCorner.y]
});
const inverseExtentX = 1 / pointLineDistance(minXYCorner, maxYCorner, maxXCorner);
const inverseExtentY = 1 / pointLineDistance(minXYCorner, maxXCorner, maxYCorner);
attributes.uvMinAndExtents = new GeometryInstanceAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 4,
normalize: false,
value: [minXYCorner.x, minXYCorner.y, inverseExtentX, inverseExtentY]
});
}
var cartographicScratch = new Cartographic_default();
var cornerScratch = new Cartesian3_default();
var northWestScratch = new Cartesian3_default();
var southEastScratch = new Cartesian3_default();
var highLowScratch = { high: 0, low: 0 };
function add2DTextureCoordinateAttributes(rectangle, projection, attributes) {
const carto = cartographicScratch;
carto.height = 0;
carto.longitude = rectangle.west;
carto.latitude = rectangle.south;
const southWestCorner = projection.project(carto, cornerScratch);
carto.latitude = rectangle.north;
const northWest = projection.project(carto, northWestScratch);
carto.longitude = rectangle.east;
carto.latitude = rectangle.south;
const southEast = projection.project(carto, southEastScratch);
const valuesHigh = [0, 0, 0, 0];
const valuesLow = [0, 0, 0, 0];
let encoded = EncodedCartesian3_default.encode(southWestCorner.x, highLowScratch);
valuesHigh[0] = encoded.high;
valuesLow[0] = encoded.low;
encoded = EncodedCartesian3_default.encode(southWestCorner.y, highLowScratch);
valuesHigh[1] = encoded.high;
valuesLow[1] = encoded.low;
encoded = EncodedCartesian3_default.encode(northWest.y, highLowScratch);
valuesHigh[2] = encoded.high;
valuesLow[2] = encoded.low;
encoded = EncodedCartesian3_default.encode(southEast.x, highLowScratch);
valuesHigh[3] = encoded.high;
valuesLow[3] = encoded.low;
attributes.planes2D_HIGH = new GeometryInstanceAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 4,
normalize: false,
value: valuesHigh
});
attributes.planes2D_LOW = new GeometryInstanceAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 4,
normalize: false,
value: valuesLow
});
}
var enuMatrixScratch = new Matrix4_default();
var inverseEnuScratch = new Matrix4_default();
var rectanglePointCartesianScratch = new Cartesian3_default();
var rectangleCenterScratch2 = new Cartographic_default();
var pointsCartographicScratch = [
new Cartographic_default(),
new Cartographic_default(),
new Cartographic_default(),
new Cartographic_default(),
new Cartographic_default(),
new Cartographic_default(),
new Cartographic_default(),
new Cartographic_default()
];
function computeRectangleBounds(rectangle, ellipsoid, height, southWestCornerResult, eastVectorResult, northVectorResult) {
const centerCartographic = Rectangle_default.center(
rectangle,
rectangleCenterScratch2
);
centerCartographic.height = height;
const centerCartesian2 = Cartographic_default.toCartesian(
centerCartographic,
ellipsoid,
rectanglePointCartesianScratch
);
const enuMatrix = Transforms_default.eastNorthUpToFixedFrame(
centerCartesian2,
ellipsoid,
enuMatrixScratch
);
const inverseEnu = Matrix4_default.inverse(enuMatrix, inverseEnuScratch);
const west = rectangle.west;
const east = rectangle.east;
const north = rectangle.north;
const south = rectangle.south;
const cartographics = pointsCartographicScratch;
cartographics[0].latitude = south;
cartographics[0].longitude = west;
cartographics[1].latitude = north;
cartographics[1].longitude = west;
cartographics[2].latitude = north;
cartographics[2].longitude = east;
cartographics[3].latitude = south;
cartographics[3].longitude = east;
const longitudeCenter = (west + east) * 0.5;
const latitudeCenter = (north + south) * 0.5;
cartographics[4].latitude = south;
cartographics[4].longitude = longitudeCenter;
cartographics[5].latitude = north;
cartographics[5].longitude = longitudeCenter;
cartographics[6].latitude = latitudeCenter;
cartographics[6].longitude = west;
cartographics[7].latitude = latitudeCenter;
cartographics[7].longitude = east;
let minX = Number.POSITIVE_INFINITY;
let maxX = Number.NEGATIVE_INFINITY;
let minY = Number.POSITIVE_INFINITY;
let maxY = Number.NEGATIVE_INFINITY;
for (let i = 0; i < 8; i++) {
cartographics[i].height = height;
const pointCartesian = Cartographic_default.toCartesian(
cartographics[i],
ellipsoid,
rectanglePointCartesianScratch
);
Matrix4_default.multiplyByPoint(inverseEnu, pointCartesian, pointCartesian);
pointCartesian.z = 0;
minX = Math.min(minX, pointCartesian.x);
maxX = Math.max(maxX, pointCartesian.x);
minY = Math.min(minY, pointCartesian.y);
maxY = Math.max(maxY, pointCartesian.y);
}
const southWestCorner = southWestCornerResult;
southWestCorner.x = minX;
southWestCorner.y = minY;
southWestCorner.z = 0;
Matrix4_default.multiplyByPoint(enuMatrix, southWestCorner, southWestCorner);
const southEastCorner = eastVectorResult;
southEastCorner.x = maxX;
southEastCorner.y = minY;
southEastCorner.z = 0;
Matrix4_default.multiplyByPoint(enuMatrix, southEastCorner, southEastCorner);
Cartesian3_default.subtract(southEastCorner, southWestCorner, eastVectorResult);
const northWestCorner = northVectorResult;
northWestCorner.x = minX;
northWestCorner.y = maxY;
northWestCorner.z = 0;
Matrix4_default.multiplyByPoint(enuMatrix, northWestCorner, northWestCorner);
Cartesian3_default.subtract(northWestCorner, southWestCorner, northVectorResult);
}
var eastwardScratch = new Cartesian3_default();
var northwardScratch = new Cartesian3_default();
var encodeScratch = new EncodedCartesian3_default();
ShadowVolumeAppearance.getPlanarTextureCoordinateAttributes = function(boundingRectangle, textureCoordinateRotationPoints4, ellipsoid, projection, height) {
Check_default.typeOf.object("boundingRectangle", boundingRectangle);
Check_default.defined(
"textureCoordinateRotationPoints",
textureCoordinateRotationPoints4
);
Check_default.typeOf.object("ellipsoid", ellipsoid);
Check_default.typeOf.object("projection", projection);
const corner = cornerScratch;
const eastward = eastwardScratch;
const northward = northwardScratch;
computeRectangleBounds(
boundingRectangle,
ellipsoid,
height ?? 0,
corner,
eastward,
northward
);
const attributes = {};
addTextureCoordinateRotationAttributes(
attributes,
textureCoordinateRotationPoints4
);
const encoded = EncodedCartesian3_default.fromCartesian(corner, encodeScratch);
attributes.southWest_HIGH = new GeometryInstanceAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
normalize: false,
value: Cartesian3_default.pack(encoded.high, [0, 0, 0])
});
attributes.southWest_LOW = new GeometryInstanceAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
normalize: false,
value: Cartesian3_default.pack(encoded.low, [0, 0, 0])
});
attributes.eastward = new GeometryInstanceAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
normalize: false,
value: Cartesian3_default.pack(eastward, [0, 0, 0])
});
attributes.northward = new GeometryInstanceAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
normalize: false,
value: Cartesian3_default.pack(northward, [0, 0, 0])
});
add2DTextureCoordinateAttributes(boundingRectangle, projection, attributes);
return attributes;
};
var spherePointScratch = new Cartesian3_default();
function latLongToSpherical(latitude, longitude, ellipsoid, result) {
const cartographic2 = cartographicScratch;
cartographic2.latitude = latitude;
cartographic2.longitude = longitude;
cartographic2.height = 0;
const spherePoint = Cartographic_default.toCartesian(
cartographic2,
ellipsoid,
spherePointScratch
);
const magXY = Math.sqrt(
spherePoint.x * spherePoint.x + spherePoint.y * spherePoint.y
);
const sphereLatitude = Math_default.fastApproximateAtan2(magXY, spherePoint.z);
const sphereLongitude = Math_default.fastApproximateAtan2(
spherePoint.x,
spherePoint.y
);
result.x = sphereLatitude;
result.y = sphereLongitude;
return result;
}
var sphericalScratch = new Cartesian2_default();
ShadowVolumeAppearance.getSphericalExtentGeometryInstanceAttributes = function(boundingRectangle, textureCoordinateRotationPoints4, ellipsoid, projection) {
Check_default.typeOf.object("boundingRectangle", boundingRectangle);
Check_default.defined(
"textureCoordinateRotationPoints",
textureCoordinateRotationPoints4
);
Check_default.typeOf.object("ellipsoid", ellipsoid);
Check_default.typeOf.object("projection", projection);
const southWestExtents = latLongToSpherical(
boundingRectangle.south,
boundingRectangle.west,
ellipsoid,
sphericalScratch
);
let south = southWestExtents.x;
let west = southWestExtents.y;
const northEastExtents = latLongToSpherical(
boundingRectangle.north,
boundingRectangle.east,
ellipsoid,
sphericalScratch
);
let north = northEastExtents.x;
let east = northEastExtents.y;
let rotationRadians = 0;
if (west > east) {
rotationRadians = Math_default.PI - west;
west = -Math_default.PI;
east += rotationRadians;
}
south -= Math_default.EPSILON5;
west -= Math_default.EPSILON5;
north += Math_default.EPSILON5;
east += Math_default.EPSILON5;
const longitudeRangeInverse = 1 / (east - west);
const latitudeRangeInverse = 1 / (north - south);
const attributes = {
sphericalExtents: new GeometryInstanceAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 4,
normalize: false,
value: [south, west, latitudeRangeInverse, longitudeRangeInverse]
}),
longitudeRotation: new GeometryInstanceAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 1,
normalize: false,
value: [rotationRadians]
})
};
addTextureCoordinateRotationAttributes(
attributes,
textureCoordinateRotationPoints4
);
add2DTextureCoordinateAttributes(boundingRectangle, projection, attributes);
return attributes;
};
ShadowVolumeAppearance.hasAttributesForTextureCoordinatePlanes = function(attributes) {
return defined_default(attributes.southWest_HIGH) && defined_default(attributes.southWest_LOW) && defined_default(attributes.northward) && defined_default(attributes.eastward) && defined_default(attributes.planes2D_HIGH) && defined_default(attributes.planes2D_LOW) && defined_default(attributes.uMaxVmax) && defined_default(attributes.uvMinAndExtents);
};
ShadowVolumeAppearance.hasAttributesForSphericalExtents = function(attributes) {
return defined_default(attributes.sphericalExtents) && defined_default(attributes.longitudeRotation) && defined_default(attributes.planes2D_HIGH) && defined_default(attributes.planes2D_LOW) && defined_default(attributes.uMaxVmax) && defined_default(attributes.uvMinAndExtents);
};
function shouldUseSpherical(rectangle) {
return Math.max(rectangle.width, rectangle.height) > ShadowVolumeAppearance.MAX_WIDTH_FOR_PLANAR_EXTENTS;
}
ShadowVolumeAppearance.shouldUseSphericalCoordinates = function(rectangle) {
Check_default.typeOf.object("rectangle", rectangle);
return shouldUseSpherical(rectangle);
};
ShadowVolumeAppearance.MAX_WIDTH_FOR_PLANAR_EXTENTS = Math_default.toRadians(1);
var ShadowVolumeAppearance_default = ShadowVolumeAppearance;
// packages/engine/Source/Scene/StencilFunction.js
var StencilFunction = {
/**
* The stencil test never passes.
*
* @type {number}
* @constant
*/
NEVER: WebGLConstants_default.NEVER,
/**
* The stencil test passes when the masked reference value is less than the masked stencil value.
*
* @type {number}
* @constant
*/
LESS: WebGLConstants_default.LESS,
/**
* The stencil test passes when the masked reference value is equal to the masked stencil value.
*
* @type {number}
* @constant
*/
EQUAL: WebGLConstants_default.EQUAL,
/**
* The stencil test passes when the masked reference value is less than or equal to the masked stencil value.
*
* @type {number}
* @constant
*/
LESS_OR_EQUAL: WebGLConstants_default.LEQUAL,
/**
* The stencil test passes when the masked reference value is greater than the masked stencil value.
*
* @type {number}
* @constant
*/
GREATER: WebGLConstants_default.GREATER,
/**
* The stencil test passes when the masked reference value is not equal to the masked stencil value.
*
* @type {number}
* @constant
*/
NOT_EQUAL: WebGLConstants_default.NOTEQUAL,
/**
* The stencil test passes when the masked reference value is greater than or equal to the masked stencil value.
*
* @type {number}
* @constant
*/
GREATER_OR_EQUAL: WebGLConstants_default.GEQUAL,
/**
* The stencil test always passes.
*
* @type {number}
* @constant
*/
ALWAYS: WebGLConstants_default.ALWAYS
};
Object.freeze(StencilFunction);
var StencilFunction_default = StencilFunction;
// packages/engine/Source/Scene/StencilOperation.js
var StencilOperation = {
/**
* Sets the stencil buffer value to zero.
*
* @type {number}
* @constant
*/
ZERO: WebGLConstants_default.ZERO,
/**
* Does not change the stencil buffer.
*
* @type {number}
* @constant
*/
KEEP: WebGLConstants_default.KEEP,
/**
* Replaces the stencil buffer value with the reference value.
*
* @type {number}
* @constant
*/
REPLACE: WebGLConstants_default.REPLACE,
/**
* Increments the stencil buffer value, clamping to unsigned byte.
*
* @type {number}
* @constant
*/
INCREMENT: WebGLConstants_default.INCR,
/**
* Decrements the stencil buffer value, clamping to zero.
*
* @type {number}
* @constant
*/
DECREMENT: WebGLConstants_default.DECR,
/**
* Bitwise inverts the existing stencil buffer value.
*
* @type {number}
* @constant
*/
INVERT: WebGLConstants_default.INVERT,
/**
* Increments the stencil buffer value, wrapping to zero when exceeding the unsigned byte range.
*
* @type {number}
* @constant
*/
INCREMENT_WRAP: WebGLConstants_default.INCR_WRAP,
/**
* Decrements the stencil buffer value, wrapping to the maximum unsigned byte instead of going below zero.
*
* @type {number}
* @constant
*/
DECREMENT_WRAP: WebGLConstants_default.DECR_WRAP
};
Object.freeze(StencilOperation);
var StencilOperation_default = StencilOperation;
// packages/engine/Source/Scene/StencilConstants.js
var StencilConstants = {
CESIUM_3D_TILE_MASK: 128,
SKIP_LOD_MASK: 112,
SKIP_LOD_BIT_SHIFT: 4,
CLASSIFICATION_MASK: 15
};
StencilConstants.setCesium3DTileBit = function() {
return {
enabled: true,
frontFunction: StencilFunction_default.ALWAYS,
frontOperation: {
fail: StencilOperation_default.KEEP,
zFail: StencilOperation_default.KEEP,
zPass: StencilOperation_default.REPLACE
},
backFunction: StencilFunction_default.ALWAYS,
backOperation: {
fail: StencilOperation_default.KEEP,
zFail: StencilOperation_default.KEEP,
zPass: StencilOperation_default.REPLACE
},
reference: StencilConstants.CESIUM_3D_TILE_MASK,
mask: StencilConstants.CESIUM_3D_TILE_MASK
};
};
var StencilConstants_default = Object.freeze(StencilConstants);
// packages/engine/Source/Scene/ClassificationPrimitive.js
function ClassificationPrimitive(options) {
options = options ?? Frozen_default.EMPTY_OBJECT;
const geometryInstances = options.geometryInstances;
this.geometryInstances = geometryInstances;
this.show = options.show ?? true;
this.classificationType = options.classificationType ?? ClassificationType_default.BOTH;
this.debugShowBoundingVolume = options.debugShowBoundingVolume ?? false;
this.debugShowShadowVolume = options.debugShowShadowVolume ?? false;
this._debugShowShadowVolume = false;
this._extruded = options._extruded ?? false;
this._uniformMap = options._uniformMap;
this._sp = void 0;
this._spStencil = void 0;
this._spPick = void 0;
this._spColor = void 0;
this._spPick2D = void 0;
this._spColor2D = void 0;
this._rsStencilDepthPass = void 0;
this._rsStencilDepthPass3DTiles = void 0;
this._rsColorPass = void 0;
this._rsPickPass = void 0;
this._commandsIgnoreShow = [];
this._ready = false;
this._primitive = void 0;
this._pickPrimitive = options._pickPrimitive;
this._hasSphericalExtentsAttribute = false;
this._hasPlanarExtentsAttributes = false;
this._hasPerColorAttribute = false;
this.appearance = options.appearance;
this._createBoundingVolumeFunction = options._createBoundingVolumeFunction;
this._updateAndQueueCommandsFunction = options._updateAndQueueCommandsFunction;
this._usePickOffsets = false;
this._primitiveOptions = {
geometryInstances: void 0,
appearance: void 0,
vertexCacheOptimize: options.vertexCacheOptimize ?? false,
interleave: options.interleave ?? false,
releaseGeometryInstances: options.releaseGeometryInstances ?? true,
allowPicking: options.allowPicking ?? true,
asynchronous: options.asynchronous ?? true,
compressVertices: options.compressVertices ?? true,
_createBoundingVolumeFunction: void 0,
_createRenderStatesFunction: void 0,
_createShaderProgramFunction: void 0,
_createCommandsFunction: void 0,
_updateAndQueueCommandsFunction: void 0,
_createPickOffsets: true
};
}
Object.defineProperties(ClassificationPrimitive.prototype, {
/**
* When true, 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;
}
},
/**
* Returns true if the ClassificationPrimitive needs a separate shader and commands for 2D.
* This is because texture coordinates on ClassificationPrimitives are computed differently,
* and are used for culling when multiple GeometryInstances are batched in one ClassificationPrimitive.
* @memberof ClassificationPrimitive.prototype
* @type {boolean}
* @readonly
* @private
*/
_needs2DShader: {
get: function() {
return this._hasPlanarExtentsAttributes || this._hasSphericalExtentsAttribute;
}
}
});
ClassificationPrimitive.isSupported = function(scene) {
return scene.context.stencilBuffer;
};
function getStencilDepthRenderState(enableStencil, mask3DTiles) {
const stencilFunction = mask3DTiles ? StencilFunction_default.EQUAL : StencilFunction_default.ALWAYS;
return {
colorMask: {
red: false,
green: false,
blue: false,
alpha: false
},
stencilTest: {
enabled: enableStencil,
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
};
}
function getColorRenderState(enableStencil) {
return {
stencilTest: {
enabled: enableStencil,
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 pickRenderState = {
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
};
function createRenderStates2(classificationPrimitive, context, appearance, twoPasses) {
if (defined_default(classificationPrimitive._rsStencilDepthPass)) {
return;
}
const stencilEnabled = !classificationPrimitive.debugShowShadowVolume;
classificationPrimitive._rsStencilDepthPass = RenderState_default.fromCache(
getStencilDepthRenderState(stencilEnabled, false)
);
classificationPrimitive._rsStencilDepthPass3DTiles = RenderState_default.fromCache(
getStencilDepthRenderState(stencilEnabled, true)
);
classificationPrimitive._rsColorPass = RenderState_default.fromCache(
getColorRenderState(stencilEnabled, false)
);
classificationPrimitive._rsPickPass = RenderState_default.fromCache(pickRenderState);
}
function modifyForEncodedNormals2(primitive, vertexShaderSource) {
if (!primitive.compressVertices) {
return vertexShaderSource;
}
if (vertexShaderSource.search(/in\s+vec3\s+extrudeDirection;/g) !== -1) {
const attributeName = "compressedAttributes";
const attributeDecl = `in vec2 ${attributeName};`;
const globalDecl = "vec3 extrudeDirection;\n";
const decode = ` extrudeDirection = czm_octDecode(${attributeName}, 65535.0);
`;
let modifiedVS = vertexShaderSource;
modifiedVS = modifiedVS.replace(/in\s+vec3\s+extrudeDirection;/g, "");
modifiedVS = ShaderSource_default.replaceMain(
modifiedVS,
"czm_non_compressed_main"
);
const compressedMain = `${"void main() \n{ \n"}${decode} czm_non_compressed_main();
}`;
return [attributeDecl, globalDecl, modifiedVS, compressedMain].join("\n");
}
}
function createShaderProgram2(classificationPrimitive, frameState) {
const context = frameState.context;
const primitive = classificationPrimitive._primitive;
let vs = ShadowVolumeAppearanceVS_default;
vs = classificationPrimitive._primitive._batchTable.getVertexShaderCallback()(
vs
);
vs = Primitive_default._appendDistanceDisplayConditionToShader(primitive, vs);
vs = Primitive_default._modifyShaderPosition(
classificationPrimitive,
vs,
frameState.scene3DOnly
);
vs = Primitive_default._updateColorAttribute(primitive, vs);
const planarExtents = classificationPrimitive._hasPlanarExtentsAttributes;
const cullFragmentsUsingExtents = planarExtents || classificationPrimitive._hasSphericalExtentsAttribute;
if (classificationPrimitive._extruded) {
vs = modifyForEncodedNormals2(primitive, vs);
}
const extrudedDefine = classificationPrimitive._extruded ? "EXTRUDED_GEOMETRY" : "";
let vsSource = new ShaderSource_default({
defines: [extrudedDefine],
sources: [vs]
});
const fsSource = new ShaderSource_default({
sources: [ShadowVolumeFS_default]
});
const attributeLocations8 = classificationPrimitive._primitive._attributeLocations;
const shadowVolumeAppearance = new ShadowVolumeAppearance_default(
cullFragmentsUsingExtents,
planarExtents,
classificationPrimitive.appearance
);
classificationPrimitive._spStencil = ShaderProgram_default.replaceCache({
context,
shaderProgram: classificationPrimitive._spStencil,
vertexShaderSource: vsSource,
fragmentShaderSource: fsSource,
attributeLocations: attributeLocations8
});
if (classificationPrimitive._primitive.allowPicking) {
let vsPick = ShaderSource_default.createPickVertexShaderSource(vs);
vsPick = Primitive_default._appendShowToShader(primitive, vsPick);
vsPick = Primitive_default._updatePickColorAttribute(vsPick);
const pickFS3D = shadowVolumeAppearance.createPickFragmentShader(false);
const pickVS3D = shadowVolumeAppearance.createPickVertexShader(
[extrudedDefine],
vsPick,
false,
frameState.mapProjection
);
classificationPrimitive._spPick = ShaderProgram_default.replaceCache({
context,
shaderProgram: classificationPrimitive._spPick,
vertexShaderSource: pickVS3D,
fragmentShaderSource: pickFS3D,
attributeLocations: attributeLocations8
});
if (cullFragmentsUsingExtents) {
let pickProgram2D = context.shaderCache.getDerivedShaderProgram(
classificationPrimitive._spPick,
"2dPick"
);
if (!defined_default(pickProgram2D)) {
const pickFS2D = shadowVolumeAppearance.createPickFragmentShader(true);
const pickVS2D = shadowVolumeAppearance.createPickVertexShader(
[extrudedDefine],
vsPick,
true,
frameState.mapProjection
);
pickProgram2D = context.shaderCache.createDerivedShaderProgram(
classificationPrimitive._spPick,
"2dPick",
{
vertexShaderSource: pickVS2D,
fragmentShaderSource: pickFS2D,
attributeLocations: attributeLocations8
}
);
}
classificationPrimitive._spPick2D = pickProgram2D;
}
} else {
classificationPrimitive._spPick = ShaderProgram_default.fromCache({
context,
vertexShaderSource: vsSource,
fragmentShaderSource: fsSource,
attributeLocations: attributeLocations8
});
}
vs = Primitive_default._appendShowToShader(primitive, vs);
vsSource = new ShaderSource_default({
defines: [extrudedDefine],
sources: [vs]
});
classificationPrimitive._sp = ShaderProgram_default.replaceCache({
context,
shaderProgram: classificationPrimitive._sp,
vertexShaderSource: vsSource,
fragmentShaderSource: fsSource,
attributeLocations: attributeLocations8
});
const fsColorSource = shadowVolumeAppearance.createFragmentShader(false);
const vsColorSource = shadowVolumeAppearance.createVertexShader(
[extrudedDefine],
vs,
false,
frameState.mapProjection
);
classificationPrimitive._spColor = ShaderProgram_default.replaceCache({
context,
shaderProgram: classificationPrimitive._spColor,
vertexShaderSource: vsColorSource,
fragmentShaderSource: fsColorSource,
attributeLocations: attributeLocations8
});
if (cullFragmentsUsingExtents) {
let colorProgram2D = context.shaderCache.getDerivedShaderProgram(
classificationPrimitive._spColor,
"2dColor"
);
if (!defined_default(colorProgram2D)) {
const fsColorSource2D = shadowVolumeAppearance.createFragmentShader(true);
const vsColorSource2D = shadowVolumeAppearance.createVertexShader(
[extrudedDefine],
vs,
true,
frameState.mapProjection
);
colorProgram2D = context.shaderCache.createDerivedShaderProgram(
classificationPrimitive._spColor,
"2dColor",
{
vertexShaderSource: vsColorSource2D,
fragmentShaderSource: fsColorSource2D,
attributeLocations: attributeLocations8
}
);
}
classificationPrimitive._spColor2D = colorProgram2D;
}
}
function createColorCommands(classificationPrimitive, colorCommands) {
const primitive = classificationPrimitive._primitive;
let length2 = primitive._va.length * 2;
colorCommands.length = length2;
let i;
let command;
let derivedCommand;
let vaIndex = 0;
let uniformMap2 = primitive._batchTable.getUniformMapCallback()(
classificationPrimitive._uniformMap
);
const needs2DShader = classificationPrimitive._needs2DShader;
for (i = 0; i < length2; i += 2) {
const vertexArray = primitive._va[vaIndex++];
command = colorCommands[i];
if (!defined_default(command)) {
command = colorCommands[i] = new DrawCommand_default({
owner: classificationPrimitive,
primitiveType: primitive._primitiveType
});
}
command.vertexArray = vertexArray;
command.renderState = classificationPrimitive._rsStencilDepthPass;
command.shaderProgram = classificationPrimitive._sp;
command.uniformMap = uniformMap2;
command.pass = Pass_default.TERRAIN_CLASSIFICATION;
derivedCommand = DrawCommand_default.shallowClone(
command,
command.derivedCommands.tileset
);
derivedCommand.renderState = classificationPrimitive._rsStencilDepthPass3DTiles;
derivedCommand.pass = Pass_default.CESIUM_3D_TILE_CLASSIFICATION;
command.derivedCommands.tileset = derivedCommand;
command = colorCommands[i + 1];
if (!defined_default(command)) {
command = colorCommands[i + 1] = new DrawCommand_default({
owner: classificationPrimitive,
primitiveType: primitive._primitiveType
});
}
command.vertexArray = vertexArray;
command.renderState = classificationPrimitive._rsColorPass;
command.shaderProgram = classificationPrimitive._spColor;
command.pass = Pass_default.TERRAIN_CLASSIFICATION;
const appearance = classificationPrimitive.appearance;
const material4 = appearance.material;
if (defined_default(material4)) {
uniformMap2 = combine_default(uniformMap2, material4._uniforms);
}
command.uniformMap = uniformMap2;
derivedCommand = DrawCommand_default.shallowClone(
command,
command.derivedCommands.tileset
);
derivedCommand.pass = Pass_default.CESIUM_3D_TILE_CLASSIFICATION;
command.derivedCommands.tileset = derivedCommand;
if (needs2DShader) {
let derived2DCommand = DrawCommand_default.shallowClone(
command,
command.derivedCommands.appearance2D
);
derived2DCommand.shaderProgram = classificationPrimitive._spColor2D;
command.derivedCommands.appearance2D = derived2DCommand;
derived2DCommand = DrawCommand_default.shallowClone(
derivedCommand,
derivedCommand.derivedCommands.appearance2D
);
derived2DCommand.shaderProgram = classificationPrimitive._spColor2D;
derivedCommand.derivedCommands.appearance2D = derived2DCommand;
}
}
const commandsIgnoreShow = classificationPrimitive._commandsIgnoreShow;
const spStencil = classificationPrimitive._spStencil;
let commandIndex = 0;
length2 = commandsIgnoreShow.length = length2 / 2;
for (let j = 0; j < length2; ++j) {
const commandIgnoreShow = commandsIgnoreShow[j] = DrawCommand_default.shallowClone(
colorCommands[commandIndex],
commandsIgnoreShow[j]
);
commandIgnoreShow.shaderProgram = spStencil;
commandIgnoreShow.pass = Pass_default.CESIUM_3D_TILE_CLASSIFICATION_IGNORE_SHOW;
commandIndex += 2;
}
}
function createPickCommands(classificationPrimitive, pickCommands) {
const usePickOffsets = classificationPrimitive._usePickOffsets;
const primitive = classificationPrimitive._primitive;
let length2 = primitive._va.length * 2;
let pickOffsets;
let pickIndex = 0;
let pickOffset;
if (usePickOffsets) {
pickOffsets = primitive._pickOffsets;
length2 = pickOffsets.length * 2;
}
pickCommands.length = length2;
let j;
let command;
let derivedCommand;
let vaIndex = 0;
const uniformMap2 = primitive._batchTable.getUniformMapCallback()(
classificationPrimitive._uniformMap
);
const needs2DShader = classificationPrimitive._needs2DShader;
for (j = 0; j < length2; j += 2) {
let vertexArray = primitive._va[vaIndex++];
if (usePickOffsets) {
pickOffset = pickOffsets[pickIndex++];
vertexArray = primitive._va[pickOffset.index];
}
command = pickCommands[j];
if (!defined_default(command)) {
command = pickCommands[j] = new DrawCommand_default({
owner: classificationPrimitive,
primitiveType: primitive._primitiveType,
pickOnly: true
});
}
command.vertexArray = vertexArray;
command.renderState = classificationPrimitive._rsStencilDepthPass;
command.shaderProgram = classificationPrimitive._sp;
command.uniformMap = uniformMap2;
command.pass = Pass_default.TERRAIN_CLASSIFICATION;
if (usePickOffsets) {
command.offset = pickOffset.offset;
command.count = pickOffset.count;
}
derivedCommand = DrawCommand_default.shallowClone(
command,
command.derivedCommands.tileset
);
derivedCommand.renderState = classificationPrimitive._rsStencilDepthPass3DTiles;
derivedCommand.pass = Pass_default.CESIUM_3D_TILE_CLASSIFICATION;
command.derivedCommands.tileset = derivedCommand;
command = pickCommands[j + 1];
if (!defined_default(command)) {
command = pickCommands[j + 1] = new DrawCommand_default({
owner: classificationPrimitive,
primitiveType: primitive._primitiveType,
pickOnly: true
});
}
command.vertexArray = vertexArray;
command.renderState = classificationPrimitive._rsPickPass;
command.shaderProgram = classificationPrimitive._spPick;
command.uniformMap = uniformMap2;
command.pass = Pass_default.TERRAIN_CLASSIFICATION;
if (usePickOffsets) {
command.offset = pickOffset.offset;
command.count = pickOffset.count;
}
derivedCommand = DrawCommand_default.shallowClone(
command,
command.derivedCommands.tileset
);
derivedCommand.pass = Pass_default.CESIUM_3D_TILE_CLASSIFICATION;
command.derivedCommands.tileset = derivedCommand;
if (needs2DShader) {
let derived2DCommand = DrawCommand_default.shallowClone(
command,
command.derivedCommands.pick2D
);
derived2DCommand.shaderProgram = classificationPrimitive._spPick2D;
command.derivedCommands.pick2D = derived2DCommand;
derived2DCommand = DrawCommand_default.shallowClone(
derivedCommand,
derivedCommand.derivedCommands.pick2D
);
derived2DCommand.shaderProgram = classificationPrimitive._spPick2D;
derivedCommand.derivedCommands.pick2D = derived2DCommand;
}
}
}
function createCommands2(classificationPrimitive, appearance, material4, translucent, twoPasses, colorCommands, pickCommands) {
createColorCommands(classificationPrimitive, colorCommands);
createPickCommands(classificationPrimitive, pickCommands);
}
function boundingVolumeIndex(commandIndex, length2) {
return Math.floor(commandIndex % length2 / 2);
}
function updateAndQueueRenderCommand(command, frameState, modelMatrix, cull, boundingVolume, debugShowBoundingVolume2) {
command.modelMatrix = modelMatrix;
command.boundingVolume = boundingVolume;
command.cull = cull;
command.debugShowBoundingVolume = debugShowBoundingVolume2;
frameState.commandList.push(command);
}
function updateAndQueuePickCommand(command, frameState, modelMatrix, cull, boundingVolume) {
command.modelMatrix = modelMatrix;
command.boundingVolume = boundingVolume;
command.cull = cull;
frameState.commandList.push(command);
}
function updateAndQueueCommands2(classificationPrimitive, frameState, colorCommands, pickCommands, modelMatrix, cull, debugShowBoundingVolume2, twoPasses) {
const primitive = classificationPrimitive._primitive;
Primitive_default._updateBoundingVolumes(primitive, frameState, modelMatrix);
let boundingVolumes;
if (frameState.mode === SceneMode_default.SCENE3D) {
boundingVolumes = primitive._boundingSphereWC;
} else if (frameState.mode === SceneMode_default.COLUMBUS_VIEW) {
boundingVolumes = primitive._boundingSphereCV;
} else if (frameState.mode === SceneMode_default.SCENE2D && defined_default(primitive._boundingSphere2D)) {
boundingVolumes = primitive._boundingSphere2D;
} else if (defined_default(primitive._boundingSphereMorph)) {
boundingVolumes = primitive._boundingSphereMorph;
}
const classificationType = classificationPrimitive.classificationType;
const queueTerrainCommands = classificationType !== ClassificationType_default.CESIUM_3D_TILE;
const queue3DTilesCommands = classificationType !== ClassificationType_default.TERRAIN;
const passes = frameState.passes;
let i;
let boundingVolume;
let command;
if (passes.render) {
const colorLength = colorCommands.length;
for (i = 0; i < colorLength; ++i) {
boundingVolume = boundingVolumes[boundingVolumeIndex(i, colorLength)];
if (queueTerrainCommands) {
command = colorCommands[i];
updateAndQueueRenderCommand(
command,
frameState,
modelMatrix,
cull,
boundingVolume,
debugShowBoundingVolume2
);
}
if (queue3DTilesCommands) {
command = colorCommands[i].derivedCommands.tileset;
updateAndQueueRenderCommand(
command,
frameState,
modelMatrix,
cull,
boundingVolume,
debugShowBoundingVolume2
);
}
}
if (frameState.invertClassification) {
const ignoreShowCommands = classificationPrimitive._commandsIgnoreShow;
const ignoreShowCommandsLength = ignoreShowCommands.length;
for (i = 0; i < ignoreShowCommandsLength; ++i) {
boundingVolume = boundingVolumes[i];
command = ignoreShowCommands[i];
updateAndQueueRenderCommand(
command,
frameState,
modelMatrix,
cull,
boundingVolume,
debugShowBoundingVolume2
);
}
}
}
if (passes.pick) {
const pickLength = pickCommands.length;
const pickOffsets = primitive._pickOffsets;
for (i = 0; i < pickLength; ++i) {
const pickOffset = pickOffsets[boundingVolumeIndex(i, pickLength)];
boundingVolume = boundingVolumes[pickOffset.index];
if (queueTerrainCommands) {
command = pickCommands[i];
updateAndQueuePickCommand(
command,
frameState,
modelMatrix,
cull,
boundingVolume
);
}
if (queue3DTilesCommands) {
command = pickCommands[i].derivedCommands.tileset;
updateAndQueuePickCommand(
command,
frameState,
modelMatrix,
cull,
boundingVolume
);
}
}
}
}
ClassificationPrimitive.prototype.update = function(frameState) {
if (!defined_default(this._primitive) && !defined_default(this.geometryInstances)) {
return;
}
let appearance = this.appearance;
if (defined_default(appearance) && defined_default(appearance.material)) {
appearance.material.update(frameState.context);
}
const that = this;
const primitiveOptions = this._primitiveOptions;
if (!defined_default(this._primitive)) {
const instances = Array.isArray(this.geometryInstances) ? this.geometryInstances : [this.geometryInstances];
const length2 = instances.length;
let i;
let instance;
let attributes;
let hasPerColorAttribute = false;
let allColorsSame = true;
let firstColor;
let hasSphericalExtentsAttribute = false;
let hasPlanarExtentsAttributes = false;
if (length2 > 0) {
attributes = instances[0].attributes;
hasSphericalExtentsAttribute = ShadowVolumeAppearance_default.hasAttributesForSphericalExtents(attributes);
hasPlanarExtentsAttributes = ShadowVolumeAppearance_default.hasAttributesForTextureCoordinatePlanes(
attributes
);
firstColor = attributes.color;
}
for (i = 0; i < length2; i++) {
instance = instances[i];
const color = instance.attributes.color;
if (defined_default(color)) {
hasPerColorAttribute = true;
} else if (hasPerColorAttribute) {
throw new DeveloperError_default(
"All GeometryInstances must have color attributes to use per-instance color."
);
}
allColorsSame = allColorsSame && defined_default(color) && ColorGeometryInstanceAttribute_default.equals(firstColor, color);
}
if (!allColorsSame && !hasSphericalExtentsAttribute && !hasPlanarExtentsAttributes) {
throw new DeveloperError_default(
"All GeometryInstances must have the same color attribute except via GroundPrimitives"
);
}
if (hasPerColorAttribute && !defined_default(appearance)) {
appearance = new PerInstanceColorAppearance_default({
flat: true
});
this.appearance = appearance;
}
if (!hasPerColorAttribute && appearance instanceof PerInstanceColorAppearance_default) {
throw new DeveloperError_default(
"PerInstanceColorAppearance requires color GeometryInstanceAttributes on all GeometryInstances"
);
}
if (defined_default(appearance.material) && !hasSphericalExtentsAttribute && !hasPlanarExtentsAttributes) {
throw new DeveloperError_default(
"Materials on ClassificationPrimitives are not supported except via GroundPrimitives"
);
}
this._usePickOffsets = !hasSphericalExtentsAttribute && !hasPlanarExtentsAttributes;
this._hasSphericalExtentsAttribute = hasSphericalExtentsAttribute;
this._hasPlanarExtentsAttributes = hasPlanarExtentsAttributes;
this._hasPerColorAttribute = hasPerColorAttribute;
const geometryInstances = new Array(length2);
for (i = 0; i < length2; ++i) {
instance = instances[i];
geometryInstances[i] = new GeometryInstance_default({
geometry: instance.geometry,
attributes: instance.attributes,
modelMatrix: instance.modelMatrix,
id: instance.id,
pickPrimitive: this._pickPrimitive ?? that
});
}
primitiveOptions.appearance = appearance;
primitiveOptions.geometryInstances = geometryInstances;
if (defined_default(this._createBoundingVolumeFunction)) {
primitiveOptions._createBoundingVolumeFunction = function(frameState2, geometry) {
that._createBoundingVolumeFunction(frameState2, geometry);
};
}
primitiveOptions._createRenderStatesFunction = function(primitive, context, appearance2, twoPasses) {
createRenderStates2(that, context);
};
primitiveOptions._createShaderProgramFunction = function(primitive, frameState2, appearance2) {
createShaderProgram2(that, frameState2);
};
primitiveOptions._createCommandsFunction = function(primitive, appearance2, material4, translucent, twoPasses, colorCommands, pickCommands) {
createCommands2(
that,
void 0,
void 0,
true,
false,
colorCommands,
pickCommands
);
};
if (defined_default(this._updateAndQueueCommandsFunction)) {
primitiveOptions._updateAndQueueCommandsFunction = function(primitive, frameState2, colorCommands, pickCommands, modelMatrix, cull, debugShowBoundingVolume2, twoPasses) {
that._updateAndQueueCommandsFunction(
primitive,
frameState2,
colorCommands,
pickCommands,
modelMatrix,
cull,
debugShowBoundingVolume2,
twoPasses
);
};
} else {
primitiveOptions._updateAndQueueCommandsFunction = function(primitive, frameState2, colorCommands, pickCommands, modelMatrix, cull, debugShowBoundingVolume2, twoPasses) {
updateAndQueueCommands2(
that,
frameState2,
colorCommands,
pickCommands,
modelMatrix,
cull,
debugShowBoundingVolume2,
twoPasses
);
};
}
this._primitive = new Primitive_default(primitiveOptions);
}
if (this.debugShowShadowVolume && !this._debugShowShadowVolume && this._ready) {
this._debugShowShadowVolume = true;
this._rsStencilDepthPass = RenderState_default.fromCache(
getStencilDepthRenderState(false, false)
);
this._rsStencilDepthPass3DTiles = RenderState_default.fromCache(
getStencilDepthRenderState(false, true)
);
this._rsColorPass = RenderState_default.fromCache(getColorRenderState(false));
} else if (!this.debugShowShadowVolume && this._debugShowShadowVolume) {
this._debugShowShadowVolume = false;
this._rsStencilDepthPass = RenderState_default.fromCache(
getStencilDepthRenderState(true, false)
);
this._rsStencilDepthPass3DTiles = RenderState_default.fromCache(
getStencilDepthRenderState(true, true)
);
this._rsColorPass = RenderState_default.fromCache(getColorRenderState(true));
}
if (this._primitive.appearance !== appearance) {
if (!this._hasSphericalExtentsAttribute && !this._hasPlanarExtentsAttributes && defined_default(appearance.material)) {
throw new DeveloperError_default(
"Materials on ClassificationPrimitives are not supported except via GroundPrimitive"
);
}
if (!this._hasPerColorAttribute && appearance instanceof PerInstanceColorAppearance_default) {
throw new DeveloperError_default(
"PerInstanceColorAppearance requires color GeometryInstanceAttribute"
);
}
this._primitive.appearance = appearance;
}
this._primitive.show = this.show;
this._primitive.debugShowBoundingVolume = this.debugShowBoundingVolume;
this._primitive.update(frameState);
frameState.afterRender.push(() => {
if (defined_default(this._primitive) && this._primitive.ready) {
this._ready = true;
if (this.releaseGeometryInstances) {
this.geometryInstances = void 0;
}
}
});
};
ClassificationPrimitive.prototype.getGeometryInstanceAttributes = function(id) {
if (!defined_default(this._primitive)) {
throw new DeveloperError_default(
"must call update before calling getGeometryInstanceAttributes"
);
}
return this._primitive.getGeometryInstanceAttributes(id);
};
ClassificationPrimitive.prototype.isDestroyed = function() {
return false;
};
ClassificationPrimitive.prototype.destroy = function() {
this._primitive = this._primitive && this._primitive.destroy();
this._sp = this._sp && this._sp.destroy();
this._spPick = this._spPick && this._spPick.destroy();
this._spColor = this._spColor && this._spColor.destroy();
this._spPick2D = void 0;
this._spColor2D = void 0;
return destroyObject_default(this);
};
var ClassificationPrimitive_default = ClassificationPrimitive;
// packages/engine/Source/Scene/GroundPrimitive.js
var GroundPrimitiveUniformMap = {
u_globeMinimumAltitude: function() {
return 55e3;
}
};
function GroundPrimitive(options) {
options = options ?? Frozen_default.EMPTY_OBJECT;
let appearance = options.appearance;
const geometryInstances = options.geometryInstances;
if (!defined_default(appearance) && defined_default(geometryInstances)) {
const geometryInstancesArray = Array.isArray(geometryInstances) ? geometryInstances : [geometryInstances];
const geometryInstanceCount = geometryInstancesArray.length;
for (let i = 0; i < geometryInstanceCount; i++) {
const attributes = geometryInstancesArray[i].attributes;
if (defined_default(attributes) && defined_default(attributes.color)) {
appearance = new PerInstanceColorAppearance_default({
flat: true
});
break;
}
}
}
this.appearance = appearance;
this.geometryInstances = options.geometryInstances;
this.show = options.show ?? true;
this.classificationType = options.classificationType ?? ClassificationType_default.BOTH;
this.debugShowBoundingVolume = options.debugShowBoundingVolume ?? false;
this.debugShowShadowVolume = options.debugShowShadowVolume ?? false;
this._boundingVolumes = [];
this._boundingVolumes2D = [];
this._ready = false;
this._primitive = void 0;
this._maxHeight = void 0;
this._minHeight = void 0;
this._maxTerrainHeight = ApproximateTerrainHeights_default._defaultMaxTerrainHeight;
this._minTerrainHeight = ApproximateTerrainHeights_default._defaultMinTerrainHeight;
this._boundingSpheresKeys = [];
this._boundingSpheres = [];
this._useFragmentCulling = false;
this._zIndex = void 0;
const that = this;
this._classificationPrimitiveOptions = {
geometryInstances: void 0,
appearance: void 0,
vertexCacheOptimize: options.vertexCacheOptimize ?? false,
interleave: options.interleave ?? false,
releaseGeometryInstances: options.releaseGeometryInstances ?? true,
allowPicking: options.allowPicking ?? true,
asynchronous: options.asynchronous ?? true,
compressVertices: options.compressVertices ?? true,
_createBoundingVolumeFunction: void 0,
_updateAndQueueCommandsFunction: void 0,
_pickPrimitive: that,
_extruded: true,
_uniformMap: GroundPrimitiveUniformMap
};
}
Object.defineProperties(GroundPrimitive.prototype, {
/**
* When true, 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;
}
}
});
GroundPrimitive.isSupported = ClassificationPrimitive_default.isSupported;
function getComputeMaximumHeightFunction(primitive) {
return function(granularity, ellipsoid) {
const r2 = ellipsoid.maximumRadius;
const delta = r2 / Math.cos(granularity * 0.5) - r2;
return primitive._maxHeight + delta;
};
}
function getComputeMinimumHeightFunction(primitive) {
return function(granularity, ellipsoid) {
return primitive._minHeight;
};
}
var scratchBVCartesianHigh = new Cartesian3_default();
var scratchBVCartesianLow = new Cartesian3_default();
var scratchBVCartesian = new Cartesian3_default();
var scratchBVCartographic = new Cartographic_default();
var scratchBVRectangle = new Rectangle_default();
function getRectangle(frameState, geometry) {
const ellipsoid = frameState.mapProjection.ellipsoid;
if (!defined_default(geometry.attributes) || !defined_default(geometry.attributes.position3DHigh)) {
if (defined_default(geometry.rectangle)) {
return geometry.rectangle;
}
return void 0;
}
const highPositions = geometry.attributes.position3DHigh.values;
const lowPositions = geometry.attributes.position3DLow.values;
const length2 = highPositions.length;
let minLat = Number.POSITIVE_INFINITY;
let minLon = Number.POSITIVE_INFINITY;
let maxLat = Number.NEGATIVE_INFINITY;
let maxLon = Number.NEGATIVE_INFINITY;
for (let i = 0; i < length2; i += 3) {
const highPosition = Cartesian3_default.unpack(
highPositions,
i,
scratchBVCartesianHigh
);
const lowPosition = Cartesian3_default.unpack(
lowPositions,
i,
scratchBVCartesianLow
);
const position = Cartesian3_default.add(
highPosition,
lowPosition,
scratchBVCartesian
);
const cartographic2 = ellipsoid.cartesianToCartographic(
position,
scratchBVCartographic
);
const latitude = cartographic2.latitude;
const longitude = cartographic2.longitude;
minLat = Math.min(minLat, latitude);
minLon = Math.min(minLon, longitude);
maxLat = Math.max(maxLat, latitude);
maxLon = Math.max(maxLon, longitude);
}
const rectangle = scratchBVRectangle;
rectangle.north = maxLat;
rectangle.south = minLat;
rectangle.east = maxLon;
rectangle.west = minLon;
return rectangle;
}
function setMinMaxTerrainHeights(primitive, rectangle, ellipsoid) {
const result = ApproximateTerrainHeights_default.getMinimumMaximumHeights(
rectangle,
ellipsoid
);
primitive._minTerrainHeight = result.minimumTerrainHeight;
primitive._maxTerrainHeight = result.maximumTerrainHeight;
}
function createBoundingVolume(groundPrimitive, frameState, geometry) {
const ellipsoid = frameState.mapProjection.ellipsoid;
const rectangle = getRectangle(frameState, geometry);
const obb = OrientedBoundingBox_default.fromRectangle(
rectangle,
groundPrimitive._minHeight,
groundPrimitive._maxHeight,
ellipsoid
);
groundPrimitive._boundingVolumes.push(obb);
if (!frameState.scene3DOnly) {
const projection = frameState.mapProjection;
const boundingVolume = BoundingSphere_default.fromRectangleWithHeights2D(
rectangle,
projection,
groundPrimitive._maxHeight,
groundPrimitive._minHeight
);
Cartesian3_default.fromElements(
boundingVolume.center.z,
boundingVolume.center.x,
boundingVolume.center.y,
boundingVolume.center
);
groundPrimitive._boundingVolumes2D.push(boundingVolume);
}
}
function boundingVolumeIndex2(commandIndex, length2) {
return Math.floor(commandIndex % length2 / 2);
}
function updateAndQueueRenderCommand2(groundPrimitive, command, frameState, modelMatrix, cull, boundingVolume, debugShowBoundingVolume2) {
const classificationPrimitive = groundPrimitive._primitive;
if (frameState.mode !== SceneMode_default.SCENE3D && command.shaderProgram === classificationPrimitive._spColor && classificationPrimitive._needs2DShader) {
command = command.derivedCommands.appearance2D;
}
command.owner = groundPrimitive;
command.modelMatrix = modelMatrix;
command.boundingVolume = boundingVolume;
command.cull = cull;
command.debugShowBoundingVolume = debugShowBoundingVolume2;
frameState.commandList.push(command);
}
function updateAndQueuePickCommand2(groundPrimitive, command, frameState, modelMatrix, cull, boundingVolume) {
const classificationPrimitive = groundPrimitive._primitive;
if (frameState.mode !== SceneMode_default.SCENE3D && command.shaderProgram === classificationPrimitive._spPick && classificationPrimitive._needs2DShader) {
command = command.derivedCommands.pick2D;
}
command.owner = groundPrimitive;
command.modelMatrix = modelMatrix;
command.boundingVolume = boundingVolume;
command.cull = cull;
frameState.commandList.push(command);
}
function updateAndQueueCommands3(groundPrimitive, frameState, colorCommands, pickCommands, modelMatrix, cull, debugShowBoundingVolume2, twoPasses) {
let boundingVolumes;
if (frameState.mode === SceneMode_default.SCENE3D) {
boundingVolumes = groundPrimitive._boundingVolumes;
} else {
boundingVolumes = groundPrimitive._boundingVolumes2D;
}
const classificationType = groundPrimitive.classificationType;
const queueTerrainCommands = classificationType !== ClassificationType_default.CESIUM_3D_TILE;
const queue3DTilesCommands = classificationType !== ClassificationType_default.TERRAIN;
const passes = frameState.passes;
const classificationPrimitive = groundPrimitive._primitive;
let i;
let boundingVolume;
let command;
if (passes.render) {
const colorLength = colorCommands.length;
for (i = 0; i < colorLength; ++i) {
boundingVolume = boundingVolumes[boundingVolumeIndex2(i, colorLength)];
if (queueTerrainCommands) {
command = colorCommands[i];
updateAndQueueRenderCommand2(
groundPrimitive,
command,
frameState,
modelMatrix,
cull,
boundingVolume,
debugShowBoundingVolume2
);
}
if (queue3DTilesCommands) {
command = colorCommands[i].derivedCommands.tileset;
updateAndQueueRenderCommand2(
groundPrimitive,
command,
frameState,
modelMatrix,
cull,
boundingVolume,
debugShowBoundingVolume2
);
}
}
if (frameState.invertClassification) {
const ignoreShowCommands = classificationPrimitive._commandsIgnoreShow;
const ignoreShowCommandsLength = ignoreShowCommands.length;
for (i = 0; i < ignoreShowCommandsLength; ++i) {
boundingVolume = boundingVolumes[i];
command = ignoreShowCommands[i];
updateAndQueueRenderCommand2(
groundPrimitive,
command,
frameState,
modelMatrix,
cull,
boundingVolume,
debugShowBoundingVolume2
);
}
}
}
if (passes.pick) {
const pickLength = pickCommands.length;
let pickOffsets;
if (!groundPrimitive._useFragmentCulling) {
pickOffsets = classificationPrimitive._primitive._pickOffsets;
}
for (i = 0; i < pickLength; ++i) {
boundingVolume = boundingVolumes[boundingVolumeIndex2(i, pickLength)];
if (!groundPrimitive._useFragmentCulling) {
const pickOffset = pickOffsets[boundingVolumeIndex2(i, pickLength)];
boundingVolume = boundingVolumes[pickOffset.index];
}
if (queueTerrainCommands) {
command = pickCommands[i];
updateAndQueuePickCommand2(
groundPrimitive,
command,
frameState,
modelMatrix,
cull,
boundingVolume
);
}
if (queue3DTilesCommands) {
command = pickCommands[i].derivedCommands.tileset;
updateAndQueuePickCommand2(
groundPrimitive,
command,
frameState,
modelMatrix,
cull,
boundingVolume
);
}
}
}
}
GroundPrimitive.initializeTerrainHeights = function() {
return ApproximateTerrainHeights_default.initialize();
};
GroundPrimitive.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 GroundPrimitives, you must call GroundPrimitive.initializeTerrainHeights() and wait for the returned promise to resolve."
);
}
GroundPrimitive.initializeTerrainHeights();
return;
}
const that = this;
const primitiveOptions = this._classificationPrimitiveOptions;
if (!defined_default(this._primitive)) {
const ellipsoid = frameState.mapProjection.ellipsoid;
let instance;
let geometry;
let instanceType;
const instances = Array.isArray(this.geometryInstances) ? this.geometryInstances : [this.geometryInstances];
const length2 = instances.length;
const groundInstances = new Array(length2);
let i;
let rectangle;
for (i = 0; i < length2; ++i) {
instance = instances[i];
geometry = instance.geometry;
const instanceRectangle = getRectangle(frameState, geometry);
if (!defined_default(rectangle)) {
rectangle = Rectangle_default.clone(instanceRectangle);
} else if (defined_default(instanceRectangle)) {
Rectangle_default.union(rectangle, instanceRectangle, rectangle);
}
const id = instance.id;
if (defined_default(id) && defined_default(instanceRectangle)) {
const boundingSphere = ApproximateTerrainHeights_default.getBoundingSphere(
instanceRectangle,
ellipsoid
);
this._boundingSpheresKeys.push(id);
this._boundingSpheres.push(boundingSphere);
}
instanceType = geometry.constructor;
if (!defined_default(instanceType) || !defined_default(instanceType.createShadowVolume)) {
throw new DeveloperError_default(
"Not all of the geometry instances have GroundPrimitive support."
);
}
}
setMinMaxTerrainHeights(this, rectangle, ellipsoid);
const exaggeration = frameState.verticalExaggeration;
const exaggerationRelativeHeight = frameState.verticalExaggerationRelativeHeight;
this._minHeight = VerticalExaggeration_default.getHeight(
this._minTerrainHeight,
exaggeration,
exaggerationRelativeHeight
);
this._maxHeight = VerticalExaggeration_default.getHeight(
this._maxTerrainHeight,
exaggeration,
exaggerationRelativeHeight
);
const useFragmentCulling = GroundPrimitive._supportsMaterials(
frameState.context
);
this._useFragmentCulling = useFragmentCulling;
if (useFragmentCulling) {
let attributes;
let usePlanarExtents = true;
for (i = 0; i < length2; ++i) {
instance = instances[i];
geometry = instance.geometry;
rectangle = getRectangle(frameState, geometry);
if (ShadowVolumeAppearance_default.shouldUseSphericalCoordinates(rectangle)) {
usePlanarExtents = false;
break;
}
}
for (i = 0; i < length2; ++i) {
instance = instances[i];
geometry = instance.geometry;
instanceType = geometry.constructor;
const boundingRectangle = getRectangle(frameState, geometry);
const textureCoordinateRotationPoints4 = geometry.textureCoordinateRotationPoints;
if (usePlanarExtents) {
attributes = ShadowVolumeAppearance_default.getPlanarTextureCoordinateAttributes(
boundingRectangle,
textureCoordinateRotationPoints4,
ellipsoid,
frameState.mapProjection,
this._maxHeight
);
} else {
attributes = ShadowVolumeAppearance_default.getSphericalExtentGeometryInstanceAttributes(
boundingRectangle,
textureCoordinateRotationPoints4,
ellipsoid,
frameState.mapProjection
);
}
const instanceAttributes = instance.attributes;
for (const attributeKey in instanceAttributes) {
if (instanceAttributes.hasOwnProperty(attributeKey)) {
attributes[attributeKey] = instanceAttributes[attributeKey];
}
}
groundInstances[i] = new GeometryInstance_default({
geometry: instanceType.createShadowVolume(
geometry,
getComputeMinimumHeightFunction(this),
getComputeMaximumHeightFunction(this)
),
attributes,
id: instance.id
});
}
} else {
for (i = 0; i < length2; ++i) {
instance = instances[i];
geometry = instance.geometry;
instanceType = geometry.constructor;
groundInstances[i] = new GeometryInstance_default({
geometry: instanceType.createShadowVolume(
geometry,
getComputeMinimumHeightFunction(this),
getComputeMaximumHeightFunction(this)
),
attributes: instance.attributes,
id: instance.id
});
}
}
primitiveOptions.geometryInstances = groundInstances;
primitiveOptions.appearance = this.appearance;
primitiveOptions._createBoundingVolumeFunction = function(frameState2, geometry2) {
createBoundingVolume(that, frameState2, geometry2);
};
primitiveOptions._updateAndQueueCommandsFunction = function(primitive, frameState2, colorCommands, pickCommands, modelMatrix, cull, debugShowBoundingVolume2, twoPasses) {
updateAndQueueCommands3(
that,
frameState2,
colorCommands,
pickCommands,
modelMatrix,
cull,
debugShowBoundingVolume2,
twoPasses
);
};
this._primitive = new ClassificationPrimitive_default(primitiveOptions);
}
this._primitive.appearance = this.appearance;
this._primitive.show = this.show;
this._primitive.debugShowShadowVolume = this.debugShowShadowVolume;
this._primitive.debugShowBoundingVolume = this.debugShowBoundingVolume;
this._primitive.update(frameState);
frameState.afterRender.push(() => {
if (!this._ready && defined_default(this._primitive) && this._primitive.ready) {
this._ready = true;
if (this.releaseGeometryInstances) {
this.geometryInstances = void 0;
}
}
});
};
GroundPrimitive.prototype.getBoundingSphere = function(id) {
const index = this._boundingSpheresKeys.indexOf(id);
if (index !== -1) {
return this._boundingSpheres[index];
}
return void 0;
};
GroundPrimitive.prototype.getGeometryInstanceAttributes = function(id) {
if (!defined_default(this._primitive)) {
throw new DeveloperError_default(
"must call update before calling getGeometryInstanceAttributes"
);
}
return this._primitive.getGeometryInstanceAttributes(id);
};
GroundPrimitive.prototype.isDestroyed = function() {
return false;
};
GroundPrimitive.prototype.destroy = function() {
this._primitive = this._primitive && this._primitive.destroy();
return destroyObject_default(this);
};
GroundPrimitive._supportsMaterials = function(context) {
return context.depthTexture;
};
GroundPrimitive.supportsMaterials = function(scene) {
Check_default.typeOf.object("scene", scene);
return GroundPrimitive._supportsMaterials(scene.frameState.context);
};
var GroundPrimitive_default = GroundPrimitive;
// packages/engine/Source/DataSources/MaterialProperty.js
function MaterialProperty() {
DeveloperError_default.throwInstantiationError();
}
Object.defineProperties(MaterialProperty.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 MaterialProperty.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 MaterialProperty.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: DeveloperError_default.throwInstantiationError
}
});
MaterialProperty.prototype.getType = DeveloperError_default.throwInstantiationError;
MaterialProperty.prototype.getValue = DeveloperError_default.throwInstantiationError;
MaterialProperty.prototype.equals = DeveloperError_default.throwInstantiationError;
var timeScratch2 = new JulianDate_default();
MaterialProperty.getValue = function(time, materialProperty, material4) {
let type;
if (!defined_default(time)) {
time = JulianDate_default.now(timeScratch2);
}
if (defined_default(materialProperty)) {
type = materialProperty.getType(time);
if (defined_default(type)) {
if (!defined_default(material4) || material4.type !== type) {
material4 = Material_default.fromType(type);
}
materialProperty.getValue(time, material4.uniforms);
return material4;
}
}
if (!defined_default(material4) || material4.type !== Material_default.ColorType) {
material4 = Material_default.fromType(Material_default.ColorType);
}
Color_default.clone(Color_default.WHITE, material4.uniforms.color);
return material4;
};
var MaterialProperty_default = MaterialProperty;
// packages/engine/Source/DataSources/DynamicGeometryUpdater.js
function DynamicGeometryUpdater(geometryUpdater, primitives, orderedGroundPrimitives) {
Check_default.defined("geometryUpdater", geometryUpdater);
Check_default.defined("primitives", primitives);
Check_default.defined("orderedGroundPrimitives", orderedGroundPrimitives);
this._primitives = primitives;
this._orderedGroundPrimitives = orderedGroundPrimitives;
this._primitive = void 0;
this._outlinePrimitive = void 0;
this._geometryUpdater = geometryUpdater;
this._options = geometryUpdater._options;
this._entity = geometryUpdater._entity;
this._material = void 0;
}
DynamicGeometryUpdater.prototype._isHidden = function(entity, geometry, time) {
return !entity.isShowing || !entity.isAvailable(time) || !Property_default.getValueOrDefault(geometry.show, time, true);
};
DynamicGeometryUpdater.prototype._setOptions = DeveloperError_default.throwInstantiationError;
DynamicGeometryUpdater.prototype.update = function(time) {
Check_default.defined("time", time);
const geometryUpdater = this._geometryUpdater;
const onTerrain = geometryUpdater._onTerrain;
const primitives = this._primitives;
const orderedGroundPrimitives = this._orderedGroundPrimitives;
if (onTerrain) {
orderedGroundPrimitives.remove(this._primitive);
} else {
primitives.removeAndDestroy(this._primitive);
primitives.removeAndDestroy(this._outlinePrimitive);
this._outlinePrimitive = void 0;
}
this._primitive = void 0;
const entity = this._entity;
const geometry = entity[this._geometryUpdater._geometryPropertyName];
this._setOptions(entity, geometry, time);
if (this._isHidden(entity, geometry, time)) {
return;
}
const shadows = this._geometryUpdater.shadowsProperty.getValue(time);
const options = this._options;
if (!defined_default(geometry.fill) || geometry.fill.getValue(time)) {
const fillMaterialProperty = geometryUpdater.fillMaterialProperty;
const isColorAppearance = fillMaterialProperty instanceof ColorMaterialProperty_default;
let appearance;
const closed = geometryUpdater._getIsClosed(options);
if (isColorAppearance) {
appearance = new PerInstanceColorAppearance_default({
closed,
flat: onTerrain && !geometryUpdater._supportsMaterialsforEntitiesOnTerrain
});
} else {
const material4 = MaterialProperty_default.getValue(
time,
fillMaterialProperty,
this._material
);
this._material = material4;
appearance = new MaterialAppearance_default({
material: material4,
translucent: material4.isTranslucent(),
closed
});
}
if (onTerrain) {
options.vertexFormat = PerInstanceColorAppearance_default.VERTEX_FORMAT;
this._primitive = orderedGroundPrimitives.add(
new GroundPrimitive_default({
geometryInstances: this._geometryUpdater.createFillGeometryInstance(time),
appearance,
asynchronous: false,
shadows,
classificationType: this._geometryUpdater.classificationTypeProperty.getValue(time)
}),
Property_default.getValueOrUndefined(this._geometryUpdater.zIndex, time)
);
} else {
options.vertexFormat = appearance.vertexFormat;
const fillInstance = this._geometryUpdater.createFillGeometryInstance(time);
if (isColorAppearance) {
appearance.translucent = fillInstance.attributes.color.value[3] !== 255;
}
this._primitive = primitives.add(
new Primitive_default({
geometryInstances: fillInstance,
appearance,
asynchronous: false,
shadows
})
);
}
}
if (!onTerrain && defined_default(geometry.outline) && geometry.outline.getValue(time)) {
const outlineInstance = this._geometryUpdater.createOutlineGeometryInstance(time);
const outlineWidth = Property_default.getValueOrDefault(
geometry.outlineWidth,
time,
1
);
this._outlinePrimitive = primitives.add(
new Primitive_default({
geometryInstances: outlineInstance,
appearance: new PerInstanceColorAppearance_default({
flat: true,
translucent: outlineInstance.attributes.color.value[3] !== 255,
renderState: {
lineWidth: geometryUpdater._scene.clampLineWidth(outlineWidth)
}
}),
asynchronous: false,
shadows
})
);
}
};
DynamicGeometryUpdater.prototype.getBoundingSphere = function(result) {
if (!defined_default(result)) {
throw new DeveloperError_default("result is required.");
}
const entity = this._entity;
const primitive = this._primitive;
const outlinePrimitive = this._outlinePrimitive;
let attributes;
if (defined_default(primitive) && primitive.show && primitive.ready) {
attributes = primitive.getGeometryInstanceAttributes(entity);
if (defined_default(attributes) && defined_default(attributes.boundingSphere)) {
BoundingSphere_default.clone(attributes.boundingSphere, result);
return BoundingSphereState_default.DONE;
}
}
if (defined_default(outlinePrimitive) && outlinePrimitive.show && outlinePrimitive.ready) {
attributes = outlinePrimitive.getGeometryInstanceAttributes(entity);
if (defined_default(attributes) && defined_default(attributes.boundingSphere)) {
BoundingSphere_default.clone(attributes.boundingSphere, result);
return BoundingSphereState_default.DONE;
}
}
if (defined_default(primitive) && !primitive.ready || defined_default(outlinePrimitive) && !outlinePrimitive.ready) {
return BoundingSphereState_default.PENDING;
}
return BoundingSphereState_default.FAILED;
};
DynamicGeometryUpdater.prototype.isDestroyed = function() {
return false;
};
DynamicGeometryUpdater.prototype.destroy = function() {
const primitives = this._primitives;
const orderedGroundPrimitives = this._orderedGroundPrimitives;
if (this._geometryUpdater._onTerrain) {
orderedGroundPrimitives.remove(this._primitive);
} else {
primitives.removeAndDestroy(this._primitive);
}
primitives.removeAndDestroy(this._outlinePrimitive);
destroyObject_default(this);
};
var DynamicGeometryUpdater_default = DynamicGeometryUpdater;
// 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(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/TrackingReferenceFrame.js
var TrackingReferenceFrame = {
/**
* Auto-detect algorithm. The reference frame used to track the Entity will
* be automatically selected based on its trajectory: near-surface slow moving
* objects will be tracked in the entity's local east-north-up reference
* frame, while faster objects like satellites will use VVLH (Vehicle Velocity,
* Local Horizontal).
*
* @type {number}
* @constant
*/
AUTODETECT: 0,
/**
* The entity's local East-North-Up reference frame.
*
* @type {number}
* @constant
*/
ENU: 1,
/**
* The entity's inertial reference frame. If entity has no defined orientation
* property, it falls back to auto-detect algorithm.
*
* @type {number}
* @constant
*/
INERTIAL: 2,
/**
* The entity's inertial reference frame with orientation fixed to its
* {@link VelocityOrientationProperty}, ignoring its own orientation.
*
* @type {number}
* @constant
*/
VELOCITY: 3
};
Object.freeze(TrackingReferenceFrame);
var TrackingReferenceFrame_default = TrackingReferenceFrame;
// packages/engine/Source/Core/ArcType.js
var ArcType = {
/**
* Straight line that does not conform to the surface of the ellipsoid.
*
* @type {number}
* @constant
*/
NONE: 0,
/**
* Follow geodesic path.
*
* @type {number}
* @constant
*/
GEODESIC: 1,
/**
* Follow rhumb or loxodrome path.
*
* @type {number}
* @constant
*/
RHUMB: 2
};
Object.freeze(ArcType);
var ArcType_default = ArcType;
// packages/engine/Source/Core/arrayRemoveDuplicates.js
var removeDuplicatesEpsilon = Math_default.EPSILON10;
function arrayRemoveDuplicates(values, equalsEpsilon, wrapAround, removedIndices) {
Check_default.defined("equalsEpsilon", equalsEpsilon);
if (!defined_default(values)) {
return void 0;
}
wrapAround = wrapAround ?? false;
const storeRemovedIndices = defined_default(removedIndices);
const length2 = values.length;
if (length2 < 2) {
return values;
}
let i;
let v02 = values[0];
let v12;
let cleanedValues;
let lastCleanIndex = 0;
let removedIndexLCI = -1;
for (i = 1; i < length2; ++i) {
v12 = values[i];
if (equalsEpsilon(v02, v12, removeDuplicatesEpsilon)) {
if (!defined_default(cleanedValues)) {
cleanedValues = values.slice(0, i);
lastCleanIndex = i - 1;
removedIndexLCI = 0;
}
if (storeRemovedIndices) {
removedIndices.push(i);
}
} else {
if (defined_default(cleanedValues)) {
cleanedValues.push(v12);
lastCleanIndex = i;
if (storeRemovedIndices) {
removedIndexLCI = removedIndices.length;
}
}
v02 = v12;
}
}
if (wrapAround && equalsEpsilon(values[0], values[length2 - 1], removeDuplicatesEpsilon)) {
if (storeRemovedIndices) {
if (defined_default(cleanedValues)) {
removedIndices.splice(removedIndexLCI, 0, lastCleanIndex);
} else {
removedIndices.push(length2 - 1);
}
}
if (defined_default(cleanedValues)) {
cleanedValues.length -= 1;
} else {
cleanedValues = values.slice(0, -1);
}
}
return defined_default(cleanedValues) ? cleanedValues : values;
}
var arrayRemoveDuplicates_default = arrayRemoveDuplicates;
// packages/engine/Source/Core/EllipsoidGeodesic.js
function setConstants(ellipsoidGeodesic2) {
const uSquared = ellipsoidGeodesic2._uSquared;
const a3 = ellipsoidGeodesic2._ellipsoid.maximumRadius;
const b = ellipsoidGeodesic2._ellipsoid.minimumRadius;
const f2 = (a3 - b) / a3;
const cosineHeading = Math.cos(ellipsoidGeodesic2._startHeading);
const sineHeading = Math.sin(ellipsoidGeodesic2._startHeading);
const tanU = (1 - f2) * Math.tan(ellipsoidGeodesic2._start.latitude);
const cosineU = 1 / Math.sqrt(1 + tanU * tanU);
const sineU = cosineU * tanU;
const sigma = Math.atan2(tanU, cosineHeading);
const sineAlpha = cosineU * sineHeading;
const sineSquaredAlpha = sineAlpha * sineAlpha;
const cosineSquaredAlpha = 1 - sineSquaredAlpha;
const cosineAlpha = Math.sqrt(cosineSquaredAlpha);
const u2Over4 = uSquared / 4;
const u4Over16 = u2Over4 * u2Over4;
const u6Over64 = u4Over16 * u2Over4;
const u8Over256 = u4Over16 * u4Over16;
const a0 = 1 + u2Over4 - 3 * u4Over16 / 4 + 5 * u6Over64 / 4 - 175 * u8Over256 / 64;
const a1 = 1 - u2Over4 + 15 * u4Over16 / 8 - 35 * u6Over64 / 8;
const a22 = 1 - 3 * u2Over4 + 35 * u4Over16 / 4;
const a32 = 1 - 5 * u2Over4;
const distanceRatio = a0 * sigma - a1 * Math.sin(2 * sigma) * u2Over4 / 2 - a22 * Math.sin(4 * sigma) * u4Over16 / 16 - a32 * Math.sin(6 * sigma) * u6Over64 / 48 - Math.sin(8 * sigma) * 5 * u8Over256 / 512;
const constants = ellipsoidGeodesic2._constants;
constants.a = a3;
constants.b = b;
constants.f = f2;
constants.cosineHeading = cosineHeading;
constants.sineHeading = sineHeading;
constants.tanU = tanU;
constants.cosineU = cosineU;
constants.sineU = sineU;
constants.sigma = sigma;
constants.sineAlpha = sineAlpha;
constants.sineSquaredAlpha = sineSquaredAlpha;
constants.cosineSquaredAlpha = cosineSquaredAlpha;
constants.cosineAlpha = cosineAlpha;
constants.u2Over4 = u2Over4;
constants.u4Over16 = u4Over16;
constants.u6Over64 = u6Over64;
constants.u8Over256 = u8Over256;
constants.a0 = a0;
constants.a1 = a1;
constants.a2 = a22;
constants.a3 = a32;
constants.distanceRatio = distanceRatio;
}
function computeC(f2, cosineSquaredAlpha) {
return f2 * cosineSquaredAlpha * (4 + f2 * (4 - 3 * cosineSquaredAlpha)) / 16;
}
function computeDeltaLambda(f2, sineAlpha, cosineSquaredAlpha, sigma, sineSigma, cosineSigma, cosineTwiceSigmaMidpoint) {
const C = computeC(f2, cosineSquaredAlpha);
return (1 - C) * f2 * sineAlpha * (sigma + C * sineSigma * (cosineTwiceSigmaMidpoint + C * cosineSigma * (2 * cosineTwiceSigmaMidpoint * cosineTwiceSigmaMidpoint - 1)));
}
function vincentyInverseFormula(ellipsoidGeodesic2, major, minor, firstLongitude, firstLatitude, secondLongitude, secondLatitude) {
const eff = (major - minor) / major;
const l2 = secondLongitude - firstLongitude;
const u12 = Math.atan((1 - eff) * Math.tan(firstLatitude));
const u22 = Math.atan((1 - eff) * Math.tan(secondLatitude));
const cosineU1 = Math.cos(u12);
const sineU1 = Math.sin(u12);
const cosineU2 = Math.cos(u22);
const sineU2 = Math.sin(u22);
const cc = cosineU1 * cosineU2;
const cs = cosineU1 * sineU2;
const ss = sineU1 * sineU2;
const sc = sineU1 * cosineU2;
let lambda = l2;
let lambdaDot;
let cosineLambda;
let sineLambda;
let sigma;
let cosineSigma;
let sineSigma;
let cosineSquaredAlpha;
let cosineTwiceSigmaMidpoint;
do {
cosineLambda = Math.cos(lambda);
sineLambda = Math.sin(lambda);
const temp = cs - sc * cosineLambda;
sineSigma = Math.sqrt(
cosineU2 * cosineU2 * sineLambda * sineLambda + temp * temp
);
cosineSigma = ss + cc * cosineLambda;
sigma = Math.atan2(sineSigma, cosineSigma);
let sineAlpha;
if (sineSigma === 0) {
sineAlpha = 0;
cosineSquaredAlpha = 1;
} else {
sineAlpha = cc * sineLambda / sineSigma;
cosineSquaredAlpha = 1 - sineAlpha * sineAlpha;
}
lambdaDot = lambda;
cosineTwiceSigmaMidpoint = cosineSigma - 2 * ss / cosineSquaredAlpha;
if (!isFinite(cosineTwiceSigmaMidpoint)) {
cosineTwiceSigmaMidpoint = 0;
}
lambda = l2 + computeDeltaLambda(
eff,
sineAlpha,
cosineSquaredAlpha,
sigma,
sineSigma,
cosineSigma,
cosineTwiceSigmaMidpoint
);
} while (Math.abs(lambda - lambdaDot) > Math_default.EPSILON12);
const uSquared = cosineSquaredAlpha * (major * major - minor * minor) / (minor * minor);
const A = 1 + uSquared * (4096 + uSquared * (uSquared * (320 - 175 * uSquared) - 768)) / 16384;
const B = uSquared * (256 + uSquared * (uSquared * (74 - 47 * uSquared) - 128)) / 1024;
const cosineSquaredTwiceSigmaMidpoint = cosineTwiceSigmaMidpoint * cosineTwiceSigmaMidpoint;
const deltaSigma = B * sineSigma * (cosineTwiceSigmaMidpoint + B * (cosineSigma * (2 * cosineSquaredTwiceSigmaMidpoint - 1) - B * cosineTwiceSigmaMidpoint * (4 * sineSigma * sineSigma - 3) * (4 * cosineSquaredTwiceSigmaMidpoint - 3) / 6) / 4);
const distance2 = minor * A * (sigma - deltaSigma);
const startHeading = Math.atan2(
cosineU2 * sineLambda,
cs - sc * cosineLambda
);
const endHeading = Math.atan2(cosineU1 * sineLambda, cs * cosineLambda - sc);
ellipsoidGeodesic2._distance = distance2;
ellipsoidGeodesic2._startHeading = startHeading;
ellipsoidGeodesic2._endHeading = endHeading;
ellipsoidGeodesic2._uSquared = uSquared;
}
var scratchCart1 = new Cartesian3_default();
var scratchCart2 = new Cartesian3_default();
function computeProperties(ellipsoidGeodesic2, start, end, ellipsoid) {
const firstCartesian = Cartesian3_default.normalize(
ellipsoid.cartographicToCartesian(start, scratchCart2),
scratchCart1
);
const lastCartesian = Cartesian3_default.normalize(
ellipsoid.cartographicToCartesian(end, scratchCart2),
scratchCart2
);
Check_default.typeOf.number.greaterThanOrEquals(
"value",
Math.abs(
Math.abs(Cartesian3_default.angleBetween(firstCartesian, lastCartesian)) - Math.PI
),
0.0125
);
vincentyInverseFormula(
ellipsoidGeodesic2,
ellipsoid.maximumRadius,
ellipsoid.minimumRadius,
start.longitude,
start.latitude,
end.longitude,
end.latitude
);
ellipsoidGeodesic2._start = Cartographic_default.clone(
start,
ellipsoidGeodesic2._start
);
ellipsoidGeodesic2._end = Cartographic_default.clone(end, ellipsoidGeodesic2._end);
ellipsoidGeodesic2._start.height = 0;
ellipsoidGeodesic2._end.height = 0;
setConstants(ellipsoidGeodesic2);
}
function EllipsoidGeodesic(start, end, ellipsoid) {
const e = ellipsoid ?? Ellipsoid_default.default;
this._ellipsoid = e;
this._start = new Cartographic_default();
this._end = new Cartographic_default();
this._constants = {};
this._startHeading = void 0;
this._endHeading = void 0;
this._distance = void 0;
this._uSquared = void 0;
if (defined_default(start) && defined_default(end)) {
computeProperties(this, start, end, e);
}
}
Object.defineProperties(EllipsoidGeodesic.prototype, {
/**
* Gets the ellipsoid.
* @memberof EllipsoidGeodesic.prototype
* @type {Ellipsoid}
* @readonly
*/
ellipsoid: {
get: function() {
return this._ellipsoid;
}
},
/**
* Gets the surface distance between the start and end point
* @memberof EllipsoidGeodesic.prototype
* @type {number}
* @readonly
*/
surfaceDistance: {
get: function() {
Check_default.defined("distance", this._distance);
return this._distance;
}
},
/**
* Gets the initial planetodetic point on the path.
* @memberof EllipsoidGeodesic.prototype
* @type {Cartographic}
* @readonly
*/
start: {
get: function() {
return this._start;
}
},
/**
* Gets the final planetodetic point on the path.
* @memberof EllipsoidGeodesic.prototype
* @type {Cartographic}
* @readonly
*/
end: {
get: function() {
return this._end;
}
},
/**
* Gets the heading at the initial point.
* @memberof EllipsoidGeodesic.prototype
* @type {number}
* @readonly
*/
startHeading: {
get: function() {
Check_default.defined("distance", this._distance);
return this._startHeading;
}
},
/**
* Gets the heading at the final point.
* @memberof EllipsoidGeodesic.prototype
* @type {number}
* @readonly
*/
endHeading: {
get: function() {
Check_default.defined("distance", this._distance);
return this._endHeading;
}
}
});
EllipsoidGeodesic.prototype.setEndPoints = function(start, end) {
Check_default.defined("start", start);
Check_default.defined("end", end);
computeProperties(this, start, end, this._ellipsoid);
};
EllipsoidGeodesic.prototype.interpolateUsingFraction = function(fraction, result) {
return this.interpolateUsingSurfaceDistance(
this._distance * fraction,
result
);
};
EllipsoidGeodesic.prototype.interpolateUsingSurfaceDistance = function(distance2, result) {
Check_default.defined("distance", this._distance);
const constants = this._constants;
const s2 = constants.distanceRatio + distance2 / constants.b;
const cosine2S = Math.cos(2 * s2);
const cosine4S = Math.cos(4 * s2);
const cosine6S = Math.cos(6 * s2);
const sine2S = Math.sin(2 * s2);
const sine4S = Math.sin(4 * s2);
const sine6S = Math.sin(6 * s2);
const sine8S = Math.sin(8 * s2);
const s22 = s2 * s2;
const s3 = s2 * s22;
const u8Over256 = constants.u8Over256;
const u2Over4 = constants.u2Over4;
const u6Over64 = constants.u6Over64;
const u4Over16 = constants.u4Over16;
let sigma = 2 * s3 * u8Over256 * cosine2S / 3 + s2 * (1 - u2Over4 + 7 * u4Over16 / 4 - 15 * u6Over64 / 4 + 579 * u8Over256 / 64 - (u4Over16 - 15 * u6Over64 / 4 + 187 * u8Over256 / 16) * cosine2S - (5 * u6Over64 / 4 - 115 * u8Over256 / 16) * cosine4S - 29 * u8Over256 * cosine6S / 16) + (u2Over4 / 2 - u4Over16 + 71 * u6Over64 / 32 - 85 * u8Over256 / 16) * sine2S + (5 * u4Over16 / 16 - 5 * u6Over64 / 4 + 383 * u8Over256 / 96) * sine4S - s22 * ((u6Over64 - 11 * u8Over256 / 2) * sine2S + 5 * u8Over256 * sine4S / 2) + (29 * u6Over64 / 96 - 29 * u8Over256 / 16) * sine6S + 539 * u8Over256 * sine8S / 1536;
const theta = Math.asin(Math.sin(sigma) * constants.cosineAlpha);
const latitude = Math.atan(constants.a / constants.b * Math.tan(theta));
sigma = sigma - constants.sigma;
const cosineTwiceSigmaMidpoint = Math.cos(2 * constants.sigma + sigma);
const sineSigma = Math.sin(sigma);
const cosineSigma = Math.cos(sigma);
const cc = constants.cosineU * cosineSigma;
const ss = constants.sineU * sineSigma;
const lambda = Math.atan2(
sineSigma * constants.sineHeading,
cc - ss * constants.cosineHeading
);
const l2 = lambda - computeDeltaLambda(
constants.f,
constants.sineAlpha,
constants.cosineSquaredAlpha,
sigma,
sineSigma,
cosineSigma,
cosineTwiceSigmaMidpoint
);
if (defined_default(result)) {
result.longitude = this._start.longitude + l2;
result.latitude = latitude;
result.height = 0;
return result;
}
return new Cartographic_default(this._start.longitude + l2, latitude, 0);
};
var EllipsoidGeodesic_default = EllipsoidGeodesic;
// packages/engine/Source/Core/EllipsoidRhumbLine.js
function calculateM(ellipticity, major, latitude) {
if (ellipticity === 0) {
return major * latitude;
}
const e2 = ellipticity * ellipticity;
const e4 = e2 * e2;
const e6 = e4 * e2;
const e8 = e6 * e2;
const e10 = e8 * e2;
const e12 = e10 * e2;
const phi = latitude;
const sin2Phi = Math.sin(2 * phi);
const sin4Phi = Math.sin(4 * phi);
const sin6Phi = Math.sin(6 * phi);
const sin8Phi = Math.sin(8 * phi);
const sin10Phi = Math.sin(10 * phi);
const sin12Phi = Math.sin(12 * phi);
return major * ((1 - e2 / 4 - 3 * e4 / 64 - 5 * e6 / 256 - 175 * e8 / 16384 - 441 * e10 / 65536 - 4851 * e12 / 1048576) * phi - (3 * e2 / 8 + 3 * e4 / 32 + 45 * e6 / 1024 + 105 * e8 / 4096 + 2205 * e10 / 131072 + 6237 * e12 / 524288) * sin2Phi + (15 * e4 / 256 + 45 * e6 / 1024 + 525 * e8 / 16384 + 1575 * e10 / 65536 + 155925 * e12 / 8388608) * sin4Phi - (35 * e6 / 3072 + 175 * e8 / 12288 + 3675 * e10 / 262144 + 13475 * e12 / 1048576) * sin6Phi + (315 * e8 / 131072 + 2205 * e10 / 524288 + 43659 * e12 / 8388608) * sin8Phi - (693 * e10 / 1310720 + 6237 * e12 / 5242880) * sin10Phi + 1001 * e12 / 8388608 * sin12Phi);
}
function calculateInverseM(M, ellipticity, major) {
const d = M / major;
if (ellipticity === 0) {
return d;
}
const d2 = d * d;
const d3 = d2 * d;
const d4 = d3 * d;
const e = ellipticity;
const e2 = e * e;
const e4 = e2 * e2;
const e6 = e4 * e2;
const e8 = e6 * e2;
const e10 = e8 * e2;
const e12 = e10 * e2;
const sin2D = Math.sin(2 * d);
const cos2D = Math.cos(2 * d);
const sin4D = Math.sin(4 * d);
const cos4D = Math.cos(4 * d);
const sin6D = Math.sin(6 * d);
const cos6D = Math.cos(6 * d);
const sin8D = Math.sin(8 * d);
const cos8D = Math.cos(8 * d);
const sin10D = Math.sin(10 * d);
const cos10D = Math.cos(10 * d);
const sin12D = Math.sin(12 * d);
return d + d * e2 / 4 + 7 * d * e4 / 64 + 15 * d * e6 / 256 + 579 * d * e8 / 16384 + 1515 * d * e10 / 65536 + 16837 * d * e12 / 1048576 + (3 * d * e4 / 16 + 45 * d * e6 / 256 - d * (32 * d2 - 561) * e8 / 4096 - d * (232 * d2 - 1677) * e10 / 16384 + d * (399985 - 90560 * d2 + 512 * d4) * e12 / 5242880) * cos2D + (21 * d * e6 / 256 + 483 * d * e8 / 4096 - d * (224 * d2 - 1969) * e10 / 16384 - d * (33152 * d2 - 112599) * e12 / 1048576) * cos4D + (151 * d * e8 / 4096 + 4681 * d * e10 / 65536 + 1479 * d * e12 / 16384 - 453 * d3 * e12 / 32768) * cos6D + (1097 * d * e10 / 65536 + 42783 * d * e12 / 1048576) * cos8D + 8011 * d * e12 / 1048576 * cos10D + (3 * e2 / 8 + 3 * e4 / 16 + 213 * e6 / 2048 - 3 * d2 * e6 / 64 + 255 * e8 / 4096 - 33 * d2 * e8 / 512 + 20861 * e10 / 524288 - 33 * d2 * e10 / 512 + d4 * e10 / 1024 + 28273 * e12 / 1048576 - 471 * d2 * e12 / 8192 + 9 * d4 * e12 / 4096) * sin2D + (21 * e4 / 256 + 21 * e6 / 256 + 533 * e8 / 8192 - 21 * d2 * e8 / 512 + 197 * e10 / 4096 - 315 * d2 * e10 / 4096 + 584039 * e12 / 16777216 - 12517 * d2 * e12 / 131072 + 7 * d4 * e12 / 2048) * sin4D + (151 * e6 / 6144 + 151 * e8 / 4096 + 5019 * e10 / 131072 - 453 * d2 * e10 / 16384 + 26965 * e12 / 786432 - 8607 * d2 * e12 / 131072) * sin6D + (1097 * e8 / 131072 + 1097 * e10 / 65536 + 225797 * e12 / 10485760 - 1097 * d2 * e12 / 65536) * sin8D + (8011 * e10 / 2621440 + 8011 * e12 / 1048576) * sin10D + 293393 * e12 / 251658240 * sin12D;
}
function calculateSigma(ellipticity, latitude) {
if (ellipticity === 0) {
return Math.log(Math.tan(0.5 * (Math_default.PI_OVER_TWO + latitude)));
}
const eSinL = ellipticity * Math.sin(latitude);
return Math.log(Math.tan(0.5 * (Math_default.PI_OVER_TWO + latitude))) - ellipticity / 2 * Math.log((1 + eSinL) / (1 - eSinL));
}
function calculateHeading(ellipsoidRhumbLine, firstLongitude, firstLatitude, secondLongitude, secondLatitude) {
const sigma1 = calculateSigma(ellipsoidRhumbLine._ellipticity, firstLatitude);
const sigma2 = calculateSigma(
ellipsoidRhumbLine._ellipticity,
secondLatitude
);
return Math.atan2(
Math_default.negativePiToPi(secondLongitude - firstLongitude),
sigma2 - sigma1
);
}
function calculateArcLength(ellipsoidRhumbLine, major, minor, firstLongitude, firstLatitude, secondLongitude, secondLatitude) {
const heading = ellipsoidRhumbLine._heading;
const deltaLongitude = secondLongitude - firstLongitude;
let distance2;
if (Math_default.equalsEpsilon(
Math.abs(heading),
Math_default.PI_OVER_TWO,
Math_default.EPSILON8
)) {
if (major === minor) {
distance2 = major * Math.cos(firstLatitude) * Math_default.negativePiToPi(deltaLongitude);
} else {
const sinPhi = Math.sin(firstLatitude);
distance2 = major * Math.cos(firstLatitude) * Math_default.negativePiToPi(deltaLongitude) / Math.sqrt(1 - ellipsoidRhumbLine._ellipticitySquared * sinPhi * sinPhi);
}
} else {
const M1 = calculateM(
ellipsoidRhumbLine._ellipticity,
major,
firstLatitude
);
const M2 = calculateM(
ellipsoidRhumbLine._ellipticity,
major,
secondLatitude
);
distance2 = (M2 - M1) / Math.cos(heading);
}
return Math.abs(distance2);
}
var scratchCart12 = new Cartesian3_default();
var scratchCart22 = new Cartesian3_default();
function computeProperties2(ellipsoidRhumbLine, start, end, ellipsoid) {
const firstCartesian = Cartesian3_default.normalize(
ellipsoid.cartographicToCartesian(start, scratchCart22),
scratchCart12
);
const lastCartesian = Cartesian3_default.normalize(
ellipsoid.cartographicToCartesian(end, scratchCart22),
scratchCart22
);
Check_default.typeOf.number.greaterThanOrEquals(
"value",
Math.abs(
Math.abs(Cartesian3_default.angleBetween(firstCartesian, lastCartesian)) - Math.PI
),
0.0125
);
const major = ellipsoid.maximumRadius;
const minor = ellipsoid.minimumRadius;
const majorSquared = major * major;
const minorSquared = minor * minor;
ellipsoidRhumbLine._ellipticitySquared = (majorSquared - minorSquared) / majorSquared;
ellipsoidRhumbLine._ellipticity = Math.sqrt(
ellipsoidRhumbLine._ellipticitySquared
);
ellipsoidRhumbLine._start = Cartographic_default.clone(
start,
ellipsoidRhumbLine._start
);
ellipsoidRhumbLine._start.height = 0;
ellipsoidRhumbLine._end = Cartographic_default.clone(end, ellipsoidRhumbLine._end);
ellipsoidRhumbLine._end.height = 0;
ellipsoidRhumbLine._heading = calculateHeading(
ellipsoidRhumbLine,
start.longitude,
start.latitude,
end.longitude,
end.latitude
);
ellipsoidRhumbLine._distance = calculateArcLength(
ellipsoidRhumbLine,
ellipsoid.maximumRadius,
ellipsoid.minimumRadius,
start.longitude,
start.latitude,
end.longitude,
end.latitude
);
}
function interpolateUsingSurfaceDistance(start, heading, distance2, major, ellipticity, result) {
if (distance2 === 0) {
return Cartographic_default.clone(start, result);
}
const ellipticitySquared = ellipticity * ellipticity;
let longitude;
let latitude;
let deltaLongitude;
if (Math.abs(Math_default.PI_OVER_TWO - Math.abs(heading)) > Math_default.EPSILON8) {
const M1 = calculateM(ellipticity, major, start.latitude);
const deltaM = distance2 * Math.cos(heading);
const M2 = M1 + deltaM;
latitude = calculateInverseM(M2, ellipticity, major);
if (Math.abs(heading) < Math_default.EPSILON10) {
longitude = Math_default.negativePiToPi(start.longitude);
} else {
const sigma1 = calculateSigma(ellipticity, start.latitude);
const sigma2 = calculateSigma(ellipticity, latitude);
deltaLongitude = Math.tan(heading) * (sigma2 - sigma1);
longitude = Math_default.negativePiToPi(start.longitude + deltaLongitude);
}
} else {
latitude = start.latitude;
let localRad;
if (ellipticity === 0) {
localRad = major * Math.cos(start.latitude);
} else {
const sinPhi = Math.sin(start.latitude);
localRad = major * Math.cos(start.latitude) / Math.sqrt(1 - ellipticitySquared * sinPhi * sinPhi);
}
deltaLongitude = distance2 / localRad;
if (heading > 0) {
longitude = Math_default.negativePiToPi(start.longitude + deltaLongitude);
} else {
longitude = Math_default.negativePiToPi(start.longitude - deltaLongitude);
}
}
if (defined_default(result)) {
result.longitude = longitude;
result.latitude = latitude;
result.height = 0;
return result;
}
return new Cartographic_default(longitude, latitude, 0);
}
function EllipsoidRhumbLine(start, end, ellipsoid) {
const e = ellipsoid ?? Ellipsoid_default.default;
this._ellipsoid = e;
this._start = new Cartographic_default();
this._end = new Cartographic_default();
this._heading = void 0;
this._distance = void 0;
this._ellipticity = void 0;
this._ellipticitySquared = void 0;
if (defined_default(start) && defined_default(end)) {
computeProperties2(this, start, end, e);
}
}
Object.defineProperties(EllipsoidRhumbLine.prototype, {
/**
* Gets the ellipsoid.
* @memberof EllipsoidRhumbLine.prototype
* @type {Ellipsoid}
* @readonly
*/
ellipsoid: {
get: function() {
return this._ellipsoid;
}
},
/**
* Gets the surface distance between the start and end point
* @memberof EllipsoidRhumbLine.prototype
* @type {number}
* @readonly
*/
surfaceDistance: {
get: function() {
Check_default.defined("distance", this._distance);
return this._distance;
}
},
/**
* Gets the initial planetodetic point on the path.
* @memberof EllipsoidRhumbLine.prototype
* @type {Cartographic}
* @readonly
*/
start: {
get: function() {
return this._start;
}
},
/**
* Gets the final planetodetic point on the path.
* @memberof EllipsoidRhumbLine.prototype
* @type {Cartographic}
* @readonly
*/
end: {
get: function() {
return this._end;
}
},
/**
* Gets the heading from the start point to the end point.
* @memberof EllipsoidRhumbLine.prototype
* @type {number}
* @readonly
*/
heading: {
get: function() {
Check_default.defined("distance", this._distance);
return this._heading;
}
}
});
EllipsoidRhumbLine.fromStartHeadingDistance = function(start, heading, distance2, ellipsoid, result) {
Check_default.defined("start", start);
Check_default.defined("heading", heading);
Check_default.defined("distance", distance2);
Check_default.typeOf.number.greaterThan("distance", distance2, 0);
const e = ellipsoid ?? Ellipsoid_default.default;
const major = e.maximumRadius;
const minor = e.minimumRadius;
const majorSquared = major * major;
const minorSquared = minor * minor;
const ellipticity = Math.sqrt((majorSquared - minorSquared) / majorSquared);
heading = Math_default.negativePiToPi(heading);
const end = interpolateUsingSurfaceDistance(
start,
heading,
distance2,
e.maximumRadius,
ellipticity
);
if (!defined_default(result) || defined_default(ellipsoid) && !ellipsoid.equals(result.ellipsoid)) {
return new EllipsoidRhumbLine(start, end, e);
}
result.setEndPoints(start, end);
return result;
};
EllipsoidRhumbLine.prototype.setEndPoints = function(start, end) {
Check_default.defined("start", start);
Check_default.defined("end", end);
computeProperties2(this, start, end, this._ellipsoid);
};
EllipsoidRhumbLine.prototype.interpolateUsingFraction = function(fraction, result) {
return this.interpolateUsingSurfaceDistance(
fraction * this._distance,
result
);
};
EllipsoidRhumbLine.prototype.interpolateUsingSurfaceDistance = function(distance2, result) {
Check_default.typeOf.number("distance", distance2);
if (!defined_default(this._distance) || this._distance === 0) {
throw new DeveloperError_default(
"EllipsoidRhumbLine must have distinct start and end set."
);
}
return interpolateUsingSurfaceDistance(
this._start,
this._heading,
distance2,
this._ellipsoid.maximumRadius,
this._ellipticity,
result
);
};
EllipsoidRhumbLine.prototype.findIntersectionWithLongitude = function(intersectionLongitude, result) {
Check_default.typeOf.number("intersectionLongitude", intersectionLongitude);
if (!defined_default(this._distance) || this._distance === 0) {
throw new DeveloperError_default(
"EllipsoidRhumbLine must have distinct start and end set."
);
}
const ellipticity = this._ellipticity;
const heading = this._heading;
const absHeading = Math.abs(heading);
const start = this._start;
intersectionLongitude = Math_default.negativePiToPi(intersectionLongitude);
if (Math_default.equalsEpsilon(
Math.abs(intersectionLongitude),
Math.PI,
Math_default.EPSILON14
)) {
intersectionLongitude = Math_default.sign(start.longitude) * Math.PI;
}
if (!defined_default(result)) {
result = new Cartographic_default();
}
if (Math.abs(Math_default.PI_OVER_TWO - absHeading) <= Math_default.EPSILON8) {
result.longitude = intersectionLongitude;
result.latitude = start.latitude;
result.height = 0;
return result;
} else if (Math_default.equalsEpsilon(
Math.abs(Math_default.PI_OVER_TWO - absHeading),
Math_default.PI_OVER_TWO,
Math_default.EPSILON8
)) {
if (Math_default.equalsEpsilon(
intersectionLongitude,
start.longitude,
Math_default.EPSILON12
)) {
return void 0;
}
result.longitude = intersectionLongitude;
result.latitude = Math_default.PI_OVER_TWO * Math_default.sign(Math_default.PI_OVER_TWO - heading);
result.height = 0;
return result;
}
const phi1 = start.latitude;
const eSinPhi1 = ellipticity * Math.sin(phi1);
const leftComponent = Math.tan(0.5 * (Math_default.PI_OVER_TWO + phi1)) * Math.exp((intersectionLongitude - start.longitude) / Math.tan(heading));
const denominator = (1 + eSinPhi1) / (1 - eSinPhi1);
let newPhi = start.latitude;
let phi;
do {
phi = newPhi;
const eSinPhi = ellipticity * Math.sin(phi);
const numerator = (1 + eSinPhi) / (1 - eSinPhi);
newPhi = 2 * Math.atan(
leftComponent * Math.pow(numerator / denominator, ellipticity / 2)
) - Math_default.PI_OVER_TWO;
} while (!Math_default.equalsEpsilon(newPhi, phi, Math_default.EPSILON12));
result.longitude = intersectionLongitude;
result.latitude = newPhi;
result.height = 0;
return result;
};
EllipsoidRhumbLine.prototype.findIntersectionWithLatitude = function(intersectionLatitude, result) {
Check_default.typeOf.number("intersectionLatitude", intersectionLatitude);
if (!defined_default(this._distance) || this._distance === 0) {
throw new DeveloperError_default(
"EllipsoidRhumbLine must have distinct start and end set."
);
}
const ellipticity = this._ellipticity;
const heading = this._heading;
const start = this._start;
if (Math_default.equalsEpsilon(
Math.abs(heading),
Math_default.PI_OVER_TWO,
Math_default.EPSILON8
)) {
return;
}
const sigma1 = calculateSigma(ellipticity, start.latitude);
const sigma2 = calculateSigma(ellipticity, intersectionLatitude);
const deltaLongitude = Math.tan(heading) * (sigma2 - sigma1);
const longitude = Math_default.negativePiToPi(start.longitude + deltaLongitude);
if (defined_default(result)) {
result.longitude = longitude;
result.latitude = intersectionLatitude;
result.height = 0;
return result;
}
return new Cartographic_default(longitude, intersectionLatitude, 0);
};
var EllipsoidRhumbLine_default = EllipsoidRhumbLine;
// packages/engine/Source/Core/GroundPolylineGeometry.js
var PROJECTIONS = [GeographicProjection_default, WebMercatorProjection_default];
var PROJECTION_COUNT = PROJECTIONS.length;
var MITER_BREAK_SMALL = Math.cos(Math_default.toRadians(30));
var MITER_BREAK_LARGE = Math.cos(Math_default.toRadians(150));
var WALL_INITIAL_MIN_HEIGHT = 0;
var WALL_INITIAL_MAX_HEIGHT = 1e3;
function GroundPolylineGeometry(options) {
options = options ?? Frozen_default.EMPTY_OBJECT;
const positions = options.positions;
if (!defined_default(positions) || positions.length < 2) {
throw new DeveloperError_default("At least two positions are required.");
}
if (defined_default(options.arcType) && options.arcType !== ArcType_default.GEODESIC && options.arcType !== ArcType_default.RHUMB) {
throw new DeveloperError_default(
"Valid options for arcType are ArcType.GEODESIC and ArcType.RHUMB."
);
}
this.width = options.width ?? 1;
this._positions = positions;
this.granularity = options.granularity ?? 9999;
this.loop = options.loop ?? false;
this.arcType = options.arcType ?? ArcType_default.GEODESIC;
this._ellipsoid = Ellipsoid_default.default;
this._projectionIndex = 0;
this._workerName = "createGroundPolylineGeometry";
this._scene3DOnly = false;
}
Object.defineProperties(GroundPolylineGeometry.prototype, {
/**
* The number of elements used to pack the object into an array.
* @memberof GroundPolylineGeometry.prototype
* @type {number}
* @readonly
* @private
*/
packedLength: {
get: function() {
return 1 + this._positions.length * 3 + 1 + 1 + 1 + Ellipsoid_default.packedLength + 1 + 1;
}
}
});
GroundPolylineGeometry.setProjectionAndEllipsoid = function(groundPolylineGeometry, mapProjection) {
let projectionIndex = 0;
for (let i = 0; i < PROJECTION_COUNT; i++) {
if (mapProjection instanceof PROJECTIONS[i]) {
projectionIndex = i;
break;
}
}
groundPolylineGeometry._projectionIndex = projectionIndex;
groundPolylineGeometry._ellipsoid = mapProjection.ellipsoid;
};
var cart3Scratch1 = new Cartesian3_default();
var cart3Scratch2 = new Cartesian3_default();
var cart3Scratch3 = new Cartesian3_default();
function computeRightNormal(start, end, maxHeight, ellipsoid, result) {
const startBottom = getPosition(ellipsoid, start, 0, cart3Scratch1);
const startTop = getPosition(ellipsoid, start, maxHeight, cart3Scratch2);
const endBottom = getPosition(ellipsoid, end, 0, cart3Scratch3);
const up = direction(startTop, startBottom, cart3Scratch2);
const forward = direction(endBottom, startBottom, cart3Scratch3);
Cartesian3_default.cross(forward, up, result);
return Cartesian3_default.normalize(result, result);
}
var interpolatedCartographicScratch = new Cartographic_default();
var interpolatedBottomScratch = new Cartesian3_default();
var interpolatedTopScratch = new Cartesian3_default();
var interpolatedNormalScratch = new Cartesian3_default();
function interpolateSegment(start, end, minHeight, maxHeight, granularity, arcType, ellipsoid, normalsArray, bottomPositionsArray, topPositionsArray, cartographicsArray) {
if (granularity === 0) {
return;
}
let ellipsoidLine;
if (arcType === ArcType_default.GEODESIC) {
ellipsoidLine = new EllipsoidGeodesic_default(start, end, ellipsoid);
} else if (arcType === ArcType_default.RHUMB) {
ellipsoidLine = new EllipsoidRhumbLine_default(start, end, ellipsoid);
}
const surfaceDistance = ellipsoidLine.surfaceDistance;
if (surfaceDistance < granularity) {
return;
}
const interpolatedNormal = computeRightNormal(
start,
end,
maxHeight,
ellipsoid,
interpolatedNormalScratch
);
const segments = Math.ceil(surfaceDistance / granularity);
const interpointDistance = surfaceDistance / segments;
let distanceFromStart = interpointDistance;
const pointsToAdd = segments - 1;
let packIndex = normalsArray.length;
for (let i = 0; i < pointsToAdd; i++) {
const interpolatedCartographic = ellipsoidLine.interpolateUsingSurfaceDistance(
distanceFromStart,
interpolatedCartographicScratch
);
const interpolatedBottom = getPosition(
ellipsoid,
interpolatedCartographic,
minHeight,
interpolatedBottomScratch
);
const interpolatedTop = getPosition(
ellipsoid,
interpolatedCartographic,
maxHeight,
interpolatedTopScratch
);
Cartesian3_default.pack(interpolatedNormal, normalsArray, packIndex);
Cartesian3_default.pack(interpolatedBottom, bottomPositionsArray, packIndex);
Cartesian3_default.pack(interpolatedTop, topPositionsArray, packIndex);
cartographicsArray.push(interpolatedCartographic.latitude);
cartographicsArray.push(interpolatedCartographic.longitude);
packIndex += 3;
distanceFromStart += interpointDistance;
}
}
var heightlessCartographicScratch = new Cartographic_default();
function getPosition(ellipsoid, cartographic2, height, result) {
Cartographic_default.clone(cartographic2, heightlessCartographicScratch);
heightlessCartographicScratch.height = height;
return Cartographic_default.toCartesian(
heightlessCartographicScratch,
ellipsoid,
result
);
}
GroundPolylineGeometry.pack = function(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
Check_default.defined("array", array);
let index = startingIndex ?? 0;
const positions = value._positions;
const positionsLength = positions.length;
array[index++] = positionsLength;
for (let i = 0; i < positionsLength; ++i) {
const cartesian11 = positions[i];
Cartesian3_default.pack(cartesian11, array, index);
index += 3;
}
array[index++] = value.granularity;
array[index++] = value.loop ? 1 : 0;
array[index++] = value.arcType;
Ellipsoid_default.pack(value._ellipsoid, array, index);
index += Ellipsoid_default.packedLength;
array[index++] = value._projectionIndex;
array[index] = value._scene3DOnly ? 1 : 0;
return array;
};
GroundPolylineGeometry.unpack = function(array, startingIndex, result) {
Check_default.defined("array", array);
let index = startingIndex ?? 0;
const positionsLength = array[index++];
const positions = new Array(positionsLength);
for (let i = 0; i < positionsLength; i++) {
positions[i] = Cartesian3_default.unpack(array, index);
index += 3;
}
const granularity = array[index++];
const loop = array[index++] === 1;
const arcType = array[index++];
const ellipsoid = Ellipsoid_default.unpack(array, index);
index += Ellipsoid_default.packedLength;
const projectionIndex = array[index++];
const scene3DOnly = array[index] === 1;
if (!defined_default(result)) {
result = new GroundPolylineGeometry({
positions
});
}
result._positions = positions;
result.granularity = granularity;
result.loop = loop;
result.arcType = arcType;
result._ellipsoid = ellipsoid;
result._projectionIndex = projectionIndex;
result._scene3DOnly = scene3DOnly;
return result;
};
function direction(target, origin, result) {
Cartesian3_default.subtract(target, origin, result);
Cartesian3_default.normalize(result, result);
return result;
}
function tangentDirection(target, origin, up, result) {
result = direction(target, origin, result);
result = Cartesian3_default.cross(result, up, result);
result = Cartesian3_default.normalize(result, result);
result = Cartesian3_default.cross(up, result, result);
return result;
}
var toPreviousScratch = new Cartesian3_default();
var toNextScratch = new Cartesian3_default();
var forwardScratch = new Cartesian3_default();
var vertexUpScratch = new Cartesian3_default();
var cosine90 = 0;
var cosine180 = -1;
function computeVertexMiterNormal(previousBottom, vertexBottom, vertexTop, nextBottom, result) {
const up = direction(vertexTop, vertexBottom, vertexUpScratch);
const toPrevious = tangentDirection(
previousBottom,
vertexBottom,
up,
toPreviousScratch
);
const toNext = tangentDirection(nextBottom, vertexBottom, up, toNextScratch);
if (Math_default.equalsEpsilon(
Cartesian3_default.dot(toPrevious, toNext),
cosine180,
Math_default.EPSILON5
)) {
result = Cartesian3_default.cross(up, toPrevious, result);
result = Cartesian3_default.normalize(result, result);
return result;
}
result = Cartesian3_default.add(toNext, toPrevious, result);
result = Cartesian3_default.normalize(result, result);
const forward = Cartesian3_default.cross(up, result, forwardScratch);
if (Cartesian3_default.dot(toNext, forward) < cosine90) {
result = Cartesian3_default.negate(result, result);
}
return result;
}
var XZ_PLANE = Plane_default.fromPointNormal(Cartesian3_default.ZERO, Cartesian3_default.UNIT_Y);
var previousBottomScratch = new Cartesian3_default();
var vertexBottomScratch = new Cartesian3_default();
var vertexTopScratch = new Cartesian3_default();
var nextBottomScratch = new Cartesian3_default();
var vertexNormalScratch = new Cartesian3_default();
var intersectionScratch = new Cartesian3_default();
var cartographicScratch0 = new Cartographic_default();
var cartographicScratch1 = new Cartographic_default();
var cartographicIntersectionScratch = new Cartographic_default();
GroundPolylineGeometry.createGeometry = function(groundPolylineGeometry) {
const compute2dAttributes = !groundPolylineGeometry._scene3DOnly;
let loop = groundPolylineGeometry.loop;
const ellipsoid = groundPolylineGeometry._ellipsoid;
const granularity = groundPolylineGeometry.granularity;
const arcType = groundPolylineGeometry.arcType;
const projection = new PROJECTIONS[groundPolylineGeometry._projectionIndex](
ellipsoid
);
const minHeight = WALL_INITIAL_MIN_HEIGHT;
const maxHeight = WALL_INITIAL_MAX_HEIGHT;
let index;
let i;
const positions = groundPolylineGeometry._positions;
const positionsLength = positions.length;
if (positionsLength === 2) {
loop = false;
}
let p0;
let p1;
let c0;
let c14;
const rhumbLine = new EllipsoidRhumbLine_default(void 0, void 0, ellipsoid);
let intersection;
let intersectionCartographic;
let intersectionLongitude;
const splitPositions = [positions[0]];
for (i = 0; i < positionsLength - 1; i++) {
p0 = positions[i];
p1 = positions[i + 1];
intersection = IntersectionTests_default.lineSegmentPlane(
p0,
p1,
XZ_PLANE,
intersectionScratch
);
if (defined_default(intersection) && !Cartesian3_default.equalsEpsilon(intersection, p0, Math_default.EPSILON7) && !Cartesian3_default.equalsEpsilon(intersection, p1, Math_default.EPSILON7)) {
if (groundPolylineGeometry.arcType === ArcType_default.GEODESIC) {
splitPositions.push(Cartesian3_default.clone(intersection));
} else if (groundPolylineGeometry.arcType === ArcType_default.RHUMB) {
intersectionLongitude = ellipsoid.cartesianToCartographic(
intersection,
cartographicScratch0
).longitude;
c0 = ellipsoid.cartesianToCartographic(p0, cartographicScratch0);
c14 = ellipsoid.cartesianToCartographic(p1, cartographicScratch1);
rhumbLine.setEndPoints(c0, c14);
intersectionCartographic = rhumbLine.findIntersectionWithLongitude(
intersectionLongitude,
cartographicIntersectionScratch
);
intersection = ellipsoid.cartographicToCartesian(
intersectionCartographic,
intersectionScratch
);
if (defined_default(intersection) && !Cartesian3_default.equalsEpsilon(intersection, p0, Math_default.EPSILON7) && !Cartesian3_default.equalsEpsilon(intersection, p1, Math_default.EPSILON7)) {
splitPositions.push(Cartesian3_default.clone(intersection));
}
}
}
splitPositions.push(p1);
}
if (loop) {
p0 = positions[positionsLength - 1];
p1 = positions[0];
intersection = IntersectionTests_default.lineSegmentPlane(
p0,
p1,
XZ_PLANE,
intersectionScratch
);
if (defined_default(intersection) && !Cartesian3_default.equalsEpsilon(intersection, p0, Math_default.EPSILON7) && !Cartesian3_default.equalsEpsilon(intersection, p1, Math_default.EPSILON7)) {
if (groundPolylineGeometry.arcType === ArcType_default.GEODESIC) {
splitPositions.push(Cartesian3_default.clone(intersection));
} else if (groundPolylineGeometry.arcType === ArcType_default.RHUMB) {
intersectionLongitude = ellipsoid.cartesianToCartographic(
intersection,
cartographicScratch0
).longitude;
c0 = ellipsoid.cartesianToCartographic(p0, cartographicScratch0);
c14 = ellipsoid.cartesianToCartographic(p1, cartographicScratch1);
rhumbLine.setEndPoints(c0, c14);
intersectionCartographic = rhumbLine.findIntersectionWithLongitude(
intersectionLongitude,
cartographicIntersectionScratch
);
intersection = ellipsoid.cartographicToCartesian(
intersectionCartographic,
intersectionScratch
);
if (defined_default(intersection) && !Cartesian3_default.equalsEpsilon(intersection, p0, Math_default.EPSILON7) && !Cartesian3_default.equalsEpsilon(intersection, p1, Math_default.EPSILON7)) {
splitPositions.push(Cartesian3_default.clone(intersection));
}
}
}
}
let cartographicsLength = splitPositions.length;
let cartographics = new Array(cartographicsLength);
for (i = 0; i < cartographicsLength; i++) {
const cartographic2 = Cartographic_default.fromCartesian(
splitPositions[i],
ellipsoid
);
cartographic2.height = 0;
cartographics[i] = cartographic2;
}
cartographics = arrayRemoveDuplicates_default(
cartographics,
Cartographic_default.equalsEpsilon
);
cartographicsLength = cartographics.length;
if (cartographicsLength < 2) {
return void 0;
}
const cartographicsArray = [];
const normalsArray = [];
const bottomPositionsArray = [];
const topPositionsArray = [];
let previousBottom = previousBottomScratch;
let vertexBottom = vertexBottomScratch;
let vertexTop = vertexTopScratch;
let nextBottom = nextBottomScratch;
let vertexNormal = vertexNormalScratch;
const startCartographic = cartographics[0];
const nextCartographic = cartographics[1];
const prestartCartographic = cartographics[cartographicsLength - 1];
previousBottom = getPosition(
ellipsoid,
prestartCartographic,
minHeight,
previousBottom
);
nextBottom = getPosition(ellipsoid, nextCartographic, minHeight, nextBottom);
vertexBottom = getPosition(
ellipsoid,
startCartographic,
minHeight,
vertexBottom
);
vertexTop = getPosition(ellipsoid, startCartographic, maxHeight, vertexTop);
if (loop) {
vertexNormal = computeVertexMiterNormal(
previousBottom,
vertexBottom,
vertexTop,
nextBottom,
vertexNormal
);
} else {
vertexNormal = computeRightNormal(
startCartographic,
nextCartographic,
maxHeight,
ellipsoid,
vertexNormal
);
}
Cartesian3_default.pack(vertexNormal, normalsArray, 0);
Cartesian3_default.pack(vertexBottom, bottomPositionsArray, 0);
Cartesian3_default.pack(vertexTop, topPositionsArray, 0);
cartographicsArray.push(startCartographic.latitude);
cartographicsArray.push(startCartographic.longitude);
interpolateSegment(
startCartographic,
nextCartographic,
minHeight,
maxHeight,
granularity,
arcType,
ellipsoid,
normalsArray,
bottomPositionsArray,
topPositionsArray,
cartographicsArray
);
for (i = 1; i < cartographicsLength - 1; ++i) {
previousBottom = Cartesian3_default.clone(vertexBottom, previousBottom);
vertexBottom = Cartesian3_default.clone(nextBottom, vertexBottom);
const vertexCartographic = cartographics[i];
getPosition(ellipsoid, vertexCartographic, maxHeight, vertexTop);
getPosition(ellipsoid, cartographics[i + 1], minHeight, nextBottom);
computeVertexMiterNormal(
previousBottom,
vertexBottom,
vertexTop,
nextBottom,
vertexNormal
);
index = normalsArray.length;
Cartesian3_default.pack(vertexNormal, normalsArray, index);
Cartesian3_default.pack(vertexBottom, bottomPositionsArray, index);
Cartesian3_default.pack(vertexTop, topPositionsArray, index);
cartographicsArray.push(vertexCartographic.latitude);
cartographicsArray.push(vertexCartographic.longitude);
interpolateSegment(
cartographics[i],
cartographics[i + 1],
minHeight,
maxHeight,
granularity,
arcType,
ellipsoid,
normalsArray,
bottomPositionsArray,
topPositionsArray,
cartographicsArray
);
}
const endCartographic = cartographics[cartographicsLength - 1];
const preEndCartographic = cartographics[cartographicsLength - 2];
vertexBottom = getPosition(
ellipsoid,
endCartographic,
minHeight,
vertexBottom
);
vertexTop = getPosition(ellipsoid, endCartographic, maxHeight, vertexTop);
if (loop) {
const postEndCartographic = cartographics[0];
previousBottom = getPosition(
ellipsoid,
preEndCartographic,
minHeight,
previousBottom
);
nextBottom = getPosition(
ellipsoid,
postEndCartographic,
minHeight,
nextBottom
);
vertexNormal = computeVertexMiterNormal(
previousBottom,
vertexBottom,
vertexTop,
nextBottom,
vertexNormal
);
} else {
vertexNormal = computeRightNormal(
preEndCartographic,
endCartographic,
maxHeight,
ellipsoid,
vertexNormal
);
}
index = normalsArray.length;
Cartesian3_default.pack(vertexNormal, normalsArray, index);
Cartesian3_default.pack(vertexBottom, bottomPositionsArray, index);
Cartesian3_default.pack(vertexTop, topPositionsArray, index);
cartographicsArray.push(endCartographic.latitude);
cartographicsArray.push(endCartographic.longitude);
if (loop) {
interpolateSegment(
endCartographic,
startCartographic,
minHeight,
maxHeight,
granularity,
arcType,
ellipsoid,
normalsArray,
bottomPositionsArray,
topPositionsArray,
cartographicsArray
);
index = normalsArray.length;
for (i = 0; i < 3; ++i) {
normalsArray[index + i] = normalsArray[i];
bottomPositionsArray[index + i] = bottomPositionsArray[i];
topPositionsArray[index + i] = topPositionsArray[i];
}
cartographicsArray.push(startCartographic.latitude);
cartographicsArray.push(startCartographic.longitude);
}
return generateGeometryAttributes(
loop,
projection,
bottomPositionsArray,
topPositionsArray,
normalsArray,
cartographicsArray,
compute2dAttributes
);
};
var lineDirectionScratch = new Cartesian3_default();
var matrix3Scratch = new Matrix3_default();
var quaternionScratch = new Quaternion_default();
function breakMiter(endGeometryNormal, startBottom, endBottom, endTop) {
const lineDirection = direction(endBottom, startBottom, lineDirectionScratch);
const dot2 = Cartesian3_default.dot(lineDirection, endGeometryNormal);
if (dot2 > MITER_BREAK_SMALL || dot2 < MITER_BREAK_LARGE) {
const vertexUp = direction(endTop, endBottom, vertexUpScratch);
const angle = dot2 < MITER_BREAK_LARGE ? Math_default.PI_OVER_TWO : -Math_default.PI_OVER_TWO;
const quaternion = Quaternion_default.fromAxisAngle(
vertexUp,
angle,
quaternionScratch
);
const rotationMatrix = Matrix3_default.fromQuaternion(quaternion, matrix3Scratch);
Matrix3_default.multiplyByVector(
rotationMatrix,
endGeometryNormal,
endGeometryNormal
);
return true;
}
return false;
}
var endPosCartographicScratch = new Cartographic_default();
var normalStartpointScratch = new Cartesian3_default();
var normalEndpointScratch = new Cartesian3_default();
function projectNormal(projection, cartographic2, normal2, projectedPosition2, result) {
const position = Cartographic_default.toCartesian(
cartographic2,
projection._ellipsoid,
normalStartpointScratch
);
let normalEndpoint = Cartesian3_default.add(position, normal2, normalEndpointScratch);
let flipNormal = false;
const ellipsoid = projection._ellipsoid;
let normalEndpointCartographic = ellipsoid.cartesianToCartographic(
normalEndpoint,
endPosCartographicScratch
);
if (Math.abs(cartographic2.longitude - normalEndpointCartographic.longitude) > Math_default.PI_OVER_TWO) {
flipNormal = true;
normalEndpoint = Cartesian3_default.subtract(
position,
normal2,
normalEndpointScratch
);
normalEndpointCartographic = ellipsoid.cartesianToCartographic(
normalEndpoint,
endPosCartographicScratch
);
}
normalEndpointCartographic.height = 0;
const normalEndpointProjected = projection.project(
normalEndpointCartographic,
result
);
result = Cartesian3_default.subtract(
normalEndpointProjected,
projectedPosition2,
result
);
result.z = 0;
result = Cartesian3_default.normalize(result, result);
if (flipNormal) {
Cartesian3_default.negate(result, result);
}
return result;
}
var adjustHeightNormalScratch = new Cartesian3_default();
var adjustHeightOffsetScratch = new Cartesian3_default();
function adjustHeights(bottom, top, minHeight, maxHeight, adjustHeightBottom, adjustHeightTop) {
const adjustHeightNormal = Cartesian3_default.subtract(
top,
bottom,
adjustHeightNormalScratch
);
Cartesian3_default.normalize(adjustHeightNormal, adjustHeightNormal);
const distanceForBottom = minHeight - WALL_INITIAL_MIN_HEIGHT;
let adjustHeightOffset = Cartesian3_default.multiplyByScalar(
adjustHeightNormal,
distanceForBottom,
adjustHeightOffsetScratch
);
Cartesian3_default.add(bottom, adjustHeightOffset, adjustHeightBottom);
const distanceForTop = maxHeight - WALL_INITIAL_MAX_HEIGHT;
adjustHeightOffset = Cartesian3_default.multiplyByScalar(
adjustHeightNormal,
distanceForTop,
adjustHeightOffsetScratch
);
Cartesian3_default.add(top, adjustHeightOffset, adjustHeightTop);
}
var nudgeDirectionScratch = new Cartesian3_default();
function nudgeXZ(start, end) {
const startToXZdistance = Plane_default.getPointDistance(XZ_PLANE, start);
const endToXZdistance = Plane_default.getPointDistance(XZ_PLANE, end);
let offset = nudgeDirectionScratch;
if (Math_default.equalsEpsilon(startToXZdistance, 0, Math_default.EPSILON2)) {
offset = direction(end, start, offset);
Cartesian3_default.multiplyByScalar(offset, Math_default.EPSILON2, offset);
Cartesian3_default.add(start, offset, start);
} else if (Math_default.equalsEpsilon(endToXZdistance, 0, Math_default.EPSILON2)) {
offset = direction(start, end, offset);
Cartesian3_default.multiplyByScalar(offset, Math_default.EPSILON2, offset);
Cartesian3_default.add(end, offset, end);
}
}
function nudgeCartographic(start, end) {
const absStartLon = Math.abs(start.longitude);
const absEndLon = Math.abs(end.longitude);
if (Math_default.equalsEpsilon(absStartLon, Math_default.PI, Math_default.EPSILON11)) {
const endSign = Math_default.sign(end.longitude);
start.longitude = endSign * (absStartLon - Math_default.EPSILON11);
return 1;
} else if (Math_default.equalsEpsilon(absEndLon, Math_default.PI, Math_default.EPSILON11)) {
const startSign = Math_default.sign(start.longitude);
end.longitude = startSign * (absEndLon - Math_default.EPSILON11);
return 2;
}
return 0;
}
var startCartographicScratch = new Cartographic_default();
var endCartographicScratch = new Cartographic_default();
var segmentStartTopScratch = new Cartesian3_default();
var segmentEndTopScratch = new Cartesian3_default();
var segmentStartBottomScratch = new Cartesian3_default();
var segmentEndBottomScratch = new Cartesian3_default();
var segmentStartNormalScratch = new Cartesian3_default();
var segmentEndNormalScratch = new Cartesian3_default();
var getHeightCartographics = [
startCartographicScratch,
endCartographicScratch
];
var getHeightRectangleScratch = new Rectangle_default();
var adjustHeightStartTopScratch = new Cartesian3_default();
var adjustHeightEndTopScratch = new Cartesian3_default();
var adjustHeightStartBottomScratch = new Cartesian3_default();
var adjustHeightEndBottomScratch = new Cartesian3_default();
var segmentStart2DScratch = new Cartesian3_default();
var segmentEnd2DScratch = new Cartesian3_default();
var segmentStartNormal2DScratch = new Cartesian3_default();
var segmentEndNormal2DScratch = new Cartesian3_default();
var offsetScratch3 = new Cartesian3_default();
var startUpScratch = new Cartesian3_default();
var endUpScratch = new Cartesian3_default();
var rightScratch2 = new Cartesian3_default();
var startPlaneNormalScratch = new Cartesian3_default();
var endPlaneNormalScratch = new Cartesian3_default();
var encodeScratch2 = new EncodedCartesian3_default();
var encodeScratch2D = new EncodedCartesian3_default();
var forwardOffset2DScratch = new Cartesian3_default();
var right2DScratch = new Cartesian3_default();
var normalNudgeScratch = new Cartesian3_default();
var scratchBoundingSpheres = [new BoundingSphere_default(), new BoundingSphere_default()];
var REFERENCE_INDICES = [
0,
2,
1,
0,
3,
2,
// right
0,
7,
3,
0,
4,
7,
// start
0,
5,
4,
0,
1,
5,
// bottom
5,
7,
4,
5,
6,
7,
// left
5,
2,
6,
5,
1,
2,
// end
3,
6,
2,
3,
7,
6
// top
];
var REFERENCE_INDICES_LENGTH = REFERENCE_INDICES.length;
function generateGeometryAttributes(loop, projection, bottomPositionsArray, topPositionsArray, normalsArray, cartographicsArray, compute2dAttributes) {
let i;
let index;
const ellipsoid = projection._ellipsoid;
const segmentCount = bottomPositionsArray.length / 3 - 1;
const vertexCount = segmentCount * 8;
const arraySizeVec4 = vertexCount * 4;
const indexCount = segmentCount * 36;
const indices = vertexCount > 65535 ? new Uint32Array(indexCount) : new Uint16Array(indexCount);
const positionsArray = new Float64Array(vertexCount * 3);
const startHiAndForwardOffsetX = new Float32Array(arraySizeVec4);
const startLoAndForwardOffsetY = new Float32Array(arraySizeVec4);
const startNormalAndForwardOffsetZ = new Float32Array(arraySizeVec4);
const endNormalAndTextureCoordinateNormalizationX = new Float32Array(
arraySizeVec4
);
const rightNormalAndTextureCoordinateNormalizationY = new Float32Array(
arraySizeVec4
);
let startHiLo2D;
let offsetAndRight2D;
let startEndNormals2D;
let texcoordNormalization2D;
if (compute2dAttributes) {
startHiLo2D = new Float32Array(arraySizeVec4);
offsetAndRight2D = new Float32Array(arraySizeVec4);
startEndNormals2D = new Float32Array(arraySizeVec4);
texcoordNormalization2D = new Float32Array(vertexCount * 2);
}
const cartographicsLength = cartographicsArray.length / 2;
let length2D = 0;
const startCartographic = startCartographicScratch;
startCartographic.height = 0;
const endCartographic = endCartographicScratch;
endCartographic.height = 0;
let segmentStartCartesian = segmentStartTopScratch;
let segmentEndCartesian = segmentEndTopScratch;
if (compute2dAttributes) {
index = 0;
for (i = 1; i < cartographicsLength; i++) {
startCartographic.latitude = cartographicsArray[index];
startCartographic.longitude = cartographicsArray[index + 1];
endCartographic.latitude = cartographicsArray[index + 2];
endCartographic.longitude = cartographicsArray[index + 3];
segmentStartCartesian = projection.project(
startCartographic,
segmentStartCartesian
);
segmentEndCartesian = projection.project(
endCartographic,
segmentEndCartesian
);
length2D += Cartesian3_default.distance(
segmentStartCartesian,
segmentEndCartesian
);
index += 2;
}
}
const positionsLength = topPositionsArray.length / 3;
segmentEndCartesian = Cartesian3_default.unpack(
topPositionsArray,
0,
segmentEndCartesian
);
let length3D = 0;
index = 3;
for (i = 1; i < positionsLength; i++) {
segmentStartCartesian = Cartesian3_default.clone(
segmentEndCartesian,
segmentStartCartesian
);
segmentEndCartesian = Cartesian3_default.unpack(
topPositionsArray,
index,
segmentEndCartesian
);
length3D += Cartesian3_default.distance(segmentStartCartesian, segmentEndCartesian);
index += 3;
}
let j;
index = 3;
let cartographicsIndex = 0;
let vec2sWriteIndex = 0;
let vec3sWriteIndex = 0;
let vec4sWriteIndex = 0;
let miterBroken = false;
let endBottom = Cartesian3_default.unpack(
bottomPositionsArray,
0,
segmentEndBottomScratch
);
let endTop = Cartesian3_default.unpack(topPositionsArray, 0, segmentEndTopScratch);
let endGeometryNormal = Cartesian3_default.unpack(
normalsArray,
0,
segmentEndNormalScratch
);
if (loop) {
const preEndBottom = Cartesian3_default.unpack(
bottomPositionsArray,
bottomPositionsArray.length - 6,
segmentStartBottomScratch
);
if (breakMiter(endGeometryNormal, preEndBottom, endBottom, endTop)) {
endGeometryNormal = Cartesian3_default.negate(
endGeometryNormal,
endGeometryNormal
);
}
}
let lengthSoFar3D = 0;
let lengthSoFar2D = 0;
let sumHeights = 0;
for (i = 0; i < segmentCount; i++) {
const startBottom = Cartesian3_default.clone(endBottom, segmentStartBottomScratch);
const startTop = Cartesian3_default.clone(endTop, segmentStartTopScratch);
let startGeometryNormal = Cartesian3_default.clone(
endGeometryNormal,
segmentStartNormalScratch
);
if (miterBroken) {
startGeometryNormal = Cartesian3_default.negate(
startGeometryNormal,
startGeometryNormal
);
}
endBottom = Cartesian3_default.unpack(
bottomPositionsArray,
index,
segmentEndBottomScratch
);
endTop = Cartesian3_default.unpack(topPositionsArray, index, segmentEndTopScratch);
endGeometryNormal = Cartesian3_default.unpack(
normalsArray,
index,
segmentEndNormalScratch
);
miterBroken = breakMiter(endGeometryNormal, startBottom, endBottom, endTop);
startCartographic.latitude = cartographicsArray[cartographicsIndex];
startCartographic.longitude = cartographicsArray[cartographicsIndex + 1];
endCartographic.latitude = cartographicsArray[cartographicsIndex + 2];
endCartographic.longitude = cartographicsArray[cartographicsIndex + 3];
let start2D;
let end2D;
let startGeometryNormal2D;
let endGeometryNormal2D;
if (compute2dAttributes) {
const nudgeResult = nudgeCartographic(startCartographic, endCartographic);
start2D = projection.project(startCartographic, segmentStart2DScratch);
end2D = projection.project(endCartographic, segmentEnd2DScratch);
const direction2D = direction(end2D, start2D, forwardOffset2DScratch);
direction2D.y = Math.abs(direction2D.y);
startGeometryNormal2D = segmentStartNormal2DScratch;
endGeometryNormal2D = segmentEndNormal2DScratch;
if (nudgeResult === 0 || Cartesian3_default.dot(direction2D, Cartesian3_default.UNIT_Y) > MITER_BREAK_SMALL) {
startGeometryNormal2D = projectNormal(
projection,
startCartographic,
startGeometryNormal,
start2D,
segmentStartNormal2DScratch
);
endGeometryNormal2D = projectNormal(
projection,
endCartographic,
endGeometryNormal,
end2D,
segmentEndNormal2DScratch
);
} else if (nudgeResult === 1) {
endGeometryNormal2D = projectNormal(
projection,
endCartographic,
endGeometryNormal,
end2D,
segmentEndNormal2DScratch
);
startGeometryNormal2D.x = 0;
startGeometryNormal2D.y = Math_default.sign(
startCartographic.longitude - Math.abs(endCartographic.longitude)
);
startGeometryNormal2D.z = 0;
} else {
startGeometryNormal2D = projectNormal(
projection,
startCartographic,
startGeometryNormal,
start2D,
segmentStartNormal2DScratch
);
endGeometryNormal2D.x = 0;
endGeometryNormal2D.y = Math_default.sign(
startCartographic.longitude - endCartographic.longitude
);
endGeometryNormal2D.z = 0;
}
}
const segmentLength3D = Cartesian3_default.distance(startTop, endTop);
const encodedStart = EncodedCartesian3_default.fromCartesian(
startBottom,
encodeScratch2
);
const forwardOffset = Cartesian3_default.subtract(
endBottom,
startBottom,
offsetScratch3
);
const forward = Cartesian3_default.normalize(forwardOffset, rightScratch2);
let startUp = Cartesian3_default.subtract(startTop, startBottom, startUpScratch);
startUp = Cartesian3_default.normalize(startUp, startUp);
let rightNormal = Cartesian3_default.cross(forward, startUp, rightScratch2);
rightNormal = Cartesian3_default.normalize(rightNormal, rightNormal);
let startPlaneNormal = Cartesian3_default.cross(
startUp,
startGeometryNormal,
startPlaneNormalScratch
);
startPlaneNormal = Cartesian3_default.normalize(startPlaneNormal, startPlaneNormal);
let endUp = Cartesian3_default.subtract(endTop, endBottom, endUpScratch);
endUp = Cartesian3_default.normalize(endUp, endUp);
let endPlaneNormal = Cartesian3_default.cross(
endGeometryNormal,
endUp,
endPlaneNormalScratch
);
endPlaneNormal = Cartesian3_default.normalize(endPlaneNormal, endPlaneNormal);
const texcoordNormalization3DX = segmentLength3D / length3D;
const texcoordNormalization3DY = lengthSoFar3D / length3D;
let segmentLength2D = 0;
let encodedStart2D;
let forwardOffset2D;
let right2D;
let texcoordNormalization2DX = 0;
let texcoordNormalization2DY = 0;
if (compute2dAttributes) {
segmentLength2D = Cartesian3_default.distance(start2D, end2D);
encodedStart2D = EncodedCartesian3_default.fromCartesian(
start2D,
encodeScratch2D
);
forwardOffset2D = Cartesian3_default.subtract(
end2D,
start2D,
forwardOffset2DScratch
);
right2D = Cartesian3_default.normalize(forwardOffset2D, right2DScratch);
const swap5 = right2D.x;
right2D.x = right2D.y;
right2D.y = -swap5;
texcoordNormalization2DX = segmentLength2D / length2D;
texcoordNormalization2DY = lengthSoFar2D / length2D;
}
for (j = 0; j < 8; j++) {
const vec4Index = vec4sWriteIndex + j * 4;
const vec2Index = vec2sWriteIndex + j * 2;
const wIndex = vec4Index + 3;
const rightPlaneSide = j < 4 ? 1 : -1;
const topBottomSide = j === 2 || j === 3 || j === 6 || j === 7 ? 1 : -1;
Cartesian3_default.pack(encodedStart.high, startHiAndForwardOffsetX, vec4Index);
startHiAndForwardOffsetX[wIndex] = forwardOffset.x;
Cartesian3_default.pack(encodedStart.low, startLoAndForwardOffsetY, vec4Index);
startLoAndForwardOffsetY[wIndex] = forwardOffset.y;
Cartesian3_default.pack(
startPlaneNormal,
startNormalAndForwardOffsetZ,
vec4Index
);
startNormalAndForwardOffsetZ[wIndex] = forwardOffset.z;
Cartesian3_default.pack(
endPlaneNormal,
endNormalAndTextureCoordinateNormalizationX,
vec4Index
);
endNormalAndTextureCoordinateNormalizationX[wIndex] = texcoordNormalization3DX * rightPlaneSide;
Cartesian3_default.pack(
rightNormal,
rightNormalAndTextureCoordinateNormalizationY,
vec4Index
);
let texcoordNormalization = texcoordNormalization3DY * topBottomSide;
if (texcoordNormalization === 0 && topBottomSide < 0) {
texcoordNormalization = 9;
}
rightNormalAndTextureCoordinateNormalizationY[wIndex] = texcoordNormalization;
if (compute2dAttributes) {
startHiLo2D[vec4Index] = encodedStart2D.high.x;
startHiLo2D[vec4Index + 1] = encodedStart2D.high.y;
startHiLo2D[vec4Index + 2] = encodedStart2D.low.x;
startHiLo2D[vec4Index + 3] = encodedStart2D.low.y;
startEndNormals2D[vec4Index] = -startGeometryNormal2D.y;
startEndNormals2D[vec4Index + 1] = startGeometryNormal2D.x;
startEndNormals2D[vec4Index + 2] = endGeometryNormal2D.y;
startEndNormals2D[vec4Index + 3] = -endGeometryNormal2D.x;
offsetAndRight2D[vec4Index] = forwardOffset2D.x;
offsetAndRight2D[vec4Index + 1] = forwardOffset2D.y;
offsetAndRight2D[vec4Index + 2] = right2D.x;
offsetAndRight2D[vec4Index + 3] = right2D.y;
texcoordNormalization2D[vec2Index] = texcoordNormalization2DX * rightPlaneSide;
texcoordNormalization = texcoordNormalization2DY * topBottomSide;
if (texcoordNormalization === 0 && topBottomSide < 0) {
texcoordNormalization = 9;
}
texcoordNormalization2D[vec2Index + 1] = texcoordNormalization;
}
}
const adjustHeightStartBottom = adjustHeightStartBottomScratch;
const adjustHeightEndBottom = adjustHeightEndBottomScratch;
const adjustHeightStartTop = adjustHeightStartTopScratch;
const adjustHeightEndTop = adjustHeightEndTopScratch;
const getHeightsRectangle = Rectangle_default.fromCartographicArray(
getHeightCartographics,
getHeightRectangleScratch
);
const minMaxHeights = ApproximateTerrainHeights_default.getMinimumMaximumHeights(
getHeightsRectangle,
ellipsoid
);
const minHeight = minMaxHeights.minimumTerrainHeight;
const maxHeight = minMaxHeights.maximumTerrainHeight;
sumHeights += Math.abs(minHeight);
sumHeights += Math.abs(maxHeight);
adjustHeights(
startBottom,
startTop,
minHeight,
maxHeight,
adjustHeightStartBottom,
adjustHeightStartTop
);
adjustHeights(
endBottom,
endTop,
minHeight,
maxHeight,
adjustHeightEndBottom,
adjustHeightEndTop
);
let normalNudge = Cartesian3_default.multiplyByScalar(
rightNormal,
Math_default.EPSILON5,
normalNudgeScratch
);
Cartesian3_default.add(
adjustHeightStartBottom,
normalNudge,
adjustHeightStartBottom
);
Cartesian3_default.add(adjustHeightEndBottom, normalNudge, adjustHeightEndBottom);
Cartesian3_default.add(adjustHeightStartTop, normalNudge, adjustHeightStartTop);
Cartesian3_default.add(adjustHeightEndTop, normalNudge, adjustHeightEndTop);
nudgeXZ(adjustHeightStartBottom, adjustHeightEndBottom);
nudgeXZ(adjustHeightStartTop, adjustHeightEndTop);
Cartesian3_default.pack(adjustHeightStartBottom, positionsArray, vec3sWriteIndex);
Cartesian3_default.pack(adjustHeightEndBottom, positionsArray, vec3sWriteIndex + 3);
Cartesian3_default.pack(adjustHeightEndTop, positionsArray, vec3sWriteIndex + 6);
Cartesian3_default.pack(adjustHeightStartTop, positionsArray, vec3sWriteIndex + 9);
normalNudge = Cartesian3_default.multiplyByScalar(
rightNormal,
-2 * Math_default.EPSILON5,
normalNudgeScratch
);
Cartesian3_default.add(
adjustHeightStartBottom,
normalNudge,
adjustHeightStartBottom
);
Cartesian3_default.add(adjustHeightEndBottom, normalNudge, adjustHeightEndBottom);
Cartesian3_default.add(adjustHeightStartTop, normalNudge, adjustHeightStartTop);
Cartesian3_default.add(adjustHeightEndTop, normalNudge, adjustHeightEndTop);
nudgeXZ(adjustHeightStartBottom, adjustHeightEndBottom);
nudgeXZ(adjustHeightStartTop, adjustHeightEndTop);
Cartesian3_default.pack(
adjustHeightStartBottom,
positionsArray,
vec3sWriteIndex + 12
);
Cartesian3_default.pack(
adjustHeightEndBottom,
positionsArray,
vec3sWriteIndex + 15
);
Cartesian3_default.pack(adjustHeightEndTop, positionsArray, vec3sWriteIndex + 18);
Cartesian3_default.pack(adjustHeightStartTop, positionsArray, vec3sWriteIndex + 21);
cartographicsIndex += 2;
index += 3;
vec2sWriteIndex += 16;
vec3sWriteIndex += 24;
vec4sWriteIndex += 32;
lengthSoFar3D += segmentLength3D;
lengthSoFar2D += segmentLength2D;
}
index = 0;
let indexOffset = 0;
for (i = 0; i < segmentCount; i++) {
for (j = 0; j < REFERENCE_INDICES_LENGTH; j++) {
indices[index + j] = REFERENCE_INDICES[j] + indexOffset;
}
indexOffset += 8;
index += REFERENCE_INDICES_LENGTH;
}
const boundingSpheres = scratchBoundingSpheres;
BoundingSphere_default.fromVertices(
bottomPositionsArray,
Cartesian3_default.ZERO,
3,
boundingSpheres[0]
);
BoundingSphere_default.fromVertices(
topPositionsArray,
Cartesian3_default.ZERO,
3,
boundingSpheres[1]
);
const boundingSphere = BoundingSphere_default.fromBoundingSpheres(boundingSpheres);
boundingSphere.radius += sumHeights / (segmentCount * 2);
const attributes = {
position: new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
normalize: false,
values: positionsArray
}),
startHiAndForwardOffsetX: getVec4GeometryAttribute(
startHiAndForwardOffsetX
),
startLoAndForwardOffsetY: getVec4GeometryAttribute(
startLoAndForwardOffsetY
),
startNormalAndForwardOffsetZ: getVec4GeometryAttribute(
startNormalAndForwardOffsetZ
),
endNormalAndTextureCoordinateNormalizationX: getVec4GeometryAttribute(
endNormalAndTextureCoordinateNormalizationX
),
rightNormalAndTextureCoordinateNormalizationY: getVec4GeometryAttribute(
rightNormalAndTextureCoordinateNormalizationY
)
};
if (compute2dAttributes) {
attributes.startHiLo2D = getVec4GeometryAttribute(startHiLo2D);
attributes.offsetAndRight2D = getVec4GeometryAttribute(offsetAndRight2D);
attributes.startEndNormals2D = getVec4GeometryAttribute(startEndNormals2D);
attributes.texcoordNormalization2D = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 2,
normalize: false,
values: texcoordNormalization2D
});
}
return new Geometry_default({
attributes,
indices,
boundingSphere
});
}
function getVec4GeometryAttribute(typedArray) {
return new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 4,
normalize: false,
values: typedArray
});
}
GroundPolylineGeometry._projectNormal = projectNormal;
var GroundPolylineGeometry_default = GroundPolylineGeometry;
// packages/engine/Source/Shaders/PolylineShadowVolumeFS.js
var PolylineShadowVolumeFS_default = 'in vec4 v_startPlaneNormalEcAndHalfWidth;\nin vec4 v_endPlaneNormalEcAndBatchId;\nin vec4 v_rightPlaneEC; // Technically can compute distance for this here\nin vec4 v_endEcAndStartEcX;\nin vec4 v_texcoordNormalizationAndStartEcYZ;\n\n#ifdef PER_INSTANCE_COLOR\nin vec4 v_color;\n#endif\n\nvoid main(void)\n{\n float logDepthOrDepth = czm_branchFreeTernary(czm_sceneMode == czm_sceneMode2D, gl_FragCoord.z, czm_unpackDepth(texture(czm_globeDepthTexture, gl_FragCoord.xy / czm_viewport.zw)));\n vec3 ecStart = vec3(v_endEcAndStartEcX.w, v_texcoordNormalizationAndStartEcYZ.zw);\n\n // Discard for sky\n if (logDepthOrDepth == 0.0) {\n#ifdef DEBUG_SHOW_VOLUME\n out_FragColor = vec4(1.0, 0.0, 0.0, 0.5);\n return;\n#else // DEBUG_SHOW_VOLUME\n discard;\n#endif // DEBUG_SHOW_VOLUME\n }\n\n vec4 eyeCoordinate = czm_windowToEyeCoordinates(gl_FragCoord.xy, logDepthOrDepth);\n eyeCoordinate /= eyeCoordinate.w;\n\n float halfMaxWidth = v_startPlaneNormalEcAndHalfWidth.w * czm_metersPerPixel(eyeCoordinate);\n // Check distance of the eye coordinate against the right-facing plane\n float widthwiseDistance = czm_planeDistance(v_rightPlaneEC, eyeCoordinate.xyz);\n\n // Check eye coordinate against the mitering planes\n float distanceFromStart = czm_planeDistance(v_startPlaneNormalEcAndHalfWidth.xyz, -dot(ecStart, v_startPlaneNormalEcAndHalfWidth.xyz), eyeCoordinate.xyz);\n float distanceFromEnd = czm_planeDistance(v_endPlaneNormalEcAndBatchId.xyz, -dot(v_endEcAndStartEcX.xyz, v_endPlaneNormalEcAndBatchId.xyz), eyeCoordinate.xyz);\n\n if (abs(widthwiseDistance) > halfMaxWidth || distanceFromStart < 0.0 || distanceFromEnd < 0.0) {\n#ifdef DEBUG_SHOW_VOLUME\n out_FragColor = vec4(1.0, 0.0, 0.0, 0.5);\n return;\n#else // DEBUG_SHOW_VOLUME\n discard;\n#endif // DEBUG_SHOW_VOLUME\n }\n\n // Check distance of the eye coordinate against start and end planes with normals in the right plane.\n // For computing unskewed lengthwise texture coordinate.\n // Can also be used for clipping extremely pointy miters, but in practice unnecessary because of miter breaking.\n\n // aligned plane: cross the right plane normal with miter plane normal, then cross the result with right again to point it more "forward"\n vec3 alignedPlaneNormal;\n\n // start aligned plane\n alignedPlaneNormal = cross(v_rightPlaneEC.xyz, v_startPlaneNormalEcAndHalfWidth.xyz);\n alignedPlaneNormal = normalize(cross(alignedPlaneNormal, v_rightPlaneEC.xyz));\n distanceFromStart = czm_planeDistance(alignedPlaneNormal, -dot(alignedPlaneNormal, ecStart), eyeCoordinate.xyz);\n\n // end aligned plane\n alignedPlaneNormal = cross(v_rightPlaneEC.xyz, v_endPlaneNormalEcAndBatchId.xyz);\n alignedPlaneNormal = normalize(cross(alignedPlaneNormal, v_rightPlaneEC.xyz));\n distanceFromEnd = czm_planeDistance(alignedPlaneNormal, -dot(alignedPlaneNormal, v_endEcAndStartEcX.xyz), eyeCoordinate.xyz);\n\n#ifdef PER_INSTANCE_COLOR\n out_FragColor = czm_gammaCorrect(v_color);\n#else // PER_INSTANCE_COLOR\n // Clamp - distance to aligned planes may be negative due to mitering,\n // so fragment texture coordinate might be out-of-bounds.\n float s = clamp(distanceFromStart / (distanceFromStart + distanceFromEnd), 0.0, 1.0);\n s = (s * v_texcoordNormalizationAndStartEcYZ.x) + v_texcoordNormalizationAndStartEcYZ.y;\n float t = (widthwiseDistance + halfMaxWidth) / (2.0 * halfMaxWidth);\n\n czm_materialInput materialInput;\n\n materialInput.s = s;\n materialInput.st = vec2(s, t);\n materialInput.str = vec3(s, t, 0.0);\n\n czm_material material = czm_getMaterial(materialInput);\n out_FragColor = vec4(material.diffuse + material.emission, material.alpha);\n#endif // PER_INSTANCE_COLOR\n\n // Premultiply alpha. Required for classification primitives on translucent globe.\n out_FragColor.rgb *= out_FragColor.a;\n\n czm_writeDepthClamp();\n}\n';
// packages/engine/Source/Shaders/PolylineShadowVolumeMorphFS.js
var PolylineShadowVolumeMorphFS_default = "in vec3 v_forwardDirectionEC;\nin vec3 v_texcoordNormalizationAndHalfWidth;\nin float v_batchId;\n\n#ifdef PER_INSTANCE_COLOR\nin vec4 v_color;\n#else\nin vec2 v_alignedPlaneDistances;\nin float v_texcoordT;\n#endif\n\nfloat rayPlaneDistanceUnsafe(vec3 origin, vec3 direction, vec3 planeNormal, float planeDistance) {\n // We don't expect the ray to ever be parallel to the plane\n return (-planeDistance - dot(planeNormal, origin)) / dot(planeNormal, direction);\n}\n\nvoid main(void)\n{\n vec4 eyeCoordinate = gl_FragCoord;\n eyeCoordinate /= eyeCoordinate.w;\n\n#ifdef PER_INSTANCE_COLOR\n out_FragColor = czm_gammaCorrect(v_color);\n#else // PER_INSTANCE_COLOR\n // Use distances for planes aligned with segment to prevent skew in dashing\n float distanceFromStart = rayPlaneDistanceUnsafe(eyeCoordinate.xyz, -v_forwardDirectionEC, v_forwardDirectionEC.xyz, v_alignedPlaneDistances.x);\n float distanceFromEnd = rayPlaneDistanceUnsafe(eyeCoordinate.xyz, v_forwardDirectionEC, -v_forwardDirectionEC.xyz, v_alignedPlaneDistances.y);\n\n // Clamp - distance to aligned planes may be negative due to mitering\n distanceFromStart = max(0.0, distanceFromStart);\n distanceFromEnd = max(0.0, distanceFromEnd);\n\n float s = distanceFromStart / (distanceFromStart + distanceFromEnd);\n s = (s * v_texcoordNormalizationAndHalfWidth.x) + v_texcoordNormalizationAndHalfWidth.y;\n\n czm_materialInput materialInput;\n\n materialInput.s = s;\n materialInput.st = vec2(s, v_texcoordT);\n materialInput.str = vec3(s, v_texcoordT, 0.0);\n\n czm_material material = czm_getMaterial(materialInput);\n out_FragColor = vec4(material.diffuse + material.emission, material.alpha);\n#endif // PER_INSTANCE_COLOR\n}\n";
// packages/engine/Source/Shaders/PolylineShadowVolumeMorphVS.js
var PolylineShadowVolumeMorphVS_default = `in vec3 position3DHigh;
in vec3 position3DLow;
in vec4 startHiAndForwardOffsetX;
in vec4 startLoAndForwardOffsetY;
in vec4 startNormalAndForwardOffsetZ;
in vec4 endNormalAndTextureCoordinateNormalizationX;
in vec4 rightNormalAndTextureCoordinateNormalizationY;
in vec4 startHiLo2D;
in vec4 offsetAndRight2D;
in vec4 startEndNormals2D;
in vec2 texcoordNormalization2D;
in float batchId;
out vec3 v_forwardDirectionEC;
out vec3 v_texcoordNormalizationAndHalfWidth;
out float v_batchId;
// For materials
#ifdef WIDTH_VARYING
out float v_width;
#endif
#ifdef ANGLE_VARYING
out float v_polylineAngle;
#endif
#ifdef PER_INSTANCE_COLOR
out vec4 v_color;
#else
out vec2 v_alignedPlaneDistances;
out float v_texcoordT;
#endif
// Morphing planes using SLERP or NLERP doesn't seem to work, so instead draw the material directly on the shadow volume.
// Morph views are from very far away and aren't meant to be used precisely, so this should be sufficient.
void main()
{
v_batchId = batchId;
// Start position
vec4 posRelativeToEye2D = czm_translateRelativeToEye(vec3(0.0, startHiLo2D.xy), vec3(0.0, startHiLo2D.zw));
vec4 posRelativeToEye3D = czm_translateRelativeToEye(startHiAndForwardOffsetX.xyz, startLoAndForwardOffsetY.xyz);
vec4 posRelativeToEye = czm_columbusViewMorph(posRelativeToEye2D, posRelativeToEye3D, czm_morphTime);
vec3 posEc2D = (czm_modelViewRelativeToEye * posRelativeToEye2D).xyz;
vec3 posEc3D = (czm_modelViewRelativeToEye * posRelativeToEye3D).xyz;
vec3 startEC = (czm_modelViewRelativeToEye * posRelativeToEye).xyz;
// Start plane
vec4 startPlane2D;
vec4 startPlane3D;
startPlane2D.xyz = czm_normal * vec3(0.0, startEndNormals2D.xy);
startPlane3D.xyz = czm_normal * startNormalAndForwardOffsetZ.xyz;
startPlane2D.w = -dot(startPlane2D.xyz, posEc2D);
startPlane3D.w = -dot(startPlane3D.xyz, posEc3D);
// Right plane
vec4 rightPlane2D;
vec4 rightPlane3D;
rightPlane2D.xyz = czm_normal * vec3(0.0, offsetAndRight2D.zw);
rightPlane3D.xyz = czm_normal * rightNormalAndTextureCoordinateNormalizationY.xyz;
rightPlane2D.w = -dot(rightPlane2D.xyz, posEc2D);
rightPlane3D.w = -dot(rightPlane3D.xyz, posEc3D);
// End position
posRelativeToEye2D = posRelativeToEye2D + vec4(0.0, offsetAndRight2D.xy, 0.0);
posRelativeToEye3D = posRelativeToEye3D + vec4(startHiAndForwardOffsetX.w, startLoAndForwardOffsetY.w, startNormalAndForwardOffsetZ.w, 0.0);
posRelativeToEye = czm_columbusViewMorph(posRelativeToEye2D, posRelativeToEye3D, czm_morphTime);
posEc2D = (czm_modelViewRelativeToEye * posRelativeToEye2D).xyz;
posEc3D = (czm_modelViewRelativeToEye * posRelativeToEye3D).xyz;
vec3 endEC = (czm_modelViewRelativeToEye * posRelativeToEye).xyz;
vec3 forwardEc3D = czm_normal * normalize(vec3(startHiAndForwardOffsetX.w, startLoAndForwardOffsetY.w, startNormalAndForwardOffsetZ.w));
vec3 forwardEc2D = czm_normal * normalize(vec3(0.0, offsetAndRight2D.xy));
// End plane
vec4 endPlane2D;
vec4 endPlane3D;
endPlane2D.xyz = czm_normal * vec3(0.0, startEndNormals2D.zw);
endPlane3D.xyz = czm_normal * endNormalAndTextureCoordinateNormalizationX.xyz;
endPlane2D.w = -dot(endPlane2D.xyz, posEc2D);
endPlane3D.w = -dot(endPlane3D.xyz, posEc3D);
// Forward direction
v_forwardDirectionEC = normalize(endEC - startEC);
vec2 cleanTexcoordNormalization2D;
cleanTexcoordNormalization2D.x = abs(texcoordNormalization2D.x);
cleanTexcoordNormalization2D.y = czm_branchFreeTernary(texcoordNormalization2D.y > 1.0, 0.0, abs(texcoordNormalization2D.y));
vec2 cleanTexcoordNormalization3D;
cleanTexcoordNormalization3D.x = abs(endNormalAndTextureCoordinateNormalizationX.w);
cleanTexcoordNormalization3D.y = rightNormalAndTextureCoordinateNormalizationY.w;
cleanTexcoordNormalization3D.y = czm_branchFreeTernary(cleanTexcoordNormalization3D.y > 1.0, 0.0, abs(cleanTexcoordNormalization3D.y));
v_texcoordNormalizationAndHalfWidth.xy = mix(cleanTexcoordNormalization2D, cleanTexcoordNormalization3D, czm_morphTime);
#ifdef PER_INSTANCE_COLOR
v_color = czm_batchTable_color(batchId);
#else // PER_INSTANCE_COLOR
// For computing texture coordinates
v_alignedPlaneDistances.x = -dot(v_forwardDirectionEC, startEC);
v_alignedPlaneDistances.y = -dot(-v_forwardDirectionEC, endEC);
#endif // PER_INSTANCE_COLOR
#ifdef WIDTH_VARYING
float width = czm_batchTable_width(batchId);
float halfWidth = width * 0.5;
v_width = width;
v_texcoordNormalizationAndHalfWidth.z = halfWidth;
#else
float halfWidth = 0.5 * czm_batchTable_width(batchId);
v_texcoordNormalizationAndHalfWidth.z = halfWidth;
#endif
// Compute a normal along which to "push" the position out, extending the miter depending on view distance.
// Position has already been "pushed" by unit length along miter normal, and miter normals are encoded in the planes.
// Decode the normal to use at this specific vertex, push the position back, and then push to where it needs to be.
// Since this is morphing, compute both 3D and 2D positions and then blend.
// ****** 3D ******
// Check distance to the end plane and start plane, pick the plane that is closer
vec4 positionEc3D = czm_modelViewRelativeToEye * czm_translateRelativeToEye(position3DHigh, position3DLow); // w = 1.0, see czm_computePosition
float absStartPlaneDistance = abs(czm_planeDistance(startPlane3D, positionEc3D.xyz));
float absEndPlaneDistance = abs(czm_planeDistance(endPlane3D, positionEc3D.xyz));
vec3 planeDirection = czm_branchFreeTernary(absStartPlaneDistance < absEndPlaneDistance, startPlane3D.xyz, endPlane3D.xyz);
vec3 upOrDown = normalize(cross(rightPlane3D.xyz, planeDirection)); // Points "up" for start plane, "down" at end plane.
vec3 normalEC = normalize(cross(planeDirection, upOrDown)); // In practice, the opposite seems to work too.
// Nudge the top vertex upwards to prevent flickering
vec3 geodeticSurfaceNormal = normalize(cross(normalEC, forwardEc3D));
geodeticSurfaceNormal *= float(0.0 <= rightNormalAndTextureCoordinateNormalizationY.w && rightNormalAndTextureCoordinateNormalizationY.w <= 1.0);
geodeticSurfaceNormal *= MAX_TERRAIN_HEIGHT;
positionEc3D.xyz += geodeticSurfaceNormal;
// Determine if this vertex is on the "left" or "right"
normalEC *= sign(endNormalAndTextureCoordinateNormalizationX.w);
// A "perfect" implementation would push along normals according to the angle against forward.
// In practice, just pushing the normal out by halfWidth is sufficient for morph views.
positionEc3D.xyz += halfWidth * max(0.0, czm_metersPerPixel(positionEc3D)) * normalEC; // prevent artifacts when czm_metersPerPixel is negative (behind camera)
// ****** 2D ******
// Check distance to the end plane and start plane, pick the plane that is closer
vec4 positionEc2D = czm_modelViewRelativeToEye * czm_translateRelativeToEye(position2DHigh.zxy, position2DLow.zxy); // w = 1.0, see czm_computePosition
absStartPlaneDistance = abs(czm_planeDistance(startPlane2D, positionEc2D.xyz));
absEndPlaneDistance = abs(czm_planeDistance(endPlane2D, positionEc2D.xyz));
planeDirection = czm_branchFreeTernary(absStartPlaneDistance < absEndPlaneDistance, startPlane2D.xyz, endPlane2D.xyz);
upOrDown = normalize(cross(rightPlane2D.xyz, planeDirection)); // Points "up" for start plane, "down" at end plane.
normalEC = normalize(cross(planeDirection, upOrDown)); // In practice, the opposite seems to work too.
// Nudge the top vertex upwards to prevent flickering
geodeticSurfaceNormal = normalize(cross(normalEC, forwardEc2D));
geodeticSurfaceNormal *= float(0.0 <= texcoordNormalization2D.y && texcoordNormalization2D.y <= 1.0);
geodeticSurfaceNormal *= MAX_TERRAIN_HEIGHT;
positionEc2D.xyz += geodeticSurfaceNormal;
// Determine if this vertex is on the "left" or "right"
normalEC *= sign(texcoordNormalization2D.x);
#ifndef PER_INSTANCE_COLOR
// Use vertex's sidedness to compute its texture coordinate.
v_texcoordT = clamp(sign(texcoordNormalization2D.x), 0.0, 1.0);
#endif
// A "perfect" implementation would push along normals according to the angle against forward.
// In practice, just pushing the normal out by halfWidth is sufficient for morph views.
positionEc2D.xyz += halfWidth * max(0.0, czm_metersPerPixel(positionEc2D)) * normalEC; // prevent artifacts when czm_metersPerPixel is negative (behind camera)
// Blend for actual position
gl_Position = czm_projection * mix(positionEc2D, positionEc3D, czm_morphTime);
#ifdef ANGLE_VARYING
// Approximate relative screen space direction of the line.
vec2 approxLineDirection = normalize(vec2(v_forwardDirectionEC.x, -v_forwardDirectionEC.y));
approxLineDirection.y = czm_branchFreeTernary(approxLineDirection.x == 0.0 && approxLineDirection.y == 0.0, -1.0, approxLineDirection.y);
v_polylineAngle = czm_fastApproximateAtan(approxLineDirection.x, approxLineDirection.y);
#endif
}
`;
// packages/engine/Source/Shaders/PolylineShadowVolumeVS.js
var PolylineShadowVolumeVS_default = 'in vec3 position3DHigh;\nin vec3 position3DLow;\n\n// In 2D and in 3D, texture coordinate normalization component signs encodes:\n// * X sign - sidedness relative to right plane\n// * Y sign - is negative OR magnitude is greater than 1.0 if vertex is on bottom of volume\n#ifndef COLUMBUS_VIEW_2D\nin vec4 startHiAndForwardOffsetX;\nin vec4 startLoAndForwardOffsetY;\nin vec4 startNormalAndForwardOffsetZ;\nin vec4 endNormalAndTextureCoordinateNormalizationX;\nin vec4 rightNormalAndTextureCoordinateNormalizationY;\n#else\nin vec4 startHiLo2D;\nin vec4 offsetAndRight2D;\nin vec4 startEndNormals2D;\nin vec2 texcoordNormalization2D;\n#endif\n\nin float batchId;\n\nout vec4 v_startPlaneNormalEcAndHalfWidth;\nout vec4 v_endPlaneNormalEcAndBatchId;\nout vec4 v_rightPlaneEC;\nout vec4 v_endEcAndStartEcX;\nout vec4 v_texcoordNormalizationAndStartEcYZ;\n\n// For materials\n#ifdef WIDTH_VARYING\nout float v_width;\n#endif\n#ifdef ANGLE_VARYING\nout float v_polylineAngle;\n#endif\n\n#ifdef PER_INSTANCE_COLOR\nout vec4 v_color;\n#endif\n\nvoid main()\n{\n#ifdef COLUMBUS_VIEW_2D\n vec3 ecStart = (czm_modelViewRelativeToEye * czm_translateRelativeToEye(vec3(0.0, startHiLo2D.xy), vec3(0.0, startHiLo2D.zw))).xyz;\n\n vec3 forwardDirectionEC = czm_normal * vec3(0.0, offsetAndRight2D.xy);\n vec3 ecEnd = forwardDirectionEC + ecStart;\n forwardDirectionEC = normalize(forwardDirectionEC);\n\n // Right plane\n v_rightPlaneEC.xyz = czm_normal * vec3(0.0, offsetAndRight2D.zw);\n v_rightPlaneEC.w = -dot(v_rightPlaneEC.xyz, ecStart);\n\n // start plane\n vec4 startPlaneEC;\n startPlaneEC.xyz = czm_normal * vec3(0.0, startEndNormals2D.xy);\n startPlaneEC.w = -dot(startPlaneEC.xyz, ecStart);\n\n // end plane\n vec4 endPlaneEC;\n endPlaneEC.xyz = czm_normal * vec3(0.0, startEndNormals2D.zw);\n endPlaneEC.w = -dot(endPlaneEC.xyz, ecEnd);\n\n v_texcoordNormalizationAndStartEcYZ.x = abs(texcoordNormalization2D.x);\n v_texcoordNormalizationAndStartEcYZ.y = texcoordNormalization2D.y;\n\n#else // COLUMBUS_VIEW_2D\n vec3 ecStart = (czm_modelViewRelativeToEye * czm_translateRelativeToEye(startHiAndForwardOffsetX.xyz, startLoAndForwardOffsetY.xyz)).xyz;\n vec3 offset = czm_normal * vec3(startHiAndForwardOffsetX.w, startLoAndForwardOffsetY.w, startNormalAndForwardOffsetZ.w);\n vec3 ecEnd = ecStart + offset;\n\n vec3 forwardDirectionEC = normalize(offset);\n\n // start plane\n vec4 startPlaneEC;\n startPlaneEC.xyz = czm_normal * startNormalAndForwardOffsetZ.xyz;\n startPlaneEC.w = -dot(startPlaneEC.xyz, ecStart);\n\n // end plane\n vec4 endPlaneEC;\n endPlaneEC.xyz = czm_normal * endNormalAndTextureCoordinateNormalizationX.xyz;\n endPlaneEC.w = -dot(endPlaneEC.xyz, ecEnd);\n\n // Right plane\n v_rightPlaneEC.xyz = czm_normal * rightNormalAndTextureCoordinateNormalizationY.xyz;\n v_rightPlaneEC.w = -dot(v_rightPlaneEC.xyz, ecStart);\n\n v_texcoordNormalizationAndStartEcYZ.x = abs(endNormalAndTextureCoordinateNormalizationX.w);\n v_texcoordNormalizationAndStartEcYZ.y = rightNormalAndTextureCoordinateNormalizationY.w;\n\n#endif // COLUMBUS_VIEW_2D\n\n v_endEcAndStartEcX.xyz = ecEnd;\n v_endEcAndStartEcX.w = ecStart.x;\n v_texcoordNormalizationAndStartEcYZ.zw = ecStart.yz;\n\n#ifdef PER_INSTANCE_COLOR\n v_color = czm_batchTable_color(batchId);\n#endif // PER_INSTANCE_COLOR\n\n // Compute a normal along which to "push" the position out, extending the miter depending on view distance.\n // Position has already been "pushed" by unit length along miter normal, and miter normals are encoded in the planes.\n // Decode the normal to use at this specific vertex, push the position back, and then push to where it needs to be.\n vec4 positionRelativeToEye = czm_computePosition();\n\n // Check distance to the end plane and start plane, pick the plane that is closer\n vec4 positionEC = czm_modelViewRelativeToEye * positionRelativeToEye; // w = 1.0, see czm_computePosition\n float absStartPlaneDistance = abs(czm_planeDistance(startPlaneEC, positionEC.xyz));\n float absEndPlaneDistance = abs(czm_planeDistance(endPlaneEC, positionEC.xyz));\n vec3 planeDirection = czm_branchFreeTernary(absStartPlaneDistance < absEndPlaneDistance, startPlaneEC.xyz, endPlaneEC.xyz);\n vec3 upOrDown = normalize(cross(v_rightPlaneEC.xyz, planeDirection)); // Points "up" for start plane, "down" at end plane.\n vec3 normalEC = normalize(cross(planeDirection, upOrDown)); // In practice, the opposite seems to work too.\n\n // Extrude bottom vertices downward for far view distances, like for GroundPrimitives\n upOrDown = cross(forwardDirectionEC, normalEC);\n upOrDown = float(czm_sceneMode == czm_sceneMode3D) * upOrDown;\n upOrDown = float(v_texcoordNormalizationAndStartEcYZ.y > 1.0 || v_texcoordNormalizationAndStartEcYZ.y < 0.0) * upOrDown;\n upOrDown = min(GLOBE_MINIMUM_ALTITUDE, czm_geometricToleranceOverMeter * length(positionRelativeToEye.xyz)) * upOrDown;\n positionEC.xyz += upOrDown;\n\n v_texcoordNormalizationAndStartEcYZ.y = czm_branchFreeTernary(v_texcoordNormalizationAndStartEcYZ.y > 1.0, 0.0, abs(v_texcoordNormalizationAndStartEcYZ.y));\n\n // Determine distance along normalEC to push for a volume of appropriate width.\n // Make volumes about double pixel width for a conservative fit - in practice the\n // extra cost here is minimal compared to the loose volume heights.\n //\n // N = normalEC (guaranteed "right-facing")\n // R = rightEC\n // p = angle between N and R\n // w = distance to push along R if R == N\n // d = distance to push along N\n //\n // N R\n // { p| } * cos(p) = dot(N, R) = w / d\n // d | |w * d = w / dot(N, R)\n // { | }\n // o---------- polyline segment ---->\n //\n float width = czm_batchTable_width(batchId);\n#ifdef WIDTH_VARYING\n v_width = width;\n#endif\n\n v_startPlaneNormalEcAndHalfWidth.xyz = startPlaneEC.xyz;\n v_startPlaneNormalEcAndHalfWidth.w = width * 0.5;\n\n v_endPlaneNormalEcAndBatchId.xyz = endPlaneEC.xyz;\n v_endPlaneNormalEcAndBatchId.w = batchId;\n\n width = width * max(0.0, czm_metersPerPixel(positionEC)); // width = distance to push along R\n width = width / dot(normalEC, v_rightPlaneEC.xyz); // width = distance to push along N\n\n // Determine if this vertex is on the "left" or "right"\n#ifdef COLUMBUS_VIEW_2D\n normalEC *= sign(texcoordNormalization2D.x);\n#else\n normalEC *= sign(endNormalAndTextureCoordinateNormalizationX.w);\n#endif\n\n positionEC.xyz += width * normalEC;\n gl_Position = czm_depthClamp(czm_projection * positionEC);\n\n#ifdef ANGLE_VARYING\n // Approximate relative screen space direction of the line.\n vec2 approxLineDirection = normalize(vec2(forwardDirectionEC.x, -forwardDirectionEC.y));\n approxLineDirection.y = czm_branchFreeTernary(approxLineDirection.x == 0.0 && approxLineDirection.y == 0.0, -1.0, approxLineDirection.y);\n v_polylineAngle = czm_fastApproximateAtan(approxLineDirection.x, approxLineDirection.y);\n#endif\n}\n';
// packages/engine/Source/Shaders/Appearances/PolylineColorAppearanceVS.js
var PolylineColorAppearanceVS_default = "in vec3 position3DHigh;\nin vec3 position3DLow;\nin vec3 prevPosition3DHigh;\nin vec3 prevPosition3DLow;\nin vec3 nextPosition3DHigh;\nin vec3 nextPosition3DLow;\nin vec2 expandAndWidth;\nin vec4 color;\nin float batchId;\n\nout vec4 v_color;\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_color = color;\n}\n";
// packages/engine/Source/Shaders/PolylineCommon.js
var PolylineCommon_default = "void clipLineSegmentToNearPlane(\n vec3 p0,\n vec3 p1,\n out vec4 positionWC,\n out bool clipped,\n out bool culledByNearPlane,\n out vec4 clippedPositionEC)\n{\n culledByNearPlane = false;\n clipped = false;\n\n vec3 p0ToP1 = p1 - p0;\n float magnitude = length(p0ToP1);\n vec3 direction = normalize(p0ToP1);\n\n // Distance that p0 is behind the near plane. Negative means p0 is\n // in front of the near plane.\n float endPoint0Distance = czm_currentFrustum.x + p0.z;\n\n // Camera looks down -Z.\n // When moving a point along +Z: LESS VISIBLE\n // * Points in front of the camera move closer to the camera.\n // * Points behind the camrea move farther away from the camera.\n // When moving a point along -Z: MORE VISIBLE\n // * Points in front of the camera move farther away from the camera.\n // * Points behind the camera move closer to the camera.\n\n // Positive denominator: -Z, becoming more visible\n // Negative denominator: +Z, becoming less visible\n // Nearly zero: parallel to near plane\n float denominator = -direction.z;\n\n if (endPoint0Distance > 0.0 && abs(denominator) < czm_epsilon7)\n {\n // p0 is behind the near plane and the line to p1 is nearly parallel to\n // the near plane, so cull the segment completely.\n culledByNearPlane = true;\n }\n else if (endPoint0Distance > 0.0)\n {\n // p0 is behind the near plane, and the line to p1 is moving distinctly\n // toward or away from it.\n\n // t = (-plane distance - dot(plane normal, ray origin)) / dot(plane normal, ray direction)\n float t = endPoint0Distance / denominator;\n if (t < 0.0 || t > magnitude)\n {\n // Near plane intersection is not between the two points.\n // We already confirmed p0 is behind the naer plane, so now\n // we know the entire segment is behind it.\n culledByNearPlane = true;\n }\n else\n {\n // Segment crosses the near plane, update p0 to lie exactly on it.\n p0 = p0 + t * direction;\n\n // Numerical noise might put us a bit on the wrong side of the near plane.\n // Don't let that happen.\n p0.z = min(p0.z, -czm_currentFrustum.x);\n\n clipped = true;\n }\n }\n\n clippedPositionEC = vec4(p0, 1.0);\n positionWC = czm_eyeToWindowCoordinates(clippedPositionEC);\n}\n\nvec4 getPolylineWindowCoordinatesEC(vec4 positionEC, vec4 prevEC, vec4 nextEC, float expandDirection, float width, bool usePrevious, out float angle)\n{\n // expandDirection +1 is to the _left_ when looking from positionEC toward nextEC.\n\n#ifdef POLYLINE_DASH\n // Compute the window coordinates of the points.\n vec4 positionWindow = czm_eyeToWindowCoordinates(positionEC);\n vec4 previousWindow = czm_eyeToWindowCoordinates(prevEC);\n vec4 nextWindow = czm_eyeToWindowCoordinates(nextEC);\n\n // Determine the relative screen space direction of the line.\n vec2 lineDir;\n if (usePrevious) {\n lineDir = normalize(positionWindow.xy - previousWindow.xy);\n }\n else {\n lineDir = normalize(nextWindow.xy - positionWindow.xy);\n }\n angle = atan(lineDir.x, lineDir.y) - 1.570796327; // precomputed atan(1,0)\n\n // Quantize the angle so it doesn't change rapidly between segments.\n angle = floor(angle / czm_piOverFour + 0.5) * czm_piOverFour;\n#endif\n\n vec4 clippedPrevWC, clippedPrevEC;\n bool prevSegmentClipped, prevSegmentCulled;\n clipLineSegmentToNearPlane(prevEC.xyz, positionEC.xyz, clippedPrevWC, prevSegmentClipped, prevSegmentCulled, clippedPrevEC);\n\n vec4 clippedNextWC, clippedNextEC;\n bool nextSegmentClipped, nextSegmentCulled;\n clipLineSegmentToNearPlane(nextEC.xyz, positionEC.xyz, clippedNextWC, nextSegmentClipped, nextSegmentCulled, clippedNextEC);\n\n bool segmentClipped, segmentCulled;\n vec4 clippedPositionWC, clippedPositionEC;\n clipLineSegmentToNearPlane(positionEC.xyz, usePrevious ? prevEC.xyz : nextEC.xyz, clippedPositionWC, segmentClipped, segmentCulled, clippedPositionEC);\n\n if (segmentCulled)\n {\n return vec4(0.0, 0.0, 0.0, 1.0);\n }\n\n vec2 directionToPrevWC = normalize(clippedPrevWC.xy - clippedPositionWC.xy);\n vec2 directionToNextWC = normalize(clippedNextWC.xy - clippedPositionWC.xy);\n\n // If a segment was culled, we can't use the corresponding direction\n // computed above. We should never see both of these be true without\n // `segmentCulled` above also being true.\n if (prevSegmentCulled)\n {\n directionToPrevWC = -directionToNextWC;\n }\n else if (nextSegmentCulled)\n {\n directionToNextWC = -directionToPrevWC;\n }\n\n vec2 thisSegmentForwardWC, otherSegmentForwardWC;\n if (usePrevious)\n {\n thisSegmentForwardWC = -directionToPrevWC;\n otherSegmentForwardWC = directionToNextWC;\n }\n else\n {\n thisSegmentForwardWC = directionToNextWC;\n otherSegmentForwardWC = -directionToPrevWC;\n }\n\n vec2 thisSegmentLeftWC = vec2(-thisSegmentForwardWC.y, thisSegmentForwardWC.x);\n\n vec2 leftWC = thisSegmentLeftWC;\n float expandWidth = width * 0.5;\n\n // When lines are split at the anti-meridian, the position may be at the\n // same location as the next or previous position, and we need to handle\n // that to avoid producing NaNs.\n if (!czm_equalsEpsilon(prevEC.xyz - positionEC.xyz, vec3(0.0), czm_epsilon1) && !czm_equalsEpsilon(nextEC.xyz - positionEC.xyz, vec3(0.0), czm_epsilon1))\n {\n vec2 otherSegmentLeftWC = vec2(-otherSegmentForwardWC.y, otherSegmentForwardWC.x);\n\n vec2 leftSumWC = thisSegmentLeftWC + otherSegmentLeftWC;\n float leftSumLength = length(leftSumWC);\n leftWC = leftSumLength < czm_epsilon6 ? thisSegmentLeftWC : (leftSumWC / leftSumLength);\n\n // The sine of the angle between the two vectors is given by the formula\n // |a x b| = |a||b|sin(theta)\n // which is\n // float sinAngle = length(cross(vec3(leftWC, 0.0), vec3(-thisSegmentForwardWC, 0.0)));\n // Because the z components of both vectors are zero, the x and y coordinate will be zero.\n // Therefore, the sine of the angle is just the z component of the cross product.\n vec2 u = -thisSegmentForwardWC;\n vec2 v = leftWC;\n float sinAngle = abs(u.x * v.y - u.y * v.x);\n expandWidth = clamp(expandWidth / sinAngle, 0.0, width * 2.0);\n }\n\n vec2 offset = leftWC * expandDirection * expandWidth * czm_pixelRatio;\n return vec4(clippedPositionWC.xy + offset, -clippedPositionWC.z, 1.0) * (czm_projection * clippedPositionEC).w;\n}\n\nvec4 getPolylineWindowCoordinates(vec4 position, vec4 previous, vec4 next, float expandDirection, float width, bool usePrevious, out float angle)\n{\n vec4 positionEC = czm_modelViewRelativeToEye * position;\n vec4 prevEC = czm_modelViewRelativeToEye * previous;\n vec4 nextEC = czm_modelViewRelativeToEye * next;\n return getPolylineWindowCoordinatesEC(positionEC, prevEC, nextEC, expandDirection, width, usePrevious, angle);\n}\n";
// packages/engine/Source/Scene/PolylineColorAppearance.js
var defaultVertexShaderSource = `#define CLIP_POLYLINE
${PolylineCommon_default}
${PolylineColorAppearanceVS_default}`;
var defaultFragmentShaderSource = PerInstanceFlatColorAppearanceFS_default;
function PolylineColorAppearance(options) {
options = options ?? Frozen_default.EMPTY_OBJECT;
const translucent = options.translucent ?? true;
const closed = false;
const vertexFormat = PolylineColorAppearance.VERTEX_FORMAT;
this.material = void 0;
this.translucent = translucent;
this._vertexShaderSource = options.vertexShaderSource ?? defaultVertexShaderSource;
this._fragmentShaderSource = options.fragmentShaderSource ?? defaultFragmentShaderSource;
this._renderState = Appearance_default.getDefaultRenderState(
translucent,
closed,
options.renderState
);
this._closed = closed;
this._vertexFormat = vertexFormat;
}
Object.defineProperties(PolylineColorAppearance.prototype, {
/**
* The GLSL source code for the vertex shader.
*
* @memberof PolylineColorAppearance.prototype
*
* @type {string}
* @readonly
*/
vertexShaderSource: {
get: function() {
return this._vertexShaderSource;
}
},
/**
* The GLSL source code for the fragment shader.
*
* @memberof PolylineColorAppearance.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 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 = `#define CLIP_POLYLINE
${PolylineCommon_default}
${PolylineMaterialAppearanceVS_default}`;
var defaultFragmentShaderSource2 = PolylineFS_default;
function PolylineMaterialAppearance(options) {
options = options ?? Frozen_default.EMPTY_OBJECT;
const translucent = 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 = options.vertexShaderSource ?? defaultVertexShaderSource2;
this._fragmentShaderSource = 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 = options ?? Frozen_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 = options.show ?? true;
this.classificationType = options.classificationType ?? ClassificationType_default.BOTH;
this.debugShowBoundingVolume = options.debugShowBoundingVolume ?? false;
this._debugShowShadowVolume = options.debugShowShadowVolume ?? false;
this._primitiveOptions = {
geometryInstances: void 0,
appearance: void 0,
vertexCacheOptimize: false,
interleave: options.interleave ?? false,
releaseGeometryInstances: options.releaseGeometryInstances ?? true,
allowPicking: options.allowPicking ?? true,
asynchronous: options.asynchronous ?? true,
compressVertices: false,
_createShaderProgramFunction: void 0,
_createCommandsFunction: void 0,
_updateAndQueueCommandsFunction: void 0
};
this._zIndex = void 0;
this._ready = false;
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;
}
},
/**
* This property is for debugging only; it is not for production use nor is it optimized.
* * 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, material4, translucent, colorCommands, pickCommands) { const primitive = groundPolylinePrimitive._primitive; const length2 = primitive._va.length; colorCommands.length = length2; pickCommands.length = length2; const isPolylineColorAppearance = appearance instanceof PolylineColorAppearance_default; const materialUniforms = isPolylineColorAppearance ? {} : material4._uniforms; const uniformMap2 = primitive._batchTable.getUniformMapCallback()(materialUniforms); for (let i = 0; i < length2; 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, material4, translucent, twoPasses, colorCommands, pickCommands) { createCommands3( that, appearance, material4, 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._ready = true; if (this.releaseGeometryInstances) { this.geometryInstances = void 0; } } }); }; 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 = options ?? Frozen_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"; }; var timeScratch3 = new JulianDate_default(); ImageMaterialProperty.prototype.getValue = function(time, result) { if (!defined_default(time)) { time = JulianDate_default.now(timeScratch3); } 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(options ?? Frozen_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 = this.show ?? source.show; this.dimensions = this.dimensions ?? source.dimensions; this.heightReference = this.heightReference ?? source.heightReference; this.fill = this.fill ?? source.fill; this.material = this.material ?? source.material; this.outline = this.outline ?? source.outline; this.outlineColor = this.outlineColor ?? source.outlineColor; this.outlineWidth = this.outlineWidth ?? source.outlineWidth; this.shadows = this.shadows ?? source.shadows; this.distanceDisplayCondition = 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 }; Object.freeze(ReferenceFrame); var ReferenceFrame_default = 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); } const icrfToFixed2 = Transforms_default.computeIcrfToCentralBodyFixedMatrix( 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 = 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; } } }); var timeScratch4 = new JulianDate_default(); ConstantPositionProperty.prototype.getValue = function(time, result) { if (!defined_default(time)) { time = JulianDate_default.now(timeScratch4); } 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(options ?? Frozen_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 = this.show ?? source.show; this.positions = this.positions ?? source.positions; this.width = this.width ?? source.width; this.height = this.height ?? source.height; this.heightReference = this.heightReference ?? source.heightReference; this.extrudedHeight = this.extrudedHeight ?? source.extrudedHeight; this.extrudedHeightReference = this.extrudedHeightReference ?? source.extrudedHeightReference; this.cornerType = this.cornerType ?? source.cornerType; this.granularity = this.granularity ?? source.granularity; this.fill = this.fill ?? source.fill; this.material = this.material ?? source.material; this.outline = this.outline ?? source.outline; this.outlineColor = this.outlineColor ?? source.outlineColor; this.outlineWidth = this.outlineWidth ?? source.outlineWidth; this.shadows = this.shadows ?? source.shadows; this.distanceDisplayCondition = this.distanceDisplayCondition ?? source.distanceDisplayCondition; this.classificationType = this.classificationType ?? source.classificationType; this.zIndex = 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(options ?? Frozen_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 = this.show ?? source.show; this.length = this.length ?? source.length; this.topRadius = this.topRadius ?? source.topRadius; this.bottomRadius = this.bottomRadius ?? source.bottomRadius; this.heightReference = this.heightReference ?? source.heightReference; this.fill = this.fill ?? source.fill; this.material = this.material ?? source.material; this.outline = this.outline ?? source.outline; this.outlineColor = this.outlineColor ?? source.outlineColor; this.outlineWidth = this.outlineWidth ?? source.outlineWidth; this.numberOfVerticalLines = this.numberOfVerticalLines ?? source.numberOfVerticalLines; this.slices = this.slices ?? source.slices; this.shadows = this.shadows ?? source.shadows; this.distanceDisplayCondition = 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(options ?? Frozen_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 = this.show ?? source.show; this.semiMajorAxis = this.semiMajorAxis ?? source.semiMajorAxis; this.semiMinorAxis = this.semiMinorAxis ?? source.semiMinorAxis; this.height = this.height ?? source.height; this.heightReference = this.heightReference ?? source.heightReference; this.extrudedHeight = this.extrudedHeight ?? source.extrudedHeight; this.extrudedHeightReference = this.extrudedHeightReference ?? source.extrudedHeightReference; this.rotation = this.rotation ?? source.rotation; this.stRotation = this.stRotation ?? source.stRotation; this.granularity = this.granularity ?? source.granularity; this.fill = this.fill ?? source.fill; this.material = this.material ?? source.material; this.outline = this.outline ?? source.outline; this.outlineColor = this.outlineColor ?? source.outlineColor; this.outlineWidth = this.outlineWidth ?? source.outlineWidth; this.numberOfVerticalLines = this.numberOfVerticalLines ?? source.numberOfVerticalLines; this.shadows = this.shadows ?? source.shadows; this.distanceDisplayCondition = this.distanceDisplayCondition ?? source.distanceDisplayCondition; this.classificationType = this.classificationType ?? source.classificationType; this.zIndex = 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(options ?? Frozen_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 = this.show ?? source.show; this.radii = this.radii ?? source.radii; this.innerRadii = this.innerRadii ?? source.innerRadii; this.minimumClock = this.minimumClock ?? source.minimumClock; this.maximumClock = this.maximumClock ?? source.maximumClock; this.minimumCone = this.minimumCone ?? source.minimumCone; this.maximumCone = this.maximumCone ?? source.maximumCone; this.heightReference = this.heightReference ?? source.heightReference; this.fill = this.fill ?? source.fill; this.material = this.material ?? source.material; this.outline = this.outline ?? source.outline; this.outlineColor = this.outlineColor ?? source.outlineColor; this.outlineWidth = this.outlineWidth ?? source.outlineWidth; this.stackPartitions = this.stackPartitions ?? source.stackPartitions; this.slicePartitions = this.slicePartitions ?? source.slicePartitions; this.subdivisions = this.subdivisions ?? source.subdivisions; this.shadows = this.shadows ?? source.shadows; this.distanceDisplayCondition = 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(options ?? Frozen_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);1.0.
* @memberof ModelGraphics.prototype
* @type {Property|undefined}
* @default true
*/
enableVerticalExaggeration: createPropertyDescriptor_default(
"enableVerticalExaggeration"
),
/**
* Gets or sets the numeric Property specifying 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 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"
),
/**
* Gets or sets the {@link DynamicEnvironmentMapManager.ConstructorOptions} to apply to this model. This is represented as an {@link PropertyBag}.
* @memberof ModelGraphics.prototype
* @type {PropertyBag}
*/
environmentMapOptions: createPropertyDescriptor_default(
"environmentMapOptions",
void 0,
createEnvironmentMapPropertyBag
),
/**
* 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.enableVerticalExaggeration = this.enableVerticalExaggeration;
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.environmentMapOptions = this.environmentMapOptions;
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 = this.show ?? source.show;
this.uri = this.uri ?? source.uri;
this.scale = this.scale ?? source.scale;
this.enableVerticalExaggeration = this.enableVerticalExaggeration ?? source.enableVerticalExaggeration;
this.minimumPixelSize = this.minimumPixelSize ?? source.minimumPixelSize;
this.maximumScale = this.maximumScale ?? source.maximumScale;
this.incrementallyLoadTextures = this.incrementallyLoadTextures ?? source.incrementallyLoadTextures;
this.runAnimations = this.runAnimations ?? source.runAnimations;
this.clampAnimations = this.clampAnimations ?? source.clampAnimations;
this.shadows = this.shadows ?? source.shadows;
this.heightReference = this.heightReference ?? source.heightReference;
this.silhouetteColor = this.silhouetteColor ?? source.silhouetteColor;
this.silhouetteSize = this.silhouetteSize ?? source.silhouetteSize;
this.color = this.color ?? source.color;
this.colorBlendMode = this.colorBlendMode ?? source.colorBlendMode;
this.colorBlendAmount = this.colorBlendAmount ?? source.colorBlendAmount;
this.imageBasedLightingFactor = this.imageBasedLightingFactor ?? source.imageBasedLightingFactor;
this.environmentMapOptions = this.environmentMapOptions ?? source.environmentMapOptions;
this.lightColor = this.lightColor ?? source.lightColor;
this.distanceDisplayCondition = this.distanceDisplayCondition ?? source.distanceDisplayCondition;
this.clippingPlanes = this.clippingPlanes ?? source.clippingPlanes;
this.customShader = 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(options ?? Frozen_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 = this.show ?? source.show;
this.uri = this.uri ?? source.uri;
this.maximumScreenSpaceError = 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._relativeTo = void 0;
this._relativeToSubscription = void 0;
this._materialMode = void 0;
this._materialModeSubscription = void 0;
this.merge(options ?? Frozen_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.
* Fractional positive values are allowed; in PORTIONS materialMode, non-positive values fall back to the default resolution of 60 seconds.
* @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"
),
/**
* Gets or sets the frame in which to visualize the path. Use another entity's id to visualize the path relative to that entity, or use the string values "FIXED" or "INERTIAL" to visualize the path in those reference frames.
* @memberof PathGraphics.prototype
* @type {Property|undefined}
* @experimental This feature is not final and is subject to change without Cesium's standard deprecation policy.
*/
relativeTo: createPropertyDescriptor_default("relativeTo"),
materialMode: createPropertyDescriptor_default("materialMode")
});
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;
result.relativeTo = this.relativeTo;
result.materialMode = this.materialMode;
return result;
};
PathGraphics.prototype.merge = function(source) {
if (!defined_default(source)) {
throw new DeveloperError_default("source is required.");
}
this.show = this.show ?? source.show;
this.leadTime = this.leadTime ?? source.leadTime;
this.trailTime = this.trailTime ?? source.trailTime;
this.width = this.width ?? source.width;
this.resolution = this.resolution ?? source.resolution;
this.material = this.material ?? source.material;
this.distanceDisplayCondition = this.distanceDisplayCondition ?? source.distanceDisplayCondition;
this.relativeTo = this.relativeTo ?? source.relativeTo;
this.materialMode = this.materialMode ?? source.materialMode;
};
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(options ?? Frozen_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 = this.show ?? source.show; this.plane = this.plane ?? source.plane; this.dimensions = this.dimensions ?? source.dimensions; this.fill = this.fill ?? source.fill; this.material = this.material ?? source.material; this.outline = this.outline ?? source.outline; this.outlineColor = this.outlineColor ?? source.outlineColor; this.outlineWidth = this.outlineWidth ?? source.outlineWidth; this.shadows = this.shadows ?? source.shadows; this.distanceDisplayCondition = 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._splitDirection = void 0; this._splitDirectionSubscription = void 0; this.merge(options ?? Frozen_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" ), /** * Gets or sets the Property specifying the {@link SplitDirection} of this point. * @memberof PointGraphics.prototype * @type {Property|undefined} * @default SplitDirection.NONE */ splitDirection: createPropertyDescriptor_default("splitDirection") }); 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; result.splitDirection = this.splitDirection; return result; }; PointGraphics.prototype.merge = function(source) { if (!defined_default(source)) { throw new DeveloperError_default("source is required."); } this.show = this.show ?? source.show; this.pixelSize = this.pixelSize ?? source.pixelSize; this.heightReference = this.heightReference ?? source.heightReference; this.color = this.color ?? source.color; this.outlineColor = this.outlineColor ?? source.outlineColor; this.outlineWidth = this.outlineWidth ?? source.outlineWidth; this.scaleByDistance = this.scaleByDistance ?? source.scaleByDistance; this.translucencyByDistance = this._translucencyByDistance ?? source.translucencyByDistance; this.distanceDisplayCondition = this.distanceDisplayCondition ?? source.distanceDisplayCondition; this.disableDepthTestDistance = this.disableDepthTestDistance ?? source.disableDepthTestDistance; this.splitDirection = this.splitDirection ?? source.splitDirection; }; 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(options ?? Frozen_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 = this.show ?? source.show; this.hierarchy = this.hierarchy ?? source.hierarchy; this.height = this.height ?? source.height; this.heightReference = this.heightReference ?? source.heightReference; this.extrudedHeight = this.extrudedHeight ?? source.extrudedHeight; this.extrudedHeightReference = this.extrudedHeightReference ?? source.extrudedHeightReference; this.stRotation = this.stRotation ?? source.stRotation; this.granularity = this.granularity ?? source.granularity; this.fill = this.fill ?? source.fill; this.material = this.material ?? source.material; this.outline = this.outline ?? source.outline; this.outlineColor = this.outlineColor ?? source.outlineColor; this.outlineWidth = this.outlineWidth ?? source.outlineWidth; this.perPositionHeight = this.perPositionHeight ?? source.perPositionHeight; this.closeTop = this.closeTop ?? source.closeTop; this.closeBottom = this.closeBottom ?? source.closeBottom; this.arcType = this.arcType ?? source.arcType; this.shadows = this.shadows ?? source.shadows; this.distanceDisplayCondition = this.distanceDisplayCondition ?? source.distanceDisplayCondition; this.classificationType = this.classificationType ?? source.classificationType; this.zIndex = this.zIndex ?? source.zIndex; this.textureCoordinates = 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(options ?? Frozen_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 = this.show ?? source.show; this.positions = this.positions ?? source.positions; this.width = this.width ?? source.width; this.granularity = this.granularity ?? source.granularity; this.material = this.material ?? source.material; this.depthFailMaterial = this.depthFailMaterial ?? source.depthFailMaterial; this.arcType = this.arcType ?? source.arcType; this.clampToGround = this.clampToGround ?? source.clampToGround; this.shadows = this.shadows ?? source.shadows; this.distanceDisplayCondition = this.distanceDisplayCondition ?? source.distanceDisplayCondition; this.classificationType = this.classificationType ?? source.classificationType; this.zIndex = 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(options ?? Frozen_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 = this.show ?? source.show; this.positions = this.positions ?? source.positions; this.shape = this.shape ?? source.shape; this.cornerType = this.cornerType ?? source.cornerType; this.granularity = this.granularity ?? source.granularity; this.fill = this.fill ?? source.fill; this.material = this.material ?? source.material; this.outline = this.outline ?? source.outline; this.outlineColor = this.outlineColor ?? source.outlineColor; this.outlineWidth = this.outlineWidth ?? source.outlineWidth; this.shadows = this.shadows ?? source.shadows; this.distanceDisplayCondition = 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(options ?? Frozen_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 = this.show ?? source.show; this.coordinates = this.coordinates ?? source.coordinates; this.height = this.height ?? source.height; this.heightReference = this.heightReference ?? source.heightReference; this.extrudedHeight = this.extrudedHeight ?? source.extrudedHeight; this.extrudedHeightReference = this.extrudedHeightReference ?? source.extrudedHeightReference; this.rotation = this.rotation ?? source.rotation; this.stRotation = this.stRotation ?? source.stRotation; this.granularity = this.granularity ?? source.granularity; this.fill = this.fill ?? source.fill; this.material = this.material ?? source.material; this.outline = this.outline ?? source.outline; this.outlineColor = this.outlineColor ?? source.outlineColor; this.outlineWidth = this.outlineWidth ?? source.outlineWidth; this.shadows = this.shadows ?? source.shadows; this.distanceDisplayCondition = this.distanceDisplayCondition ?? source.distanceDisplayCondition; this.classificationType = this.classificationType ?? source.classificationType; this.zIndex = 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(options ?? Frozen_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 = this.show ?? source.show; this.positions = this.positions ?? source.positions; this.minimumHeights = this.minimumHeights ?? source.minimumHeights; this.maximumHeights = this.maximumHeights ?? source.maximumHeights; this.granularity = this.granularity ?? source.granularity; this.fill = this.fill ?? source.fill; this.material = this.material ?? source.material; this.outline = this.outline ?? source.outline; this.outlineColor = this.outlineColor ?? source.outlineColor; this.outlineWidth = this.outlineWidth ?? source.outlineWidth; this.shadows = this.shadows ?? source.shadows; this.distanceDisplayCondition = this.distanceDisplayCondition ?? source.distanceDisplayCondition; }; var WallGraphics_default = WallGraphics; // packages/engine/Source/DataSources/Entity.js var cartoScratch = new Cartographic_default(); var ExtraPropertyNames = []; 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 = options ?? Frozen_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 = options.show ?? true; this._trackingReferenceFrame = options.trackingReferenceFrame ?? TrackingReferenceFrame_default.AUTODETECT; 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", ...ExtraPropertyNames ]; 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 length2 = children.length; for (let i = 0; i < length2; 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 or sets the entity's tracking reference frame. * @demo {@link https://sandcastle.cesium.com/index.html?id=entity-tracking|Cesium Sandcastle Entity tracking Demo} * * @memberof Entity.prototype * @type {TrackingReferenceFrame} */ trackingReferenceFrame: createRawPropertyDescriptor_default("trackingReferenceFrame"), /** * 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 in respect to Earth-fixed-Earth-centered (ECEF). * Defaults to east-north-up at entity position. * @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.registerEntityType = function(propertyName, Type) { Object.defineProperties(Entity.prototype, { [propertyName]: createPropertyTypeDescriptor(propertyName, Type) }); if (!ExtraPropertyNames.includes(propertyName)) { ExtraPropertyNames.push(propertyName); } }; 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 = this.name ?? source.name; this.availability = 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 (isHeightReferenceClamp(heightReference)) { 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. * * @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 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 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 = geometry.material ?? defaultMaterial; this._fillProperty = fillProperty ?? defaultFill; this._showProperty = show ?? defaultShow; this._showOutlineProperty = geometry.outline ?? defaultOutline; this._outlineColorProperty = outlineEnabled ? geometry.outlineColor ?? defaultOutlineColor : void 0; this._shadowsProperty = geometry.shadows ?? defaultShadows; this._distanceDisplayConditionProperty = geometry.distanceDisplayCondition ?? defaultDistanceDisplayCondition; this._classificationTypeProperty = 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; } } }); var timeScratch7 = new JulianDate_default(); CallbackProperty.prototype.getValue = function(time, result) { if (!defined_default(time)) { time = JulianDate_default.now(timeScratch7); } 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(); 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.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 position = this._position; if (Cartesian3_default.equals(position, Cartesian3_default.ZERO)) { this._terrainHeight = 0; return; } const ellipsoid = scene.ellipsoid; const cartographicPosition = ellipsoid.cartesianToCartographic( position, this._cartographicPosition ); const height = scene.getHeight(cartographicPosition, this._heightReference); if (defined_default(height)) { this._terrainHeight = height; } else { this._terrainHeight = 0; } const updateFunction = (clampedPosition) => { this._terrainHeight = clampedPosition.height; this.definitionChanged.raiseEvent(); }; this._removeCallbackFunc = scene.updateHeight( cartographicPosition, updateFunction, this._heightReference ); }; var timeScratch8 = new JulianDate_default(); TerrainOffsetProperty.prototype.getValue = function(time, result) { if (!defined_default(time)) { time = JulianDate_default.now(timeScratch8); } 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 && !isHeightReferenceRelative(extrudedHeightReference)) { 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.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.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.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/DataSources/CallbackPositionProperty.js function CallbackPositionProperty(callback, isConstant, referenceFrame) { this._callback = void 0; this._isConstant = void 0; this._referenceFrame = referenceFrame ?? ReferenceFrame_default.FIXED; this._definitionChanged = new Event_default(); this.setCallback(callback, isConstant); } Object.defineProperties(CallbackPositionProperty.prototype, { /** * Gets a value indicating if this property is constant. * @memberof CallbackPositionProperty.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 considered to have changed if a call to getValue would return * a different result for the same time. * @memberof CallbackPositionProperty.prototype * * @type {Event} * @readonly */ definitionChanged: { get: function() { return this._definitionChanged; } }, /** * Gets the reference frame in which the position is defined. * @memberof CallbackPositionProperty.prototype * @type {ReferenceFrame} * @default ReferenceFrame.FIXED; */ referenceFrame: { get: function() { return this._referenceFrame; } } }); var timeScratch9 = new JulianDate_default(); CallbackPositionProperty.prototype.getValue = function(time, result) { if (!defined_default(time)) { time = JulianDate_default.now(timeScratch9); } return this.getValueInReferenceFrame(time, ReferenceFrame_default.FIXED, result); }; CallbackPositionProperty.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); } }; CallbackPositionProperty.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 value = this._callback(time, result); return PositionProperty_default.convertToReferenceFrame( time, value, this._referenceFrame, referenceFrame, result ); }; CallbackPositionProperty.prototype.equals = function(other) { return this === other || other instanceof CallbackPositionProperty && this._callback === other._callback && this._isConstant === other._isConstant && this._referenceFrame === other._referenceFrame; }; var CallbackPositionProperty_default = CallbackPositionProperty; // node_modules/dompurify/dist/purify.es.mjs /*! @license DOMPurify 3.4.13 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.13/LICENSE */ function _arrayLikeToArray(r2, a3) { (null == a3 || a3 > r2.length) && (a3 = r2.length); for (var e = 0, n2 = Array(a3); e < a3; e++) n2[e] = r2[e]; return n2; } function _arrayWithHoles(r2) { if (Array.isArray(r2)) return r2; } function _iterableToArrayLimit(r2, l2) { var t2 = null == r2 ? null : "undefined" != typeof Symbol && r2[Symbol.iterator] || r2["@@iterator"]; if (null != t2) { var e, n2, i, u4, a3 = [], f2 = true, o = false; try { if (i = (t2 = t2.call(r2)).next, 0 === l2) ; else for (; !(f2 = (e = i.call(t2)).done) && (a3.push(e.value), a3.length !== l2); f2 = true) ; } catch (r3) { o = true, n2 = r3; } finally { try { if (!f2 && null != t2.return && (u4 = t2.return(), Object(u4) !== u4)) return; } finally { if (o) throw n2; } } return a3; } } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _slicedToArray(r2, e) { return _arrayWithHoles(r2) || _iterableToArrayLimit(r2, e) || _unsupportedIterableToArray(r2, e) || _nonIterableRest(); } function _unsupportedIterableToArray(r2, a3) { if (r2) { if ("string" == typeof r2) return _arrayLikeToArray(r2, a3); var t2 = {}.toString.call(r2).slice(8, -1); return "Object" === t2 && r2.constructor && (t2 = r2.constructor.name), "Map" === t2 || "Set" === t2 ? Array.from(r2) : "Arguments" === t2 || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t2) ? _arrayLikeToArray(r2, a3) : void 0; } } var entries = Object.entries; var setPrototypeOf = Object.setPrototypeOf; var isFrozen = Object.isFrozen; var getPrototypeOf = Object.getPrototypeOf; var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; var freeze = Object.freeze; var seal = Object.seal; var create = Object.create; var _ref = typeof Reflect !== "undefined" && Reflect; var apply = _ref.apply; var construct = _ref.construct; if (!freeze) { freeze = function freeze2(x) { return x; }; } if (!seal) { seal = function seal2(x) { return x; }; } if (!apply) { apply = function apply2(func, thisArg) { for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } return func.apply(thisArg, args); }; } if (!construct) { construct = function construct2(Func) { for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } return new Func(...args); }; } var arrayForEach = unapply(Array.prototype.forEach); var arrayLastIndexOf = unapply(Array.prototype.lastIndexOf); var arrayPop = unapply(Array.prototype.pop); var arrayPush = unapply(Array.prototype.push); var arraySplice = unapply(Array.prototype.splice); var arrayIsArray = Array.isArray; var stringToLowerCase = unapply(String.prototype.toLowerCase); var stringToString = unapply(String.prototype.toString); var stringMatch = unapply(String.prototype.match); var stringReplace = unapply(String.prototype.replace); var stringIndexOf = unapply(String.prototype.indexOf); var stringTrim = unapply(String.prototype.trim); var numberToString = unapply(Number.prototype.toString); var booleanToString = unapply(Boolean.prototype.toString); var bigintToString = typeof BigInt === "undefined" ? null : unapply(BigInt.prototype.toString); var symbolToString = typeof Symbol === "undefined" ? null : unapply(Symbol.prototype.toString); var objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty); var objectToString = unapply(Object.prototype.toString); var regExpTest = unapply(RegExp.prototype.test); var typeErrorCreate = unconstruct(TypeError); function unapply(func) { return function(thisArg) { if (thisArg instanceof RegExp) { thisArg.lastIndex = 0; } for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { args[_key3 - 1] = arguments[_key3]; } return apply(func, thisArg, args); }; } function unconstruct(Func) { return function() { for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } return construct(Func, args); }; } function addToSet(set2, array) { let transformCaseFunc = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : stringToLowerCase; if (setPrototypeOf) { setPrototypeOf(set2, null); } if (!arrayIsArray(array)) { return set2; } let l2 = array.length; while (l2--) { let element = array[l2]; if (typeof element === "string") { const lcElement = transformCaseFunc(element); if (lcElement !== element) { if (!isFrozen(array)) { array[l2] = lcElement; } element = lcElement; } } set2[element] = true; } return set2; } function cleanArray(array) { for (let index = 0; index < array.length; index++) { const isPropertyExist = objectHasOwnProperty(array, index); if (!isPropertyExist) { array[index] = null; } } return array; } function clone2(object2) { const newObject = create(null); for (const _ref2 of entries(object2)) { var _ref3 = _slicedToArray(_ref2, 2); const property = _ref3[0]; const value = _ref3[1]; const isPropertyExist = objectHasOwnProperty(object2, property); if (isPropertyExist) { if (arrayIsArray(value)) { newObject[property] = cleanArray(value); } else if (value && typeof value === "object" && value.constructor === Object) { newObject[property] = clone2(value); } else { newObject[property] = value; } } } return newObject; } function stringifyValue(value) { switch (typeof value) { case "string": { return value; } case "number": { return numberToString(value); } case "boolean": { return booleanToString(value); } case "bigint": { return bigintToString ? bigintToString(value) : "0"; } case "symbol": { return symbolToString ? symbolToString(value) : "Symbol()"; } case "undefined": { return objectToString(value); } case "function": case "object": { if (value === null) { return objectToString(value); } const valueAsRecord = value; const valueToString = lookupGetter(valueAsRecord, "toString"); if (typeof valueToString === "function") { const stringified = valueToString(valueAsRecord); return typeof stringified === "string" ? stringified : objectToString(stringified); } return objectToString(value); } default: { return objectToString(value); } } } function lookupGetter(object2, prop) { while (object2 !== null) { const desc = getOwnPropertyDescriptor(object2, prop); if (desc) { if (desc.get) { return unapply(desc.get); } if (typeof desc.value === "function") { return unapply(desc.value); } } object2 = getPrototypeOf(object2); } function fallbackValue() { return null; } return fallbackValue; } function isRegex(value) { try { regExpTest(value, ""); return true; } catch (_unused) { return false; } } var html$1 = freeze(["a", "abbr", "acronym", "address", "area", "article", "aside", "audio", "b", "bdi", "bdo", "big", "blink", "blockquote", "body", "br", "button", "canvas", "caption", "center", "cite", "code", "col", "colgroup", "content", "data", "datalist", "dd", "decorator", "del", "details", "dfn", "dialog", "dir", "div", "dl", "dt", "element", "em", "fieldset", "figcaption", "figure", "font", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "i", "img", "input", "ins", "kbd", "label", "legend", "li", "main", "map", "mark", "marquee", "menu", "menuitem", "meter", "nav", "nobr", "ol", "optgroup", "option", "output", "p", "picture", "pre", "progress", "q", "rp", "rt", "ruby", "s", "samp", "search", "section", "select", "shadow", "slot", "small", "source", "spacer", "span", "strike", "strong", "style", "sub", "summary", "sup", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "time", "tr", "track", "tt", "u", "ul", "var", "video", "wbr"]); var svg$1 = freeze(["svg", "a", "altglyph", "altglyphdef", "altglyphitem", "animatecolor", "animatemotion", "animatetransform", "circle", "clippath", "defs", "desc", "ellipse", "enterkeyhint", "exportparts", "filter", "font", "g", "glyph", "glyphref", "hkern", "image", "inputmode", "line", "lineargradient", "marker", "mask", "metadata", "mpath", "part", "path", "pattern", "polygon", "polyline", "radialgradient", "rect", "stop", "style", "switch", "symbol", "text", "textpath", "title", "tref", "tspan", "view", "vkern"]); var svgFilters = freeze(["feBlend", "feColorMatrix", "feComponentTransfer", "feComposite", "feConvolveMatrix", "feDiffuseLighting", "feDisplacementMap", "feDistantLight", "feDropShadow", "feFlood", "feFuncA", "feFuncB", "feFuncG", "feFuncR", "feGaussianBlur", "feImage", "feMerge", "feMergeNode", "feMorphology", "feOffset", "fePointLight", "feSpecularLighting", "feSpotLight", "feTile", "feTurbulence"]); var svgDisallowed = freeze(["animate", "color-profile", "cursor", "discard", "font-face", "font-face-format", "font-face-name", "font-face-src", "font-face-uri", "foreignobject", "hatch", "hatchpath", "mesh", "meshgradient", "meshpatch", "meshrow", "missing-glyph", "script", "set", "solidcolor", "unknown", "use"]); var mathMl$1 = freeze(["math", "menclose", "merror", "mfenced", "mfrac", "mglyph", "mi", "mlabeledtr", "mmultiscripts", "mn", "mo", "mover", "mpadded", "mphantom", "mroot", "mrow", "ms", "mspace", "msqrt", "mstyle", "msub", "msup", "msubsup", "mtable", "mtd", "mtext", "mtr", "munder", "munderover", "mprescripts"]); var mathMlDisallowed = freeze(["maction", "maligngroup", "malignmark", "mlongdiv", "mscarries", "mscarry", "msgroup", "mstack", "msline", "msrow", "semantics", "annotation", "annotation-xml", "mprescripts", "none"]); var text = freeze(["#text"]); var html = freeze(["accept", "action", "align", "alt", "autocapitalize", "autocomplete", "autopictureinpicture", "autoplay", "background", "bgcolor", "border", "capture", "cellpadding", "cellspacing", "checked", "cite", "class", "clear", "color", "cols", "colspan", "command", "commandfor", "controls", "controlslist", "coords", "crossorigin", "datetime", "decoding", "default", "dir", "disabled", "disablepictureinpicture", "disableremoteplayback", "download", "draggable", "enctype", "enterkeyhint", "exportparts", "face", "for", "headers", "height", "hidden", "high", "href", "hreflang", "id", "inert", "inputmode", "integrity", "ismap", "kind", "label", "lang", "list", "loading", "loop", "low", "max", "maxlength", "media", "method", "min", "minlength", "multiple", "muted", "name", "nonce", "noshade", "novalidate", "nowrap", "open", "optimum", "part", "pattern", "placeholder", "playsinline", "popover", "popovertarget", "popovertargetaction", "poster", "preload", "pubdate", "radiogroup", "readonly", "rel", "required", "rev", "reversed", "role", "rows", "rowspan", "spellcheck", "scope", "selected", "shape", "size", "sizes", "slot", "span", "srclang", "start", "src", "srcset", "step", "style", "summary", "tabindex", "title", "translate", "type", "usemap", "valign", "value", "width", "wrap", "xmlns"]); var svg = freeze(["accent-height", "accumulate", "additive", "alignment-baseline", "amplitude", "ascent", "attributename", "attributetype", "azimuth", "basefrequency", "baseline-shift", "begin", "bias", "by", "class", "clip", "clippathunits", "clip-path", "clip-rule", "color", "color-interpolation", "color-interpolation-filters", "color-profile", "color-rendering", "cx", "cy", "d", "dx", "dy", "diffuseconstant", "direction", "display", "divisor", "dominant-baseline", "dur", "edgemode", "elevation", "end", "exponent", "fill", "fill-opacity", "fill-rule", "filter", "filterunits", "flood-color", "flood-opacity", "font-family", "font-size", "font-size-adjust", "font-stretch", "font-style", "font-variant", "font-weight", "fx", "fy", "g1", "g2", "glyph-name", "glyphref", "gradientunits", "gradienttransform", "height", "href", "id", "image-rendering", "in", "in2", "intercept", "k", "k1", "k2", "k3", "k4", "kerning", "keypoints", "keysplines", "keytimes", "lang", "lengthadjust", "letter-spacing", "kernelmatrix", "kernelunitlength", "lighting-color", "local", "marker-end", "marker-mid", "marker-start", "markerheight", "markerunits", "markerwidth", "maskcontentunits", "maskunits", "max", "mask", "mask-type", "media", "method", "mode", "min", "name", "numoctaves", "offset", "operator", "opacity", "order", "orient", "orientation", "origin", "overflow", "paint-order", "path", "pathlength", "patterncontentunits", "patterntransform", "patternunits", "points", "preservealpha", "preserveaspectratio", "primitiveunits", "r", "rx", "ry", "radius", "refx", "refy", "repeatcount", "repeatdur", "restart", "result", "rotate", "scale", "seed", "shape-rendering", "slope", "specularconstant", "specularexponent", "spreadmethod", "startoffset", "stddeviation", "stitchtiles", "stop-color", "stop-opacity", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke", "stroke-width", "style", "surfacescale", "systemlanguage", "tabindex", "tablevalues", "targetx", "targety", "transform", "transform-origin", "text-anchor", "text-decoration", "text-orientation", "text-rendering", "textlength", "type", "u1", "u2", "unicode", "values", "viewbox", "visibility", "version", "vert-adv-y", "vert-origin-x", "vert-origin-y", "width", "word-spacing", "wrap", "writing-mode", "xchannelselector", "ychannelselector", "x", "x1", "x2", "xmlns", "y", "y1", "y2", "z", "zoomandpan"]); var mathMl = freeze(["accent", "accentunder", "align", "bevelled", "close", "columnalign", "columnlines", "columnspacing", "columnspan", "denomalign", "depth", "dir", "display", "displaystyle", "encoding", "fence", "frame", "height", "href", "id", "largeop", "length", "linethickness", "lquote", "lspace", "mathbackground", "mathcolor", "mathsize", "mathvariant", "maxsize", "minsize", "movablelimits", "notation", "numalign", "open", "rowalign", "rowlines", "rowspacing", "rowspan", "rspace", "rquote", "scriptlevel", "scriptminsize", "scriptsizemultiplier", "selection", "separator", "separators", "stretchy", "subscriptshift", "supscriptshift", "symmetric", "voffset", "width", "xmlns"]); var xml = freeze(["xlink:href", "xml:id", "xlink:title", "xml:space", "xmlns:xlink"]); var MUSTACHE_EXPR = seal(/{{[\w\W]*|^[\w\W]*}}/g); var ERB_EXPR = seal(/<%[\w\W]*|^[\w\W]*%>/g); var TMPLIT_EXPR = seal(/\${[\w\W]*/g); var DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/); var ARIA_ATTR = seal(/^aria-[\-\w]+$/); var IS_ALLOWED_URI = seal( /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i // eslint-disable-line no-useless-escape ); var IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i); var ATTR_WHITESPACE = seal( /[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex ); var DOCTYPE_NAME = seal(/^html$/i); var CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i); var ELEMENT_MARKUP_PROBE = seal(/<[/\w!]/g); var COMMENT_MARKUP_PROBE = seal(/<[/\w]/g); var FALLBACK_TAG_CLOSE = seal(/<\/no(script|embed|frames)/i); var SELF_CLOSING_TAG = seal(/\/>/i); var NODE_TYPE = { element: 1, attribute: 2, text: 3, cdataSection: 4, entityReference: 5, // Deprecated entityNode: 6, // Deprecated processingInstruction: 7, comment: 8, document: 9, documentType: 10, documentFragment: 11, notation: 12 // Deprecated }; var getGlobal = function getGlobal2() { return typeof window === "undefined" ? null : window; }; var _createTrustedTypesPolicy = function _createTrustedTypesPolicy2(trustedTypes, purifyHostElement) { if (typeof trustedTypes !== "object" || typeof trustedTypes.createPolicy !== "function") { return null; } let suffix = null; const ATTR_NAME = "data-tt-policy-suffix"; if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) { suffix = purifyHostElement.getAttribute(ATTR_NAME); } const policyName = "dompurify" + (suffix ? "#" + suffix : ""); try { return trustedTypes.createPolicy(policyName, { createHTML(html2) { return html2; }, createScriptURL(scriptUrl) { return scriptUrl; } }); } catch (_) { console.warn("TrustedTypes policy " + policyName + " could not be created."); return null; } }; var _createHooksMap = function _createHooksMap2() { return { afterSanitizeAttributes: [], afterSanitizeElements: [], afterSanitizeShadowDOM: [], beforeSanitizeAttributes: [], beforeSanitizeElements: [], beforeSanitizeShadowDOM: [], uponSanitizeAttribute: [], uponSanitizeElement: [], uponSanitizeShadowNode: [] }; }; var _resolveSetOption = function _resolveSetOption2(cfg, key, fallback, options) { return objectHasOwnProperty(cfg, key) && arrayIsArray(cfg[key]) ? addToSet(options.base ? clone2(options.base) : {}, cfg[key], options.transform) : fallback; }; function createDOMPurify() { let window2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : getGlobal(); const DOMPurify = (root) => createDOMPurify(root); DOMPurify.version = "3.4.13"; DOMPurify.removed = []; if (!window2 || !window2.document || window2.document.nodeType !== NODE_TYPE.document || !window2.Element) { DOMPurify.isSupported = false; return DOMPurify; } let document2 = window2.document; const originalDocument = document2; const currentScript = originalDocument.currentScript; window2.DocumentFragment; const HTMLTemplateElement = window2.HTMLTemplateElement, Node6 = window2.Node, Element2 = window2.Element, NodeFilter = window2.NodeFilter, _window$NamedNodeMap = window2.NamedNodeMap; _window$NamedNodeMap === void 0 ? window2.NamedNodeMap || window2.MozNamedAttrMap : _window$NamedNodeMap; window2.HTMLFormElement; const DOMParser2 = window2.DOMParser, trustedTypes = window2.trustedTypes; const ElementPrototype = Element2.prototype; const cloneNode = lookupGetter(ElementPrototype, "cloneNode"); const remove4 = lookupGetter(ElementPrototype, "remove"); const getNextSibling = lookupGetter(ElementPrototype, "nextSibling"); const getChildNodes = lookupGetter(ElementPrototype, "childNodes"); const getParentNode = lookupGetter(ElementPrototype, "parentNode"); const getShadowRoot = lookupGetter(ElementPrototype, "shadowRoot"); const getAttributes2 = lookupGetter(ElementPrototype, "attributes"); const getNodeType = Node6 && Node6.prototype ? lookupGetter(Node6.prototype, "nodeType") : null; const getNodeName = Node6 && Node6.prototype ? lookupGetter(Node6.prototype, "nodeName") : null; const getOwnerDocument = Node6 && Node6.prototype ? lookupGetter(Node6.prototype, "ownerDocument") : null; if (typeof HTMLTemplateElement === "function") { const template = document2.createElement("template"); if (template.content && template.content.ownerDocument) { document2 = template.content.ownerDocument; } } let trustedTypesPolicy; let emptyHTML = ""; let defaultTrustedTypesPolicy; let defaultTrustedTypesPolicyResolved = false; let IN_TRUSTED_TYPES_POLICY = 0; const _assertNotInTrustedTypesPolicy = function _assertNotInTrustedTypesPolicy2() { if (IN_TRUSTED_TYPES_POLICY > 0) { throw typeErrorCreate('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.'); } }; const _createTrustedHTML = function _createTrustedHTML2(html2) { _assertNotInTrustedTypesPolicy(); IN_TRUSTED_TYPES_POLICY++; try { return trustedTypesPolicy.createHTML(html2); } finally { IN_TRUSTED_TYPES_POLICY--; } }; const _createTrustedScriptURL = function _createTrustedScriptURL2(scriptUrl) { _assertNotInTrustedTypesPolicy(); IN_TRUSTED_TYPES_POLICY++; try { return trustedTypesPolicy.createScriptURL(scriptUrl); } finally { IN_TRUSTED_TYPES_POLICY--; } }; const _getDefaultTrustedTypesPolicy = function _getDefaultTrustedTypesPolicy2() { if (!defaultTrustedTypesPolicyResolved) { defaultTrustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript); defaultTrustedTypesPolicyResolved = true; } return defaultTrustedTypesPolicy; }; const _document = document2, implementation2 = _document.implementation, createNodeIterator = _document.createNodeIterator, createDocumentFragment = _document.createDocumentFragment, getElementsByTagName = _document.getElementsByTagName; const importNode = originalDocument.importNode; let hooks2 = _createHooksMap(); DOMPurify.isSupported = typeof entries === "function" && typeof getParentNode === "function" && implementation2 && implementation2.createHTMLDocument !== void 0; const MUSTACHE_EXPR$1 = MUSTACHE_EXPR, ERB_EXPR$1 = ERB_EXPR, TMPLIT_EXPR$1 = TMPLIT_EXPR, DATA_ATTR$1 = DATA_ATTR, ARIA_ATTR$1 = ARIA_ATTR, IS_SCRIPT_OR_DATA$1 = IS_SCRIPT_OR_DATA, ATTR_WHITESPACE$1 = ATTR_WHITESPACE, CUSTOM_ELEMENT$1 = CUSTOM_ELEMENT; let IS_ALLOWED_URI$1 = IS_ALLOWED_URI; let ALLOWED_TAGS = null; const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]); let ALLOWED_ATTR = null; const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]); let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, { tagNameCheck: { writable: true, configurable: false, enumerable: true, value: null }, attributeNameCheck: { writable: true, configurable: false, enumerable: true, value: null }, allowCustomizedBuiltInElements: { writable: true, configurable: false, enumerable: true, value: false } })); let FORBID_TAGS = null; let FORBID_ATTR = null; const EXTRA_ELEMENT_HANDLING = Object.seal(create(null, { tagCheck: { writable: true, configurable: false, enumerable: true, value: null }, attributeCheck: { writable: true, configurable: false, enumerable: true, value: null } })); let ALLOW_ARIA_ATTR = true; let ALLOW_DATA_ATTR = true; let ALLOW_UNKNOWN_PROTOCOLS = false; let ALLOW_SELF_CLOSE_IN_ATTR = true; let SAFE_FOR_TEMPLATES = false; let SAFE_FOR_XML = true; let WHOLE_DOCUMENT = false; let SET_CONFIG = false; let SET_CONFIG_ALLOWED_TAGS = null; let SET_CONFIG_ALLOWED_ATTR = null; let FORCE_BODY = false; let RETURN_DOM = false; let RETURN_DOM_FRAGMENT = false; let RETURN_TRUSTED_TYPE = false; let SANITIZE_DOM = true; let SANITIZE_NAMED_PROPS = false; const SANITIZE_NAMED_PROPS_PREFIX = "user-content-"; let KEEP_CONTENT = true; let IN_PLACE = false; let USE_PROFILES = {}; let FORBID_CONTENTS = null; const DEFAULT_FORBID_CONTENTS = addToSet({}, [ "annotation-xml", "audio", "colgroup", "desc", "foreignobject", "head", "iframe", "math", "mi", "mn", "mo", "ms", "mtext", "noembed", "noframes", "noscript", "plaintext", "script", //